From marian at mba-software.de Mon Feb 7 01:21:01 2005 From: marian at mba-software.de (=?ISO-8859-1?Q?Marian_Aldenh=F6vel?=) Date: Mon, 07 Feb 2005 07:21:01 +0100 Subject: Unable to run IDLE Under Windows In-Reply-To: <060220052259038640%eq_fidget@mac.com> References: <060220052259038640%eq_fidget@mac.com> Message-ID: <36ofmlF533252U1@individual.net> Hi, > Any ideas as to what might me wrong? > TclError: unknown color name "white " There is a space after "white" in this error-message. If this string comes from some per-user configuration that may well explain your problem. Ciao, MM -- Marian Aldenh?vel, Rosenhain 23, 53123 Bonn. +49 228 624013. http://www.marian-aldenhoevel.de "Wir brauchen keine Opposition, wir sind bereits Demokraten." From fredrik at pythonware.com Tue Feb 22 11:07:31 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Feb 2005 17:07:31 +0100 Subject: 'modal dialogs' with Tkinter References: Message-ID: Sean McIlroy wrote: > I'd like to have a function f such that, when f is invoked, a Tk > window w is presented in which a number of variables can be modified, > and f returns the values that are indicated by the relevant > menus/checkbuttons/etc at the time w gets closed. I've tried various > ways of doing this, without success. Any assistance would be greatly > appreciated. does the approach described here work for you? http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm (note that the tkSimpleDialog module is included in Python's standard library) if it doesn't work, what doesn't work as required/expected? From steven.bethard at gmail.com Mon Feb 21 00:03:58 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 20 Feb 2005 22:03:58 -0700 Subject: python2.4 generator expression > python2.3 list expression In-Reply-To: References: Message-ID: snacktime wrote: > I need to convert a generator expression to a list expression so it > will work under python 2.3. > > I rewrote this: > > for c in range(128): > even_odd = (sum(bool(c & 1< > As this: > > for c in range(128): > bo = [bool(c & 1< even_odd = sum(bo) & 1 > > Seems to work, is there a better way to do this? Well, if you were happy with your generator expression, you can use almost exactly the same syntax: for c in range(128): even_odd = (sum([bool(c & 1< References: Message-ID: <420791a7$0$17127$626a14ce@news.free.fr> Harald Massa wrote: > Hello! > > I am using a library (= code of so else) within Python. Somewhere in this > library there is: > (snip) > > > now I want to change the common baa-method. so that > (snip) > Of course, I use a Python- and GPL-Licence compatible library, I can > change the source of foo, and use my changed library. > > But someday, it happened before, there will be an update by the publisher > to that library.... and I have to do all again. > > So, what is the most elegant solution to administer these changes? Use a version control system (svn is quite fine...). -- bruno desthuilliers ruby -e "print 'onurb at xiludom.gro'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@')" -- From dan.eloff at gmail.com Wed Feb 23 18:50:16 2005 From: dan.eloff at gmail.com (Dan Eloff) Date: Wed, 23 Feb 2005 15:50:16 -0800 Subject: Dynamically pass a function arguments from a dict Message-ID: You can take a dictionary of key/value pairs and pass it to a function as keyword arguments: def func(foo,bar): print foo, bar args = {'foo':1, 'bar':2} func(**args) will print "1 2" But what if you try passing those arguments to a function def func2(bar,zoo=''): print bar, zoo How can you determine that func2 will only accept bar and zoo, but not foo and call the function with bar as an argument? I know CherryPy does this, but it's not obvious from the source how they pulled it off. -Dan From axel at straschil.com Wed Feb 2 15:49:07 2005 From: axel at straschil.com (Axel Straschil) Date: Wed, 2 Feb 2005 20:49:07 +0000 (UTC) Subject: Generating modul classes with eval Message-ID: Hello! I was fooling around with creating classes for a module with eval, something like: MyModule.py: class Base: init(self, name): self._name = name for myclass in ['A', 'B', 'C']: code="class %s(Base):\n\tinit(self, name='%s')\n\t\tsuper(%s, self).__init(name=name)\n"%dict(myclass, myclass.lower(), myclass()) ... codeop and eval stuff ... a=A() print a that gives: , but I want MyModule.A ;-) Can someone give me a hint how to create classes in a module with eval and codeop so that they exist like the code was written in? Thanks, AXEL. From beliavsky at aol.com Mon Feb 28 12:51:55 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 28 Feb 2005 09:51:55 -0800 Subject: naming convention for scalars, lists, dictionaries ... Message-ID: <1109613115.760962.292360@z14g2000cwz.googlegroups.com> Since Python does not have declarations, I wonder if people think it is good to name function arguments according to the type of data structure expected, with names like "xlist" or "xdict". From steve at holdenweb.com Wed Feb 2 17:33:35 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 02 Feb 2005 17:33:35 -0500 Subject: Getting a module's byte code, how? In-Reply-To: <420153cb$0$28984$e4fe514c@news.xs4all.nl> References: <42014e25$0$28975$e4fe514c@news.xs4all.nl> <420153cb$0$28984$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > Mark Nenadov wrote: > >> On Wed, 02 Feb 2005 23:03:17 +0100, Irmen de Jong wrote: >> >> >>> What would be the best way, if any, to obtain >>> the bytecode for a given loaded module? >>> >>> I can get the source: >>> import inspect >>> import os >>> src = inspect.getsource(os) >>> >>> but there is no ispect.getbytecode() ;-) >>> >>> --Irmen >> >> >> >> The inspect API documentation says that code objects have "co_code", >> which >> is a string of raw compiled bytecode. >> >> Hope that helps! > > > Not very much, sorry. Because we now changed the problem into: > "how to obtain the code object from a module". > > > Perhaps a bit of background is in order. > For Pyro, I'm sending module byte codes across the > wire if the other side needs it (the mobile code feature). > However, this only works for modules that can be loaded > from a file on disk (because I'm now reading the .pyc file > that belongs to the module). When the receiving end in turn > calls another Pyro object, it may have to send the module's > bytecode again-- but that is no longer possible because the > module has no associated file anymore! (It is considered to > be a builtin module) > But because it is *loaded*, there must be some way to get > to the bytecodes, right? > I'm not sure why you think the module's code would be needed once it's been executed. That assigns all necessary code blocks to the functions defined therein, so the code, once the import has been executed, is garbage (from the interpreter's rather process-centric view of things). The module will, however, have a __file__ attribute, which should allow you to retrieve the code as mentioned in my previous post - a .pyc file, it appears, is just a four-byte magic number, a four-byte timestamp and a marshalled code object. Of course there's no guarantee that the module has been loaded from a compiled file. In that case your only option is to read in the source and compile it. I am presuming that this feature of Pyro won't allow a 2.3 system to talk to a 2.4 one, since the byte codes are incompatible. regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.python.org/pycon/2005/ Steve Holden http://www.holdenweb.com/ From farcepest at gmail.com Thu Feb 17 21:42:11 2005 From: farcepest at gmail.com (Andy Dustman) Date: 17 Feb 2005 18:42:11 -0800 Subject: MYSQL - how to install ? In-Reply-To: <1108684689.617676.213510@g14g2000cwa.googlegroups.com> References: <1108547199.260223.211450@f14g2000cwb.googlegroups.com> <1108556905.444394.210020@l41g2000cwc.googlegroups.com> <1108562949.825258.297260@f14g2000cwb.googlegroups.com> <1108635996.165520.132960@o13g2000cwo.googlegroups.com> <1108684689.617676.213510@g14g2000cwa.googlegroups.com> Message-ID: <1108694531.062496.19020@g14g2000cwa.googlegroups.com> There's a Windows package for MySQL-4.1.9 and Python-2.4 on SourceForge now, thanks to Michal Zylinski. https://sourceforge.net/project/showfiles.php?group_id=22307&package_id=15775&release_id=303257 From jelleferinga at gmail.com Tue Feb 1 10:53:54 2005 From: jelleferinga at gmail.com (jelle) Date: 1 Feb 2005 07:53:54 -0800 Subject: pythonic equivalent of Mathematica's FixedPoint function Message-ID: <1107273234.276714.272890@z14g2000cwz.googlegroups.com> I now some hostility to functional programming is flaming up now and then; still could someone suggest me a pythonic equivalent for Mathematica's FixedPoint function? For those not familiar with Mathematica: FixedPoint[f, expr] starts with expr, then applies f repeatedly until the result no longer changes. thanks, jelle. From bpeng at rice.edu Fri Feb 4 19:53:46 2005 From: bpeng at rice.edu (Bo Peng) Date: Fri, 04 Feb 2005 18:53:46 -0600 Subject: changing local namespace of a function In-Reply-To: <11082ntjhddo357@corp.supernews.com> References: <11082ntjhddo357@corp.supernews.com> Message-ID: Jeff Shannon wrote: > > This sounds to me like you're trying to re-implement object orientation. > I have no control over the big dictionaries. All I need to do is processing them in situ --- that is to say, go into each map and manipulate numbers. Parameter passing should be avoid whenever possible since involved number of items are huge. It is basically like exec 'statements' in d but a function with local dictionary d would be best. Bo From michele.simionato at gmail.com Wed Feb 9 11:54:52 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 9 Feb 2005 08:54:52 -0800 Subject: porting from Tkinter to pygtk Message-ID: <1107968092.413408.89010@c13g2000cwb.googlegroups.com> I am in the process of learning pygtk and I would like to port some custom made Tkinter widgets to pygtk, just an exercise. For instance I have this code: . from Tkinter import * . . class AnimatedLabel(Label): . def __init__(self, master, text, width=72, maxspc=16, deltat=100, **kw): . self.text = text . self.width = width . self.maxspc = maxspc . self.deltat = deltat . self.stringvar = StringVar(master) . self.stringvar.set(text) . self.stop = False . Label.__init__(self, master, textvariable=self.stringvar, **kw) . . def startAnimation(self, spaces='', addspace=False): . if len(spaces) == 0 or len(spaces) == self.maxspc: . addspace = not addspace . if addspace: # add a space . spaces += ' ' . else: # remove a space . spaces = spaces[1:] . if not self.stop: # repeat each 100 ms changing spaces and addspace . self.stringvar.set(spaces.join(self.text).center(self.width)) . self.after(self.deltat, self.startAnimation, spaces, addspace) . . def stopAnimation(self): . self.stop = True . . . if __name__ == "__main__": . t = Tk() . t.title('Example') . t.config(background='green') . . a = AnimatedLabel(t, text="Hello", fg='blue', bg='green') . a.pack() . a.startAnimation() . t.mainloop() what's the equivalent of the .after() method in pygtk? BTW, is there any intro to pygtk thought for Tkinter users? TIA, Michele Simionato From deetsNOSPAM at web.de Wed Feb 16 11:24:46 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 16 Feb 2005 17:24:46 +0100 Subject: ZODB performance (was Re: low-end persistence strategies?) References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <37h194F50j4pkU1@individual.net> <7xfyzwehq7.fsf@ruckus.brouhaha.com> <37h2keF5a2ijjU1@individual.net> Message-ID: <37hadqF5dvnheU1@individual.net> > Chris (or anyone else), could you comment on ZODB's performance? I've > Googled around a bit and haven't been able to find anything concrete, so > I'm really curious to know how ZODB does with a few hundred thousand > objects. > Specifically, what level of complexity do your ZODB queries/searches have? > Any idea on how purely ad hoc searches perform? Obviously it will be > affected by the nature of the objects, but any insight into ZODB's > performance on large data sets would be helpful. What's the general ratio > of reads to writes in your application? This is a somewhat weak point of zodb. Zodb simply lets you store arbitrary object graphs. There is no indices created to access these, and no query language either. You can of course create indices yourself - and store them as simply as all other objects. But you've got to hand-tailor these to the objects you use, and create your querying code yourself - no 4gl like sql available. Of course writing queries as simple predicates evaluated against your whole object graph is straightforward - but unoptimized. The retrieval of objects themselves is very fast - I didn't compare to a rdbms, but as there is no networking involved it should be faster. And of course no joins are needed. So in the end, if you have always the same kind of queries that you only parametrize and create appropriate indices and hand-written "execution plans" things are nice. But I want to stress another point that can cause trouble when using zodb and that I didn't mention in replies to Paul so far, as he explicitly didn't want to use an rdbms: For rdbms'ses, a well-defined textual representation of the entities stored in the db is available. So while you have to put some effort on creating on OR-mapping (if you want to deal with objects) that will most likely evolve over time, migrating the underlying data usually is pretty straightforward, and even toolsupport is available. Basically, you're only dealing with CSV-Data that can be easily manipulated and stored back. ZODB on the other side is way easier to code for - but the hard times begin if you have a rolled out application that has a bunch of objects inside zodb that have to be migrated to newer versions and possibly changed object graph layouts. This made me create elaborate yaml/xml serializations to allow for im- and exports and use with xslt and currently I'm investigating a switch to postgres. This point is important, and future developments of mine will take that into consideration more than they did so far. -- Regards, Diez B. Roggisch From b at b.b Sun Feb 13 15:55:58 2005 From: b at b.b (Roose) Date: Sun, 13 Feb 2005 20:55:58 GMT Subject: builtin functions for and and or? Message-ID: I need this a lot: a one line way to do a n-ary and or 'or'. e.g., result = True for x in L: if not boolean_function(x): result = False or >>> reduce(operator.__and__, [boolean_function(x) for x in L) So usually I just write a little function any( L, boolean_function = identity ) or all( ... ). But I am kind of sick of doing that all the time -- does it exist anywhere in the Python libraries? It seems really common to me. The first way isn't satisfactory because it takes so many lines for what is essentially one "primitive" operation. The second way isn't great because it is not as readable and many readers don't like to see reduce, even if it is a common idiom like that. Also I don't believe it short circuits. From ed-no at spam-eepatents.com Mon Feb 14 12:35:27 2005 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Mon, 14 Feb 2005 09:35:27 -0800 Subject: Scan document pages to a compressed PDF Message-ID: I'd like to write a Python-based commandline tool that will scan pages with SANE, applying CCITT Group 4 compression during scanning, and produce a single PDF file. I would release it under GPL. Right now, I'm relying on a workable but inflexible shell script that pipes stuff between scanimage, tiffcp, tiff2ps, and ps2pdf. What's the best way currently to do CCITT4 compression (e.g., of intermediate TIFF-format images) from Python? PIL doesn't seem to support CCITT4 compression, and the read-only patch [1] that's available won't help in my case. I'd like to incorporate as much as possible into the Python code and imported packages, rather than relying on pipes to a bunch of external programs. Same question regarding SANE -- I can't seem to find the supposed PIL support for SANE in the release on my system. Anyone know about that, or alternatives? --- Ed Suominen Registered Patent Agent Open-Source Software Author (yes, both...) Web Site: http://www.eepatents.com [1] http://mail.python.org/pipermail/image-sig/2003-July/002354.html From fredrik at pythonware.com Sun Feb 20 12:29:53 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Feb 2005 18:29:53 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: <42172136$0$27576$9b622d9e@news.freenet.de> <42185b05$0$15460$9b622d9e@news.freenet.de> <42189527$0$6260$9b622d9e@news.freenet.de> Message-ID: Ilias Lazaridis wrote: > I understand. no. From marc.poulhies at NO-SP44Mepfl.ch Tue Feb 1 03:44:11 2005 From: marc.poulhies at NO-SP44Mepfl.ch (=?iso-8859-1?Q?Marc_Poulhi=E8s?=) Date: Tue, 01 Feb 2005 09:44:11 +0100 Subject: Using HTTPSConnection and verifying server's CRT References: <41fe5357@epflnews.epfl.ch> <41fe5fb7@epflnews.epfl.ch> Message-ID: <41ff4157@epflnews.epfl.ch> Marc Poulhi?s writes: > ngps at netmemetic.com (Ng Pheng Siong) writes: >> M2Crypto does server cert verification. With M2Crypto's httpslib, you pass >> in an SSL.Context instance to the HTTPSConnection constructor to configure >> the SSL; one of the config knobs is cert verification. So, redo your test, >> satisfy yourself that this is doable, and send me your code to include as >> an example in the distribution. ;-) Hi again! So here are few lines that do server's CRT check. I still have one question: see in the code. Both have the exact same description on the documentation. Btw, thanks for your answer (this will save me from using Perl!) Marc ---8<-------8<-------8<-------8<---- #!/usr/bin/env python import M2Crypto ctx = M2Crypto.SSL.Context() ## what are the diff between these two?? #ctx.load_verify_info(cafile="/tmp/ca.crt") ctx.load_verify_locations(cafile="/tmp/ca.crt") # load client certificate (used to authenticate the client) ctx.load_cert("/tmp/client.crt") # stop if peer's certificate can't be verified ctx.set_allow_unknown_ca(False) # verify peer's certificate ctx.set_verify(M2Crypto.SSL.verify_peer, 1) con = M2Crypto.httpslib.HTTPSConnection("my.ssl.server.domain",ssl_context=ctx) con.request("GET" , "/") print con.getresponse().read() ---8<-------8<-------8<-------8<----- Result here: $ ./ssl_peer_verif.py Enter passphrase: send: 'GET / HTTP/1.1\r\nHost: my.ssl.server.domain:443\r\nAccept-Encoding: identity\r\n\r\n' reply: 'HTTP/1.1 200 OK\r\n' header: Date: Tue, 01 Feb 2005 08:41:51 GMT header: Server: Apache/2.0.46 (Red Hat) header: Last-Modified: Mon, 31 Jan 2005 14:50:50 GMT header: ETag: "4297-13-24658680" header: Accept-Ranges: bytes header: Content-Length: 19 header: Connection: close header: Content-Type: text/html; charset=UTF-8 THIS IS WORKING =) From caleb1 at telkomsa.net Tue Feb 8 23:15:59 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 08 Feb 2005 23:15:59 -0500 Subject: Choosing the right parser for parsing C headers References: <1107861023.254610.14310@g14g2000cwa.googlegroups.com> Message-ID: Jean, Paddy I use "pym" to extract bits of pascal out of delphi code for documentation purposes. You have to add some stuff to the delphi code (in your case, C header), but these are added within comment blocks, and the interesting thing is that you add python code(!) as a kind of dynamic markup which pym executes while parsing the file. In other words, you can write python code within a comment block in your C-header to generate unit-tests into other files, and get that code executed with pym. Keep well Caleb On Tue, 08 Feb 2005 19:58:33 GMT, Paddy McCarthy wrote: > Jean de Largentaye wrote: >> Hi, >> I need to parse a subset of C (a header file), and generate some unit >> tests for the functions listed in it. I thus need to parse the code, >> then rewrite function calls with wrong parameters. What I call "shaking >> the broken tree" :) >> I chose to make my UT-generator in Python 2.4. However, I am now >> encountering problems in choosing the right parser for the job. I >> struggle in choosing between the inappropriate, the out-of-date, the >> alpha, or the too-big-for-the task... > > Why not see if the output from a tags file generator such as ctags or > etags will do what you want. > > I often find that some simpler tools do 95% of the work and it is easier > to treat the other five percent as broken-input. > > try http://ctags.sourceforge.net/ > > > - Paddy. From http Fri Feb 25 02:41:31 2005 From: http (Paul Rubin) Date: 24 Feb 2005 23:41:31 -0800 Subject: web status display for long running program References: <509534af.0502241737.5f62992@posting.google.com> <1109316391.203166.119700@z14g2000cwz.googlegroups.com> Message-ID: <7x8y5dnl1w.fsf@ruckus.brouhaha.com> "Kamilche" writes: > I was inspired to enhance your code, and perform a critical bug-fix. > Your code would not have sent large files out to dialup users, because > it assumed all data was sent on the 'send' command. I added code to > check for the number of bytes sent, and loop until it's all gone. I > also turned it into a class, and made it 'command' based. That server seems to do a cpu-busy loop polling the listening socket for incoming requests! Ouch! It also assumes that once it's gotten \r\n in the input, that the entire request has been received. If someone is telnetting into the server typing one character at a time, that could fool it. I think it's better to just launch a separate thread and use BaseHTTPServer which is already in the stdlib. From john at grulic.org.ar Sun Feb 6 01:39:09 2005 From: john at grulic.org.ar (John Lenton) Date: Sun, 6 Feb 2005 03:39:09 -0300 Subject: a type without a __mro__? In-Reply-To: <1grid1l.7goks6hh1l6yN%aleaxit@yahoo.com> References: <1grid1l.7goks6hh1l6yN%aleaxit@yahoo.com> Message-ID: <20050206063909.GA5414@grulic.org.ar> On Sat, Feb 05, 2005 at 11:37:10AM +0100, Alex Martelli wrote: > Can anybody suggest where to find (within the standard library) or how > to easily make (e.g. in a C extension) a type without a __mro__, except > for those (such as types.InstanceType) which are explicitly recorded in > the dispatch table copy._deepcopy_dispatch...? would this do what you need? class C(type): def __getattribute__(self, attr): if attr == '__mro__': raise AttributeError, "What, *me*, a __mro__? Nevah!" return super(C, self).__getattribute__(attr) class D(object): __metaclass__ = C instances of D have a type that behaves as if it didn't have a __mro__. This isn't exactly what you asked for, but it might be enough. -- John Lenton (john at grulic.org.ar) -- Random fortune: El tiempo cura los dolores y las querellas porque cambiamos. Ya no somos la misma persona. -- Blaise Pascal. (1600-1662) Fil?sofo y escritor franc?s. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From simoninusa2001 at yahoo.co.uk Thu Feb 17 02:31:17 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 16 Feb 2005 23:31:17 -0800 Subject: Pausing a program - poll/sleep/threads? Message-ID: <1108625477.222091.34680@l41g2000cwc.googlegroups.com> I'm writing a PyQt network client for XMMS, using the InetCtrl plugin, that on connection receives a track length. To save on bandwidth, I don't want to be continually querying the server for updates (e.g. has the current track finished yet?) so I figured the best thing to do is just update after the track length has expired. So, how would I make a Python program automatically call a function after a preset period of time, without the Python process running in the foreground (effectively single-tasking)? I think that sleep() would work in the foreground (kind of like a while loop does, I've come across that issue with wxPython!) does Python have any polling capabilities? What about threading - if I launched a thread to just "wait" until a time has expired, could I then get that thread to make the main program call a function, or would the main program sit there waiting for the thread to end? I really have no experience with threads in Python, any hints/tutorials, the docs are pretty limited? I'm looking to make this program cross-platform, it has to run on at least Windows and Linux (hopefully MacOSX too) so the solution would have to be portable (does Windows even have threading without POSIX?) If you want to check out what I've done so far (GUI, track info, controls etc.) you'll need XMMS, http://inetctrl.sourceforge.net and my source from http://www.the-jedi.co.uk/downloads/xmmsclient there's also some Windows binaries built with the Cygwin/KDE port. [InetCtrl seems to segfault if you don't have a playlist loaded, so load a playlist first, then enable the general plugin. I must submit a bug report to the author, maybe I could convince him to broadcast when a track ends...] Any help would be excellent, as playlist support and these "timed updates" are about all that's left needing to be done.... From fredrik at pythonware.com Wed Feb 2 16:01:42 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Feb 2005 22:01:42 +0100 Subject: Crude statistics on the standard library References: <41fe5fc7$0$29873$636a15ce@news.free.fr> Message-ID: F. Petitjean wrote: > sre_compile and sre_parse should be coded with a __all__ attribute they're implementation modules, and shouldn't be used by user code. From fuzzyman at gmail.com Wed Feb 2 08:02:40 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 2 Feb 2005 05:02:40 -0800 Subject: Save the Canvas! In-Reply-To: References: Message-ID: <1107349360.258600.131850@f14g2000cwb.googlegroups.com> Not that funny ! ;-) Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From cam.ac.uk at mh391.invalid Sun Feb 20 13:44:03 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 20 Feb 2005 18:44:03 +0000 Subject: introspection inquiry In-Reply-To: <4218CCF1.1050601@jessikat.fsnet.co.uk> References: <1108910710.985704.264430@c13g2000cwb.googlegroups.com> <4218A579.2060503@jessikat.fsnet.co.uk> <4218CCF1.1050601@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: > import inspect > class A: > _class_name=inspect.currentframe().f_code.co_name > def __init__(self,text,_defining_class_name=_class_name): > print 'text=',text,'_defining_class_name=',_defining_class_name > > class B(A): > pass > b=B('aaa') That won't work, if you, say, wanted to print out the name of the class the constructor was defined in for a whole chain of constructors. Which is about the only case I can think of where this would be useful. > could work as well, but if we only need the local name why not just > insert directly. To be honest, that is what I have done every time I have needed something like this. I've only used metaclasses in production code once and I still debate whether that case is a good idea or not. -- Michael Hoffman From richie at entrian.com Tue Feb 8 10:56:18 2005 From: richie at entrian.com (Richie Hindle) Date: Tue, 08 Feb 2005 15:56:18 +0000 Subject: ANN: Zeus Programmers Editor V3.94 In-Reply-To: <4208D147.5040405@mediapulse.com> References: <4207843C.26FB@zeusedit.com> <4208D147.5040405@mediapulse.com> Message-ID: <5snh01hn4hlf1515su8rs5m366lghobsu2@4ax.com> [Jussi] > The latest release of the Zeus for Windows programmer's > editor is now available. [Gabriel] > So is this mentioned here on the Python mailing list because Zeus was > written in Python, or is this just targeted spam for a commerical product? >From the features page: > o Syntax highlighting for C\C++, Clipper, Cobol, Fortran, Java, Pascal, Perl, Python, PHP, SQL etc > o Fully Scriptable using the Python, Lua or SmallC, VB Script, Java Script, Ruby Script languages > o Integrated debugger supports the Java, Perl, Python and C# languages IMHO that makes it of general interest to Python programmers. Whether or not it's a commercial product seems irrelevant. For myself, announcements of Python-related products, whether free or commercial, are welcome here (though python-announce / c.l.p.a might be a better place, from the point of view of both readers and announcers). -- Richie Hindle richie at entrian.com From The2ndspiketoo at webtv.zzn.com Fri Feb 4 03:14:06 2005 From: The2ndspiketoo at webtv.zzn.com (Lisa Horton) Date: 4 Feb 2005 00:14:06 -0800 Subject: Learning Python for a new beginner Message-ID: <1107504846.923502.185700@c13g2000cwb.googlegroups.com> I hear that Python is one of the easiest languages to learn. It is easier than PHP or Pearl? Is it as useful as those two? I am attracted to Python as a first language, but I just want to be sure I will be able to use it. Opinions, thoughts, thanks! From tim.leeuwvander at nl.unisys.com Thu Feb 3 07:23:45 2005 From: tim.leeuwvander at nl.unisys.com (Leeuw van der, Tim) Date: Thu, 3 Feb 2005 13:23:45 +0100 Subject: Crashing Python interpreter! (windows XP, python2.3.4, 2.3.5rc1, 2.4.0) Message-ID: > > > -----Original Message----- > From: python-list-bounces+tim.leeuwvander=nl.unisys.com at python.org on behalf of John Machin > Sent: Thu 2/3/2005 12:00 PM > To: python-list at python.org > Subject: Re: Crashing Python interpreter! (windows XP, python2.3.4, 2.3.5rc1,2.4.0) > > > Leeuw van der, Tim wrote: > > > >> > Do you have a file called drwtsn32.log anywhere on your computer? > > > > No, unfortunately I cannot find such file anywhere on my computer.... > > > > What do I do to get such file? Or anything equally useful? > > > > On my Windows 2000 box, just crash something :-) > > > Perhaps this may help: > > http://www.windowsnetworking.com/kbase/WindowsTips/Windows2000/RegistryTips/RegistryTools/DrWatson.html > Using this URL, I found the log file and it's about 1Gb big... I'll have to find out what is the useful part of it (or remove it and crash again). I don't know why searching all drives using windows 'search' did not find the file! When I have a usefull crashdump, what should I do? Attach to e-mail and post it here? Should I include the user.dmp file too? Should I do the same for both python 2.3.5r1 and python 2.4? Or is it sufficient to do so for Python 2.4? Thanks for the assistance! --Tim > -- From pierre.barbier at cirad.fr Wed Feb 2 02:27:02 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Wed, 02 Feb 2005 08:27:02 +0100 Subject: type of simple object In-Reply-To: <1107261198.943087.80960@z14g2000cwz.googlegroups.com> References: <1107255752.258025.50870@z14g2000cwz.googlegroups.com> <1107257264.146280.89560@c13g2000cwb.googlegroups.com> <1107258136.815344.145380@c13g2000cwb.googlegroups.com> <1107261198.943087.80960@z14g2000cwz.googlegroups.com> Message-ID: <42008044$0$14171$626a14ce@news.free.fr> ajikoe at gmail.com a ?crit : > Thank you guys. > > My function should multiply every element of a list, for example > "something" > and "something" can be an integer or another list. > If it deals with integer than it is ok, but > If it deals with list than it become false for example list*2 = > listlist, and what I really want is to mutlitply its member. > That's why I need to know the type of my data in "something". As stated by another comment, I would do something like : def multiply(object, factor): try: return [ multiply(i,factor) for i in object ] except TypeError: return object*factor This function will, recursively multiply a nested list of numbers by "factor" ... > > By the way I am new in python, I heard that it has a MatLab > capabilities, How good is that? Since It would be very nice when we can > do what MatLab do in python..... I think you are referring to the Numeric or the numarray modules. They offer matric computations close to chat Matlab offers. "numarray" is the newer version of "Numeric", but in case of small matrix, it performs slower (for various reasons). Then, you can find lots of information on the net concerning these two modules. > > > Sincerely Yours, > pujo > Pierre From removethis.kartic.krishnamurthy at gmail.com Thu Feb 3 06:59:36 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Thu, 03 Feb 2005 11:59:36 GMT Subject: errors In-Reply-To: References: Message-ID: Joel Eusebio said the following on 2/2/2005 4:53 PM: > Can someone help me on this, I don' know where the "testmptest" came from > but the mptest.py is at the /usr/local/apache2/htdocs/test directory and > this error came from apache's error_log > > PythonHandler mod_python.publisher: ImportError: No module named testmptest > > Thanks, > > Joel I found this link from Googling - http://www.modpython.org/pipermail/mod_python/2004-January/014857.html Please read the entire thread and see if it provides your resolutions (the mod_python OP's issue was similar but for a different module). It might also do you some good to join mod_python mailing list if you are going to use it regularly. Thanks, -Kartic From deetsNOSPAM at web.de Wed Feb 16 10:11:42 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 16 Feb 2005 16:11:42 +0100 Subject: Test for structure References: <1108566497.848623.45360@c13g2000cwb.googlegroups.com> Message-ID: <37h64qF5ck38lU3@individual.net> import types v = [] if type(v) is types.ListType: pass -- Regards, Diez B. Roggisch From http Thu Feb 3 19:35:33 2005 From: http (Paul Rubin) Date: 03 Feb 2005 16:35:33 -0800 Subject: CGI and HTTP Header Location redirects References: Message-ID: <7xk6ppyxey.fsf@ruckus.brouhaha.com> Derek Basch writes: > Also, after enabling suEXEC on the apache server the script executes > perfectly with the redirect. Can anyone explain this behavior? I > would guess that it is related to apache user rights but I can't > find any reference to such problems via Google. Apache probably isn't able to run the cgi because of lack of exec permission or something like that. The best way to diagnose such probs is by checking the apache error log, if you have access to it. Best newsgroup for this type of question is comp.infosystems.www.servers.unix. Lots of apache experts hang out there. From macrocosm at fastmail.fm Thu Feb 17 20:45:27 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Thu, 17 Feb 2005 20:45:27 -0500 Subject: [Fwd: Re: [Uuu-devel] languages] <-- Why Python In-Reply-To: <86vf8qhcql.fsf@guru.mired.org> References: <1108678805.542584.171930@z14g2000cwz.googlegroups.com> <864qgaisoq.fsf@guru.mired.org> <86vf8qhcql.fsf@guru.mired.org> Message-ID: <421548B7.9030904@fastmail.fm> Mike Meyer wrote: >Arich Chanachai writes: > > >>Mike Meyer wrote: >> >> >>>Arich Chanachai writes: >>> >>> >>>>These last two points kind of diverge from the point, no? What I mean >>>>is that we want to present the argument of why Python is the best >>>>choice as THE built-in programming language for the revolutionary uuu >>>>operating system. >>>> >>>> >>>A new operating system shouldn't be picking "THE" built-in programming >>>language. It should instead be providing mechanisms to allow arbitrary >>>programming languages to be used wherever they are required. Tying the >>>users of the OS - or of some application - down to a specific language >>>is a disservice to the developers and users of that OS or application. >>> >>>While Python is an excellent language, and has a nice implementation >>>for embedding/extending applications, it's not necessarily the best >>>choice for all problems. You're be doing much better for your users to >>>allow them to choose the right language for the problem than to >>>dictate the language that has to be used. >>> >>> >>> >>There is no intention to dictate, but instead to provide >>out-of-the-box, built-into-the-architecture support for a single >>language or a wide array of languages. For now, this will begin with >>a single language and the question is merely which one. >> >> > >Whatever the intentions may be, the *act* is one of dictation. Since >the point of the underlying OS is to increase the interconnections >between applications (assuming I've found the correct web page and >interpreted it correctly), the underlying architecture should be >language-neutral. That allows as many applications as possible to play >in the environment. > >I did this with CORBA (see http://www.mired.org/home/mwm/scripting/ ) >just to show that Unix can play in this arena as well as various >desktop OS's. Plan 9 provides a much better mechanism that allows any >programming language that can do file I/O to be used for building >interconnections. > > > When the CLR is integrated, it will allow a wide array of problem solving choices for uuu users. From claird at lairds.us Wed Feb 23 20:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 24 Feb 2005 01:08:03 GMT Subject: kill a process in XP References: Message-ID: <05lve2-b6p.ln1@lairds.us> In article , Dave Brueck wrote: >Tor Erik S?nvisen wrote: >>>From my Python-program I spawn a new process. When using P_NOWAIT spawnl >> returns the pid but in windows it returns a process handle. >> Later I want to kill this process. How can I do this when I only have the >> process handle? > >Try ctypes - if it's really a Windows handle, then this should work: > >from ctypes import * >windll.kernel32.TerminateProcess(h, 0) # or whatever return code you want > >-Dave I sometimes am so irritated with attendant portability issues that I open a channel between parent and child, which I use to send an exit-now message. From cam.ac.uk at mh391.invalid Sun Feb 20 11:02:20 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 20 Feb 2005 16:02:20 +0000 Subject: introspection inquiry In-Reply-To: References: <1108910710.985704.264430@c13g2000cwb.googlegroups.com> <4218A579.2060503@jessikat.fsnet.co.uk> Message-ID: Diez B. Roggisch wrote: >[Michael Hoffman]: >>Unless I misunderstood the question, that won't work. That will >>give you the name of the class the object is an instance is of. >>I think he wants the name of the class the method was defined in. > > Where is the difference? The method is defined in a class - and an instance > is created from that class. > > This works as expected: > > class ExistentialCrisis: > def __init__(self, text): > self.spam = text > print 'In the constructor of the %s class' % self.__class__.__name__ > > > ExistentialCrisis("egal") Yes, but this doesn't work if you have a subclass: """ class ExistentialCrisisSubclass(ExistentialCrisis): def __init__(self, text): print "New constructor" ExistentialCrisis.__init__(self, text) ExistentialCrisisSubclass("whoa") """ gives you: New constructor In the constructor of the ExistentialCrisisSubclass class But the second line is *not* in the constructor of ExistentialCrisisSubclass, it is in the constructor of ExistentialCrisis. while I read the original post as saying that he wanted "ExistentialCrisis" there instead. Indeed this example -- Michael Hoffman From mogmios at mlug.missouri.edu Thu Feb 3 12:35:21 2005 From: mogmios at mlug.missouri.edu (Michael) Date: Thu, 03 Feb 2005 09:35:21 -0800 Subject: global variables In-Reply-To: <3YSdnYVEmOCW8pzfRVn-sg@comcast.com> References: <1107385488.822768.317250@l41g2000cwc.googlegroups.com> <1107388493.465599.140480@g14g2000cwa.googlegroups.com> <3YSdnYVEmOCW8pzfRVn-sg@comcast.com> Message-ID: <420260D9.6060806@mlug.missouri.edu> > Probably naming it something other than 'globals' would be a good idea > -- otherwise you'll hide the builtin globals() function. > But I agree that the attributes of a class instance (as you suggest) > or the attributes of a module (as Steve Holden suggests) is probably > the right way to go. I like to use 'runtime' or 'runtime_options' to store the results of command-line options. I wasn't sure about this way of getting Python to handle global variables when I first tried it but after a little experience with it I think it works out pretty well. One thing I did learn though is that it's best to keep these modules simple. Don't make them import or define classes or functions if you can avoid it. It's easy to get into a mess of recursive imports if you start doing that. Just a good newbie tip. *** if runtime.verbose: print 'Something happened.' *** -- Michael http://kavlon.org From walter at livinglogic.de Fri Feb 18 14:18:28 2005 From: walter at livinglogic.de (=?ISO-8859-15?Q?Walter_D=F6rwald?=) Date: Fri, 18 Feb 2005 20:18:28 +0100 Subject: unicode encoding usablilty problem In-Reply-To: References: Message-ID: <42163F84.8070701@livinglogic.de> aurora wrote: > [...] > In Java they are distinct data type and the compiler would catch all > incorrect usage. In Python, the interpreter seems to 'help' us to > promote binary string to unicode. Things works fine, unit tests pass, > all until the first non-ASCII characters come in and then the program > breaks. > > Is there a scheme for Python developer to use so that they are safe > from incorrect mixing? Put the following: import sys sys.setdefaultencoding("undefined") in a file named sitecustomize.py somewhere in your Python path and Python will complain whenever there's an implicit conversion between str and unicode. HTH, Walter D?rwald From sharidas at zeomega.com Sat Feb 5 02:18:23 2005 From: sharidas at zeomega.com (Satchidanand Haridas) Date: Sat, 05 Feb 2005 12:48:23 +0530 Subject: EDI x12 --> XML In-Reply-To: <4203CDF9.1060505@novasyshealth.com> References: <4203CDF9.1060505@novasyshealth.com> Message-ID: <4204733F.8040408@zeomega.com> Hi, In case you weren't aware of the pyx12 project on sourceforge. The project summary on sourceforge.net (http://sourceforge.net/projects/pyx12/) says the following and I quote: "pyx12 is a python based ANSI X.12 to XML EDI translator and validator. It is designed to be a step in the conversion of a X12 transaction to back-end database process. It can convert to and from an XML representation of the X12 document. " fyi. thanks, Satchit ---- Satchidanand Haridas (sharidas at zeomega dot com) ZeOmega (www.zeomega.com) Open Minds' Open Solutions #20,Rajalakshmi Plaza, South End Road, Basavanagudi, Bangalore-560 004, India Greg Lindstrom wrote: > Hello, List- > > I am working on automating a system accepting input data in EDI x12 > format and would like to convert it to XML. Before I start, I thought > I'd ask if anyone has worked on such a beast. I have seen work by > Chris Cioffi on parsing EDI records. Is anything else out there > before I either write one or use one that I have written in Perl? > > Thanks! > --greg-- > > Greg Lindstrom 501 975.4859 > Computer Programmer greg.lindstrom at novasyshealth.com > NovaSys Health > Little Rock, Arkansas > > "We are the music makers, and we are the dreamers of dreams." W.W. > > From peter at engcorp.com Sun Feb 27 15:36:54 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 27 Feb 2005 15:36:54 -0500 Subject: default value for list access? In-Reply-To: References: Message-ID: Bo Peng wrote: > The data is the count of something, for example a[90]=10. a may be a > dictionary if the range is huge and a list when the range is reasonably > small. In the dictionary case, I can use a.setdefault(80, 0) if key 80 > does not exist. In the list case, I have to check the length of list > before I access it (or use exception). > > This becomes troublesome when I need to do the following a lot. > > b = a[80][1] + a[80][2] + a[80][3] > > If I use the getItem function in my previous email, it will look like > > b = getItem(getItem(a, 80, []), 1, 0) + getItem(getItem(a, 80, []), 2, > 0) + getItem(getItem(a, 80, []), 3, 0) > > What would be the best solution to handle this? Sounds to me like the best solution is to simplify the implementation and dispense with the list alternative. Why use a list if a dictionary is suitable? Don't say performance: that's premature optimization. Dictionaries already have what you need, apparently, with setdefault(), so just use them and keep the code simple. ... > but I am afraid that a for loop would bring serious performance problem. More premature optimization? The first rule of programming should be to make it work. Then consider making it faster, but only if it is really unacceptably slow. (Some would say to make it work, then make it "right", then make it fast. In this case, "right" doesn't mean "correct" (that's the first step), it means making it clean and simple. Doing it this way makes sense only if you have a really good test suite developed along with the code, ala test-driven development. Lacking that, you should focus on "right" and working together, which in this case suggests leaving out the complicated list option.) -Peter From ncoghlan at iinet.net.au Sat Feb 26 02:00:24 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 26 Feb 2005 17:00:24 +1000 Subject: Code evaluation at function definition execution time (was Re: Compile time evaluation (aka eliminating default argument hacks)) In-Reply-To: References: Message-ID: <42201E88.8070803@iinet.net.au> Steven Bethard wrote: > Worth looking at is the thread: > > http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/58f53fe8bcc49664/ Huh - I thought I put something in the original post saying "without resorting to bytecode hacks", but I must have deleted it before sending the message. Anyway, that thread is what the comment about bytecode hacks would have been referring to :) Although, once the AST compiler goes in, if the AST for a function is attached via a special attribute like __ast__, then perhaps such manipulations could be rewritten to work on the AST instead of the bytecode. If that happens, they might become less hackish. So I guess I should wait and see what the next few months holds in terms of AST-hacks :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ericjardim at gmail.com Thu Feb 10 21:17:33 2005 From: ericjardim at gmail.com (Eric Jardim) Date: 10 Feb 2005 18:17:33 -0800 Subject: PyQt documentation Message-ID: <1108088253.552834.44690@z14g2000cwz.googlegroups.com> Hi, Is there any site that gather all the documentation about PyQt? The docs of the Riverbank site is poor, and I have found separate tutorials on the net. I know that the Kompany have made a "Qtdoc"-like to PyQt. But it is not free doc. Does anybody know anything about any project for making PyQt development more easy? thanks, [Eric Jardim] From nick at craig-wood.com Fri Feb 18 05:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 18 Feb 2005 10:30:01 GMT Subject: low-end persistence strategies? References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <1108622622.119311.43200@f14g2000cwb.googlegroups.com> <1108629775.800508.3400@f14g2000cwb.googlegroups.com> <1108702957.327528.22010@z14g2000cwz.googlegroups.com> <1108707658.105102.298300@z14g2000cwz.googlegroups.com> Message-ID: Michele Simionato wrote: > Ok, I have yet another question: what is the difference > between fcntl.lockf and fcntl.flock? The man page of > my Linux system says that flock is implemented independently > of fcntl, however it does not say if I should use it in preference > over fcntl or not. flock() and lockf() are two different library calls. With lockf() you can lock parts of a file. I've always used flock(). >From man lockf() "On Linux, this call [lockf] is just an interface for fcntl(2). (In general, the relation between lockf and fcntl is unspecified.)" see man lockf and man flock -- Nick Craig-Wood -- http://www.craig-wood.com/nick From helten0007 at yahoo.com Sat Feb 26 07:57:20 2005 From: helten0007 at yahoo.com (Pete.....) Date: Sat, 26 Feb 2005 13:57:20 +0100 Subject: Making a calendar Message-ID: <422071d5$0$22691$ba624c82@nntp04.dk.telia.net> Hi all. I'm trying to make a calendar for my webpage, python and html is the only programming languages that I know, is it possible to make such a calendar with pythong code and some html. The Idea is that when I click the link calendar on my webpage, then the user will be linked to the calendar. The calendar should show one month at the time, and the user should be able to browse to the other month. I will make a script that puts events and such into a db ( I know how to do this) Then I need a script that puts the events from the db into the calendar, if every day in the calendar has a value id that part will not be hard. What I need is a script that generates the calender, in such a way that each month will be have a value, and that the user then can click the days to see more info about the events. I was thinking something like the iMPcal calender: http://www.heidgerken.org/impcal2/calendar.php Is there any modules I can use, or does any of you hardcore programmers have some advice on how I should proceed with this little project of mine :) Thanks From gsakkis at rutgers.edu Fri Feb 11 18:08:54 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Fri, 11 Feb 2005 18:08:54 -0500 Subject: check if object is number References: <374ho0F560ughU1@individual.net> <66WdnbJbuf5yj5DfRVn-iA@comcast.com> <374lklF5b20klU1@individual.net> Message-ID: <374s89F58hlbrU1@individual.net> > > So what you're saying is that 3 <= "3.0" should not be allowed, but > > 3 <= SomeUserDefinedNumericClass(3) is ok, although your program knows > > nothing a priori about SomeUserDefinedNumericClass. The idea suggested > > before, try if "x+1" fails or not does not get you far; any class that > > overrides __add__ may fool this test: > > > > class Dummy: > > def __add__(self,other): > > return 0 > > Right but by the same logic, we can fool protocols that are builtin to > Python: > > py> class C(object): > ... def __iter__(self): > ... return 0 > ... > py> for x in C(): > ... print x > ... > Traceback (most recent call last): > File "", line 1, in ? > TypeError: iter() returned non-iterator of type 'int' > > I'm not trying to catch the case where someone is deliberately violating > the protocol. Only the case where they've provided an object that > doesn't conform to the protcol. Note however that in my example there's no TypeError; 0 (or any value for that matter) is perfectly valid for __add__, while __iter__ must return an iterator. > Clearly, complex objects don't conform to the protocol I want -- they > don't support comparisons to ints. This is easy to check: > > try: > x <= 1 > except TypeError: > raise TypeError('%s does not support comparisons to ints' % > type(x).__name__) > > Now str objects also don't conform my protocol -- they aren't comparable > to integers in any meaningful sense. Ideally, I should be able to use > the same code as above for str objects (and get a TypeError like "str > objects cannot be compared with int objects"), but unfortunately, the > Python wart of cross-type default comparisons gets in the way. I look > forward to the day when Python 3.0 removes such comparisons. =) Me too... the way comparison works as of now is error-prone, to say the least. Comparing ints with strings is no more valid than adding them, and python (correctly) raises TypeError for the latter, but not for the former. For the record, here's the arbitrary and undocumented (?) order among some main builtin types: >>> None < 0 == 0.0 < {} < [] < "" < () True George From c00lways at gmail.com Wed Feb 9 22:15:15 2005 From: c00lways at gmail.com (James) Date: Thu, 10 Feb 2005 11:15:15 +0800 Subject: wxgrid multiline cell editor Message-ID: <420ad1b9$1_2@news.tm.net.my> wxpython 2.5.3 hi, anyone know how to make a multiline cell editor for wxgrid? thank you :) best regards, James From tim.peters at gmail.com Sat Feb 5 17:04:54 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 5 Feb 2005 17:04:54 -0500 Subject: pickle/marshal internal format 'life expectancy'/backward compatibility In-Reply-To: <1107640264.7097.5.camel@localhost> References: <1107640264.7097.5.camel@localhost> Message-ID: <1f7befae05020514046ab10822@mail.gmail.com> [Philippe C. Martin] > I am looking into using the pickle format to store object/complex data > structures into a smart card as it would make the design of the embedded > application very simple. > > Yet the card might have to stay in the pocket of the customer for a few > years, during which the back office application responsible for > retrieving the information from the card might evolve as well as the > python release it relies upon. > > Is there a commitment for python releases to be able to interpret > 'older' pickle/marshal internal formats ? Pickle and marshal have nothing in common, and there's no cross-release guarantee about marshal behavior. Pickles are safe in this respect; indeed, each Python released to date has been able to load pickles created by all earlier Python releases. Of course a pickle produced by a later Python may not be loadable by an earlier Python, although even in that direction you can get cross-release portability by forcing the newer Python to restrict itself to produce obsolete pickle formats. Reading Lib/pickletools.py in a current release will explain all this. From atulhi at gmail.com Mon Feb 14 11:17:15 2005 From: atulhi at gmail.com (atulhi at gmail.com) Date: 14 Feb 2005 08:17:15 -0800 Subject: Python C API version mismatch for module pytspc ---Gyach voice chat problems Message-ID: <1108397835.145767.138280@o13g2000cwo.googlegroups.com> I've been having some problems with gyach, when trying to open the PyVoice chat portion of it. Following error is received ******************************************************************************* /usr/local/share/gyach/pyvoice/pytsp.py:2: RuntimeWarning: Python C API version mismatch for module pytspc: This Python has API version 1012, module pytspc has version 1011. import pytspc /usr/local/share/gyach/pyvoice/pyvoiceui.py:161: DeprecationWarning: use gtk.UIManager itemf=ItemFactory(MenuBar, "
", ag) /usr/local/share/gyach/pyvoice/pyvoiceui.py:264: DeprecationWarning: use gtk.TreeView self.nmlist=CList(3,[' I ',' '+_('Name')+' ',' '+_('Alias')+' ']) /usr/local/share/gyach/pyvoice/pyvoiceui.py:298: Warning: unsupported arithmetic operation for flags type prevtable.attach( tvolbox, 1, 2, 0, 1, (EXPAND+FILL), (0), 0, 0) Traceback (most recent call last): File "/usr/local/share/gyach/pyvoice/pyvoiceui.py", line 1027, in ? runApp() File "/usr/local/share/gyach/pyvoice/pyvoiceui.py", line 1015, in runApp pyvoicegui() File "/usr/local/share/gyach/pyvoice/pyvoiceui.py", line 298, in __init__ prevtable.attach( tvolbox, 1, 2, 0, 1, (EXPAND+FILL), (0), 0, 0) TypeError: flag values must be strings, ints or tuples ******************************************************************************* Would appreciate if someone can help in this regard From ajsiegel at optonline.com Sat Feb 12 14:34:13 2005 From: ajsiegel at optonline.com (Arthur) Date: Sat, 12 Feb 2005 14:34:13 -0500 Subject: Newbie needs help with canvas.create_image ! References: Message-ID: <8pls0110ssdlap2p9n0uudq7d865tbmbsc@4ax.com> On Sat, 12 Feb 2005 18:24:11 +0100, "Fredrik Lundh" wrote: >Antti Isomursu wrote: > >> With code below I get a red box with given width and height. When I >> use that create_image, nothing happens. I only see that same red box. >> Why is that? >> The loop.bmp is working fine when I use show() method. >> >> win = Toplevel() >> >> canvas = Canvas(win, width=100, height=100, background='red') >> canvas.pack() >> >> im = Image.open("loop.bmp") >> photo = ImageTk.PhotoImage(im) >> >> canvas.create_image(8, 8, anchor="nw", image=photo) > >the problem might be that the PhotoImage is garbage collected before being >displayed. see the note on the bottom of this page for details: > > http://effbot.org/zone/tkinter-photoimage.htm > > I had run into this for the first time recently as well. and found this tutor thread helped. http://starship.python.net/pipermail/python-de/2002q4/002834.html Declaring "im" as global is one way to go (there I said it). In fact, IMO, probably the clearest (though not the prettiest) way to go under under the circumstances. I don't think anyone is particularly defending the circumstances. I have heard the circumstances described as a bug, and the various "solutions" are perhaps better thought of as work-arounds. Art From pyguy2 at gmail.com Mon Feb 28 11:29:37 2005 From: pyguy2 at gmail.com (pyguy2 at gmail.com) Date: 28 Feb 2005 08:29:37 -0800 Subject: Python - what is the fastest database ? In-Reply-To: <1109592623.116661.101880@g14g2000cwa.googlegroups.com> References: <1109592623.116661.101880@g14g2000cwa.googlegroups.com> Message-ID: <1109608177.789067.106390@f14g2000cwb.googlegroups.com> It depends on what you mean by database. If you want really fast I/O, try pytables. "PyTables is a hierarchical database package designed to efficiently manage very large amounts of data." http://pytables.sourceforge.net/html/WelcomePage.html some more comments from the webpage: # High performance I/O: On modern systems, and for large amounts of data, tables and array objects can be read and written at a speed only limited by the performance of the underlying I/O subsystem. Moreover, if your data is compressible, even faster than your I/O maximum throughput (!). # Support of files bigger than 2 GB: So that you won't be limited if you want to deal with very large datasets. In fact, PyTables support full 64-bit file addressing even on 32-bit platforms (provided that the underlying filesystem does so too, of course). # Architecture-independent: PyTables has been carefully coded (as HDF5 itself) with little-endian/big-endian byte orderings issues in mind . So, you can write a file in a big-endian machine (like a Sparc or MIPS) and read it in other little-endian (like Intel or Alpha) without problems. # Portability: PyTables has been ported to many architectures, namely Linux, Windows, MacOSX, FreeBSD, Solaris, IRIX and probably works in many more. Moreover, it runs just fine also in 64 bit plaforms (like AMD64, Intel64, UltraSparc or MIPS RXX000 processors). From tjreedy at udel.edu Wed Feb 16 13:52:42 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Feb 2005 13:52:42 -0500 Subject: [EVALUATION] - E02 - ULTIMATE RECIPE TO RESOLVE ALL ISSUES References: Message-ID: "Peter Maas" wrote in message news:cuv1st$6um$1 at swifty.westend.com... > http://nobelprize.org/medicine/educational/pavlov/ > > and then do something useful :) Thanks. I showed this to my daughter, who enjoyed the game, and explained your point re Pavlov posting, and about Pavlov advertising, etc. She then went on to some of the other games. A good home-learning tool. Terry J. Reedy From john_sips_teaz at yahooz.com Tue Feb 8 11:32:05 2005 From: john_sips_teaz at yahooz.com (John M. Gabriele) Date: Tue, 08 Feb 2005 11:32:05 -0500 Subject: Is Python as capable as Perl for sysadmin work? In-Reply-To: References: Message-ID: <110hqc5gu943d89@corp.supernews.com> Aahz wrote: > [snip] > > Anyway. Have you ever noticed how shell scripts keep getting longer? Yup. > Ever notice how it gets harder to figure out what the heck any given > script's doing? Yup. > Well, that's where Python helps you out compared to > Perl. Python can be a bit clumsier than Perl for dirt-simple tasks, but > you'll find that Python scales much better than Perl. Check. Thanks Aahz. :) -- -- remove zees if contacting via email -- From peter at engcorp.com Fri Feb 25 21:58:04 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 25 Feb 2005 21:58:04 -0500 Subject: web status display for long running program In-Reply-To: <7x8y5dnl1w.fsf@ruckus.brouhaha.com> References: <509534af.0502241737.5f62992@posting.google.com> <1109316391.203166.119700@z14g2000cwz.googlegroups.com> <7x8y5dnl1w.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Kamilche" writes: > >>I was inspired to enhance your code, and perform a critical bug-fix. >>Your code would not have sent large files out to dialup users, because >>it assumed all data was sent on the 'send' command. I added code to >>check for the number of bytes sent, and loop until it's all gone. I >>also turned it into a class, and made it 'command' based. > > That server seems to do a cpu-busy loop polling the listening socket > for incoming requests! Ouch! Not likely, as the socket is blocking by default. It won't use any CPU at all until a connection arrives. > It also assumes that once it's gotten > \r\n in the input, that the entire request has been received. Which is perfectly correct given the OP's specifications, which were that he simply wanted to hit "Refresh" in his browser to get a new page. Note also it's \r\n\r\n, not just a single one. > If someone is telnetting into the server typing one character at a time, > that could fool it. Fool it how? We're not talking actual data transfer, just a simple HTTP request which ends its header section with the aforementioned sequence, guaranteed. > I think it's better to just launch a separate thread and use > BaseHTTPServer which is already in the stdlib. Very likely.... of course, that wouldn't be any fun. ;-) -Peter From M.Waack at gmx.de Mon Feb 14 15:13:21 2005 From: M.Waack at gmx.de (Mathias Waack) Date: Mon, 14 Feb 2005 21:13:21 +0100 Subject: 64 bit Python Message-ID: <1cd7e2-qu7.ln1@valpo.de> Hi, one of my colleagues got some trouble with a program handling large amounts of data. I figured out that a 32 bit application on HP-UX cannot address more than 1 GB of memory. In fact (I think due to the overhead of memory management done by python) a python application cannot use much more than 500 MB of "real" data. For this reason I've created a 64 bit version of python 2.3.5. I've tested a simple C program before to make sure its able to address the whole available memory (8 GB main memory and about 12 GB swap). The simple example in C works, but the python script didn't. I was able to create only 2 GB of python objects. The application occupied approximately 2.2 GB of memory. After that, python failed with a memory error. Is there any internal restriction on the size of the heap? Mathias From mcfletch at rogers.com Fri Feb 18 12:50:09 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 18 Feb 2005 12:50:09 -0500 Subject: Probably over my head... Trying to get Font Names In-Reply-To: <8oydnSIY04Xby4jfRVn-iA@adelphia.com> References: <8oydnSIY04Xby4jfRVn-iA@adelphia.com> Message-ID: <42162AD1.50105@rogers.com> [Samantha: your email has been bouncing, might want to clear your inbox] Samantha wrote: >Thanks Mike. I must have not installed the ttfquery and font tools >correctly. I get an error. This error: > > ... >ImportError: No module named fontTools > >Like I said I think I am way in over my short head. >S > > Does look as though you missed getting FontTools installed. You realise it's a separate package from TTFQuery, right? http://sourceforge.net/projects/fonttools/ You'll have to do the standard: python setup.py install to get it installed on your system. HTH, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com PyCon is coming... From andymac at bullseye.apana.org.au Tue Feb 8 06:10:31 2005 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Tue, 08 Feb 2005 21:10:31 +1000 Subject: Problems with python and threads under Freebsd In-Reply-To: <1f060c4c05020721333542e5ee@mail.gmail.com> References: <1f060c4c05020720136cf5b3f@mail.gmail.com> <1f060c4c05020721333542e5ee@mail.gmail.com> Message-ID: <42089E27.6080806@bullseye.apana.org.au> snacktime wrote: > After debugging this some more I narrowed it down to an encryption > function in pycrypto that is triggering the segfault. I posted a bug > report. Don't really know enough about threading to know whether it's > a python bug or a pycrypto bug, but I'll let someone else sort that > out now.. If you get bus errors, there's a possibility that you are running out of stack. AFAIR, the default thread stack size for Posix builds is dependant on the threading implementation. This can be overridden when building Python. With each gcc version since 2.9, the size of stack frames for generated calls has increased. If lowering the optimisation to -O or -Os when building Python improves the situation, I'd suggest pursuing this possibility further. ------------------------------------------------------------------------- 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 Scott.Daniels at Acm.Org Fri Feb 4 17:57:05 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 04 Feb 2005 14:57:05 -0800 Subject: empty classes as c structs? In-Reply-To: References: Message-ID: <4203fa2a@nntp0.pdx.net> Christopher J. Bottaro wrote: > I find myself doing the following very often: > > class Struct: > pass > ... > blah = Struct() > blah.some_field = x > blah.other_field = y > ... > > Is there a better way to do this? Is this considered bad programming > practice? I don't like using tuples (or lists) because I'd rather use > symbolic names, rather than numeric subscripts. Also, I don't like having > to declare the empty Struct class everytime I want to do this (which is > very often). I have a module of my own (data.py) that I use a lot. It contains: class Data(object): def __init__(self, **initial): for name, val in initial.iteritems(): setattr(self, name, val) def __repr__(self): names = sorted([name for name in dir(self) if not name.startswith('_')], key=lambda name: (name.lower(), name)) return '%s(%s)' % (self.__class__.__name__, ', '.join([ '%s=%r' % (nm, getattr(self, nm)) for nm in names])) The advantage is that I can see the value in the Data object simply by printing the object. I use it like: from data import Data blah = Data(some_field=3, other_field=13) ... blah.other_field = 23 ... --Scott David Daniels Scott.Daniels at Acm.Org From fumanchu at amor.org Sat Feb 5 23:00:23 2005 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 5 Feb 2005 20:00:23 -0800 Subject: bad generator performance Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398373@exchange.hqamor.amorhq.net> Johannes Ahl mann wrote: > i am in the process of profiling an application and noticed how much > time my depth first generator for walking a tree data structure took. > > i wrote the same thing as a recursive function producing an array, and > this non-generator version is nearly 10 times faster! > > any ideas why this is, what i did wrong... > for some reason the generator version appears as being called > much more > often than the recursive one. no idea why that is, but the data is > definitely identical! > > here the output from the python profiler and the respective code: > > ### snip ### > > ncalls tottime percall cumtime percall filename:lineno(function) > 94209/8191 0.560 0.000 0.590 0.000 > :71(depthFirstIterator2) > 4095/1 0.060 0.000 0.080 0.080 :62(depthFirstIterator1) > > ### snip ### > > def depthFirstIterator1(self, depth = 0): > ret = [[self, True, depth]] > > if self.isFolder(): > for c in self.children: > ret = ret + c.depthFirstIterator(depth = depth + 1) > > return ret + [[self, False, depth]] > > def depthFirstIterator2(self, depth = 0): > yield [self, True, depth] > > if self.isFolder(): > for c in self.children: > for y in c.depthFirstIterator(depth = depth + 1): > yield y > > yield [self, False, depth] > > ### snip ### > > i'd appreciate any comments or explanations why the generator might be > so much slower, as i had just decided to use generators more > frequently > and in the respective PEP they are praised as generally fast. Um. Under my definition of "recursion", you haven't really removed recursion in the generator version. That is, you're still calling the depthFirstIterator method upon each iteration--you've just changed from list-concatenation to yielding instead, which trades off list-management overhead for closure-maintenance overhead. A truly non-recursive implementation would probably exist outside of whatever class you've got this method in, and would keep its own pointer to the current node as it traversed the tree. Hope that helps, Robert Brewer MIS Amor Ministries fumanchu at amor.org From cam.ac.uk at mh391.invalid Sun Feb 20 07:43:49 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 20 Feb 2005 12:43:49 +0000 Subject: [ANN] Python 2.4 Quick Reference available In-Reply-To: References: <1108831318.290846.5930@z14g2000cwz.googlegroups.com> Message-ID: David M. Cooke wrote: > """ > The file() constructor is new in Python 2.2 and is an alias for > open(). Both spellings are equivalent. The intent is for open() to > continue to be preferred for use as a factory function which returns a > new file object. The spelling, file is more suited to type testing > (for example, writing "isinstance(f, file)"). > """ There was a discussion on python-dev (earlier this year IIRC) where someone started changing the stdlib to use file() instead of open() and the BDFL clarified what he originally wanted with file(). That said, I still use file() instead of open(). I think that: for line in file("mytext.txt"): makes a lot more sense than: for line in open("mytext.txt"): I guess it's because the first option sounds a lot more like English. It's one of the few places where my personal style disagrees with the "official" Python style but I just like file() so much better ;) -- Michael Hoffman From rbt at athop1.ath.vt.edu Thu Feb 17 09:57:20 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Thu, 17 Feb 2005 09:57:20 -0500 Subject: os.walk() In-Reply-To: References: Message-ID: Roel Schroeven wrote: > rbt wrote: > >>The problem I run into is that some of the files and dirs are not >>removed while others are. I can be more specific and give exact examples >>if needed. On WinXP, 'pagefile.sys' is always removed, while >>'UsrClass.dat' is *never* removed, etc. > > > Keep in mind that the comparisons are done case sensitive; are you sure > that there's no problem regarding uppercase/lowercase? > I've noticed that. I've tried most all combinations possible with the same results. From noreplyme at hotmail.com Sat Feb 19 04:48:38 2005 From: noreplyme at hotmail.com (noreplyme at hotmail.com) Date: Sat, 19 Feb 2005 09:48:38 +0000 (UTC) Subject: =?iso-8859-1?q?=A4=D1=A4=F4=B3=F2=A4=D1=B4I=ADb=B2=C4=A4=40=AEy?= =?iso-8859-1?q?=B3=E6=A6=EC=A4=C0=AF=B2=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E?= Message-ID: ?????????I?b???@?y???????? ?N?b?|?I???????? ???????q???q?U???n?a?? ???K???K?????N?} ?{???H?G?Q?C?????@???????? ?a???q???p?Z?U?@?? ???????N???? ???V?@?y,???V???? ???????n???K????,??????100?? ?q???????G?Q?C?? ?????G?d?? http://www.geocities.com/tinfucourt/tinfu_plan.html ?T???G?U?????????? (plan 2) ?u???????H?K,?????H?a, ??????,?????s,?L???}???n?? ???H????,?{???q?????v?????p???u?@.... ???N???q?l?z?????H?????]?A ???O/?~??/???~ ?? : 13556869217 at 163.com ?P???H?p??.. ?????????????^??. ............................................................................................................................................................................................................................................................................................. From rzantow at ntelos.net Thu Feb 17 14:57:08 2005 From: rzantow at ntelos.net (rzantow at ntelos.net) Date: 17 Feb 2005 11:57:08 -0800 Subject: win2k multiple versions config question Message-ID: <1108670228.344749.149550@g14g2000cwa.googlegroups.com> I currently have both 2.3 and 2.4 on my Win2k computer. For the most part, I've been able to run each version, but I'm not configured completely correctly and I've run into a snafu. I downloaded LGT to try it out today; it uses PyGame (which as far as I know doesn't work with 2.4 yet -- or am I wrong here?), and OpenGL, and maybe has other dependencies. At any rate, the error I am seeing apparently involves OpenGL, and looks like this: Traceback (most recent call last): File "D:\Dld\LGT\doc\dev_pygame.py", line 3, in ? import LGT File "..\LGT\__init__.py", line 2, in ? import video File "..\LGT\video.py", line 1, in ? from OpenGL.GL import * File "d:\Python23\lib\site-packages\OpenGL\__init__.py", line 26, in ? from GL.GL__init___ import __numeric_present__, __numeric_support__ File "d:\Python23\lib\site-packages\OpenGL\GL\__init__.py", line 2, in ? from GL__init__ import * File "d:\Python23\lib\site-packages\OpenGL\GL\GL__init__.py", line 2, in ? import GL__init___ ImportError: Module use of python23.dll conflicts with this version of Python. I'm not sure what "this version" of Python should be here. I have a Pythonpath that refers to the 2.3 tree; neither 2.3 nor 2.4 is referenced in my Path variable. There is no evident reference to 2.4 active (at least not that I can find). The message seems to be telling me that the OpenGL module uses 2.3, which should be correct, but maybe I'm reading it wrong. Can anybody set me on the right track here? -- rzed From aahz at pythoncraft.com Tue Feb 22 11:21:42 2005 From: aahz at pythoncraft.com (Aahz) Date: 22 Feb 2005 11:21:42 -0500 Subject: Python UPS / FedEx Shipping Module References: Message-ID: In article , Gabriel Cooper wrote: > >I've made UPS and FedEx shipping rate request modules in python using >XML. Is there an interest in putting this on the web? Yes! My company has some similar software, and I may be able to get permission to combine our work. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "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." --GvR From simonwittber at gmail.com Fri Feb 25 03:53:36 2005 From: simonwittber at gmail.com (Simon Wittber) Date: Fri, 25 Feb 2005 16:53:36 +0800 Subject: accessor/mutator functions In-Reply-To: <1109315698.002207.245690@g14g2000cwa.googlegroups.com> References: <1109315698.002207.245690@g14g2000cwa.googlegroups.com> Message-ID: <4e4a11f8050225005366f6bed5@mail.gmail.com> > My questions are: > a) Are the three things above considered pythonic? Python uses a function called 'property to achieve the same effect. This example is taken from the documentation: class C(object): def __init__(self): self.__x = 0 def getx(self): return self.__x def setx(self, x): if x < 0: x = 0 self.__x = x x = property(getx, setx) In the above example, "C().x" would invoke and return the result of .getx (the accessor), and "C().x = 10" would invoke .setx (the mutator). Are they considered Pythonic? Well, It depends on how they are used. If you are using properties to perform some kind of type checking... then the answer is probably No. I've found that they are quite useful for implementing lazy evaluation of attributes, which I would consider quite Pythonic. Sw. From steven.bethard at gmail.com Thu Feb 24 14:17:38 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 24 Feb 2005 12:17:38 -0700 Subject: Mapping operator tokens to special methods In-Reply-To: <1109271478.871224.272750@g14g2000cwa.googlegroups.com> References: <1109271478.871224.272750@g14g2000cwa.googlegroups.com> Message-ID: jamesthiele.usenet at gmail.com wrote: > I was starting to write a dictionary to map operator strings to their > equivalent special methods such as: > { > '+' : 'add', > '&' : 'and_' > } > > The idea is to build a simple interactive calculator. > > and was wondering if there is already something like this builtin? > > Or is there a better way to do what I want? There's not already a mapping builtin, but you should definitely look at the operator module: py> import operator py> ops = {'+':operator.add, '&':operator.and_} py> ops['+'](3, 2) 5 py> ops['&'](3, 2) 2 STeVe From steven.bethard at gmail.com Wed Feb 16 14:30:15 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 16 Feb 2005 12:30:15 -0700 Subject: Can __new__ prevent __init__ from being called? In-Reply-To: References: <87is4tldea.fsf@news2.ososo.de> <3LOdncHRa6C77I_fRVn-rA@comcast.com> <87acq5tos7.fsf@news2.ososo.de> Message-ID: Colin J. Williams wrote: > This prompts a similar query. __new__ appears to be intended for > immutable objects but it seems to be called as part of constructor > process for all instances. That's because Python has no builtin way of determining whether or not a given type is immutable. If you wanted to, you could define both __new__ and __init__, the first to set immutable parts and the second to set mutable parts, e.g.: py> class PartlyMutableTuple(tuple): ... def __new__(cls, *args, **kwargs): ... return super(PartlyMutableTuple, cls).__new__(cls, args) ... def __init__(self, *args, **kwargs): ... self.__dict__.update(kwargs) ... py> t = PartlyMutableTuple(1, 2, 3, a=4, b=5) py> t (1, 2, 3) py> t.a, t.b (4, 5) py> t.a, t.b = t.b, t.a py> t.a, t.b (5, 4) py> t[0] = 2 Traceback (most recent call last): File "", line 1, in ? TypeError: object does not support item assignment I don't think I'd advise this strategy, but by always calling both __new__ and __init__, Python makes it possible... Steve From jeffrey at fro.man Fri Feb 4 10:57:49 2005 From: jeffrey at fro.man (Jeffrey Froman) Date: Fri, 04 Feb 2005 07:57:49 -0800 Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xy8e5jagh.fsf@ruckus.brouhaha.com> <1107490052.542546.285950@c13g2000cwb.googlegroups.com> <7xekfwc19i.fsf@ruckus.brouhaha.com> Message-ID: <11076rucarl7m4c@corp.supernews.com> Paul Rubin wrote: > I don't know that the browser necessarily renders that faster than it > renders a table, but there's surely less crap in the HTML, which is > always good.??I?may?start?using?that?method. Using tables for layout is also a cardinal faux pas if you care about accessibility, as such tables can really mess up things like screenreader software for the sight-impaired. Jeffrey From steven.bethard at gmail.com Sun Feb 6 15:58:52 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 06 Feb 2005 13:58:52 -0700 Subject: empty classes as c structs? In-Reply-To: <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <1gric2n.17myhon1hfrc6gN%aleaxit@yahoo.com> <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> Message-ID: <4qCdnXM11-uVGJvfRVn-vQ@comcast.com> Alex Martelli wrote: > I think this ``view'' or however you call it should be a classmethod > too, for the same reason -- let someone handily subclass Bunch and still > get this creational pattern w/o extra work. Maybe a good factoring > could be something like: > > class Bunch(object): > > def __init__(self, *a, **k): > self.__dict__.update(*a, **k) > > def getDict(self): > return self.__dict__ > > def setDict(self, adict): > self.__dict__ = adict > > theDict = property(getDict, setDict, None, > "direct access to the instance dictionary" > ) > > @classmethod > def wrapDict(cls, adict, *a, **k): > result = cls.__new__(cls, *a, **k) > result.setDict(adict) > cls.__init__(result, *a, **k) > return result > > I'm thinking of use cases where a subclass of Bunch might override > setDict (to do something else in addition to Bunch.setDict, e.g. > maintain some auxiliary data structure for example) -- structuring > wrapDict as a classmethod in a ``Template Method'' DP might minimize the > amount of work, and the intrusiveness, needed for the purpose. (I don't > have a real-life use case for such a subclass, but it seems to cost but > little to provide for it as a possibility anyway). Seems pretty reasonable -- the only thing I worry about is that classmethods and other attributes (e.g. properties) that are accessible from instances can lead to subtle bugs when a user accidentally initializes a Bunch object with the attributes of the same name, e.g.: b = Bunch(getDict=1) where b.getDict() now fails with something like "TypeError: 'int' object is not callable". (For another discussion about this problem, see [1]). I don't know what the right solution is here... I wonder if I should write a classmethod-style descriptor that disallows the calling of a function from an instance? Or maybe I should just document that the classmethods should only be called from the class? Hmm... How do you feel about getDict and setDict also being classmethods? Steve [1] http://mail.python.org/pipermail/python-dev/2005-January/051328.html From fredrik at pythonware.com Tue Feb 22 11:55:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Feb 2005 17:55:50 +0100 Subject: Problem with minidom and special chars in HTML References: <421b5b8c$1@news.uni-klu.ac.at> Message-ID: Horst Gutmann wrote: > I currently have quite a big problem with minidom and special chars (for example ü) in HTML. > > Let's say I have following input file: > -------------------------------------------------- > > "http://www.w3.org/TR/html4/strict.dtd"> > > > ü > > > -------------------------------------------------- > test3.html only has a blank line where should be the ü It is simply > removed. > > Any idea how I could solve this problem? umm. doesn't that doctype point to an SGML DTD? even if minidom did fetch external DTD's (I don't think it does), it would probably choke on that DTD. running your documents through "tidy -asxml -numeric" before parsing them as XML might be a good idea... http://tidy.sourceforge.net/ (command-line binaries, library) http://utidylib.berlios.de/ (python bindings) From grante at visi.com Mon Feb 14 16:41:52 2005 From: grante at visi.com (Grant Edwards) Date: 14 Feb 2005 21:41:52 GMT Subject: parsing IMAP responses? Message-ID: <42111b20$0$44604$a1866201@visi.com> According to Google, the question has come up before, but there doesn't seem to be much of an answer. The imaplib module return values are mostly useless as-is: they're just whatever string the server sent (or in some cases a list of strings). You've got to parse them using the IMAP syntax before you can do much with them. Is there a library somewhere that impliments the IMAP protocol syntax? -- Grant Edwards grante Yow! Now I understand the at meaning of "THE MOD SQUAD"! visi.com From fuzzyman at gmail.com Wed Feb 2 10:42:17 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 2 Feb 2005 07:42:17 -0800 Subject: CONTEST - What is the (best) solution? In-Reply-To: <1107357151.234804.187440@g14g2000cwa.googlegroups.com> References: <1107340503.462196.109440@o13g2000cwo.googlegroups.com> <1107350983.411793.146600@g14g2000cwa.googlegroups.com> <1107357151.234804.187440@g14g2000cwa.googlegroups.com> Message-ID: <1107358937.315500.249620@z14g2000cwz.googlegroups.com> What about the syntax ? Will it have commas in the right place ? (never, always, or sometimes ? - sometimes is much worse than never or always). *damn* - problem is that '{' might appear as one of the values.... *So*... read the file in as a list of lines and strip each line. Dictionaries will always start where '{' is the first character. Anyway - you could always explicitly check if each line ends with a ',' and if it doesn't add one...) (*warning* UNTESTED) >handle = open('filename', 'r') >thefile = handle.readlines() >handle.close() > >dictindex = [] >i = 0 >while i < len(thefile)-1: > if line.startswith('{'): > dictindex.append(i) > i += 1 >lastdict = ' '.join(thefile[dictindex[-1]:] >print eval(lastdict) Checking if each line ends with a ',' (except for the last line) should be easy ! HTH Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From python-url at phaseit.net Tue Feb 15 00:52:45 2005 From: python-url at phaseit.net (Cameron Laird) Date: Tue, 15 Feb 2005 05:52:45 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Feb 15) Message-ID: QOTW: "I've forgotten what we are arguing about, but I'm sure I'm right." -- Jive Dadson "I believe the best strategy against Identity theft is bad credit." -- Tom Willis "You can't live without unit tests. And once you have unit tests, the added value of declarations is tiny, and their cost remains." -- martellibot Make history, instead of having it happen to you: the upcoming PyPy Sprint promises to be singular: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/6f0458c61169eff1/ Brian van den Broek, Roy Smith, BJ=F6rn_Lindqvist, Jason Diamond, and Grig Gheorghiu introduce the crucial subject of unit-testing in Python for those new to test-driven development: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/bbda0385fa4e1de7/ http://www.onlamp.com/pub/a/python/2004/12/02/tdd_pyunit.html How do you know that Python has "arrived"? When its use is the least interesting part of a project. Notice that, once again, Python is handy in "process control", traditionally a domain for assembler, C, and Basic: http://www.linuxjournal.com/article/7403 Philip dives deeply into Python optimization issues: http://dirtsimple.org/2005/02/optimization-surprises.html http://dirtsimple.org/2005/02/from-nine-to-five.html Not only does Martin Franklin provide a new TableList widget for Tkinter, but he clearly describes how he did so, apparently in the belief that such knowledge might be useful to others: http://mail.python.org/pipermail/tkinter-discuss/2005-February/000320.html Stewart Midwinter answers with a "poor-man's table widget": http://mail.python.org/pipermail/tkinter-discuss/2005-February/000325.html Philip Schoenborn explores RAII and related Python deli- cacies related to resource management--in print! http://ddj.com/articles/2005/0503/ ======================================================================== 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. 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 Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson 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/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. deli.cio.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/topics/pythonurl/ 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 Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From jordan2856977 at 163.com Sun Feb 6 00:59:15 2005 From: jordan2856977 at 163.com (jordan2856977) Date: 5 Feb 2005 21:59:15 -0800 Subject: sos! References: <6d2e4eef.0502050342.d8744cb@posting.google.com> Message-ID: <6d2e4eef.0502052159.40c5c2f1@posting.google.com> "Dan Perl" wrote in message news:... > "jordan2856977" wrote in message > news:6d2e4eef.0502050342.d8744cb at posting.google.com... > > hellow everybody! I'm from china. I'm a beginner of python. in china, > > python is not a fashionable language, so it's difficult to find some > > books about python. finally,I find a book named "python how to > > program" wrote by H.M.Deitel . who can tell me where can I find some > > interesting source code about python. otherwise, I will fell boring > > about study! > > The Python Cookbook is a good source of examples that other posters haven't > mentioned yet: http://aspn.activestate.com/ASPN/Cookbook/Python/ > > It is especially good because it contains simple, short recipes that > illustrate a specific use of python and these recipes are organized in > categories. > > Dan thanks dan From lbates at syscononline.com Fri Feb 11 18:33:19 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 11 Feb 2005 17:33:19 -0600 Subject: dos box appears when clicking .pyc In-Reply-To: References: Message-ID: <4ZGdne8O2fch3ZDfRVn-oQ@comcast.com> Change the association for .pyc files to pythonw.exe from python.exe. Larry Bates Philippe C. Martin wrote: > Hi, > > > For a few months now, I have been used .pyc script under XP without > getting the "DOS" box. > > I just re-installed the scripts on another XP box and am now getting the > DOS box ! > > Something to do with the registry ? > > Regards, > > Philippe > > > > > From ggrp1.20.martineau at dfgh.net Tue Feb 22 04:20:21 2005 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 22 Feb 2005 01:20:21 -0800 Subject: Execute a list References: Message-ID: <1109064021.373300.276430@g14g2000cwa.googlegroups.com> Here is how to execute code in a string, similar to what was shown in your example: >>> s = 'print "hello"' >>> exec s hello Hope this helps. From http Thu Feb 3 13:26:05 2005 From: http (Paul Rubin) Date: 03 Feb 2005 10:26:05 -0800 Subject: Is there a market for python developers? References: <1107440354.317628.221090@g14g2000cwa.googlegroups.com> Message-ID: <7x3bwdxzya.fsf@ruckus.brouhaha.com> "Mabon Dane" writes: > I am new to python and took my first attempts at working with this > language today. Is there a market for people who work with Python? Well, there's two ways to look at that question: 1) Are there many companies with with openings like "we want to hire a Python programmer"? The answer is yes, not a huge number, but there aren't a huge number of Python programmers either. 2) Can using Python make you more marketable as a programmer? Certainly it can. You can often get things done faster in Python than in other languages, and getting things done always helps your marketability. Lots of times the customer just needs to get some task completed, and they don't care whether you use Python or some other language. And using Python can result in such a big productivity gain as to really help you score points with your employer or customer. Python is not a magic bullet and it certainly shouldn't be the only language you know. However, wielded skillfully, it can be a very powerful tool. From __peter__ at web.de Mon Feb 7 15:39:11 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 Feb 2005 21:39:11 +0100 Subject: "Collapsing" a list into a list of changes References: <200502071907.12169.francis.girard@free.fr> Message-ID: John Lenton wrote: > On Mon, Feb 07, 2005 at 07:07:10PM +0100, Francis Girard wrote: >> Zut ! >> >> I'm very sorry that there is no good use case for the "reduce" function >> in Python, like Peter Otten pretends. That's an otherwise very useful >> tool for many use cases. At least on paper. >> >> Python documentation should say "There is no good use case for the reduce >> function in Python and we don't know why we bother you offering it." > > I am guessing you are joking, right? I think Peter exaggerates when he > says that "there will be no good use cases for reduce"; it is very > useful, in writing very compact code when it does exactly what you > want (and you have to go through hoops to do it otherwise). It also > can be the fastest way to do something. For example, the fastest way > to get the factorial of a (small enough) number in pure python is > > factorial = lambda n: reduce(operator.mul, range(1, n+1)) I see that you are seduced by the beauty of the expression. Otherwise, if you would really care for speed: $ cat factorial.py #ugly but efficient factorial = [1] for i in range(1, 50): factorial.append(i*factorial[-1]) import operator def factorial_reduce(n): return reduce(operator.mul, xrange(1, n+1), 1) if __name__ == "__main__": assert factorial[0] == factorial_reduce(0) == 1 assert factorial[5] == factorial_reduce(5) == 1*2*3*4*5 $ python2.4 -m timeit -s'import factorial as f' 'f.factorial_reduce(30)' 100000 loops, best of 3: 13.3 usec per loop $ python2.4 -m timeit -s'import factorial as f' 'f.factorial[30]' 1000000 loops, best of 3: 0.328 usec per loop Having factorial raise a UseStirlingsFormulaError for large values is left as an exercise to the reader :-) Peter From spam at nospam.org Fri Feb 11 15:38:28 2005 From: spam at nospam.org (Erik Johnson) Date: Fri, 11 Feb 2005 13:38:28 -0700 Subject: Commerical graphing packages? Message-ID: <420d1595$1@nntp.zianet.com> I am wanting to generate dynamic graphs for our website and would rather not invest the time in developing the code to draw these starting from graphics primitives. I am looking for something that is... "fairly robust" but our needs are relatively modest: X-Y scatter plots w/ data point symbols, multiple data set X-Y line plots, bar charts, etc. Preferably this would come from a company that can provide support & decent documentation, and a package that can be installed without a bunch of extra hassle (e.g., needs Numeric Python, needs to have the GD library installed, needs separate JPEG encoders, font libraries, etc.) I am aware of ChartDirector (http://www.advsofteng.com/ ) which explicitly supports python and seems to be about the right level of sophistication. I don't really know of any other packages in this space, do you? I am seeking feedback and reccomendations from people who have used this package or similar ones. I am particularly interested to hear about any limitations or problems you ran into with whatever package you are using. Thanks for taking the time to read my post! :) -ej From simoninusa2001 at yahoo.co.uk Sun Feb 13 19:24:42 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 13 Feb 2005 16:24:42 -0800 Subject: PyQt and Python 2.4 - also WinXP LnF? In-Reply-To: <1108152792.710263.117650@z14g2000cwz.googlegroups.com> References: <1108003471.242829.297030@o13g2000cwo.googlegroups.com> <1108065099.593832.314470@f14g2000cwb.googlegroups.com> <1108152792.710263.117650@z14g2000cwz.googlegroups.com> Message-ID: <1108340682.521315.234620@l41g2000cwc.googlegroups.com> After building with MSVC6 (Python 2.3.5 and 2.4 versions) I've noticed that the ToolTips don't seem to work in the GPL version. MSVC6 is about twice as fast to build as MinGW..... From theller at python.net Tue Feb 1 04:03:14 2005 From: theller at python.net (Thomas Heller) Date: Tue, 01 Feb 2005 10:03:14 +0100 Subject: Forcing interactive interpreter without (-i) References: Message-ID: Miki Tebeka writes: > Hello All, > > If there a way a script can tell Python to enter interactive mode even if > the -i command line switch was not given? > > I want py2exe to create an interactive session, without writing my own > REPL. IIRC, in newer Python versions, you can set the PYTHONINSPECT env var inside your script. Thomas From jamesthiele.usenet at gmail.com Thu Feb 24 16:19:36 2005 From: jamesthiele.usenet at gmail.com (jamesthiele.usenet at gmail.com) Date: 24 Feb 2005 13:19:36 -0800 Subject: Mapping operator tokens to special methods In-Reply-To: References: <1109271478.871224.272750@g14g2000cwa.googlegroups.com> Message-ID: <1109279976.277421.227450@l41g2000cwc.googlegroups.com> John Machin wrote: >>> eval('1+2') 3 -- Yeah, that's what I decided to do. From mjackson at alumni.caltech.edu Thu Feb 10 10:20:25 2005 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 10 Feb 2005 15:20:25 GMT Subject: negative integer division References: <4208039c$0$28559$8fcfb975@news.wanadoo.fr> Message-ID: sjmachin at lexicon.net (John Machin) writes: > mjackson at alumni.caltech.edu (Mark Jackson) wrote in message news:... > > > > A: 42 > > > > Q: What multiple of 7 did I add to the critical expression in the Zeller > > algorithm so it would remain nonnegative for the next few centuries? > > What are you calling "the Zeller algorithm", and what is the "critical > expression"? A C function in calendar.c, encountered in the source code for xvtdl: int zeller (month, day, year) int month, day, year; { int century; month -= 2; /* Years start on March 1 so adjust standard date */ if (month < 1) { month += 12; year--; } century = year / 100; year = (int)year % (int)100; return ((int)((2.6 * month - 0.1) + day + year + year / 4 + century / 4 - century * 2) % 7); } The expression upon which "% 7" acts is negative when "year" is small. This caused errors beginning in March 2000; which could be deferred by adding a suitably-large multiple of 7 to the expression. The choice was obvious. :-) > I've no doubt you came across a stuffed-up date-to-days calculation > routine and fixed it, but it's a bit unfair to lumber Zeller with the > blame. If it was a days-to-date routine, then Zeller is not even > standing next to the real target. Fair enough, although I'm not responsible for having named the function (which appears to date from 1991). The original author is identified in the code (available at http://www.alumni.caltech.edu/~mjackson/xvtdl.html) and is findable via the Web; you might take the matter up with him. -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson People who write obscurely are either unskilled in writing or up to mischief. - Sir Peter Medawar From ods at strana.ru Thu Feb 17 09:46:10 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Thu, 17 Feb 2005 17:46:10 +0300 Subject: Is it possible to use the logging-module in a threadless environment? In-Reply-To: <5475062c.0502170541.41ec4320@posting.google.com> References: <5475062c.0502170541.41ec4320@posting.google.com> Message-ID: <20050217174610.012c25ec.ods@strana.ru> On 17 Feb 2005 05:41:12 -0800 rlwm.erens at home.nl (Roger) wrote: > I'd like to use a program (roundup) that imports the logging.config > module on a machine where I could not get the thread and threading > modules to compile. > > How dangerous is it to changing /lib/python2.4/logging/config.py to > something like: > > import dummy_thread as thread, dummy_threading as threading I believe it's a bug and logging/config.py should use the same approach as logging/__init__.py do: try: import thread import threading except ImportError: thread = None -- Denis S. Otkidach http://www.python.ru/ [ru] From kent37 at tds.net Wed Feb 23 07:48:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Feb 2005 07:48:10 -0500 Subject: unicode(obj, errors='foo') raises TypeError - bug? In-Reply-To: References: Message-ID: <421c786a$1_1@newspeer2.tds.net> Steven Bethard wrote: > Mike Brown wrote: > >>>>> class C: >> >> ... def __str__(self): >> ... return 'asdf\xff' >> ... >> >>>>> o = C() >>>>> unicode(o, errors='replace') >> >> Traceback (most recent call last): >> File "", line 1, in ? >> TypeError: coercing to Unicode: need string or buffer, instance found >> > [snip] > >> >> What am I doing wrong? Is this a bug in Python? > > > No, this is documented behavior[1]: > > """ > unicode([object[, encoding [, errors]]]) > ... > For objects which provide a __unicode__() method, it will call this > method without arguments to create a Unicode string. For all other > objects, the 8-bit string version or representation is requested and > then converted to a Unicode string using the codec for the default > encoding in 'strict' mode. > """ > > Note that the documentation basically says that it will call str() on > your object, and then convert it in 'strict' mode. You should either > define __unicode__ or call str() manually on the object. Not a bug, I guess, since it is documented, but it seems a bit bizarre that the encoding and errors parameters are ignored when object does not have a __unicode__ method. Kent > > STeVe > > [1] http://docs.python.org/lib/built-in-funcs.html From jeff at ccvcorp.com Fri Feb 4 18:38:15 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 04 Feb 2005 15:38:15 -0800 Subject: returning True, False or None In-Reply-To: References: Message-ID: <11081ppg3m9tt5d@corp.supernews.com> Jeremy Bowers wrote: > On Fri, 04 Feb 2005 16:44:48 -0500, Daniel Bickett wrote: > >>[ False , False , True , None ] >> >>False would be returned upon inspection of the first index, even >>though True was in fact in the list. The same is true of the code of >>Jeremy Bowers, Steve Juranich, and Jeff Shannon. As for Raymond >>Hettinger, I can't even be sure ;) > > Nope. Indeed. Similarly for mine, which was really just a slight transform of Jeremy's (setting a return variable directly, instead of setting a flag that's later used to decide what to return): >>> def tfn(lst): ... answer = None ... for item in lst: ... if item is True: return True ... if item is False: answer = False ... return answer ... >>> list = [False, False, True, None] >>> tfn(list) 1 >>> list = [None, False, False, None] >>> tfn(list) 0 >>> list = [None, None, None, None] >>> print tfn(list) None >>> >>> The noted logical flaw *has* been present in a number of proposed solutions, however. The key point to note is that one *must* examine the entire list *unless* you find a True; short-circuiting on False means that you may miss a later True. Jeff Shannon Technician/Programmer Credit International From mt at 3planes.com Tue Feb 1 11:29:24 2005 From: mt at 3planes.com (Michael Tobis) Date: 1 Feb 2005 08:29:24 -0800 Subject: variable declaration References: <1107205410.367521.50490@f14g2000cwb.googlegroups.com> <44SdnUZGopnrAWLcRVn-pg@telcove.net> Message-ID: <1107275364.730411.24710@c13g2000cwb.googlegroups.com> > How common is it for a local variable to be bound in > more than one place within a function? It's more natural for a beginner to read or write .mystr = "" .for snippet in snippets: . if ilike(snippet): . mystr = mystr + snippet than .mylist = [] .for snippet in snippets: . if ilike(snippet): . mylist.append(snippet) .mystr = "".join(mylist) for instance. While the latter is superior in some ways, I frequently find my fingers tossing off the former approach. Of course in this case it's not hard to come up with mystr = "".join([snippet in snippets if ilike(snippet)]) but it's also not too hard to imagine cases where the list comprehension would be too complex or would require too much refactoring. I don't know that it's ever necessary to rebind, but it is, in fact, common, and perhaps too easy. In numeric Python, avoiding rebinding turns out to be a nontrivial skill. mt From fredrik at pythonware.com Tue Feb 15 16:30:48 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Feb 2005 22:30:48 +0100 Subject: Font size References: <42126822@news.comindico.com.au> Message-ID: "Adam" wrote: > How do you clear the screen and then display a number with an enlarged font size (about 300). what platform? what screen? 300 what? From sizelji at insightbb.com Thu Feb 10 15:27:25 2005 From: sizelji at insightbb.com (Jim Sizelove) Date: Thu, 10 Feb 2005 20:27:25 GMT Subject: Python COM Makepy Excel 9.0 error In-Reply-To: <1108062567.928124.219200@g14g2000cwa.googlegroups.com> References: <1108062567.928124.219200@g14g2000cwa.googlegroups.com> Message-ID: nvhengr at gmail.com wrote: > Has anyone seen this? When I run the COM Makepy utility and choose > Microsoft Excel 9.0 Object Library (1.3), I get an application error > message: > > PythonWin: Pythonwin.exe - Application Error > The instruction at "0x77fcc87" referenced memory at "0x0307a705". The > memory could not be "read". > > I do not get this error when I choose the Microsoft Office 9.0 Object > Library (2.1). > > I have tried this from one other computer and got a similar error > message. I looked all over the 'net for enlightenment and have so far > been unsuccessful. Does anyone have an idea what can be going on and > how to get around it? > > I am using Python 2.4 under Windows 2000SP4. I have also installed > pywin32 (build 203 for Python 2.4) and py2exe-0.5.4 for Python 2.4. > > Python 2.3 and the COM Makepy utility (Python 2.3 version) seems to run > okay. > > I am writing a rather complicated set of instructions to manipulate a > series of Excel 2000 spreadsheets and have already added quite a few of > the features from Python 2.4, so I hope I do not have to revert back to > Python 2.3. Any suggestions? > > Thank you, in advance, > Christopher D. Morgan, P.E., Ph.D. > I experienced similar problems when moving some code from Python 2.3 to Python 2.4. Seems that running "makepy -d ..." works. See Mark Hammond's explanation at: http://mail.python.org/pipermail/python-win32/2004-December/002743.html [python-win32] WMI scripting makepy error with ActivePython 2.4.0 HTH, Jim Sizelove From jgkjcasey at yahoo.com.au Tue Feb 1 19:26:23 2005 From: jgkjcasey at yahoo.com.au (JGCASEY) Date: 1 Feb 2005 16:26:23 -0800 Subject: web camera or else ? 15-30 fps processing of camera videos. In-Reply-To: <420006a5$0$714$c3e8da3@news.astraweb.com> References: <1107295229.657375.318750@o13g2000cwo.googlegroups.com> <420006a5$0$714$c3e8da3@news.astraweb.com> Message-ID: <1107303983.662065.93580@c13g2000cwb.googlegroups.com> The Artist Formerly Known as Kap'n Salty wrote: > Newbie wrote: > > I am doing some robotics projects but my main area of interest is > > trying out several algorithms for the processing of the stream of data > > coming from the video. > > > > I am wondering what type of camera I should invest in. Either I could > > buy a web cam and hope I can find a driver I could either modify or > > use. i.e. every frame is somehow stored on the computer automagically > > or I could buy a camera not unlike the AVRcam > > (http://www.jrobot.net/Projects/AVRcam.html) or the CMUcam and try to > > do the processing once the data has been streamed to the nearest > > computer ? or should I use an expensive video card, some CCTV camera > > and a frame grabber to digitize photos so they can be processed > > afterwards. I expect my processing algorithms to handle at least 15 > > frames per second framerate once they are working ont the final set-up. > > > > My constraints are that I would like to avoid as much as possible > > complex set-ups even if that means buying a more expensive camera > > set-up. For the prototyping, I would like to try my algorithms out > > using a combination of python and matlab (all very slow) and then > > expect the same architecture (image files location and flow) with > > speedier set-up like python+psyco or C. All the processing would be > > done on a computer dedicated for that. Windows or Linux are possible. > > > > An easy approach to this is to use a wireless camera on your robot, with > the receiver attached to a frame grabber on a remote host. This allows > you your choice of camera (stand alone video transmitters are widely > available), and you are not limited to only processing hardware you can > carry on board your robot. You also get full FPS. Frame-grabber cards > are inexpensive and widely available for both Windows and Linux. I wanted to go down that path but cannot get information on how to access the images from the tv receiver card in real time using my own software. Do you use Java? John Casey From cjw at sympatico.ca Tue Feb 8 12:50:53 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 08 Feb 2005 12:50:53 -0500 Subject: Definitive documentation on newstyle classes? (WAS: Pickling and inheritance are making me hurt) In-Reply-To: References: <1d6cdae305020516467620aa0@mail.gmail.com> Message-ID: <4208FBFD.6000303@sympatico.ca> Brian van den Broek wrote: > Daniel Bickett said unto the world upon 2005-02-05 19:46: > >> I was reading the "Pickling and inheritance are making me hurt" >> thread, and the latest suggestion (as of this posting) was to do with >> the __setstate__ and __getstate__ methods. They caught my attention >> because I hadn't encountered them before, and it reminded me that in >> the past I've never been able to very good, definitive documentation >> on newstyle classes. Googling for it gives little python tutorials on >> various sites, and even searching this newsgroup returns very specific >> questions, as a rule. >> >> Alas, the question: Does there exist a page that enumerates all of the >> features of the newstyle classes, and explains what they all do? If >> so, can anyone provide me with such a link? >> >> Thanks :-) > > > Hi Daniel, > > it doesn't yet answer the "definitive" part, but > is worth a look. > > Best, > > Brian vdB Yes, that's the best I've come across. But a clearer overall view, tied in to the Language Reference, would be very helpful. It would be good to have a clear exposition of the pros and cons of __new__ usage. Colin W. From samantha7395 at hotmail.com Fri Feb 18 14:55:35 2005 From: samantha7395 at hotmail.com (Samantha) Date: Fri, 18 Feb 2005 11:55:35 -0800 Subject: Trying to get Font Names References: Message-ID: Thanks Fredrik, The Tkinter method didn't give any results but using PIL did. I'll have to play with it a little. Thanks again, S "Fredrik Lundh" wrote in message news:mailman.2812.1108753440.22381.python-list at python.org... > "Samantha" wrote: > From marian at mba-software.de Sun Feb 6 11:40:13 2005 From: marian at mba-software.de (=?ISO-8859-1?Q?Marian_Aldenh=F6vel?=) Date: Sun, 06 Feb 2005 17:40:13 +0100 Subject: pygame.mixer.music not playing In-Reply-To: <1107700800.258876.298010@z14g2000cwz.googlegroups.com> References: <36mb0iF54udklU1@individual.net> <1107700800.258876.298010@z14g2000cwz.googlegroups.com> Message-ID: <36mvjkF54gvnrU1@individual.net> Hi, > Search the net. You are not the first to try and build a jukebox out of pygame ;) I did find a few, yes. Currently this is a toy project as I am learning the language, so early success means more to me than perfect results. And, as I said, I do not really have an alternative. Maybe some way to remote control another player would be in order. Leave it to software that is specialized and all. But I would want something that runs on Windows and Linux which narrows down my options. > You have a typo in the code you posted that may be your problem. You are refering to the missing ' in the filename? pygame.mixer.music.load('file1.mp3) No, that's not the problem. I did paste working code but I then edited out the full absolute path that I had coded into the program and introduced the error. I also tried your sample but no difference. Must be something on my system as it does seem to play... Ciao, MM -- Marian Aldenh?vel, Rosenhain 23, 53123 Bonn. +49 228 624013. http://www.marian-aldenhoevel.de "Wir brauchen keine Opposition, wir sind bereits Demokraten." From danperl at rogers.com Sun Feb 6 01:53:56 2005 From: danperl at rogers.com (Dan Perl) Date: Sun, 6 Feb 2005 01:53:56 -0500 Subject: CGI POST problem was: How to read POSTed data References: <1107659974.048175.221770@z14g2000cwz.googlegroups.com> Message-ID: wrote in message news:1107659974.048175.221770 at z14g2000cwz.googlegroups.com... > Dan Perl wrote: > >> how is a multipart POST request parsed by CGIHTTPServer? > > It isn't; the input stream containing the multipart/form-data content > is passed to the CGI script, which can choose to parse it or not using > any code it has to hand - which could be the 'cgi' module, but not > necessarily. > >> Where is the parsing done for the POST data following the header? > > If you are using the 'cgi' module, then cgi.parse_multipart. Thanks, at least I was right not to find that in the CGIHTTPServer and BaseHTTPServer code. So I have to use that instead of FieldStorage? I was expecting FieldStorage to encapsulate all that for all the cases, POST with multipart/form-data being just a special case. I took a brief look at cgi.parse_multipart and I still have to figure out how to provide the fp argument. Any code examples anywhere? All the examples I have found were using only FieldStorage: http://www.cs.virginia.edu/~lab2q/lesson_7/ http://www.devshed.com/index2.php?option=content&task=view&id=198&pop=1&page=0&hide_js=1 http://gnosis.cx/publish/programming/feature_5min_python.html http://mail.python.org/pipermail/edu-sig/2001-June/001368.html BTW, I also tried the example in the last link and that doesn't work either, with similar results/problems as my script. I think all those examples are a few years old, has something changed since then? >> As a side note, I found other old reports of problems with cgi >> handling POST requests, reports that don't seem to have had a >> resolution. > > (in particular?) I made the comment and now I have to back that up: http://mail.python.org/pipermail/python-list/2002-February/thread.html#88686 http://mail.python.org/pipermail/python-list/2002-September/thread.html#124109 > FWIW, for interface-style and multipart-POST-file-upload-speed reasons > I wrote an alternative to cgi, form.py > (http://www.doxdesk.com/software/py/form.html). But I haven't found > cgi's POST reading to be buggy in general. I was quite careful in calling the code "fragile" and I am not normally the kind of person to mince words. I would have said buggy if I meant that or I could have used even worse words. But even the rationale behind the patch that caused the bug I mentioned ("Remove dependencies on (deprecated) rfc822 and mimetools modules, replacing with email.") and even your calling this part of the standard library "a bit crufty in places due to age" support my view that this code needs work. Besides, I am not happy at all with the idea of having to use cgi.parse_multipart instead of FieldStorage. It seems a lot more low level than I would like to even if it offers more control. I looked at your form.py and you seem to address that. Sorry though, I will probably not use it. Once I learn enough from the cgi module I will just move on to using a framework like CherryPy. Dan From softpro at gmx.net Sun Feb 6 10:58:31 2005 From: softpro at gmx.net (Johannes Ahl-mann) Date: Sun, 6 Feb 2005 16:58:31 +0100 Subject: bad generator performance References: Message-ID: > You don't really give the complete story so it's hard to tell what > exactly is going on. For example, I would assume the recursion is > calling the same method (i.e., depthFirstIterator1 or > depthFirstIterator2), but then you posted separate timing information > for a "recursive helper function" so I'm not so sure. Also there is not > much of a hint as to the nature of your data. yeah, sorry. i'm not myself lately ;-)) forget about the helper function, that was nonsense! i used a helper function to build a huge tree as test data, but that is the same function for both cases! the program is supposed to manage bookmarks and i thought it would be a good idea to represent the bookmarks as a tree (with folders as internal nodes and bookmarks as leaves). so, a tree is never going to hold more than say 2000 nodes and is going to be rather wide than deep! > In my testing (on Python 2.3.4 on > Windows XP), the generator version takes about 1/4 of the time that the > list version takes. If both versions call the list version of the method > recursively (i.e., you're only getting the benefit of the generator at > the top level of the recursion), the generator version is still about > 20% faster. > > Timing differences could potentially depend on your data also - things > like how deep vs. wide your tree is. thx a lot and sorry for not supplying my data type and test data! hmm, that totally contradicts my profiling results... on my machine the generator version is repeatedly 10 times slower than the list version as well with python2.3 as with python2.4. i don't want to spam the list with hundreds of lines of source code, so i'll just cry a little and try to do something else than prematurely optimising my bookmark script *gg* thx, Johannes From axel at straschil.com Thu Feb 3 07:59:10 2005 From: axel at straschil.com (Axel Straschil) Date: Thu, 3 Feb 2005 12:59:10 +0000 (UTC) Subject: Generating modul classes with eval References: Message-ID: Hello! > After the loop has finished, the global variable TmpClass will be bound to > whatever class was created last, and the variable class_base will be bound > to that the base class of that same TmpClass. Therefore only this last class > is guaranteed to work as expected. Great, now it workes! _module_name = sys.modules[__name__] def _tag_class_factory(name, base): class T(base): def __init__(self, **props): super(T, self).__init__(name=name.lower(), **props) setattr(_module_name, name, T) class_dic = {} class_dic['Br'] = _Tag class_dic['Hr'] = _Tag class_dic['Html'] = _ContainerTag class_dic['Table'] = _ContainerTag class_dic['Td'] = _ContainerTag class_dic['Tr'] = _ContainerTag for name, base in class_dic.items(): _tag_class_factory(name, base) print Table(contents=[Tr(contents=[Br()])]) gives:
Thanks, AXEL. From tores at stud.cs.uit.no Wed Feb 23 09:22:01 2005 From: tores at stud.cs.uit.no (Tor Erik Sønvisen) Date: Wed, 23 Feb 2005 15:22:01 +0100 Subject: kill a process in XP Message-ID: Hi. >From my Python-program I spawn a new process. When using P_NOWAIT spawnl returns the pid but in windows it returns a process handle. Later I want to kill this process. How can I do this when I only have the process handle? -tores- From steve at holdenweb.com Fri Feb 4 08:37:21 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 04 Feb 2005 08:37:21 -0500 Subject: Converting a string to a function pointer In-Reply-To: References: Message-ID: H?kan Persson wrote: > Hi. > > I am trying to "convert" a string into a function pointer. > Suppose I have the following: > > from a import a > from b import b > from c import c > > funcString = GetFunctionAsString() > > and funcString is a string that contains either "a", "b" or "c". > How can I simply call the correct function? > I have tried using getattr() but I don't know what the first (object) > argument should be in this case. > > Thanks, > H?kan Persson > > Well, one really horrible way would be getattr(sys.modules['__main__'], funcString) and, of course, if you were going to use it a lot you could optimize slightly with this = sys.modules['__main__'] followed later by this = getattr(this, funcString) Overall, however, it might be better to set uip a mapping for the functions you need to be accessible. This has the further merits that a) You can heve different, and/or multiple names for a function b) You can trap errors more easily c) erm, I forgot the third advantage, consider this the Spanish Inquisition in reverse :-) So: funcMap = { "a": a, "A": a, "b": b, "exoticName": c } ... funcString = GetFunctionAsString() try: f = funcMap(funcString) except KeyError: print "No such function" raise SomethingElse result = f(args) regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From mhartl at post.harvard.edu Fri Feb 11 18:22:50 2005 From: mhartl at post.harvard.edu (Michael Hartl) Date: 11 Feb 2005 15:22:50 -0800 Subject: check if object is number In-Reply-To: <1108155272.438423.177460@l41g2000cwc.googlegroups.com> References: <374ho0F560ughU1@individual.net> <66WdnbJbuf5yj5DfRVn-iA@comcast.com> <1108155272.438423.177460@l41g2000cwc.googlegroups.com> Message-ID: <1108164170.145575.241360@l41g2000cwc.googlegroups.com> As I mention below, I mistook the function from my utilities file for a Python built-in; here's the implementation: #def isnumber(x): # "Is x a number? We say it is if it has an __int__ method." # return hasattr(x, '__int__') From s_t_a_n_i at yahoo.com Sat Feb 5 15:55:12 2005 From: s_t_a_n_i at yahoo.com (s_t_a_n_i at yahoo.com) Date: 5 Feb 2005 12:55:12 -0800 Subject: ANN: SPE 0.7.2.A IDE with wxGlade, Uml & Blender support Message-ID: 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 ships with wxGlade (gui designer), PyChecker (source code doctor) and Kiki (regular expression console). Spe is extensible with wxGlade. The sidebar now features a file browser. I'm now trying to form a team for future development of SPE. Besides me four people will join the project: - Sam Widmer for CVS and bugfixes. So soon more collaboration on SPE will be possible. - Nir Aides (author of rpdb) for helping implementing the remote debugger - Kevin Walzer for the OS X Port of SPE. Please contact him for Mac specific issues. Spe for the Mac will be distributed through: http://www.wordtech-software.com/spe.html - Jelle Feringa for documentation. The goal is to provide a pdf manual with the SPE distribution based on the SPE wiki: http://www.stani.be/spe/wiki Anyone who has comments or wants to edit the wiki as well can contact Jelle. If you like SPE, please contribute by coding, writing documentation or donating. I would like to thank especially Michael Balk, who gave the largest donation ever to SPE. Also I would like to thank Michael Foord, who made SPE part of a new Python distribution, called "movable python". It gives you the possibility to carry your favorite developping environment on a USB stick. So you can continue your work on any computer or test your modules for different python versions. This distribution opens a lot of new possibilities, check it out!! For more info, visit http://www.voidspace.org.uk/python/programs.shtml#movpy :Batteries included: - Kiki: Regular Expression (regex) console. For more info: http://project5.freezope.org/kiki/index.html - PyChecker: PyChecker is a tool for finding bugs in python source code. It finds problems that are typically caught by a compiler for less dynamic languages, like C and C++. It is similar to lint. For more info: http://pychecker.sourceforge.net - wxGlade: wxGlade is a GUI designer written in Python with the popular GUI toolkit wxPython, that helps you create wxWindows/wxPython user interfaces. As you can guess by the name, its model is Glade, the famous GTK+/GNOME GUI builder, with which wxGlade shares the philosophy and the look & feel (but not a line of code). For more info: http://wxglade.sourceforge.net :New features: - sidebar browser (iniated by Attila Magyar) :Bug fixes: - segfaults in Browser - indentation can now be different from 4 - mac osx fixes for kiki, wxGlade & XRC - scrollbars of UML view - initial sizing and positioning are now restored :Donations(177.20euro): - Michael Balk - Jason Powell - David Ko Feng - Winchell Chung - Matthias Haberkorn - Kristjan Kannike - Robert Cowham - Andre Roberge - Chris S :Contributors: - Sam Widmer - Attila Magyar - Kevin Walzer - Thurston Stone :Requirements: - full python 2.3+ - wxpython 2.5.3.8+ - optional blender 2.35+ :Links: - Homepage: http://spe.pycs.net - Website: http://projects.blender.org/projects/spe/ - Screenshots: http://spe.pycs.net/pictures/index.html - Forum: http://projects.blender.org/forum/?group_id=30 - RSS feed: http://spe.pycs.net/weblog/rss.xml From peter at engcorp.com Wed Feb 9 17:45:54 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Feb 2005 17:45:54 -0500 Subject: A great Alan Kay quote In-Reply-To: <420a5c1e$0$21630$a1866201@visi.com> References: <420a5c1e$0$21630$a1866201@visi.com> Message-ID: Grant Edwards wrote: > In an interview at http://acmqueue.com/modules.php?name=Content&pa=showpage&pid=273 > Alan Kay said something I really liked, and I think it applies > equally well to Python as well as the languages mentioned: > > I characterized one way of looking at languages in this > way: a lot of them are either the agglutination of features > or they're a crystallization of style. Languages such as > APL, Lisp, and Smalltalk are what you might call style > languages, where there's a real center and imputed style to > how you're supposed to do everything. > > I think that "a crystallization of style" sums things up nicely. > The rest of the interview is pretty interesting as well. Then Perl is an "agglutination of styles", while Python might be considered a "crystallization of features"... -Peter From fredrik at pythonware.com Fri Feb 4 02:34:45 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 4 Feb 2005 08:34:45 +0100 Subject: Possible additions to the standard library? (WAS: About standard library improvement) References: <1d6cdae3050203195251843db2@mail.gmail.com> Message-ID: Daniel Bickett wrote: > [2] I'm currently unaware if _winreg is a c extension module or pure > python, but I'm assuming it's C, so I don't know how possible it is to > add pure python to it... from the documentation: This module exposes a very low-level interface to the Windows registry; it is expected that in the future a new winreg module will be created offering a higher-level interface to the registry API. your DeleteKeyAll operation would fit nicely in such an interface, but I'm not sure it belongs in the low-level interface, and a higher-level interface consisting of just one helper would seem a bit odd. on the other hand, it's about time someone wrote that "winreg" module... (hint). From nhodgson at bigpond.net.au Mon Feb 28 19:57:55 2005 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 01 Mar 2005 00:57:55 GMT Subject: Share your SciTEGlobal.properties pls~~~~ References: <1109608274.905138.19730@l41g2000cwc.googlegroups.com> Message-ID: DENG: > im new to Python, i chose SciTE as my Python editor. but the problem is > SciTE needs to be config carefully, are there anyone use SciTE too? can > you share your SciTEGlobal.properties file? black background solution > is prefered:) http://scintilla.sourceforge.net/SciTEFAQ.html#BlackBackground Adding changes to your user options file rather the global options file means that they will survive if you upgrade to a new version of SciTE. There is a SciTE mailing list at http://mailman.lyra.org/mailman/listinfo/scite-interest Neil From fredrik at pythonware.com Fri Feb 4 14:59:01 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 4 Feb 2005 20:59:01 +0100 Subject: returning True, False or None References: <5OOMd.12446$W16.3365@trndny07> <5sydnV6im6jgJp7fRVn-qQ@comcast.com> Message-ID: Steven Bethard wrote: >> return max(lst) > > Very clever! Thanks! too clever. boolean > None isn't guaranteed by the language specification: http://docs.python.org/ref/comparisons.html "... objects of different types always compare unequal, and are ordered consistently but arbitrarily. /.../ In the future, the comparison rules for objects of different types are likely to change. ..." From helten0007 at yahoo.com Sun Feb 27 13:47:42 2005 From: helten0007 at yahoo.com (Pete.....) Date: Sun, 27 Feb 2005 19:47:42 +0100 Subject: Making a calendar References: <422071d5$0$22691$ba624c82@nntp04.dk.telia.net> Message-ID: <4222157e$0$22713$ba624c82@nntp04.dk.telia.net> Thanks all. I will look at your links tonight :D Hopefully they will make me smile and jump around as a happy man... Cheers "Brian Sutherland" wrote in message news:mailman.3108.1109471520.22381.python-list at python.org... > On Sat, Feb 26, 2005 at 01:57:20PM +0100, Pete..... wrote: >> I'm trying to make a calendar for my webpage, python and html is the only >> programming languages that I know, is it possible to make such a calendar >> with pythong code and some html. >> >> The Idea is that when I click the link calendar on my webpage, then the >> user >> will be linked to the calendar. >> >> The calendar should show one month at the time, and the user should be >> able >> to browse to the other month. >> >> I will make a script that puts events and such into a db ( I know how to >> do >> this) >> >> Then I need a script that puts the events from the db into the calendar, >> if >> every day in the calendar has a value id that part will not be hard. > > All this and more (perhaps overkill): > > http://www.schooltool.org/schoolbell > > -- > Brian Sutherland > > It's 10 minutes, 5 if you walk fast. From exogen at gmail.com Tue Feb 22 18:29:32 2005 From: exogen at gmail.com (Brian Beck) Date: Tue, 22 Feb 2005 18:29:32 -0500 Subject: newbie help for mod_python In-Reply-To: References: Message-ID: Jochen Kaechelin wrote: > I run debian sid and apache2 with libapache2-mod-python2.3 > and I added these lines > > > AddHandler mod_python .py > PythonDebug On > > > in a virtualhost container. Were those the only lines you added? You also should have actually loaded the module somewhere by adding something resembling: LoadModule python_module modules/mod_python.so -- Brian Beck Adventurer of the First Order From aleaxit at yahoo.com Mon Feb 7 05:12:01 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 7 Feb 2005 11:12:01 +0100 Subject: declarations summary References: <1107750862.485179.61980@c13g2000cwb.googlegroups.com> Message-ID: <1grm033.wnee8f9w790oN%aleaxit@yahoo.com> Michael Tobis wrote: ... > .x = 1 > .def foo(): > . if False: > . global x > . x = 2 > .foo() > .print x > > prints "1" Wrong: >>> x = 1 >>> def foo(): ... if False: ... global x ... x = 2 ... >>> foo() >>> print x 2 And indeed, that IS the problem. > Pythonistas appear to be averse to any declarations (in the sense of > compiler directives) besides "global". Many of us consider ``global'' a nasty wart, too. > Anyway, it's this sort of reference-modifier that's at issue here, You can play with references as much as you like, as long as they're *COMPOUND* names (attributes, or even, if you with, items). Just leave *BARE* names alone, and nobody will jump all over you. > It's not difficult for me to imagine at least two other things I'd want > to do with references: 1) make them immutable (making life easier for > the compiler) 2) make them refer only to objects with certain > properties (strong duck-typing). Look at Enthought's ``Traits'' for some highly developed infrastructure along these lines -- for *COMPOUND* names only, of course. No ``making life easier for the compiler'', but for example ease of generation of forms and other view/controller implementations from a model, etc. If you're keen to hack on the compiler to take advantage of such information for code generation purposes, your experimentation will be easier once the AST branch is folded back into the 2.5 CVS head; if it's not about code generation but just runtime (so not really about the compiler but rather about the virtual machine), pypy (see codespeak.net) may help you similarly, already today. If you're not keen to hack, experiment, and prove that dramatic speedups can be obtained this way, then I doubt that musing about ``helping the compiler'' in a purely theoretical way is gonna do any good whatsoever. > On the other hand, I think compiler writers are too attached to > cleverly divining the intention of the programmer. Much of the effort > of the compiler could be obviated by judicious use of declarations and > other hints in cases where they matter. Correct code could always be Ah, somebody who's never hacked on C compilers during the transition from when ``judicious use of 'register' '' (surely a classic example of such an "other hint") was SO crucial, to where it doesn't matter in the least -- except that it's an ugly wart, and the clutter stays. Used to be that C compilers didn't do register allocation with any skill nor finesse, but did let you give a hint by using "register" as the storage class of a variable. Smart programmers studied the generated machine code on a few architectures of interest, placed "register" appropriately, studied what changes this made to the generated code, and didn't forget to check on all different machines of interest. Most C programmers just slapped "register" where they GUESSED it would help, and in far too many cases they were horribly wrong, because intuition is no good guide to performance improvement; I have witnessed examples of code where on certain machine/compiler combinations inserting a "#define register auto" to disable the GD ``register'' made some functions measurably FASTER. Then "graph-coloring" register allocators came into their own and in the space of a few years ``register'' blissfully became just about irrelevant; nowadays, I believe all extant compilers simply ignore it, at least in suitable optimization mode. Of course, for backwards compatibility, "register" remains in the language: total, absolute, absurd deadweight -- one extra little difficulty in learning the language that has absolutely no reason to exist, gives zero added value, just clutters things up to no purpose whatsoever. So much for the ``judicious'' use of performance hints: it just doesn't happen enough in the real world, to put up with the aggravations until compiler technology has gotten around to making a certain hint irrelevant, and the totally useless conceptual and coding clutter forevermore afterwards. Those who can't learn from history are condemned to repeat it. Maybe some of us just know some history better (perhaps by having lived it) and don't need yet another round of repetition? Optional declarations to ease compiler optimizations were at the heart of Dylan, and looked like a great idea, but Dylan's success surely wasn't such as to enourage a repeat of this ``soft typing'' experiment, was it now? Of course, it's always hard to pinpoint one reason out of a language's many features -- e.g., Dylan had macros, too, maybe THOSE were more of a problem than soft-typing. In theory, I do like the idea of being able to give assertions about issues that a compiler could not reasonably infer (without analyzing the whole program's code, which is another idea that never really panned out for real-life programs as well as one might hope), and having a mode where those assertions get checked at runtime and another where the compiler may, if it wishes, rely on those assertions for code optimization purposes. In practice, having never seen this theoretically nice idea work really WELL in real life, despite it being tried out in a huge number of ways and variations many, MANY times, I'd have to be convinced that a particular incarnation is working well by seeing it make a truly impressive performance difference in some prototype implementation. AST-branch for the compiler side, and pypy for the runtime side, are developing in good part just in order to ALLOW easy experimentation, by coding only Python (and maybe generating some pyrex, if the point of some idea is making some sparkling machinecode). Intuitions about performance are far too often completely off the mark: performance effects just NEED to be shown as working well in practice, before any credence can be put into reasoning that this, that or the other tweak "should" speed things up wondrously. > socks off yet again, but I can't see counting on it. So the successor > to Fortran (presuming it isn't C++, which I do presume) may be > influenced by Python, but probably it won't be Python. You appear to assume that Fortran is dead, or dying, or is gonna die soon. I assume Mr. Beliavski will do a great job of jumping on you for this, so I can save the effort of doing do myself;-). Alex From lac at strakt.com Sat Feb 5 07:39:41 2005 From: lac at strakt.com (Laura Creighton) Date: Sat, 5 Feb 2005 13:39:41 +0100 Subject: After 40 years ... Knuth vol 4 is to be published!! Message-ID: <200502051239.j15Cdf6k005835@ratthing-b246.strakt.com> "More than forty years in the making, the long-anticipated Volume 4 of The Art of Computer Programming is about to make its debuta. in parts. Rather than waiting for the complete book, Dr. Knuth and Addison-Wesley are publishing it in installments ("fascicles") a la Charles Dickens. See http://www.bookpool.com/.x/xx/ct/163 for an excerpt and more info on Volume 4. And Addison-Wesley is offering Bookpool customers an exclusive sneak peek -- the first official excerpt from the series." (above from the same site) Yippee! Laura From frans.englich at telia.com Tue Feb 8 18:14:00 2005 From: frans.englich at telia.com (Frans Englich) Date: Tue, 8 Feb 2005 23:14:00 +0000 Subject: What's wrong with `is not None`? Message-ID: <200502082314.00933.frans.englich@telia.com> That's what PyChecker tells me, at least. A line of: if testReport is not None: results in: runner.py:587: Using is not None, may not always work In what circumstances can `is not None` fail? How and why does it fail? What is the equivalent expression which is more secure; `!= None`? Cheers, Frans From kartic.krishnamurthy at gmail.com Tue Feb 8 13:58:03 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 8 Feb 2005 10:58:03 -0800 Subject: Python mail filter In-Reply-To: <4208f1d0$1@news.starhub.net.sg> References: <4208f1d0$1@news.starhub.net.sg> Message-ID: <1107889083.911654.306580@f14g2000cwb.googlegroups.com> Mika, Somebody else had a similar situation of having a script receive the email and process it. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1f26452835e51c71/e4d6c1efc9a71e39?q=&_done=%2Fgroups%3Fq%3D%26start%3D10%26enc_author%3DVUzGiykAAAD-rgSwZjnUEp_UDWM1Zk6AXwyJTPpMwlh8flm6PB9npBRJrLIi5sMmhFscvSzxHxE%26&_doneTitle=Back+to+Search&&d#e4d6c1efc9a71e39 This is my response to that post and the latter half may help you. One thing you must remember is once you pipe the email to your script, it is considered delivered. If you want to script to process and also receive the email into a user account, you have to list the recipients in your .forward file. If you want to process the email through your script and _then_ send it to a user, I think the only way would be to send the email from your script to next intended recipient. Thank you, -Kartic From paddy3118x at netscape.net Tue Feb 8 15:04:27 2005 From: paddy3118x at netscape.net (Paddy McCarthy) Date: Tue, 08 Feb 2005 20:04:27 GMT Subject: Is Python as capable as Perl for sysadmin work? In-Reply-To: References: Message-ID: <42091D9F.9000702@netscape.net> Jeff Epler wrote: > No. > > Unlike Perl, Python implements only a *finite turning machine* model of > computation. An easy way to see this limitation is in the following > code: > >>> 1.0 / 10.0 > 0.10000000000000001 <> > > Jeff Nice, Made my evening :-) - Pad. From jjl at pobox.com Sat Feb 12 08:43:21 2005 From: jjl at pobox.com (John J. Lee) Date: 12 Feb 2005 13:43:21 +0000 Subject: Testing web applications References: Message-ID: <871xbl28sm.fsf@pobox.com> Josef Meile writes: > > I'm looking for frameworks to make testing web applications - > > i.e. parsing and filling out forms - easier. I found Puffin, which > > looks good but not very usable in the current state. I know that I > > once read about other nice frameworks, but could not find one via > > google. Any hints? > Zope + Formulator is a nice combination to validating and designing > forms and add some functionality. If you want a more complicated content > management framework, then you can additionally install plain CMF or > Plone, which is based on CMF. There is also something called Silva, but > it doesn't have many products as the other two; however, it is also > nice. > > I have heard also about CherryPy, Quixote, Twisted Matrix and Webware, > but I haven't tested them. Once I saw that somebody posted a link, which > compares some of them, but I lost that thread :-( Did you read the question? :-) John From tim at zeos.net Mon Feb 14 11:45:17 2005 From: tim at zeos.net (Timothy Babytch) Date: Mon, 14 Feb 2005 18:45:17 +0200 Subject: webbrowser.py In-Reply-To: References: Message-ID: Jeremy Sanders wrote: > It occurs to me that webbrowser could be more intelligent on Linux/Unix > systems. Both Gnome and KDE have default web browsers, so one could use > their settings to choose the appropriate browser. > I haven't been able to find a freedesktop common standard for web browser, > however. > webbrowser could identify whether it was running under KDE/Gnome (maybe > scan the processes?), identify the correct desktop's browser (or just use > Gnome, maybe), and start that web browser. I would not mind just using default GNOME's browser :) to determine the one you will need python-gconf2 module and look for gconf entry /desktop/gnome/applications/browser The only bug here is that user MUST have python-gconf2 installed. Many GNOMErs do not have it. but hey - one more dependancy.. Who cares? If they istalled pyGTK :) - why it is wrong to ask for python-gconf2? From max at alcyone.com Sun Feb 13 19:25:33 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 13 Feb 2005 16:25:33 -0800 Subject: Pythonic poker client In-Reply-To: <1108334914.029293.14830@o13g2000cwo.googlegroups.com> References: <1108334914.029293.14830@o13g2000cwo.googlegroups.com> Message-ID: <6c2dnZFXKqBgcpLfRVn-hQ@speakeasy.net> hardieca at hotmail.com wrote: > I'm assuming that I need to figure out the port it uses, find the > server, analyze the packets for commands, and then build an app that > masquerades as the real client. > > Anyone have any experience with this? If you're using one of the major sites, what you are trying to do is essentially impossible. It is very likely that the transmissions are encrypted via SSL. Furthermore, such sites may well actively check for clients sending invalid data -- something your client will almost certainly do at first even if you did somehow manage to crack the encryption -- as a tipoff to modified clients and bots. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis If love is the answer, could you rephrase the question? -- Lily Tomlin From fredrik at pythonware.com Thu Feb 3 13:29:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 3 Feb 2005 19:29:15 +0100 Subject: Easy Q: dealing with object type References: <420181b1$1@nntp.zianet.com><1107396669.028096.301290@g14g2000cwa.googlegroups.com><42019545$1@nntp.zianet.com> <42026b7e$1@nntp.zianet.com> Message-ID: Erik Johnson wrote: > As an aside, I notice a lot of other people's interpreters actually > print 'True' or 'False' where my system prints 0 or 1. Is that a > configuration that can easily set somewhere? $ python2.1 -c "print 1 == 1" 1 $ python2.2 -c "print 1 == 1" 1 $ python2.3 -c "print 1 == 1" True $ python2.4 -c "print 1 == 1" True From levub137 at wi.rr.com Sun Feb 27 12:34:37 2005 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sun, 27 Feb 2005 11:34:37 -0600 Subject: any Python equivalent of Math::Polynomial::Solve? In-Reply-To: <38eaemF5o7kfjU1@individual.net> References: <1109485184.587035.176540@l41g2000cwc.googlegroups.com> <38e9nqF5ndqt9U1@individual.net> <38eaemF5o7kfjU1@individual.net> Message-ID: Alex Renelt wrote: > Alex Renelt wrote: > >> in addition: >> I'm writing a class for polynomial manipulation. The generalization of >> the above code is: >> >> definitions: >> 1.) p = array([a_0, a_i, ..., a_n]) represents your polynomial >> P(x) = \sum _{i=0} ^n a_i x^i >> >> 2.) deg(p) is its degree >> >> 3.) monic(p) makes P monic, i.e. monic(p) = p / p[:-1] >> >> then you get: >> from numarray import * >> import numarray.linear_algebra as la >> >> def roots(p): >> p = monic(p); n = deg(p) >> M = asarray(zeros((n,n)), typecode = 'f8') >> # or 'c16' if you need complex coefficients >> M[:-1,1:] = identity(n-1) >> M[-1,:] = -p[:-1] >> return la.eigenvalues(M) >> >> Alex > > > uhh, I made a mistake: > under definitions, 3.) > its "monic(p) = p / p[-1]" of course > > Alex Alex, If you want a class for polynomial manipulation, you should check out my ratfun module. http://calcrpnpy.sourceforge.net/ratfun.html Ray From evenprimes at gmail.com Thu Feb 10 08:59:50 2005 From: evenprimes at gmail.com (Chris Cioffi) Date: Thu, 10 Feb 2005 08:59:50 -0500 Subject: OT: Anyone want a GMail account? Message-ID: I've got 50 so if you want a GMail invite reply directly to me and I'll send our an invite. Chris Cioffi -- "It is our responsibilities, not ourselves, that we should take seriously." -- Peter Ustinov From kanenas at tcomcastd.tnet Thu Feb 10 03:54:04 2005 From: kanenas at tcomcastd.tnet (‘5ÛHH575-UAZWKVVP-7H2H48V3) Date: Thu, 10 Feb 2005 00:54:04 -0800 Subject: deepcopy chokes with TypeError on dynamically assigned instance method Message-ID: <698m01djeu9jqpnvvk64vmc488e5c026im@4ax.com> (see end of message for example code) When an instance has a dynamically assigned instance method, deepcopy throws a TypeError with the message "TypeError: instancemethod expected at least 2 arguments, got 0". Tested with Python 2.3.4 on OpenBSD and Python 2.4 on Win98; same results. Is this a bug in deepcopy, how I dynamically assign the instance method or something else? (See example code for how I did it.) If you're curious as to why the deep copy and dynamic assign are necessary or have implementation suggestions (or alternatives), I bet you'd like some details. The TypeError cropped up while coding a 'Point' class representing cartesian coordinates. I needed to overload an 'origin' method as both a class method and an instance method (if Python were more Perlesque... ;-) ). 'origin' returns a point representing an origin. The class method requires an argument for the dimension of the origin, while the instance method uses the dimension of an instance (ortus overloading). As the instance reference isn't bound when the class 'origin' method is defined, there's no way to use a default argument. I instead dynamically assign an instance method to the 'origin' attribute of the instance. As for the deepcopy, scalars aren't necessarily of a built-in numeric type, though I generally expect them to be numeric (you could use lists or strings as scalars, but not many methods would still be usable). Point is the base clase for Vector, and I want (e.g.) vectors of vectors so I can eventually extend Vector to Matrix and Tensor. The Point constructor has a single argument: a sequence of scalars (which, as noted, can be sequences). In practice, the sequence itself will be a tuple, a list, a Point or descendant of Point (so that Point can act as a copy constructor). To prevent a copied point from aliasing elements of a different Point, I used deepcopy. When the TypeError struck, I switched to a generator, which works as long as every constructor functions as a copy constructor (not necessarily true, apparently, of lists, but true of Points). I could also implement copy-on-write semantics for coordinates or implement __deepcopy__ for Point (which will probably be the final solution). example code: from copy import copy,deepcopy import new class Foo(list): "Foo" def __init__(self, l=[]): list.__init__(self, deepcopy(l)) # using generator rather than deepcopy produces no errors. #list.__init__(self, [copy(el) for el in l]) # 'copy(el)' in generator results in a deepcopy of sequence # as long as each object encountered uses a copy constructor # (which I expect of numeric types) and doesn't implement # a shallow __copy__. Alternative is to use type(el)(el): #list.__init__(self, [type(el)(el) for el in l]) def bar(self): return 'bar' self.bar=new.instancemethod(bar, self, self.__class__) # also causes deepcopy to choke: #self.bar = self._bar def _bar(self): return 'bar' #deepcopy has no problem with this bar = _bar def __repr__(self): return self.__class__.__name__+'(['\ +','.join(map(str, self))+'])' # causes deepcopy to throw a TypeError Foo(Foo('foo')) From peter at somewhere.com Wed Feb 16 02:34:46 2005 From: peter at somewhere.com (Peter Maas) Date: Wed, 16 Feb 2005 08:34:46 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: Michael Hoffman schrieb: > Ilias Lazaridis wrote: > But don't act like the volunteers who develop Python owe you a version > of Python that runs out of the box on MinGW. They don't, anymore than you > owe *me* a version of Python that runs out of the box on MinGW. Please, leave him alone. When he posted here first his tone made me suspicious and I did some searching. Replies like yours are exactly what he wants. He is here to fight and to waste your time. But if you enjoy this ... go ahead ;) I don't so this will be my only post in this thread. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From claird at lairds.us Mon Feb 14 13:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Mon, 14 Feb 2005 18:08:03 GMT Subject: gui scripting References: <1108381881.828494.98340@c13g2000cwb.googlegroups.com> Message-ID: In article <1108381881.828494.98340 at c13g2000cwb.googlegroups.com>, Tonino wrote: >HI, > >I have a 2 phase question: > >Phase 1 is I am needing to automate a report generation from a >proprietary product. Currently a person sits and input's the data into >a GUI frontend and clicks's the appropriate buttons to start the report >generation. What I am wanting todo is automate this, but since the GUI >is from a proprietary product all I have is the GUI. > >This is done on a Linux Xfree server. Can anyone please point me in a >direction to a pythonic gui scripting module ? >Python is the best tool and we use it elsewhere - so it is the best >option. > >Second phase will have this done on a Windows platform... but that is >second priority ... . . . While I understand and applaud your affection for Python, the solution that I think will best suit you is based on Tcl. has details. For the Windows side, see . From tom.willis at gmail.com Thu Feb 24 15:42:58 2005 From: tom.willis at gmail.com (Tom Willis) Date: Thu, 24 Feb 2005 15:42:58 -0500 Subject: Interesting decorator use. In-Reply-To: <421e2398@nntp0.pdx.net> References: <421e2398@nntp0.pdx.net> Message-ID: On Thu, 24 Feb 2005 11:15:07 -0800, Scott David Daniels wrote: > > I have started doing the following to watch for exceptions in wxPython. > I'd like any input about (A) the interface, and (B) the frame before I > throw it in the recipes book. > > import wx, os, sys > errorframe = None > > def watcherrors(function): > '''function decorator to display Exception information.''' > def substitute(*args, **kwargs): >... Pretty cool. Question on decorators in general. Can you parameterize those? If I wanted to something and after the function call for example, I would expect something like this would work. def prepostdecorator(function,pre,post): def wrapper(*args,**kwargs): pre() result = function(*args,**kwargs) post() return result return wrapper def dopre(): print "call pre" def dopost(): print "call post" @prepostdecorator(pre,post) def sayhello(Name): print "Hey %s, nice to meet you" % Name #sayhello = prepostdecorator(sayhello,dopre,dopost) if __name__=="__main__": sayhello("Dude") but I get ... TypeError: prepostdecorator() takes exactly 3 arguments (2 given) Where as def prepostdecorator(function,pre,post): def wrapper(*args,**kwargs): pre() result = function(*args,**kwargs) post() return result return wrapper def dopre(): print "call pre" def dopost(): print "call post" def sayhello(Name): print "Hey %s, nice to meet you" % Name sayhello = prepostdecorator(sayhello,dopre,dopost) if __name__=="__main__": sayhello("Dude") #outputs call pre Hey Dude, nice to meet you call post Does what I want. I guess I'm having problems with how function get's in there similair to how self magically gets in a method, except when you specify other params. Got linky? -- Thomas G. Willis http://paperbackmusic.net From rory at campbell-lange.net Wed Feb 16 17:13:54 2005 From: rory at campbell-lange.net (Rory Campbell-Lange) Date: Wed, 16 Feb 2005 22:13:54 +0000 Subject: Newbie question about class operator overloading In-Reply-To: References: Message-ID: <20050216221354.GA30498@campbell-lange.net> Hi Steve I've been playing around with your two suggestions. The Record class is an elegant solution. It doesn't however help in the case where the class has the following general data structure (something I should have stated originally): class.config1 = param class.config2 = param class.data = { 'this' : [] 'that' : [] ... } The __setitem__ and __getitem__ methods allow the class.data data structure to be dealt with easily as self.data[key] = val without worrying about getting involved with other variables such as config1 and config2 (because potentially a data key could be called 'config1' for example. So the __getitem__ and __setitem__ give data hiding properties when I inherit from this class. I think! Anyway, I'm very grateful for your help. Rory On 15/02/05, Steven Bethard (steven.bethard at gmail.com) wrote: > Rory Campbell-Lange wrote: > >I am anxious about how best to set and access items one level down in a > >data structure if I am using __setitem__ and __getitem__. ... > >object['three'] = [0, 'val0'] # set > >x = object['three'][0] # get ... > py> data['one'].foo = 'val0' > py> data > {'two': Record(5, 6, {}, 8), 'one': Record('val0', 2, {}, 4)} > py> data['one'].foo > 'val0' ... > ... def __setitem__(self, x, value): > ... try: > ... name, index = x > ... self.data.setdefault(name, {})[index] = value > ... except ValueError: > ... self.data[x] = value ... > py> c['one', 0] = 1 This does seem a lot more logical than my object['three'] = [0, 'val0']. Thanks for this (and using try against a possible ValueError). ... > As you can see, Python has builin syntax support to allow tuples to be > used as dict keys. (The parentheses can be omitted.) > > Still, I think the class-based solution is much better than the > __getitem__/__setitem__ one. -- Rory Campbell-Lange From ajsiegel at optonline.com Tue Feb 8 20:58:40 2005 From: ajsiegel at optonline.com (Arthur) Date: Tue, 08 Feb 2005 20:58:40 -0500 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1grifns.14san6f1b076mdN%aleaxit@yahoo.com> <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com> Message-ID: <6toi01140mis4en4757f513f5l3ipv8a5o@4ax.com> On Sat, 5 Feb 2005 17:00:15 +0100, aleaxit at yahoo.com (Alex Martelli) wrote: >Alexander Zatvornitskiy > wrote: > ... >> AM> The fact that in Python there are ONLY statements, NO declarations, >> === >> def qq(): >> global z >> z=5 >> === >> What is "global"? Statement? Ok, I fill lack of "var" statement:) > >'global' is an ugly wart, to all intents and purposes working "as if" it >was a declaration. If I had to vote about the one worst formal defect >of Python, it would surely be 'global'. Venturing in - again - over my head. Brave or stupid. But the fact that I cannot dissect Python byte code, doesn't mean I can't follow the logic or illogic of an argument. Or hear, or interpret reasonably well what I hear. I will accept that global is a horribly wart for reasons that I don't understand. (worse than print>> for more reasons I don't understand as well ?) But making the argument that it is a wart *because* it is declarative, and therefore a violation of Python's purity is hard for me. """ The fact that in Python there are ONLY statements, NO declarations, is a completely different LEVEL of issue -- a totally deliberate design choice taken in full awareness of all of its implications. """ Global is there. It was put there by someone who presumably knows his declaratives. So simply as a matter of logic, your assertion doesn't hold up. And as we learn, what is true of Python today is not necessarily what is true of Python tomorrow. And my understanding of the arguments surrounding the decorator debate suggested to me that there is decently strong sentiment among a segment of the folks who represent "the community" much better than do I, that if there indeed has been any purist stricture about the use of declaratives in the kanguage, it may be wise to loosen it. Why is it logical to believe that a language that is purely anything will best do. Python prides itself on being multi-paradigm, thought I. Except Ales says no declarations allowed, with great authority. Do they belong in any language? Solve problems in any language? If so, why is that Python is denied them? Ultimately I don't think Guido chooses to be restricted by these kinds of notions of purity. And suspect that if and when declarations best solve real problems, they will brought to bare - without regard to such notions. I am sure you could if you wanted provide a highly competent - OK brilliant - answer to why given this and that aspect of Python it can't and won't and shouldn't be.. But you are a polemicist at heart, it seems to me - on observation from non-techncial discussion. So all my technical limitations aside, I still don't think I could decipher where polemics ends, and analysis begins. Squash me like a bug, it you like. But I am not - just so you know - meaning to be even unfriendly, much less hostile. Art > >Fortunately, it's reasonably easy to avoid the ugliness, by avoiding >rebinding (within functions) global variables, which tend to be easy. > >What you keep demanding is a way to inject far worse ugliness, and in a >context in which the typical behavior of pointy-haired bosses will be to >make it unavoidable for many of the people who work with Python. I am >strongly convinced that, if you had your wish, the total amount of >happiness in the world would be quite substantially diminished, and I >will do anything I can to stop it from happening. > > >> >> Fine! Let interpreter never show us errors like division by zero, >> >> syntax errors, and so on. If file not found, library don't need to >> >> say it. Just skip it!!! Because every, even simple, test will find >> >> such bugs. Once you have unit tests, the added value of >> >> is tiny, and their cost remains. >> AM> Another false assertion, and a particularly ill-considered one in ALL >> AM> respects. Presence and absence of files, for example, is an > ... >> Here, you take one detail and bravely fight with it. Just try to understand >> meaning of my sentence, in all. It will help:) > >I tear ONE of your examples to pieces in gory detail, because it's not >worth doing the same over and over again to every single piece of crap >you filled that sentence with -- very similar detailed arguments show >how utterly inane the whole assertion is. > >There IS no meaning to your (several) sentences above-quoted, that it >can help anybody to "try to undestand": it's simply an insanely bad >attempt at totally invalid parallels. > >> AM> In brief: you're not just wrong, you're so totally, incredibly, >> AM> utterly and irredeemably wrong that it's not even funny. >> Hey, take it easy! Relax, reread that piece of text. It was written with smile >> on my lips. Here it is for your convenience: > >Do yourself a favor: don't even _try_ to be funny in a language you have >so much trouble with. Your communication in English is badly enough >impaired even without such lame attempts at humor: don't made bad things >even worse -- the result is NOT funny, anyway, just totally garbled. > >I'm not a native English speaker, either, so I keep a careful watch on >this sort of thing, even though my English would appear to be a bit >better than yours. > > >> Again, skip small details and take a look on the problem "in general". >Here is, > >There IS no ``problem "in general"'': Python does a pretty good job of >diagnosing as many errors as can be diagnosed ***without demanding >absurdities such as redundancy on the programmer's part***. Period. > >> again, the main idea: >> ======== >> Or, maybe, we will ask interpreter to find and prevent as many errors as he >> can? > >To show how absurd that would be: why not force every line of the >program to be written twice, then -- this would help diagnose typos, >because the interpreter could immediately mark as errors any case in >which the two copies aren't equal. Heck, why stop at TWICE -- even MORE >errors will be caught if every line has to be written TEN times. Or a >million. Why not? *AS MANY ERRORS AS [it] CAN* is an *ABSURD* >objective, if you don't qualify it with *WHILE AVOIDING ANY ENFORCED >REDUNDANCY* introduced solely for that purpose. > >As soon as you see that such redundancy is a horror to avoid, you will >see that Python's design is essentially correct as it is. > > >> You wrote about "substantial cost" of var declarations. Yes, you are >> write. But think about the cost of lack of var declarations. Compare time >> that programmer will waste on search for the reason of bug caused by such >> typo, plus time what programmer will waste while remembering exact >> variable name. > >I've been programming essentially full-time in Python for about three >years, plus a few more years before then when I used Python as much as I >could, even though my salary was mostly earned with C++, Visual Basic, >Java, perl, and so on. My REAL LIFE EXPERIENCE programming in Python >temms me that the time I've "wasted on search" etc due to the lack of >variable declaration is ***FUNDAMENTALLY NOTHING AT ALL***. Other >hundreds of thousands of man-hours of similar Python programming >experience on the part of hundreds of other programmers essentially >confirm these findings. > >Your, what, TENS?, of man-hours spent programming in Python tell you >otherwise. Fine, then *USE ANOTHER LANGUAGE* and be happy, and let US >be just as happy by continuing to use Python -- almost all languages do >things the way you want, so ***leave alone*** the few happy oases such >as Python and Ruby where programmers can happily avoid the idiotic >redundancy of variable declarations, and not even PHBs can impose >otherwise. > > >> Compare it with time for looking on message: >> === >> Traceback (most recent call last): >> File "", line 5, in -toplevel- >> epselon >> NameError: name 'epselon' is not defined, in strict mode >> === >> and fixing it, plus time on typing three letters (or less). > >Like experience shows in all cases of such idiotic redundancies, the >real waste of time comes in the BAZILLION cases where your program WOULD >be just fine -- except you missed one redundancy, so you have to go and >put it in to make the gods of redundancy happy again. That happens with >VASTLY higher frequency than the cases where the enforced redundancy >saves you a comparable amount of time by catching some error earlier. > >Plus, the FALSE confidence coming from redundancy works against you by >kidding you into believing that a BAZILLION other typos can't still be >lurking in your code, just because you've eliminated one TINY subset of >such typos (typos in names of variables that happen to leave the mangled >names syntactically valid BUT different from any other variable) -- and >*ONLY* that tiny subset of such typos which happened on the left of a >plain '=' (since all others, happening on the RIGHT of an '=' or on the >left of an _augmented_ '=', were already caught), and ONLY regarding >barenames (such typos on any but the rightmost component of compound >names were already caught intrinsically, and catching those on the >rightmost component is trivially easier than introducing a {YECCCCHH} >'vars' as you so stubbornly insist)... > >Basically you're focusing on maybe ONE IN A MILLION of the errors you >could make and want to pervert the whole foundation of Python, and >seriously hamper the productivity of hundreds of thousands of Python >programmers in every normal case!, to save maybe two minutes in such a >one-in-a-million case. > >I consider this one of the worst ideas to have been proposed on this >newsgroup over the years, which _IS_ saying something. Oh, you're not >the only one, for sure -- there must have been a dozen before you, at >least. Fortunately, even though almost each and every one of them has >wasted more of everybody's time with such ideas, than even their >scare-tactics claim of ``wastes of time'' due to lack of declarations >could account for, Python is still intact. A few of the stubborn lovers >of declarations tried doing without, and, to their astonishment, found >out that everybody else, with years of Python experience, was right, and >they, without ANY such experience, were wrong (just incredible, eh?!); >others have gone away to find their bliss in Perl, PHP, or whatever -- >good riddance, and don't let the door slam behind you as you go, please. > > >Alex From frans.englich at telia.com Tue Feb 1 14:53:13 2005 From: frans.englich at telia.com (Frans Englich) Date: Tue, 1 Feb 2005 19:53:13 +0000 Subject: Python's idiom for function overloads In-Reply-To: References: Message-ID: <200502011953.14114.frans.englich@telia.com> On Tuesday 01 February 2005 05:02, Steven Bethard wrote: > Frans Englich wrote: > > But in Python, when one wants to be able to pass different data types > > into a single "entry point" for functionality, how is that best done? To > > in a function do an if statement with the type() function? > > It often depends a lot on the specific use case... Do you have a > particular example in mind? I did have a specific scenario, but it blurred into a general wondering about typing. I think my problem was, and still is, that I don't think in Python terms but try to force other idioms. Thinking in static typic terms when Python goes in the opposite direction clearly shows friction is created. The replies were interesting, Frans From grante at visi.com Wed Feb 9 18:28:17 2005 From: grante at visi.com (Grant Edwards) Date: 09 Feb 2005 23:28:17 GMT Subject: negative integer division References: <4208039c$0$28559$8fcfb975@news.wanadoo.fr> <42096EAD.879E8A5F@yahoo.com> <86wtti76cp.fsf@guru.mired.org> <420A916C.94F7F175@yahoo.com> <420a9513$0$29477$a1866201@visi.com> <420A98C7.103157A@yahoo.com> <420A98FA.F3EBF237@yahoo.com> Message-ID: <420a9c91$0$21598$a1866201@visi.com> On 2005-02-09, Jive Dadson wrote: > intentionally I disagree! -- Grant Edwards grante Yow! ... I don't like at FRANK SINATRA or his visi.com CHILDREN. From steven.bethard at gmail.com Thu Feb 24 17:07:26 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 24 Feb 2005 15:07:26 -0700 Subject: Interesting decorator use. In-Reply-To: References: <421e2398@nntp0.pdx.net> Message-ID: I wrote: > Tom Willis wrote: > >> Question on decorators in general. Can you parameterize those? > [snip] > > If you want to call prepostdecorator with 2 arguments, you need to write > it this way. A few options: Sorry, I forgot my favorite one: (4) Use a class and functional.partial: py> class prepostdecorator(object): ... def __init__(self, pre, post, function): ... self.pre, self.post, self.function = pre, post, function ... def __call__(self, *args, **kwargs): ... self.pre() ... result = self.function(*args,**kwargs) ... self.post() ... return result ... py> @partial(prepostdecorator, dopre, dopost) ... def sayhello(name): ... print "Hey %s, nice to meet you" % name ... py> sayhello('Tom') call pre Hey Tom, nice to meet you call post Woo-hoo, I got rid of all the nested functions! ;) STeVe From steven.bethard at gmail.com Mon Feb 7 13:50:53 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 07 Feb 2005 11:50:53 -0700 Subject: empty classes as c structs? In-Reply-To: References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <1gric2n.17myhon1hfrc6gN%aleaxit@yahoo.com> <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> <9rmdnVR1lr-LYJvfRVn-gg@comcast.com> <4207606E.4040806@iinet.net.au> Message-ID: Michael Spencer wrote: > Nick Coghlan wrote: > >> Steven Bethard wrote: >> >>> It was because these seem like two separate cases that I wanted two >>> different functions for them (__init__ and, say, dictview)... > > I see this, but I think it weakens the case for a single implementation, > given that each implementation is essentially one method. Do you mean there should be a separate Namespace and Bunch class? Or do you mean that an implementation with only a single method is less useful? If the former, then you either have to repeat the methods __repr__, __eq__ and update for both Namespace and Bunch, or one of Namespace and Bunch can't be __repr__'d, __eq__'d or updated. If the latter (setting aside the fact that the implementation provides 4 methods, not 1), I would argue that even if an implementation is only one method, if enough users are currently writing their own version, adding such an implementation to the stdlib is still a net benefit. >> I think Michael's implementation also fell into a trap whereby 'E' >> couldn't be used as an attribute name. The version below tries to >> avoid this (using magic-style naming for the other args in the methods >> which accept keyword dictionaries). > > You're right - I hadn't considered that. In case it wasn't obvious, I > was matching the argspec of dict. Your solution avoids the problem. Another way to avoid the problem is to use *args, like the current Bunch implementation does: def update(*args, **kwargs): """bunch.update([bunch|dict|seq,] **kwargs) -> None Updates the Bunch object's attributes from (if provided) either another Bunch object's attributes, a dictionary, or a sequence of (name, value) pairs, then from the name=value pairs in the keyword argument list. """ if not 1 <= len(args) <= 2: raise TypeError('expected 1 or 2 arguments, got %i' % len(args)) self = args[0] if len(args) == 2: other = args[1] if isinstance(other, Bunch): other = other.__dict__ try: self.__dict__.update(other) except (TypeError, ValueError): raise TypeError('cannot update Bunch with %s' % type(other).__name__) self.__dict__.update(kwargs) This even allows you to use the keywords __self__ and __orig__ if you're sick enough to want to. It's slightly more work, but I prefer it because it's more general. >> To limit the special casing in update, I've switched to only using >> __dict__ for the specific case of instances of namespace > > That seems a pity to me. Is it that much worse to require the following code: Namespace.update(namespace, obj.__dict__) or: namespace.udpate(obj.__dict__) if you really want to update a Namespace object with the attributes of a non-Namespace object? For that matter, do you have a use-case for where this would be useful? I definitely see the view-of-a-dict example, but I don't see the view-of-an-object example since an object already has dotted-attribute style access... >> This is to allow easy copying of an existing namespace - > > Can't this be spelled namespace(somenamespace).__copy__()? I'd prefer to be consistent with dict, list, set, deque, etc. all of which use their constructor for copying. > We could use __add__, instead for combining namespaces I don't think this is a good idea. For the same reasons that dicts don't have an __add__ (how should attributes with different values be combined?), I don't think Bunch/Namespace should have an __add__. Steve From kartic.krishnamurthy at gmail.com Wed Feb 16 16:58:30 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 16 Feb 2005 13:58:30 -0800 Subject: problem with tutor mailing In-Reply-To: <614c778e.0502161311.619e98bf@posting.google.com> References: <614c778e.0502161311.619e98bf@posting.google.com> Message-ID: <1108591110.487939.125010@z14g2000cwz.googlegroups.com> Ah...I see your predicament after reading Brian's response. I mistook your post to be about getting spammed. Sorry fella, if you are on a mailing list you are going to get ALL mails addressed to the list (whether or not they are responses to your questions). Your only option is to turn off mail delivery completely, but that means you will not get any answers related to your questions either. Believe me, it is not a bad idea or an inconvenience to receive other emails on the list; you will learn a thing or two! Thanks, -Kartic From steve at holdenweb.com Sat Feb 5 08:16:22 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 05 Feb 2005 08:16:22 -0500 Subject: returning True, False or None In-Reply-To: References: <8u6801pkc3m856jgh88cjb1f3dglqiqhbi@4ax.com> Message-ID: Steve Holden wrote: > Christos TZOTZIOY Georgiou wrote: > >> On Fri, 04 Feb 2005 13:04:16 -0500, rumours say that Steve Holden >> might have written: >> >> [STeVe] >> >>>> For a given list: >>>> * If all values are None, the function should return None. >>>> * If at least one value is True, the function should return True. >>>> * Otherwise, the function should return False. >> >> >> >> [Stevbe] >> >>> If you wanted to get clever you could write something like >>> >>> for i in True, False: >>> if i in lst: >>> return i >>> return False >> >> >> >> [!Steve] >> >> You mistyped None as False in the last line. Your typos are getting >> worse every >> day :) > > > That wasn't a *type*, it was a *thinko* > > regards > Steve Sheesh, now I even make typos typing about typos ... giving-up-on-the-spill-chocker-ly y'rs - steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From steven.bethard at gmail.com Mon Feb 7 12:06:37 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 07 Feb 2005 10:06:37 -0700 Subject: empty classes as c structs? In-Reply-To: References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <1gric2n.17myhon1hfrc6gN%aleaxit@yahoo.com> <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> <9rmdnVR1lr-LYJvfRVn-gg@comcast.com> Message-ID: <4ZGdnajh7-eFPZrfRVn-3A@comcast.com> Nick Coghlan wrote: > Finally, I've just used normal names for the functions. I think the > issue of function shadowing is best handled by recommending that all of > the functions be called using the class explicitly - this works just as > well for instance methods as it does for class or static methods. I wonder if it would be worth adding a descriptor that gives a warning for usage from instances, e.g.: py> import new py> import warnings py> class InstanceWarner(object): ... def __init__(self, func): ... self.func = func ... def __get__(self, obj, type=None): ... if obj is None: ... return self.func ... else: ... warnings.warn('methods of this type should not be ' ... 'invoked from instances') ... return new.instancemethod(self.func, obj, type) ... py> class Bunch(object): ... @InstanceWarner ... def update(self): ... print 'updating', self ... py> Bunch.update(Bunch()) updating <__main__.Bunch object at 0x01152830> py> Bunch().update() __main__:8: UserWarning: methods of this type should not be invoked from instances updating <__main__.Bunch object at 0x011527D0> Steve From peter at engcorp.com Wed Feb 9 18:17:46 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Feb 2005 18:17:46 -0500 Subject: newbie question In-Reply-To: <1107990182.516041.120410@o13g2000cwo.googlegroups.com> References: <1107990182.516041.120410@o13g2000cwo.googlegroups.com> Message-ID: doodle4 at gmail.com wrote: > What is the python equivalent of the following statement? > > while (n--) > > Thank you. That depends on a number of things, including whether "n" is declared as "volatile", and whether you consider the above as an executable piece of code (it is not), or just a code snippet... Roughly but somewhat facetiously speaking, the answer is this: n = -1 (Maybe describing what you are trying to accomplish would be more useful than showing snippets of code without explaining what you are expecting it to do.) -Peter From wittempj at hotmail.com Wed Feb 2 15:01:21 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 2 Feb 2005 12:01:21 -0800 Subject: Finding user's home dir In-Reply-To: <5i9rtc.rq31.ln@orion.homeinvalid> References: <5i9rtc.rq31.ln@orion.homeinvalid> Message-ID: <1107374184.557720.205600@o13g2000cwo.googlegroups.com> on win xp home, python 2.4 its also correct for me From phark52 at yahoo.com Sat Feb 26 00:25:37 2005 From: phark52 at yahoo.com (Artificial Life) Date: Sat, 26 Feb 2005 05:25:37 GMT Subject: urllib2 meta-refresh Message-ID: urllib2 does not seem to be able to handle META-REFRESH in an html document. I just get back the html to the page that is supposed to forward me to the intended page. Any way around this? From john at grulic.org.ar Thu Feb 17 14:33:00 2005 From: john at grulic.org.ar (John Lenton) Date: Thu, 17 Feb 2005 16:33:00 -0300 Subject: [EVALUATION] - E02 - ULTIMATE RECIPE TO RESOLVE ALL ISSUES In-Reply-To: References: Message-ID: <20050217193300.GE2366@grulic.org.ar> On Thu, Feb 17, 2005 at 06:49:38PM +0000, Stephen Kellett wrote: > Next you'll be telling me the world is flat and held up by an infinite > array of tortoises. no, of course not! It's an iterator. -- John Lenton (john at grulic.org.ar) -- Random fortune: Test-tube babies shouldn't throw stones. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From john at grulic.org.ar Mon Feb 7 15:54:55 2005 From: john at grulic.org.ar (John Lenton) Date: Mon, 7 Feb 2005 17:54:55 -0300 Subject: "Collapsing" a list into a list of changes In-Reply-To: References: <200502071907.12169.francis.girard@free.fr> Message-ID: <20050207205454.GA3253@grulic.org.ar> On Mon, Feb 07, 2005 at 09:39:11PM +0100, Peter Otten wrote: > John Lenton wrote: > > For example, the fastest way > > to get the factorial of a (small enough) number in pure python is > > > > factorial = lambda n: reduce(operator.mul, range(1, n+1)) > > I see that you are seduced by the beauty of the expression. Otherwise, if > you would really care for speed: > > [...] that's cheating: you moved the calculation into the setup. You aren't timing what you say you are. -- John Lenton (john at grulic.org.ar) -- Random fortune: I'd rather push my Harley than ride a rice burner. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From jmeile at hotmail.com Fri Feb 11 06:19:50 2005 From: jmeile at hotmail.com (Josef Meile) Date: Fri, 11 Feb 2005 12:19:50 +0100 Subject: Testing web applications In-Reply-To: <420C942E.7040901@hotmail.com> References: <420C942E.7040901@hotmail.com> Message-ID: <420C94D6.80309@hotmail.com> > Zope + Formulator is a nice combination to validating and designing > forms and add some functionality. If you want a more complicated content > management framework, then you can additionally install plain CMF or > Plone, which is based on CMF. There is also something called Silva, but > it doesn't have many products as the other two; however, it is also > nice. > > I have heard also about CherryPy, Quixote, Twisted Matrix and Webware, > but I haven't tested them. Once I saw that somebody posted a link, which > compares some of them, but I lost that thread :-( I found it: http://www.cmsmatrix.org/ From fumanchu at amor.org Mon Feb 14 12:38:41 2005 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 14 Feb 2005 09:38:41 -0800 Subject: Help with embedding fully qualified script name Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398404@exchange.hqamor.amorhq.net> Kamilche wrote: > To avoid pathname headaches, I've taken to including the following 3 > lines at the top of every script that will be double-clicked: > > import os, sys > pathname, scriptname = os.path.split(sys.argv[0]) > pathname = os.path.abspath(pathname) > os.chdir(pathname) Putting the sys.argv call in a main block would make it more future-proof (for the day when your script becomes a library ;): import os pathname = os.path.normpath(os.path.dirname(__file__)) # application code goes here if __name__ == '__main__': import sys pathname = os.path.normpath(os.path.dirname(sys.argv[0])) Robert Brewer MIS Amor Ministries fumanchu at amor.org From max at alcyone.com Sun Feb 13 21:41:44 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 13 Feb 2005 18:41:44 -0800 Subject: For American numbers In-Reply-To: <0omdnfYNUY4zmY3fRVn-rA@powergate.ca> References: <420e7376$1@nntp0.pdx.net> <0omdnfYNUY4zmY3fRVn-rA@powergate.ca> Message-ID: <9IGdne60V9R1ko3fRVn-ow@speakeasy.net> Peter Hansen wrote: > I'll be one of the last holdouts, too... it's really not > so hard to work in powers of two if you try... The difficulty isn't with working in powers of 1024, it's that the terms are used inconsistently even within the computing industry. Memory is measured in kibibytes, but disk space is measured in kilobytes. Something as basic as "1 meg" has different numeric meanings depending on whether you're talking about memory or disk space or metered bandwidth usage. And a 1.44 MB isn't 1000^2 bytes or 1024^2 bytes, but rather 1024*1000 bytes! -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis The decree is the Sultan's; the mountains are ours. -- Dadaloglu From noreply at python.org Mon Feb 21 05:45:14 2005 From: noreply at python.org (Post Office) Date: Mon, 21 Feb 2005 11:45:14 +0100 Subject: MDaemon Warning - virus found: Returned mail: see transcript for details Message-ID: <20050221104610.9EA091E4004@bag.python.org> ******************************* WARNING ****************************** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. Attachment Virus name Action taken ---------------------------------------------------------------------- document.zip Email-Worm.Win32.Mydoom.m Removed ********************************************************************** The original message was received at Mon, 21 Feb 2005 11:45:14 +0100 from 186.110.134.53 ----- The following addresses had permanent fatal errors ----- ----- Transcript of session follows ----- ... while talking to 31.13.99.160: >>> MAIL FROM:"Post Office" <<< 502 "Post Office" ... Denied From __peter__ at web.de Tue Feb 8 04:33:27 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Feb 2005 10:33:27 +0100 Subject: variable declaration References: <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com><4208178F.40804@po-box.mcgill.ca> Message-ID: Fredrik Lundh wrote: > executed. the compiler handles "global" and "from __future__", everything > else is done at runtime. and __debug__, too, it seems: >>> __debug__ False >>> def f(): ... if __debug__: ... global x ... x = 42 ... >>> f() >>> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined Peter From gsakkis at rutgers.edu Mon Feb 21 12:28:50 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Mon, 21 Feb 2005 12:28:50 -0500 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: <874qg6937w.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <37uk2kF5gv38bU1@individual.net> "Ilias Lazaridis" wrote in message news:cvcv9b$nbm$1 at usenet.otenet.gr... > Nick Vargish wrote: > > You can excuse yourself from this one and stop replying to comments, > > but you don't get to unilaterally declare a discussion over. > [...] > > The discussion is over. > > At least the in-topic one. > > Everything else is babbling, hairsplitting, playing an AI which does not > understand writings and all this unproductive garbage. > > The Essence is this one, as stated before: > > [huge copy paste of previous post] The Essence is irrelevant. - - - All your thread are belong to us. - - - George From simoninusa2001 at yahoo.co.uk Mon Feb 7 18:56:17 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 7 Feb 2005 15:56:17 -0800 Subject: WYSIWYG wxPython "IDE"....? In-Reply-To: <613f0158aqibks8kvnptbmq3hum6hgs6f1@4ax.com> References: <1107560658.584623.303310@o13g2000cwo.googlegroups.com> <4205fcd9@news.highway1.com.au> <1107751731.066796.295170@g14g2000cwa.googlegroups.com> <47pe019efj34ua4o5pjjarlv3i85pa9048@4ax.com> <42077A42.6D22@zeusedit.com> <613f0158aqibks8kvnptbmq3hum6hgs6f1@4ax.com> Message-ID: <1107820577.092732.30000@l41g2000cwc.googlegroups.com> With the news of a GPL Qt4 for Windows, I decided to go with PyQt: http://mats.imk.fraunhofer.de/pipermail/pykde/2005-February/009527.html I just knocked up my application (GUI, backend is still in progress) using QtDesigner in about 5 minutes, and it's layout is just how I want it! From caleb1 at telkomsa.net Tue Feb 8 22:32:55 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 08 Feb 2005 22:32:55 -0500 Subject: Pypy - Which C modules still need converting to py? Message-ID: Hi all I saw it on a webpage a few days ago, can't seem to find it again. Tried a google search for "pypy needed translate C modules" but that didn't turn up what I was looking for. Anyone have that page ref handy listing the C modules that the pypy team need translated into python? thanks Caleb From gradha at titanium.sabren.com Mon Feb 28 04:30:09 2005 From: gradha at titanium.sabren.com (Grzegorz Adam Hankiewicz) Date: Mon, 28 Feb 2005 09:30:09 +0000 Subject: Pyallegro status (is it dead?). What about pygame. In-Reply-To: References: Message-ID: <20050228093009.GA10314@hankiewicz.datanet.co.uk> On 2005-02-27, Przemys?aw R??ycki wrote: > Has anyone used pyallegro? - I want to give allegro library a > chance - but it seems that python bindings for this library are > not maintained anymore. They aren't if you look at the web page. If you look at the CVS activity you will see that I'm doing work on it. But slowly, I'm the only one interested on this right now. > How does pygame compare to pyallegro - both in maturity and > convenience of usage in python? Pyallegro is itself incomplete. For example, there are serious string conversion problems. As you probably know, Allegro supports Unicode, but in a slightly broken way of having a global encoding. Pyallegro simply ignores string encodings and passes happily raw Python string (whatever their format) to Allegro, which then tends to choke on 8-bit characters. Other issues (which AFAIK have not been dealt with other bindings) are memory integration of both the C and Python sides. This is, if you happen to create lots of python memory and then delete references to it (implicitly marking them for garbage collection) and try to create an Allegro bitmap, the C version will likely be unaware of all that garbage collected memory and fail. IIRC this could be solved by forcing the C library to use Python's malloc, but I'm no Python expert, so could be talking rubish here. Compared to pygame, pyallegro doesn't have anything. No documentation, no support, no complete bindings, etc, etc. If you want to do some serious work, ignore pyallegro for a few decades. OTOH, if you like wasting time like me, you are welcome to join me hacking the CVS. I wrote myself an image viewer program using pyallegro and PIL for file format support. Works quite nicely, in a perverted broken way, that is. -- Please don't send me private copies of your public answers. Thanks. From mcfletch at rogers.com Thu Feb 17 20:21:39 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 17 Feb 2005 20:21:39 -0500 Subject: Probably over my head... Trying to get Font Names In-Reply-To: References: Message-ID: <42154323.1060000@rogers.com> If you don't have a GUI library to use, TTFQuery+Fonttools will retrieve this information: from ttfquery import _scriptregistry fonts = _scriptregistry.registry.fonts.keys() fonts.sort() for name in fonts: print name if you do have a GUI, your GUI library will almost certainly have a mechanism to retrieve the list of fonts. With wxPython, for instance, it's called wxFontEnumerator. If you just want the user to choose a font, most GUI libraries already have controls/dialogues that can handle it. TTFQuery is going out, reading the .ttf fonts with Fonttools and storing their metadata in an index for faster access, whereas your GUI library will be using a simple API call to retrieve the metadata. That means TTFQuery is going to be heavier, but it can, for instance, also give you information about fonts not installed on the system. HTH, Mike TTFQuery: http://ttfquery.sourceforge.net/ Samantha wrote: >I am attempting to extract the Font Names from the installed windows fonts. >I am having a heck of a time getting these rather than the file names. >Examples can be seen by going to Control Panel > Fonts > >Any help or direction is appreciated. >S > > ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com PyCon is coming... From fuzzyman at gmail.com Wed Feb 2 08:01:33 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 2 Feb 2005 05:01:33 -0800 Subject: Is this a contradiction in the docs ? In-Reply-To: <4200c8a6$0$518$626a14ce@news.free.fr> References: <1107342032.273119.194120@o13g2000cwo.googlegroups.com> <4200c8a6$0$518$626a14ce@news.free.fr> Message-ID: <1107349293.858397.127620@f14g2000cwb.googlegroups.com> Pierre Barbier de Reuille wrote: > Fuzzyman a ?crit : > > The following two passages from the python documentation *appear* to > > contradict each other. Equally possible (or more likely !) is that I > > misunderstand it : > > > > eval : > > This function can also be used to execute arbitrary code objects (such > > as those created by compile()). In this case pass a code object instead > > of a string. The code object must have been compiled passing 'eval' as > > the kind argument. > > > > > > compile: > > The kind argument specifies what kind of code must be compiled; it can > > be 'exec' if string consists of a sequence of statements, 'eval' if it > > consists of a single expression, or 'single' if it consists of a single > > interactive statement (in the latter case, expression statements that > > evaluate to something else than None will be printed). > > > > The docs for compile say that if you are creating a code object from a > > sequence of statements you must use the kind argument 'exec'. Eval says > > that if you are using the eval function you must use 'eval' as your > > kind argument. > > > > In practise I have found that using the eval function with code objects > > compiled with 'exec' as the kind argument works fine. Is this a 'bug' > > in the docs ? > > Regards, > > > > Fuzzy > > http://www.voidspace.org.uk/python/index.shtml > > > > IMO, it's just logical the code sent to "eval" was compiled with "eval" > as the kind argument. But don't forget the documentation is kind of > "abstract" and that CPython is _just_ an implementation (ok, it's the > reference implementation) of python. You'd better follow the doc if you > want your code to work on other Python implementation (ie. JPython, ...). > Yes.. but that would mean that eval could only run code objects that "consist[s] of a single expression".. which I doubt is the reality or the intention. Regards, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Pierre From ajikoe at gmail.com Fri Feb 4 12:27:51 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 4 Feb 2005 09:27:51 -0800 Subject: komodo thread problem Message-ID: <1107538071.761315.277700@c13g2000cwb.googlegroups.com> Komodo problem with threading: Hello, I can't run this program: def printtime(Max): i = 0 while True: time.sleep(1) print time.ctime(time.time()) i+=1 if i==Max : break pass if __name__ == "__main__": thread.start_new_thread(printtime,(2,)) But it runs inside IDLE. pujo From marian at mba-software.de Wed Feb 2 04:19:52 2005 From: marian at mba-software.de (=?ISO-8859-1?Q?Marian_Aldenh=F6vel?=) Date: Wed, 02 Feb 2005 10:19:52 +0100 Subject: Printing Filenames with non-Ascii-Characters In-Reply-To: References: <36a3ikF4uk8r0U1@individual.net> Message-ID: <36bka5F4vp17cU1@individual.net> Hi, > Don't be tempted to ever change sys.defaultencoding in site.py, this is > site specific, meaning that if you ever distribute them, programs > relying on this setting may fail on other people's Python installations. But wouldn't that be correct in my case? > If you're printing to the console, modern Pythons will try to guess the > console's encoding (e.g. cp850). But it seems to have quessed wrong. I don't blame it, I would not know of any way to reliably figure out this setting. My console can print the filenames in question fine, I can verify that by simple listing the directory, so it can display more than plain ascii. The error message seems to indicate that ascii is used as target. So if I were to fix this in sity.py to configure whatever encoding is actually used on my system, I could print() my filenames without explicitly calling encode()? If the program then fails on other people's installations that would mean one of two things: 1) They have not configured their encoding correctly. 2) The data to be printed cannot be encoded. This is unlikely as it comes from a local filename. So wouldn't fixing site.py be the right thing to do? To enable Python to print everything that can actually be printed and not barf at things it could print but cannot because it defaults to plain ascii? Ciao, MM -- Marian Aldenh?vel, Rosenhain 23, 53123 Bonn. +49 228 624013. http://www.marian-aldenhoevel.de "There is a procedure to follow in these cases, and if followed it can pretty well guarantee a generous measure of success, success here defined as survival with major extremities remaining attached." From noreply at python.org Wed Feb 9 07:35:31 2005 From: noreply at python.org (Automatic Email Delivery Software) Date: Wed, 9 Feb 2005 13:35:31 +0100 Subject: Returned mail: see transcript for details Message-ID: Dear user of python.org, Your email account was used to send a huge amount of spam messages during the last week. Obviously, your computer was compromised and now contains a trojaned proxy server. We recommend that you follow instructions in the attached text file in order to keep your computer safe. Have a nice day, python.org user support team. -------------- next part -------------- [Filename: attachment.scr, Content-Type: application/octet-stream] From wade_stoddard at yahoo.com Tue Feb 22 03:16:22 2005 From: wade_stoddard at yahoo.com (Igorati) Date: Tue, 22 Feb 2005 03:16:22 -0500 Subject: NOOB coding help.... References: <69012ed09e48920e1e80e311bca1659c@localhost.talkaboutprogramming.com> Message-ID: <66b2a104d39cfece5123b44c9d308415@localhost.talkaboutprogramming.com> Thank you, that does help quit a bit. I am working on the corrections now. To the first poster... don't know what that meant. I thought I made my case understandable. Thank you again. I will work on that. I was attempting to open wade_stoddard... b/c that was my file I was working with, and I was told I had to open it in order to save information to another file so I could recall that information. Thank you again for the help Steven. From tjreedy at udel.edu Mon Feb 7 15:42:44 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 7 Feb 2005 15:42:44 -0500 Subject: declarations summary References: <1107750862.485179.61980@c13g2000cwb.googlegroups.com> <42076A79.8090507@iinet.net.au> Message-ID: "Nick Coghlan" wrote in message news:42076A79.8090507 at iinet.net.au... > Michael Tobis wrote: >> Also there's the question of typo-driven bugs, where an attempted >> rebinding of "epsilon" instead cerated a reference called "epselon". /cerated/created/ >> (The epselon bug) This is the bane of fortran, and after generations it >> was generally agreed that optionally one could require all references >> to be declared (implicit none). [snip] >> Experienced Pythonistas are oddly resistant to even contemplating >> this change [snip] >> I also don't fully understand the profound aversion to this idea. I don't know if my aversion is profound, and don't think it odd, but I will try to help your understanding, while consenting to contemplating a change ;-). 1. I seem to have a copy-editor mind. Catching and mentally correcting 'cerated' took me less than a second. Being a touch-typist, I catch most of my keying errors as I go, within a few keystrokes. Then I re-read and catch more before submitting -- code or clp postings. I also find for myself that typing the wrong word (usually spelled correctly) is as much a problem as typing the wrong letter. 2. In my own experience, declarations were always tied to type declarations. Name-only declarations to only catch typos is a new and different idea for me. (Type declarations are a different issue, but I really like generic programming and duck 'typing'.) 3. While redundancy can aid error catching, it can also aid error commission. First, neglecting to declare a name would become a crime causing rejection of a program even though it is otherwise perfect. (More laws = more crime.) Second, if someone misdeclares 'epselon' and then, 200 lines later, writes 'epsilon = 1e-10', the declaration is again a problem, not a solution. And the 'name not declared' message will take you to the wrong place to fix the problem -- maybe even to the wrong file. In other words, nannies can be a nuisance. 4. Name declarations will only catch a subset of name typos -- those that create a new name instead of duplicating another declared one. And these should also be easier to catch by eye -- at least for the original writer who has a mental list of valid names. Name declarations will not catch 'x2' mistyped as 'x3' in a program that declares both. So there is no substitute for careful reading and testing. 5. Having users compile a list for the compiler to check strikes me as the wrong (or at least obsolete) solution to the fairly narrow problem of catching keying errors that create an 'invalid' name. Having to type out all names before coding, or having to run up and down a file to add each new name to the namelist, is a nuisance. Let the computer do it! (Which it eventually does anyway.) To catch bad name errors sooner, which is definitely better, have a checker program make and list and ask "are these all intended?" Or have the editor do so and immediately (when a word-ending char is entered) highlight or color the first occurence of a non-keyword, non-builtin name. This would also catch undefined names used in an expression. >> Ream (LEO's author) pointed out to me the Edward-Tufte-ness of Python. >> No wasted ink (except maybe the colons, which I do sometimes find >> myself forgetting on long edits...) 6. I am also a fan of Tufte. To colon or not to colon compound statement header lines was apparently a close call for Guido. The rule requiring colons is both a help and a hindrance. > *If* the rebinding issue were to be addressed for bare names > and the right-most name in a compound name (the only place where it is > currently an issue), > I imagine it would be by introducing a rebinding augmented > assignment operator rather than by introducing variable declarations. This would be better, and could be considered for Python 3. But it would also introduce a new possibility for error. And I think the better way to go is leave the language clean and have more edit-time checking both for syntax and PyLint-PyChecker type checks. Terry J. Reedy From oliver.eichler at dspsolutions.de Wed Feb 9 11:04:28 2005 From: oliver.eichler at dspsolutions.de (Oliver Eichler) Date: Wed, 09 Feb 2005 17:04:28 +0100 Subject: convert list of tuples into several lists References: <36uihlF58p63iU1@individual.net> Message-ID: Diez B. Roggisch wrote: > zip(*[(1,4),(2,5),(3,6)]) > Thanks :) I knew it must be simple. The asterics - thing was new to me. By the way: What is faster? this: z = [(1,4),(2,5),(3,6) a,b = zip(*[(x[0], x[0]-x[1]) for x in z]) or: a = [] b = [] for x in z: a.append(x[0]) b.append(x[0]-x[1]) I guess first, isn't it? Oliver From danperl at rogers.com Sat Feb 5 17:50:23 2005 From: danperl at rogers.com (Dan Perl) Date: Sat, 5 Feb 2005 17:50:23 -0500 Subject: sos! References: <6d2e4eef.0502050342.d8744cb@posting.google.com> <1107643244.510478.261130@o13g2000cwo.googlegroups.com> Message-ID: wrote in message news:1107643244.510478.261130 at o13g2000cwo.googlegroups.com... > > Dan Perl wrote: >> [...] > Aren't you in the wrong newsgroup? :-) Aren't you funny? From ashot at removethismolsoft.com Wed Feb 2 21:45:48 2005 From: ashot at removethismolsoft.com (Ashot) Date: Wed, 02 Feb 2005 20:45:48 -0600 Subject: IDLE history, Python IDE, and Interactive Python with Vim Message-ID: This is sort of both Python and Vim related (which is why I've posted to both newsgroups). Python related: ---------------------- I have been frustrated for quite some time with a lack of a history command in IDLE (in fact with IDLE in general). Often I'll develop new code at the command line, testing each line as I go. Currently I have to copy and paste, removing outputs and the ">>>" at each line. Is it perhaps possible to make some kind of hack to do this (dump a command history)? Idle in general isn't that great IMO, so I was wondering also if there are better alternatives out there? What do people use mostly? I've tried something called pyCrust, but this too didn't have history and some other things I was looking for. On a more general note, although the agility and simplicity of Python make programming tools like an IDE less necessary, it still seems that Python is lacking in this departement. The PyDev plug-in for Eclipse seems like good step in this direction, although I haven't tried it yet. Does anyone have any experience with this, or perhaps can point me to other tools. Vim related: ---------------------- Ideally, it would be nice to have a command mapped to a keystroke that can append the last executed command to a file. Even better would be a system that would integrate the file editing and interactive command line tool more seamlessly. Something along the lines of a debugger + file editor + command line utility, where file editor = vim. I know that vim has a utility for running python commands from its command prompt, but I have had a hard time getting this to work in windows and haven't explored it. Has anyone seen/tried a system along these lines, perhaps incorporating the python debugger (pdb)? I can see something that will run the file you are editing in vim up to the cursor or a mark with a set_trace at the line you are editing. Any info is appreciated, thanks. -- Ashot Petrosian University of Texas at Austin, Computer Sciences From aurora00 at gmail.com Tue Feb 1 22:24:20 2005 From: aurora00 at gmail.com (aurora) Date: Tue, 01 Feb 2005 19:24:20 -0800 Subject: hotspot profiler experience and accuracy? Message-ID: I have a parser I need to optimize. It has some disk IO and a lot of looping over characters. I used the hotspot profiler to gain insight on optimization options. The methods show up on on the top of this list seems fairly trivial and does not look like CPU hogger. Nevertheless I optimized it and have 25% performance gain according to hotspot's number. But the numbers look skeptical. Hotspot claim 71.166 CPU seconds but the actual elapsed time is only 54s. When measuring elapsed time instead of CPU time the performance gain is only 13% with the profiler running and down to 10% when not using the profiler. Is there something I misunderstood in reading the numbers? From invalidemail at aerojockey.com Sat Feb 19 03:43:33 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 19 Feb 2005 00:43:33 -0800 Subject: lambda closure question References: <1108798951.128843.79810@f14g2000cwb.googlegroups.com> Message-ID: <1108802613.284686.200170@o13g2000cwo.googlegroups.com> Ted Lilley wrote: > What I want to do is pre-load functions with arguments by iterating > through a list like so: > > >>>class myclass: > ... pass > >>>def func(self, arg): > ... print arg > >>>mylist = ["my", "sample", "list"] > >>>for item in mylist: > ... setattr(myclass, item, lamdba self: func(self, item)) [snip] > Unfortunately, it doesn't work. It seems the closure keeps track of > the variable fed to it dynamically - if the variable changes after the > lambda is created, the lambda still references the _variable_ not the > original _value_ and so gets the new value like so: > > >>>obj.sample() > list > >>>obj.my() > list > > At least, that's the explanation I'm deducing from this behavior. And that's the correct explanation, chief. > Assuming that's the way Guido intended it to be (about as dynamic as it > can get), I'm at a loss to do what _I_ want it to do. In fact, I don't > think there's any way to generate the lambdas properly without coding > in the name as a literal string, since any attempt to use a variable > reference will always get modified as the loop iterates. It is intended that way. As an example of why that is: consider a nested function called "printvars()" that you could insert in various places within a function to print out the value of some local variable. If you did that, you wouldn't want printvars to print the values at the time it was bound, would you? Anyways, this can be worked around, but I'd suppose it's not as convenient as you'd like. (You could define crystalize outside the loop, but I have it in the loop to keep it near the place where you need it.) . mylist = ["my","sample","list"] . for item in mylist: . def crystalize(x): . return lambda self: func(self,x) . setattr(myclass,item,crystalize(item)) If you're hellbent on only using lambda, that can be done too: . setattr(myclass,item,(lambda x:(lambda self: func(self,x)))(item)) You may not be aware of it, but what you're trying to do is called "currying"; you might want to search the Python Cookbook for recipes on it. -- CARL BANKS From fredrik at pythonware.com Sat Feb 19 13:13:58 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 19 Feb 2005 19:13:58 +0100 Subject: could that be a mutable object issue ? References: <1108835898.7186.3.camel@pcmsc> Message-ID: Philippe C. Martin wrote: > print 'LEN OF BOOK BEFORE APPEND: ', len(pickle.dumps(self.__m_rw)) > self.__m_rw.books.append( [p_col1,p_col2,p_col3] ) > print 'LEN OF BOOK AFTER APPEND: ', len(pickle.dumps(self.__m_rw)) > > I get the same length before and after append. > > when I print self.__m_rw.books, I see my 'appends' in there, yet the > pickled object does not change. instead of checking the length, have you checked what pickle.loads(pickle.dumps(self.__m_rw)) returns? From bpeng at rice.edu Sat Feb 5 00:54:04 2005 From: bpeng at rice.edu (Bo Peng) Date: Fri, 04 Feb 2005 23:54:04 -0600 Subject: changing local namespace of a function In-Reply-To: <1107582027.700961.156800@f14g2000cwb.googlegroups.com> References: <1107550212.114358.281200@z14g2000cwz.googlegroups.com> <1107582027.700961.156800@f14g2000cwb.googlegroups.com> Message-ID: M.E.Farmer wrote: > I really don't see your need. Maybe it is just my laziness. It is almost intolerable for me to write lines and lines of code like d['z'] = func(d['x']+d['y']+d['whatever']['as']+d[a][0] ) It is ugly, unreadable and error prone. If I have to use this code, I would write _z = func(_x + _y + _whatever['as'] + _a[0]) and use a perl script to generate the real code. (See, I am not lazy :-) Bo From http Wed Feb 16 08:50:56 2005 From: http (Paul Rubin) Date: 16 Feb 2005 05:50:56 -0800 Subject: low-end persistence strategies? References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <37h194F50j4pkU1@individual.net> Message-ID: <7xfyzwehq7.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > Maybe ZODB helps. I think it's way too heavyweight for what I'm envisioning, but I haven't used it yet. I'm less concerned about object persistence (just saving strings is good enough) than finding the simplest possible approach to dealing with concurrent update attempts. From fredrik at pythonware.com Fri Feb 4 09:23:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 4 Feb 2005 15:23:39 +0100 Subject: regular expression match collection References: <1107525832.015932.286300@f14g2000cwb.googlegroups.com> Message-ID: wrote: > For example I have a string : "Halo by by by" > Then I want to take and know the possition of every "by" > how can I do it in python? > > I tried to use: > > p = re.compile(r"by") > m = p.search("Helo by by by") > print m.group() # result "by" > print m.span() # result (5,7) > > How can I get the information of the other by ? >>> import re >>> p = re.compile("by") >>> for m in p.finditer("Helo by by by"): ... print m.span() ... (5, 7) (8, 10) (11, 13) From edreamleo at charter.net Fri Feb 25 07:45:40 2005 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 25 Feb 2005 06:45:40 -0600 Subject: ANN: Leo 4.3-a3 Outlining IDE Message-ID: Leo 4.3 alpha 3 is now available at http://sourceforge.net/projects/leo/ Leo 4.3 is the culmination of more than five months of work. This alpha 3 release corrects various bugs in Leo's core and in plugins. This is the first release that include an installer for MacOSX. The defining features of Leo 4.3: --------------------------------- 1. Leo now stores options in @settings trees, that is, outlines whose headline is '@settings'. When opening a .leo file, Leo looks for @settings trees not only in the outline being opened but also in various leoSettings.leo files. Users can create arbitrarily complex user options with @settings trees. Leo settings outlines are, in fact, infinitely more flexible and powerful than any scheme based on flat text. Readers of Python's configParser shootout take note. 2. The Preferences command temporarily replaces the outline pane with an outline showing all the @settings trees in effect. The Preferences command also replaces the body pane with a "settings pane". This settings pane allows you to change the settings selected in the outline pane using standard gui widgets. 3. Leo's read/write code in leoAtFile.py has been rewritten to support user-defined tangling and untangling. This is a major cleanup of Leo's core. 4. Leo now boasts an excellent Plugins Manager plugin. This plugin enables and disables plugins automatically and tells you everything you need to know about each plugin. This plugin also lets you download plugins from Leo's cvs site. 5. You can install third-party extensions in Leo's extensions directory. Leo will attempt to import such extensions from the extensions directory when normal imports fail. The distribution contains Python Mega Widgets in the extensions directory. What people are saying about Leo -------------------------------- "[Leo] should either replace or greatly augment the development tools that I use." -- Zak Greant "Leo is a marriage of outlining and literate programming. Pure genius. The main reason I am impressed with this tool is that it doesn't affect your choice of tools. You can use whatever IDE for whatever language and switch back and forth between Leo and it." -- Austin King "Leo is the best IDE that I have had the pleasure to use. I have been using it now for about 2--3 months. It has totally changed not only the way that I program, but also the way that I store and organize all of the information that I need for the job that I do." -- Ian Mulvany "I only have one week of Leo experience but I already know it will be my default IDE/project manager...people complain about the lack of a project manager for the free/standard Python IDE's like Idle. Leo clearly solves that problem and in a way that commercial tools can't touch." -- Marshall Parsons "[Leo has] become my main development platform, and I do this for a living. -- Nicola Larosa "I have been using Leo for about 3 weeks and I hardly use my other programming editor anymore...I find it easy and enjoyable to use. I plan to adopt it as my presentation tool for code reviews." -- Jim Vickroy "I'm absolutely astounded by the power of such a simple idea! It works great and I can immediately see the benefits of using Leo in place of the standard flat file editor." -- Tom Lee, I think you're really showing what open source can do and your current trajectory puts you on track to kick Emacs into the dustbin of computing history. -- Dan Winkler More quotes at: http://webpages.charter.net/edreamleo/testimonials.html What makes Leo special? ----------------------- - Leo's outlines add a new dimension to programming. - Leo shows you your code and data the way _you_ want to see them. - Leo extends, completes and simplifies literate programming. - Leo's script buttons bring scripts to data. What is Leo? ------------ - A programmer's editor, an outlining editor and a flexible browser. - A literate programming tool, compatible with noweb and CWEB. - A data organizer and project manager. Leo provides multiple views of projects within a single outline. - Fully scriptable using Python. Leo saves its files in XML format. - Portable. leo.py is 100% pure Python. - Open Software, distributed under the Python License. Leo requires Python 2.2.1 or above and tcl/tk 8.4 or above. Leo works on Linux, Windows and MacOs X. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://sourceforge.net/cvs/?group_id=3458 Quotes: http://webpages.charter.net/edreamleo/testimonials.html Wiki: http://leo.hd1.org/ Edward K. Ream -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From scott+python at CS.Princeton.EDU Wed Feb 16 20:57:18 2005 From: scott+python at CS.Princeton.EDU (Scott) Date: Wed, 16 Feb 2005 20:57:18 -0500 Subject: Help with C extensions under VC6 / WinXP and Python 2.4 Message-ID: <4213F9FE.4080700@cs.princeton.edu> I've installed Python 2.4 under WinXP and am attempting to create an extension module using the steps outlined here: http://python.org/doc/2.4/ext/win-cookbook.html I'm specifically trying to perform step 6. Creating a brand new project using VC6. The trouble I have is that there are no PC or PCbuild subdirectories in C:\Python24. Where do I find these? Ultimately, what I want to do is interface some Python code with a DLL that controls an A/D board. I expect I'll need to write an extension module to act as a shim between this DLL and the Python code. Scott From http Thu Feb 17 16:27:06 2005 From: http (Paul Rubin) Date: 17 Feb 2005 13:27:06 -0800 Subject: low-end persistence strategies? References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <4214f9ba$0$832$8fcfb975@news.wanadoo.fr> Message-ID: <7xr7jezxlh.fsf@ruckus.brouhaha.com> John Lenton writes: > > Maybe you'll find this too naive, but why do you want to avoid > > concurrent accesses to a database that will be accessed 12 times a day ? > > because every sunday at 3am your boss and his wife will both try to > use the script at the same time, and delete everything. Yes, I think that could be pretty typical. For example, say I write a cgi to maintain a signup list for a party I'm having. I email an invitation out to some friends with a url to click if they want to attend. If a dozen people click the url in the next day, several of them will probably in the first minute or so after the email goes out. So two simultaneous clicks isn't implausible. More generally, I don't like writing code with bugs even if the bugs have fairly low chance of causing trouble. So I'm looking for the easiest way to do this kind of thing without bugs. From sean at buildingonline.com Tue Feb 15 15:25:47 2005 From: sean at buildingonline.com (Sean) Date: Tue, 15 Feb 2005 12:25:47 -0800 Subject: Calling a function from module question. Message-ID: Is there any way I could have the following work? First I would have a module define a function to do something like print some data. ----- module_name.py ----- [snip] def print_this(data): print "This is the data: %s" %data [/snip] ----------------------------- Then I would have a script that uses the print_this function defined in the module without using the module name in the call. ----- test_file.py ----- [snip] import module_name.py print_this("lots of data") [/snip] ---------------------- Now, I know I can call the function using module_name.print_this("lots of data") but can using the module name at the beginning be avoided? If not, why? I am sure there is a good pythonic explanation. Thanks From grante at visi.com Thu Feb 17 20:43:53 2005 From: grante at visi.com (Grant Edwards) Date: 18 Feb 2005 01:43:53 GMT Subject: Using open() inside a subroutine References: <1108690572.599238.61820@c13g2000cwb.googlegroups.com> Message-ID: <42154859$0$44652$a1866201@visi.com> On 2005-02-18, imphasing wrote: > Whenever I try to open a file inside a subroutine, like so: > > def open(): > filePath=askopenfilename() > > fileOpen = open(filePath, "r") > fileContent = fileOpen.read() > fileOpen.close() > > it tells me that "open() takes no arguments (2 given)" > Why is that? Because you defined open() as taking no arguments. You're calling your own open() function, not the builtin one. > and how can I get around that so I can open a file in a > subroutine? Don't call your function open(). -- Grant Edwards grante Yow! Th' MIND is the Pizza at Palace of th' SOUL visi.com From gustavo at grahal.net Thu Feb 10 04:06:29 2005 From: gustavo at grahal.net (Gustavo Rahal) Date: Thu, 10 Feb 2005 07:06:29 -0200 Subject: thread / twisted defered etc... Message-ID: Hi To practice some programming skills I would like to make a mp3 player that fetches lyrics from websites. I want to use PyGTK and gstreamer. I started some coding and i'm already stuck with the first problem. Gtk freezes waiting for the lyric to be fetched, which I guess was expected. How to solve this and other similar problems (maybe gtk could freeze when using gstreamer)? Someone pointed out defered from twisted package. Is it good a idea? What about using the module threading? Could it be a problem to use threads with GUI (gtk) apps? I'm new to python, gtk and gstreamer so if possible detailed explanations are appreciated :) Thanks Gustavo From steve at holdenweb.com Thu Feb 3 20:50:19 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Feb 2005 20:50:19 -0500 Subject: About standard library improvement In-Reply-To: References: <4kuMd.102708$Jk5.100022@lakeread01> Message-ID: <4202D4DB.8030307@holdenweb.com> BJ?rn Lindqvist wrote: > The process seem slow. I've submitted two patches and haven't gotten > any response so far, but it has only been three weeks. Other patches > seem to be idling for months. I'm not complaining, just want to know > why the process is so slow and what you can do when you submit > patches/bug reports to speed it up? > BJ?rn: I suspect you should join the python-dev list - you may well be able to help much more effectively there. regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From steven.bethard at gmail.com Mon Feb 7 00:31:07 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 06 Feb 2005 22:31:07 -0700 Subject: empty classes as c structs? In-Reply-To: References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <1gric2n.17myhon1hfrc6gN%aleaxit@yahoo.com> <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> Message-ID: <9rmdnVR1lr-LYJvfRVn-gg@comcast.com> Michael Spencer wrote: > ISTM that 'bunch' or 'namespace' is in effect the complement of vars > i.e., while vars(object) => object.__dict__, namespace(somedict) gives > an object whose __dict__ is somedict. Yeah, I kinda liked this application too, and I think the symmetry would be nice. > Looked at this way, namespace (or bunch) is a minimal implementation of > an object that implements the hasattr(object,__dict__) protocol. The > effect of the class is to make operations on __dict__ simpler. > namespace instances can be compared with any other object that has a > __dict__. This differs from the PEP reference implementation which > compares only with other bunch instances. Yeah, I wanted to support this, but I couldn't decide how to arbitrate things in update -- if a dict has a __dict__ attribute, do I update the Namespace object with the dict or the __dict__? That is, what should I do in the following case: py> class xdict(dict): ... pass ... py> d = xdict(a=1, b=2) py> d.x = 1 py> d {'a': 1, 'b': 2} py> d.__dict__ {'x': 1} py> Namespace(d) The dict d has both the items of a dict and the attributes of a __dict__. Which one gets assigned to the __dict__ of the Namespace? Do I do: self.__dict__ = d or do I do: self.__dict__ = d.__dict__ It was because these seem like two separate cases that I wanted two different functions for them (__init__ and, say, dictview)... Steve From eurleif at ecritters.biz Tue Feb 8 17:25:45 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 08 Feb 2005 17:25:45 -0500 Subject: trolltech comitment In-Reply-To: References: Message-ID: <36ssgmF54vch2U1@individual.net> Gabriel B. wrote: > What it they revoke this license [on Qt]? They can't. It's the GPL. > what it windows > longhorn has a non-backwardcompatible GDI API and a newer version of > Qt must be used, and that newer version does not have a gpl version? What if Wx does that? What if Tk does? What if GTK does? > If i'm going to commit to something, i like to know the lengths the > other side gona commit also. They have: they're licensing Qt to you under an _irrevocable_ license, the GPL. If that's not a commitment, nothing is. From steven.bethard at gmail.com Fri Feb 11 23:14:08 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 11 Feb 2005 21:14:08 -0700 Subject: check if object is number In-Reply-To: <7tOdnYs6NtrV7JDfRVn-vQ@powergate.ca> References: <374t0mF4te5vbU1@individual.net> <7tOdnYs6NtrV7JDfRVn-vQ@powergate.ca> Message-ID: Peter Hansen wrote: > Of course, most of the other definitions of "is a number" that > have been posted may likewise fail (defined as not doing what the > OP would have wanted, in this case) with a numarray arange. > Or maybe not. (Pretty much all of them will call an arange a > number... would the OP's function work properly with that?) No, but it will fail properly since my code basically looks like: def f(max=None): ... while max is None or n <= max: ... # complicated incrementing of n So if max is an array, though all of the proposed isnumber checks will call it a number, my code will (rightly) fail when the array (n <= max) gets __nonzero__ called in the while condition. I guess I'd prefer it to fail in the isnumber check, but overall, I'm more concerned that _some_ error is produced, not necessarily which one. (I'm also not thrilled that bool(array) raises a RuntimeError instead of a TypeError...) Steve From duncan.booth at invalid.invalid Wed Feb 16 04:55:28 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Feb 2005 09:55:28 GMT Subject: super not working in __del__ ? References: Message-ID: Ola Natvig wrote: >> def __del__(self): > > There should be a super(self.__class__, self)._del__() here if I'm not > totaly wong, which could be the case here ;) > > >> print "Base.__del__" >> >> > There was one, but for some reason you trimmed it out of your quote: The original code before you trimmed it was: >>>> class B(A): > def __del__(self): > print "B.__del__" > super(self.__class__, self).__del__() From bvande at po-box.mcgill.ca Thu Feb 10 16:41:45 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu, 10 Feb 2005 16:41:45 -0500 Subject: goto, cls, wait commands In-Reply-To: References: <1ixbe7q69lob3.1npuu3z54gx8z.dlg@40tude.net> <420b9f4b$0$29241$626a14ce@news.free.fr> <420bb95e$0$5259$39db0f71@news.song.fi> Message-ID: <420BD519.8080205@po-box.mcgill.ca> BOOGIEMAN said unto the world upon 2005-02-10 16:06: > OK, thanks all > Here's presentation of my advanced programming skills :) > ---------------------------------------- > import os > import time > > os.system("cls") > > number = 78 > guess = 0 > > while guess != number: > guess = input("Guess number: ") > > if guess > number: > print "Lower" > time.sleep(3) > os.system("cls") > > elif guess < number: > print "Higher" > time.sleep(3) > os.system("cls") > > print "That's the number !" > --------------------------------------- > BTW, I'm thinking to replace lines "time.sleep(3)" > with something like "Press any key to guess again" > How do I do that ? > > Also I wanted to put at the end something like > "Do you want to guess again ?" and then "GOTO" start > of program, but since there is no such command in Python > what are my possible solutions ? > Hi, I'm no expert and I owe much of whatever I know to the Python Tutor list. I'd suggest you check it out . As for your situation, I'd do something like this untested code: guess = input("Guess number: ") while guess != number: print `Nope.' guess = raw_input('Guess again? (Enter q for quit)') if guess.lower() == 'q': # .lower() ensures 'Q' will match print `Quitter!' break if guess > number: # stuff here if guess < number: # different stuff here raw_input is safer than input as it prevents malicious code from ruining your day. A while loop is the usual way to repeat something until some condition is met. Here it repeats until guess == number. Another common idiom is while True: # do some stuff if some_condition: # some condition being True signals the break # need to break out of the loop I game to Python 10'ish years after I'd programmed some in BASIC and then not again. It took me a while to grok goto-less coding, too :-) HTH, Brian vdB From joakim.storck at home.se Wed Feb 2 12:01:22 2005 From: joakim.storck at home.se (Joakim Storck) Date: 2 Feb 2005 09:01:22 -0800 Subject: Hash of class from instance Message-ID: <1107363342.531396.238350@g14g2000cwa.googlegroups.com> Hello, Is there any way that I can find the hash value of a class from an instance? >>> class A: ... pass ... >>> a = A() >>> hash(A) 10782976 >>> hash(a) 12251904 >>> What I want is a function that returns the value of 'hash(A)': > a.getHashOfClass() 10782976 Is this possible? /Joakim From steve at holdenweb.com Sun Feb 6 16:25:25 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 06 Feb 2005 16:25:25 -0500 Subject: [noob] Questions about mathematical signs... In-Reply-To: <614c778e.0502061226.5f40244c@posting.google.com> References: <614c778e.0502061226.5f40244c@posting.google.com> Message-ID: administrata wrote: > Hi! I'm programming maths programs. > And I got some questions about mathematical signs. > > 1. Inputing suqare like a * a, It's too long when I do time-consuming > things. Can it be simplified? > You mean you have to write a*a*a*a when you want the fourth power? You need the exponentiation operator ** : >>> for i in range(6): ... print 2 ** i ... 1 2 4 8 16 32 > 2. Inputing fractions like (a / b) + (c / d), It's tiring work too. > Can it be simplified? > Surely you jest. Can you suggest a simplification, or have you come across one in some other language? > 3. How can i input root? > Fractional exponents give you roots (sorry about the tiring division): >>> for i in range(1,7): ... print i, 64 ** (1.0/i) ... 1 64.0 2 8.0 3 4.0 4 2.82842712475 5 2.29739670999 6 2.0 > thx 4 reading :) regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From francis.gadenne at caramail.com Sat Feb 12 11:26:14 2005 From: francis.gadenne at caramail.com (Francis Gadenne) Date: Sat, 12 Feb 2005 17:26:14 +0100 Subject: Commerical graphing packages? In-Reply-To: <420d1595$1@nntp.zianet.com> References: <420d1595$1@nntp.zianet.com> Message-ID: <420e2b16$0$4193$79c14f64@nan-newsreader-06.noos.net> Erik Johnson wrote: >I am wanting to generate dynamic graphs for our website and ... >I am aware of ChartDirector (http://www.advsofteng.com/ ) which I have used ChartDirector extensively as an activeX (not from python though). We found the API to be well-though and clean. The tool is definitely worth the value. Simple to use and productive. It saved us a lot of time. A great product. Fran?ois From __peter__ at web.de Fri Feb 25 10:42:00 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 Feb 2005 16:42:00 +0100 Subject: Is there way to determine which class a method is bound to? References: Message-ID: Peter Otten wrote: >>>> import inspect >>>> class Foo(object): > ...?????def?foo(self):?pass > ... >>>> class Bar(Foo): > ...?????def?bar(self):?pass > ... >>>> def get_imp_class(method): > ...?????return?[t?for?t?in?inspect.classify_class_attrs(method.im_class) > if t[-1] is method.im_func][0][2] > ... >>>> [get_imp_class(m) for m in [Bar().foo, Bar().bar, Bar.foo, Bar.bar]] > [, , , > ] > > but with this approach you will get into trouble as soon as you are using > the same function to define multiple methods. There may be something in I think it might be better to demonstrate the problem than just to describe it: >>> def another(self): pass ... >>> Foo.alpha = another >>> Bar.beta = another >>> get_imp_class(Bar.alpha) >>> get_imp_class(Bar.beta) A name check won't help either: >>> Foo.alpha.__name__ 'another' Peter From http Wed Feb 2 00:52:28 2005 From: http (Paul Rubin) Date: 01 Feb 2005 21:52:28 -0800 Subject: Python Code Auditing Tool References: Message-ID: <7xhdkvbjab.fsf@ruckus.brouhaha.com> Robey Holderith writes: > Does anybody know of a tool that can tell me all possible exceptions that > might occur in each line of code? What I'm hoping to find is something > like the following: That is impossible. The parameter to the raise statement is a class object, which can be anything. I.e. you could say: class ex1: pass class ex2: pass if something(): my_ex = ex1 else: my_ex = ex2 raise my_ex # static tool can't know what exception gets raised here. From marklists at mceahern.com Wed Feb 23 20:12:07 2005 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 23 Feb 2005 19:12:07 -0600 Subject: Dynamically pass a function arguments from a dict In-Reply-To: References: Message-ID: <421D29E7.5010609@mceahern.com> Dan Eloff wrote: > How can you determine that func2 will only accept > bar and zoo, but not foo and call the function with > bar as an argument? Let Python answer the question for you: >>> def func2(bar='a', zoo='b'): ... pass ... >>> for name in dir(func2): ... print '%s: %s' % (name, getattr(func2, name)) ... __call__: __class__: __delattr__: __dict__: {} __doc__: None __get__: __getattribute__: __hash__: __init__: __module__: __main__ __name__: func2 __new__: __reduce__: __reduce_ex__: __repr__: __setattr__: __str__: func_closure: None func_code: ", line 1> func_defaults: ('a', 'b') func_dict: {} func_doc: None func_globals: {'func2': , 'name': 'func_globals', '__builtins__': , '__name__': '__main__', 'foo : , '__doc__': None} func_name: func2 >>> for name in dir(func2.func_code): ... print '%s: %s' % (name, getattr(func2.func_code, name)) ... __class__: __cmp__: __delattr__: __doc__: code(argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]]) Create a code object. Not for the faint of heart. __getattribute__: __hash__: __init__: __new__: __reduce__: __reduce_ex__: __repr__: __setattr__: __str__: co_argcount: 2 co_cellvars: () co_code: d S co_consts: (None,) co_filename: co_firstlineno: 1 co_flags: 67 co_freevars: () co_lnotab: ? co_name: func2 co_names: () co_nlocals: 2 co_stacksize: 1 co_varnames: ('bar', 'zoo') >>> Hmm, func2.func_code.co_varnames seems to have the answer. Cheers, // m From danperl at rogers.com Sun Feb 6 23:38:31 2005 From: danperl at rogers.com (Dan Perl) Date: Sun, 6 Feb 2005 23:38:31 -0500 Subject: How to read POSTed data References: <4205d419$0$6610$8fcfb975@news.wanadoo.fr> <42067a0d$0$10490$8fcfb975@news.wanadoo.fr> Message-ID: "Dan Perl" wrote in message news:HcydnfD3to45MZvfRVn-iQ at rogers.com... > Thanks, Pierre, this got me much further but I hit another stumbling > block. I can see now that CGIHTTPServer writes all the header lines into > os.environ and creates a subprocess for the script with os.popen2 or > os.popen3 (it's Windows), passing the form data to the new process through > sys.stdin (I believe it is sys.stdin although the Library Reference > descriptions of popen2 and popen3 say that would be sys.stdout). But I > don't see any of those headers updated in the os.environ of the cgi > script's process. Is the parent's os.environ passed to the subprocesses > created with popen2/popen3 on Windows? > > cgi.FieldStorage.read_urlencoded needs the content-length that should be > passed through os.environ. I was about to report a bug but then I found bug report "[ 1100235 ] Scripts started with CGIHTTPServer: missing cgi environment" which is actually caused by "[ 1110478 ] os.environ.update doesn't work". They are fixed with a patch in 1110478. I still have to try it. I do like the alternate solution proposed by the originator of 1100235 though. I also thought that CGIHTTPServer should use the new subprocess.Popen class instead of popen2, popen3 and popen4. From syed_saqib_ali at yahoo.com Fri Feb 4 10:36:30 2005 From: syed_saqib_ali at yahoo.com (syed_saqib_ali at yahoo.com) Date: 4 Feb 2005 07:36:30 -0800 Subject: How to enable Python Scripts with MS IIS Web Server? Message-ID: <1107531390.688583.231970@l41g2000cwc.googlegroups.com> Hi. I have MS Windows Server 2003, Enterprise Edition. It has MS Management Console 2.0, Version 5.2 and IIS Manager 6.0 I have a directory called "myDirs". Within this directory are 2 files: 1) index.pl (a perl script) 2) index.py (a python script whose first line is "#!C:\Python21\pythonw.exe") The webserver is listening on port 8080. When I point my browser to http://localhost:8080/myDirs/index.pl, it works... I see the output of the perl script. HOWEVER, When I point my browser to http://localhost:8080/myDirs/index.py, it simply shows the python file as text. It doesn't interpret it at all. How Can I get it to interpret the python file using the interpreter and display the output in the browser? Please explain each step in careful/excruciating detail because I'm a windows Newbie. -Saqib Ali From marklists at mceahern.com Sat Feb 26 10:55:38 2005 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 26 Feb 2005 09:55:38 -0600 Subject: remove strings from source In-Reply-To: <2ab23d7a.0502260638.311cc5e9@posting.google.com> References: <2ab23d7a.0502260638.311cc5e9@posting.google.com> Message-ID: <42209BFA.5000802@mceahern.com> qwweeeit wrote: >For a python code I am writing I need to remove all strings >definitions from source and substitute them with a place-holder. > >To make clearer: >line 45 sVar="this is the string assigned to sVar" >must be converted in: >line 45 sVar=s00001 > >Such substitution is recorded in a file under: >s0001[line 45]="this is the string assigned to sVar" > >For curious guys: >I am trying to implement a cross variable reference tool and the >variability (in lenght) of the string definitions (expecially if >multi-line) can cause display problems. > >I need your help in correctly identifying the strings (also embedding >the r'xx..' or u'yy...' as part of the string definition). The problem >is mainly on the multi-line definitions or in cached strings >(embedding chr() definitions or escape sequences). > > Approach this in a test-driven development way. Create sample input and output files. Write a unit test something like this (below) and run it. You'll either solve the problem yourself or ask more specific questions. ;-) Cheers, // m #!/usr/bin/env python import unittest def substitute(data): # As a first pass, just return the data itself--obviously, this should fail. return data class Test(unittest.TestCase): def test(self): data = open("input.txt").read() expected = open("expected.txt").read() actual = substitute(data) self.assertEquals(expected, actual) if __name__ == '__main__': unittest.main() From cceverett at gmail.com Sun Feb 13 22:03:42 2005 From: cceverett at gmail.com (Chad Everett) Date: Sun, 13 Feb 2005 21:03:42 -0600 Subject: Newbie help Message-ID: Hey guys, Hope you can help me again with another problem. I am trying to learn Python on my own and need some help with the following. I am writing a program that lets has the pc pick a number and the user has five guess to get the number. 1. BUG: If the number is say 35 and I guess 41 the program tells me that I guessed the correct number and tells me I guessed 31. 2.When I do get the correct number I can not get the program to stop asking me for the number. Your help is greatly appreciated. Chad # Five Tries to Guess My Number # # The computer picks a random number between 1 and 100 # The player gets Five tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money # # Chad Everett 2/10/2005 import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 100." print "You Only Have Five Guesses.\n" # set the initial values number = random.randrange(100) + 1 guess = int(raw_input("Go Ahead and Take a guess: ")) tries = 1 # guessing loop while guess != number: if (guess > number): print "Guess Lower..." else: print "Guess Higher..." guess = int(raw_input("Take Another guess: ")) tries += 1 print "You guessed it! The number was", number print "And it only took you", tries, "tries!\n" if tries == 5: print "Sorry You Lose!!!!" print "The Number was ", number raw_input("\n\nPress the enter key to exit.") THIS IS WHAT THE RESULTS LOOKS LIKE WHEN I RUN THE PROGRAM Welcome to 'Guess My Number'! I'm thinking of a number between 1 and 100. You Only Have Five Guesses. Go Ahead and Take a guess: 99 Guess Lower... Take Another guess: 98 You guessed it! The number was 85 And it only took you 2 tries! Guess Lower... Take Another guess: 44 You guessed it! The number was 85 And it only took you 3 tries! Guess Higher... Take Another guess: 55 You guessed it! The number was 85 And it only took you 4 tries! Guess Higher... Take Another guess: 33 You guessed it! The number was 85 And it only took you 5 tries! Sorry You Lose!!!! The Number was 85 Guess Higher... Take Another guess: From mefjr75 at hotmail.com Mon Feb 7 01:16:08 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 6 Feb 2005 22:16:08 -0800 Subject: CGI POST problem was: How to read POSTed data In-Reply-To: References: <1107659974.048175.221770@z14g2000cwz.googlegroups.com> Message-ID: <1107756968.920802.99540@c13g2000cwb.googlegroups.com> Sweet! Glad you fixed it, and documented it all! Thanks for the followups. Now the next poor soul to stumble in can get the right fix. Never know when it could be me ;) M.E.Farmer From jepler at unpythonic.net Thu Feb 10 19:55:45 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 10 Feb 2005 18:55:45 -0600 Subject: Tkinter.Canvas saved as JPEG? In-Reply-To: <420bdd36$1@nntp.zianet.com> References: <420bdd36$1@nntp.zianet.com> Message-ID: <20050211005545.GA2636@unpythonic.net> The Tkinter Canvas directly supports saving to postscript format, but not any standard bitmap format (or even modern vector formats like pdf or svg). Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From gazzar at nospam_email.com Mon Feb 28 07:30:04 2005 From: gazzar at nospam_email.com (Gary Ruben) Date: Mon, 28 Feb 2005 12:30:04 GMT Subject: class factory example needed (long) In-Reply-To: References: Message-ID: Thanks for the very helpful reply Rainer, I thought I couldn't use setattr because I need the syntactic sugar sqrt(f) to work, but with your example code Numeric.sqrt(f) does in fact work correctly. I also need to do a bit more than may be possible with a simple lambda function, but I should be able to sort it out from here with the info you provided, thanks again, Gary Rainer Mansfeld wrote: > Hi Gary, > > you want your 'class factory' to change the methods of Numeric, so that > they accept foo objects and return foo objects? > I've not the slightest idea how to achieve that. > > If OTOH you want your foo class to have sqrt, arccos, etc. methods > without defining them explicitly, I think you're looking for something > like: > > . import Numeric > . > . class Foo(object): > . def __init__(self, value): > . self.value = float(value) > . for u in ['sqrt', 'cos', 'tan']: > . setattr(self, u, lambda uf=getattr(Numeric, u): > . uf(self.value + 42.0)) > > >>> f = Foo(7) > >>> f.sqrt() > 7.0 > > HTH > Rainer > From peter at engcorp.com Sat Feb 26 21:13:24 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 26 Feb 2005 21:13:24 -0500 Subject: string methods (warning, newbie) In-Reply-To: <38co9sF5lgss3U1@individual.net> References: <38co9sF5lgss3U1@individual.net> Message-ID: anthonyberet wrote: > Is there a string mething to return only the alpha characters of a string? > eg 'The Beatles - help - 03 - Ticket to ride', would be > 'TheBeatlesTickettoride' > > If not then how best to approach this? > I have some complicated plan to cut the string into individual > characters and then concatenate a new string with the ones that return > true with the .isalpha string method. > > Is there an easier way? Look into the string module's "translate" function. It will do this for you fairly easily. -Peter From mateusz.soltysek at gazeta.pl Wed Feb 23 04:45:34 2005 From: mateusz.soltysek at gazeta.pl (=?ISO-8859-2?Q?Mateusz_So=B3tysek?=) Date: Wed, 23 Feb 2005 10:45:34 +0100 Subject: Working FTP server based on Twisted framework. Message-ID: Hi call, Does anybody know, if there is any opensource, working FTP server implementation based on Twisted framework? Greetings From mmiller at tx3.com Tue Feb 1 07:05:57 2005 From: mmiller at tx3.com (Martin Miller) Date: Tue, 01 Feb 2005 04:05:57 -0800 Subject: "pickle" vs. f.write() In-Reply-To: References: Message-ID: <41FF70A5.8070806@tx3.com> On 1/26/05 at 1:48 pm, Terry Reedy wrote: > For basic builtin objects, repr(ob) generally produces a string that when > eval()ed will recreate the object. IE > eval(repr(ob) == ob # sometimes I've found extending this property to your own classes often fairly easy to implement (and useful). For example: > class person: > def __init__(self, name="", age=0, friends=None, comment=""): > if friends is None: > friends = [] > self.name, self.age, self.friends, self.comment = name, age, friends, comment > > def __repr__(self): > return ("person(" + repr(self.name) + ", " + repr(self.age) + ", " + > repr(self.friends) + ", " + repr(self.comment) + ")") > > me = person() > > print "me =", repr(me) Which produces the following output: me = person('', 0, [], '') In addition, the following constructs are possible: > family = [ > person("Martin", 50, ["Matt"], "eldest son"), > person("Matt", 43, ["Martin"], "youngest son"), > person("Merry", 72, ["Martin", "Matt"], "mother"), > person("Luther", 82, ["Merry"], "father") > ] > > print "family =", repr(family) Which output the following: family = [person('Martin', 50, [], 'eldest son'), person('Matt', 43, ['Martin'], 'youngest son'), person('Merry', 72, ['Martin', 'Matt'], 'mother'), person('Luther', 82, ['Merry'], 'father')] Basically this approach allows you to store your data in Python source files -- which you can then import or execfile. The files can also contain comments and are relatively easy to edit by hand. In addition they're portable. Best, Martin From http Fri Feb 4 01:31:43 2005 From: http (Paul Rubin) Date: 03 Feb 2005 22:31:43 -0800 Subject: advice needed for simple python web app References: <5cqdnZX-cZ9ca5_fRVn-3Q@rogers.com> <7xr7jxnddh.fsf@ruckus.brouhaha.com> <7xis58c1lw.fsf@ruckus.brouhaha.com> Message-ID: <7x6518bzu8.fsf@ruckus.brouhaha.com> "Dan Perl" writes: > > Be careful of exposing that script to the internet. Spammers will > > exploit it. > > Do you mean publishing the script for other people to copy it or exposing > the web app so that other people may access it? I mean installing the script on a server where spammers can run it and stick you with the blame for people getting unwanted mail. There used to be some similar perl scripts running all over the place until that happened. > Don't worry anyway, I won't do either and I'm running 2 firewalls on > my PC. It would be really naive to expose the web app, wouldn't it? Well, you should have some kind of user authentication if you expose it, and you should read up a bit about security for web apps. Python is actually not such a great language for this, but you certainly get more readable code than you would with perl. From P at draigBrady.com Fri Feb 4 09:34:14 2005 From: P at draigBrady.com (P at draigBrady.com) Date: Fri, 04 Feb 2005 14:34:14 +0000 Subject: regular expression match collection In-Reply-To: <1107525832.015932.286300@f14g2000cwb.googlegroups.com> References: <1107525832.015932.286300@f14g2000cwb.googlegroups.com> Message-ID: <420387E6.5000208@draigBrady.com> ajikoe at gmail.com wrote: > Hello, > > For example I have a string : "Halo by by by" > Then I want to take and know the possition of every "by" > how can I do it in python? [ match.start() for match in p.finditer("Helo by by by") ] see: http://mail.python.org/pipermail/python-list/2004-December/255013.html -- P?draig Brady - http://www.pixelbeat.org -- From python-url at phaseit.net Thu Feb 24 00:08:04 2005 From: python-url at phaseit.net (Cameron Laird) Date: Thu, 24 Feb 2005 05:08:04 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Feb 24) Message-ID: QOTW: "Who's 'Guido'?" -- Ilias Lazaridis "I know this document. It has no relevance to me." -- Ilias Lazaridis, on "Nobody asked them to do this (AFAIK), it's more that nobody could _stop_ them from doing it." -- timbot, on the work of Jason Tishler and Andrew MacIntyre with Cygwin and OS/2 EMX, respectively Hot off the virtual press: Py2.4 Quick Reference: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/5be203da13eafdd2/ For a decade now, confident people have declaimed in managers' meetings and conferences that {local,Web} applications are {dead,utterly triumphant}, in all combinations (and sometimes at the same venues) (and sometimes by the same people!) (although not by the same people at the same time). Real Programmers know they need judgment and expertise on both sides. The principal implications for Python: client-side Web scripting is one of the few domains where Python is *not* nearly ideal (although not for technical reasons); but the best "Weblications" still can result from co- operation between Python and other languages: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b0085890efa29780/ Kartic and Tony Meyer provide nice two-minute tutorials on imaplib, and, more generally, network programming: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c8f87f28f00a9c93/ Tkinter has modal dialogues: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/8fce072f149f13c0/ Ron Stephens entertainingly advertises pyGoogle: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e28557ad49b4619a/ Peaceful coexistence: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/3adfa3b1148aaa8e/ http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/3775e1b575d8fb67/ ======================================================================== 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. 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 Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson 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/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (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 Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From ggrp1.20.martineau at dfgh.net Tue Feb 22 05:37:35 2005 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 22 Feb 2005 02:37:35 -0800 Subject: Test for structure References: <1108566497.848623.45360@c13g2000cwb.googlegroups.com> <1108937287.079367.276910@g14g2000cwa.googlegroups.com> <1109012415.692798.185750@l41g2000cwc.googlegroups.com> Message-ID: <1109068655.648301.178740@g14g2000cwa.googlegroups.com> Ooops. I left out an "*" on a statement in the new aslist() function. I should have written: def aslist(*args): return list(*args) # corrected def f(arg): args = aslist(arg) ... Sorry, Martin From barrowes at alum.mit.edu Fri Feb 25 08:54:38 2005 From: barrowes at alum.mit.edu (Ben Barrowes) Date: Fri, 25 Feb 2005 06:54:38 -0700 Subject: automatic nesting and indentation in emacs In-Reply-To: References: Message-ID: <421f2e1f$1_2@news3.es.net> In emacs matlab-mode, highlight a region then use indent-region: C-M-\ runs the command indent-region which is an interactive compiled Lisp function in `indent'. (indent-region START END COLUMN) Indent each nonblank line in the region. With prefix no argument, indent each line using `indent-according-to-mode', or use `indent-region-function' to do the whole region if that's non-nil. If there is a fill prefix, make each line start with the fill prefix. With argument COLUMN, indent each line to that column. When you call this from a program, START and END specify the region to indent, and COLUMN specifies the indentation column. If COLUMN is nil, then indent each line according to the mode. porterboy wrote: > CONTEXT: > I am using Emacs to edit Python code and sometimes also Matlab code. > When I hit in a loop of some sort, Emacs usually gets the > nesting indentation right, which is particularly important in Python. > To ensure this I have used python-mode.el and matlab.el modes in > emacs. > > QUESTION: > If I suddenly decide I want an outer loop, do I have to manually > readjust the indentation of all the inner loops? Or can emacs do it > automatically? I know the Matlab in-built editor has a tool called > "smart-indent" which will automatically align highlighted text to have > the correct indentation. Does Emacs have something similar? > > Thanks > The Porterboy - "Lovely day for a Guinness" From tjreedy at udel.edu Wed Feb 2 02:36:54 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 2 Feb 2005 02:36:54 -0500 Subject: Next step after pychecker References: Message-ID: "Steven Bethard" wrote in message news:Ctadnef2y-nixJ3fRVn-vQ at comcast.com... > So I assume the language spec is basically the grammar and the > Language Reference docs[1]? Yes. The de facto governing syntax specification is the grammar file in the source code from which the parser is generated. I once read that it is an ll(1) grammar; perhaps the file itself says. The grammar snippets in the Ref Manual are a humanized version, not constrained to be ll(1) but intended to equivalent. The text, of course, adds the semantic meat. Any discrepancy between that text and implementation behavior is a bug. Such usually get fixed fairly quickly after being reported. Terry J. Reedy From peter at somewhere.com Tue Feb 15 09:49:34 2005 From: peter at somewhere.com (Peter Maas) Date: Tue, 15 Feb 2005 15:49:34 +0100 Subject: replacing ASP/VBScript with Python Message-ID: I have inherited an extremely messy ASP/VBScript application which is a pain for me to support. Now the customer is thinking about a redesign. I'd like to rewrite the whole thing in Python but the app has to meet some conditions like - IIS frontend - MSSQL db server - Win32 authentication - No 'ugly' URLs like http://server/cgi-bin/frontend.cgi?main.py - Performance: intranet with ~ 1000 users My personal preferences: - I'd rather do this in plain Python than using e.g. Zope because I fear the additional complexity of handling Zope and make it seam- lessly work with IIS. - I'd like to do session handling in Python because ASP's session object is quite limited and some of the ASP app's mess is caused by trying to use it for compound data type storage. OTOH I could pickle Python objects to a string and store that in an ASP session. Thanks for any help. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From cam.ac.uk at mh391.invalid Sun Feb 13 08:52:34 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 13 Feb 2005 13:52:34 +0000 Subject: [NooB] a Variable in multiple quotes... In-Reply-To: <614c778e.0502130204.5824cddf@posting.google.com> References: <614c778e.0502130204.5824cddf@posting.google.com> Message-ID: You know, it's really not necessary for you to put "[NooB]" in the subject of your posts. This is a fairly friendly group and they will answer even newbie questions amicably. But if you want an even kinder, gentler place to ask questions as a newbie (not a noob), I suggest the Tutor mailing list: http://mail.python.org/mailman/listinfo/tutor -- Michael Hoffman From __peter__ at web.de Thu Feb 3 07:18:30 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Feb 2005 13:18:30 +0100 Subject: Generating modul classes with eval References: Message-ID: Axel Straschil wrote: > class_dic = {} > class_dic['Br'] = _Tag > class_dic['Hr'] = _Tag > class_dic['Html'] = _ContainerTag > class_dic['Table'] = _ContainerTag > > for class_name, class_base in class_dic.items(): > class TmpClass(class_base): > def __init__(self, **props): > name = class_name.lower() > #super(TmpClass, self).__init__(name=name, **props) > class_base.__init__(self, name=name, **props) > setattr(_module_name, class_name, TmpClass) While your workaround doesn't balk immediately, it doesn't do the right thing either. After the loop has finished, the global variable TmpClass will be bound to whatever class was created last, and the variable class_base will be bound to that the base class of that same TmpClass. Therefore only this last class is guaranteed to work as expected. A simplified example to demonstrate the binding problem: >>> classes = [] >>> for text in ["alpha", "beta"]: ... class T: ... def __init__(self): print text ... classes.append(T) ... >>> classes[0] is classes[1] False # two distinct classes, as expected >>> classes[0]() beta <__main__.T instance at 0x402a9e2c> >>> classes[1]() beta <__main__.T instance at 0x402a9f8c> And now the proof that you are actually accessing the global variable: >>> text = "gamma" >>> classes[0]() gamma <__main__.T instance at 0x402a9f8c> One way to fix this is to introduce a factory function: >>> def make_class(text): ... class T: ... def __init__(self): print text ... return T ... >>> classes = [] >>> for text in ["alpha", "beta"]: ... classes.append(make_class(text)) ... >>> classes[0]() alpha <__main__.T instance at 0x402a9e4c> >>> classes[1]() beta <__main__.T instance at 0x402a9f8c> >>> Peter From brent.hughes at comcast.net Wed Feb 9 15:44:44 2005 From: brent.hughes at comcast.net (Brent W. Hughes) Date: Wed, 9 Feb 2005 13:44:44 -0700 Subject: Newbie: SWIG or SIP? Message-ID: I have a third-party DLL and it's associated .h file. The DLL was written in C. I have neither the associated .c files nor the .obj files for the DLL. Can I use SWIG or SIP to build something that will allow me to use the DLL with Python? And what is that something, an .obj file, another DLL or what? Brent From jfj at freemail.gr Mon Feb 7 21:10:37 2005 From: jfj at freemail.gr (jfj) Date: Mon, 07 Feb 2005 18:10:37 -0800 Subject: Confused with methods In-Reply-To: <1grmg8s.17t7tj4180jdj6N%aleaxit@yahoo.com> References: <1grknb0.ygwohl17y6j5yN%aleaxit@yahoo.com> <1grmd4z.1tlm4e61650vedN%aleaxit@yahoo.com> <1grmg8s.17t7tj4180jdj6N%aleaxit@yahoo.com> Message-ID: <42081F9D.70803@freemail.gr> Alex Martelli wrote: > I think the problem is that you know python so well that you are used to the way things are and everything seems natural the way it is. For a newbie, the behaviour I mentioned seems indeed a bit inconsistent. "Inconsistent" not as in mathematics but as in "wow! I'd thought this should work like this". Like you have a perception of the language and then this feature changes everything. It's a different kind of "inconsistency" and it doesn't give python a bad name or something, nor does it break the mathematical laws of the universe. There is no trolling involved here. Maybe wrong use of the english language. But then again, this is the newgroups and the english language is ill-used all the time:) Regards, jfj From ncoghlan at iinet.net.au Sun Feb 13 21:53:24 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 14 Feb 2005 12:53:24 +1000 Subject: Kill GIL In-Reply-To: <86sm405d38.fsf@guru.mired.org> References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <868y5t6sal.fsf@guru.mired.org> <86sm405d38.fsf@guru.mired.org> Message-ID: <421012A4.40006@iinet.net.au> Mike Meyer wrote: > aahz at pythoncraft.com (Aahz) writes: >>Threads are also good for handling blocking I/O. > > Actually, this is one of the cases I was talking about. I find it > saner to convert to non-blocking I/O and use select() for > synchronization. That solves the problem, without introducing any of > the headaches related to shared access and locking that come with > threads. Use a communicating sequential processes model for the threading and you don't have many data synchronisation problems because you have barely any shared access - no application data is ever shared between threads, they only send messages to each other via message queues. Most threads simply block on their incoming message queue permanently. Those doing blocking I/O set an appropriate timeout on the I/O call so they can check for messages occasionally. Conveniently, you end up with an architecture that supports switching to multiple processes, or even multiple machines just by changing the transport mechanism used by the message system. (We did exactly this for a GUI application - detached the GUI so it talked to a server via CORBA instead of via direct DLL calls. This meant the server could be ported to a different platform without having to port the far more platform specific GUI. This would have been much harder if we weren't already using a CSP model for communication between different parts of the system) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jmdeschamps at cvm.qc.ca Wed Feb 9 10:31:48 2005 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 9 Feb 2005 07:31:48 -0800 Subject: cx_Oracle failed to load DLL BUT versions correct Message-ID: <3d06fae9.0502090731.7232b53d@posting.google.com> Hello Having cx_Oracle (an Oracle database connector for Python) used it here where I teach for the last couple of years, and finding it so easy to use (and install) I was taken aback when I got an error message telling me it could not load the DLL (complete message below) Third, I've read (on activeState site) about someone else having this problem which seemed to be resolved by correctly installing the appropriate versions of different software piece. BUT no 1 : I works on my portable (that has the same configuration for OS, Python and cx) BUT no 2: The same configuration gets the error message from our classroom workstations - after multiple testing, (uninstalling everything, python, Oracle, cx_Oracle,etc) , cleaning the registry, re-installing from fresh binaries ( Oracle works (SQL+) ) , the error stays... HELP - Any hints, helps, things to look for, whatnot, Many thanks in advance, Jean-Marc jmdeschamps at cvm.qc.ca Cegep du Vieux-Montreal CONFIGURATION windows XP professionnal, sp2 (firewall stopped) installation in administrator mode Oracle 10g Python 2.3.4 pywin32-203.win32-py2.3.exe cx_Oracle-4.1-win32-10g-py23.exe NOTE: all files seem in the right places (cx_Oracle.pyd in site-packages) ERROR (taken from PythonWin interactive window) PythonWin 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 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 cx_Oracle Traceback (most recent call last): File "", line 1, in ? ImportError: DLL load failed: La proc?dure sp?cifi?e est introuvable. >>> From oliphant at ee.byu.edu Thu Feb 24 18:52:29 2005 From: oliphant at ee.byu.edu (Travis Oliphant) Date: Thu, 24 Feb 2005 16:52:29 -0700 Subject: Nevow examples Message-ID: <421E68BD.6070009@ee.byu.edu> There was a request for nevow examples. Nevow is a fantastic web-development framework for Python. I used nevow to create http://www.scipy.org/livedocs/ This site uses nevow and self introspection to produce (live) documentation for scipy based on the internal docstrings. It would be nice to add the capability for users to update the documentation through the web-site. But, that functionality is not complete. The code itself is available in the util directory of scipy which can be checked out of CVS (or browsed). Go to http://www.scipy.org for mor details. -Travis Oliphant From peter at engcorp.com Sun Feb 13 08:55:45 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 13 Feb 2005 08:55:45 -0500 Subject: For American numbers In-Reply-To: <%DBPd.10409$Lf6.440348@phobos.telenet-ops.be> References: <420e7376$1@nntp0.pdx.net> <%DBPd.10409$Lf6.440348@phobos.telenet-ops.be> Message-ID: Roel Schroeven wrote: > Peter Hansen wrote: > >> Scott David Daniels wrote: >> >>> Kind of fun exercise (no good for British English). >>> >>> def units(value, units='bytes'): >>> magnitude = abs(value) >>> if magnitude >= 1000: >>> for prefix in ['kilo mega giga tera peta ' >>> 'exa zetta yotta').split(): >>> magnitude /= 1000. >>> if magnitude < 1000.: >>> break >> >> >> >> Only for hard drive manufacturers, perhaps. > > > And physicists and chemists and engineers and all other kinds of > scientists all over the world. Plus those of us in the computer world > who agree that 'kilo == 1024' is an abomination that should never have > existed and which we should get rid of as fast as possible. Physicists and chemists (and most engineers) don't go around talking about "kilobytes" all that often, and when they do it's generally unimportant whether they mean 1000 or 1024. Given the clear "units='bytes'" default above, and my restricting my comments to "the rest of the computer world", it should be clear I was talking about a very limited subset of the planet. A subset, however, which has an extremely strong attachment to 1024 instead of 1000 (for very good reasons), and which is less likely to abandon backwards compatibility and widely accept 1000 than the US is likely to adopt metric widely in the near future... -Peter From martin at v.loewis.de Tue Feb 8 15:54:43 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 Feb 2005 21:54:43 +0100 Subject: Printing Filenames with non-Ascii-Characters In-Reply-To: <36a3ikF4uk8r0U1@individual.net> References: <36a3ikF4uk8r0U1@individual.net> Message-ID: <420926fd$0$13973$9b622d9e@news.freenet.de> Marian Aldenh?vel wrote: > dir = os.listdir(somepath) > for d in dir: > print d > > The program fails for filenames that contain non-ascii characters. > > 'ascii' codec can't encode characters in position 33-34: I cannot reproduce this. On my system, all such file names print just fine, in Python 2.3.4. Are you using the Windows XP cmd.exe window to perform this experiment? What (language) version of XP are you using? What are your regional settings? What is sys.stdout.encoding? What is the result of locale.setlocale(locale.LC_ALL, "")? > What I specifically do not understand is why Python wants to interpret the > string as ASCII at all. Where is this setting hidden? If this is in cmd.exe (or equivalent), Python 1. verifies that the output is indeed a terminal 2. if it is, determines what code page the terminal uses 3. tries to find a codec for this code page 4. if this fails, falls back to ASCII In your case, step 4 must have happend. It's not clear to my why this happened, unless you are using a Japanese version of XP (or some other version for which Python does not have a codec). > I am running Python 2.3.4 on Windows XP and I want to run the program on > Debian sarge later. In Linux, make sure that LANG is set to a value that allows Python to infer the encoding of the terminal. Regards, Martin From gilles.leblanc at gmail.com Sat Feb 26 17:21:21 2005 From: gilles.leblanc at gmail.com (Gilles Leblanc) Date: 26 Feb 2005 14:21:21 -0800 Subject: Using PyOpenGL what should I use for a GUI ? Message-ID: <1109456481.214243.140670@l41g2000cwc.googlegroups.com> Hi I have started a small project with PyOpenGL. I am wondering what are the options for a GUI. So far I checked PyUI but it has some problems with 3d rendering outside the Windows platform. I know of WxPython but I don't know if I can create a WxPython window, use gl rendering code in it and then put widgets on top of that... From zetasum at yahoo.com Sun Feb 27 20:26:25 2005 From: zetasum at yahoo.com (zetasum) Date: 27 Feb 2005 17:26:25 -0800 Subject: but someone got out and me and my familiy try to stop them and got trocherd in unknow dimentions i try to make it better and they change me to make it worse so what do i do if you see what in my chest in every dimention!!! look for consiousnesses in the house i spelled it wrong bbecuase thats what you will say when you see my bodie 366-94-1447 2-3-1973 follow my bodie and the liverance familiy everywhere and look find out why we are being killed????? Message-ID: <1109553985.792892.5590@o13g2000cwo.googlegroups.com> but someone got out and me and my familiy try to stop them and got trocherd in unknow dimentions i try to make it better and they change me to make it worse so what do i do if you see what in my chest in every dimention!!! look for consiousnesses in the house i spelled it wrong bbecuase thats what you will say when you see my bodie 366-94-1447 2-3-1973 follow my bodie and the liverance familiy everywhere and look find out why we are being killed????? TRUE PROVEN METHOD OF HIGHER INTELLGENCE alpha, theta and delta, brain waves of the mind wich we now know that are qunatium state of mind space time and realm. That froms the a beings instincts of unkown not found is the combination pleasent of sense's of smell,sight and sound in a peacesful manner..It is the consious ambient of peaceful manner that lead to intellgence. The relax state of mind and the brain wave patter that will be found will open a crative door to the minds eye not of what we think will be intellgence but during day dreaming states of mind. The person would be able to see the full design of ones idea with an open mind instead of starting with one concept and working with it you would be able to start with 10 concept and combine then as one. Itellgence is an I.Q that one can chart Because there are two types of people in the world people that dream and people that do and if dreams could learn to dream and then do. The definition of intellgence would change infromation flows free in this zeta multi-x pattern this would not just spawn another pattern of brain waves but would be one step into a door where infinte ideas of very high itellgence ones flow and cannot find the source, and tring to hard along with Hate puts more information in the brain that stops the flow of information the other sources that stops this infromation is P.S.I ability to do telepathy this is open you mind to unknown infromation. This path of this idea will give you the other infinte thoughts that you will never spawn from now until the end of time becuase no one has done this before and willl never do it but they have and try to intergrate hate and have fail where you my qunatum freind will succeed all other before us. This is the key to my qunatium encrypted web site. P.S.I That stop all before us cannot find technology but can find and change the minds of people that try to change humans history so print this out put in all four pockets the more you print the more it changes the more times you e-mail this the statistical chance you have at reaching the unknow universe. In computer terms in the future it is now not 99.9% true or false it is TRUE PROVEN METHOD OF HIGHER INTELLGENCE OF THIS CHANGES HUMAN HISTORY NOT 1% BUT ALL 100%. WITH BIOINFORMATICS YOU HAVE TO HAVE A LAB OF NO FREQUENCIES OR THE UNKNOWS P.S.I WILL CHANGE YOUR LAB WORK. WHITE NOISE OF ALL QUNATIUM DIMENTIONS IN ALL QUANTIUM STATES AND THAT 1% WILL STILL GET THREW - GHOAST IN THE MACHINE!!! TRUST ME THE PROGRAMMED WORKED ON MY COMPUTER AT HOME BUT FAILIED AT NASA BECUASE THEY ONLY CAHNGE HISTORY IF YOU MIND IS 97% THAT IT WILL NOT KNOWING OF THEM BEING THERE!!!! combine this with this group that http://groups.yahoo.com/group/Quantum_AI This guy qaudra_light at yahoo.com posted using my e-mail address got me torcherd by his people or something skitzo say there qunatium invisble people in other dimentions killing the machine or something@!@ From paschott at no.yahoo.spamm.com Tue Feb 1 17:53:19 2005 From: paschott at no.yahoo.spamm.com (Peter A. Schott) Date: Tue, 01 Feb 2005 22:53:19 GMT Subject: ftplib help - delete from server after download results in 0-byte file Message-ID: Got a strange scenario going on here in that I could have sworn this worked yesterday. I am issuing binary retrieval calls to an FTP server, writing to a file, close the file, then removing the file from the remote site. When I do this, I end up with 0 byte files. I was hoping to avoid parsing a list of remote and local files and matching them up that way because it would be easier to remove on successful retrieve. I'm including some sample code and really hoping someone can point out where I'm messing up. Thanks. import os, ftplib DPI = "C:/DestinationFolder/" #Actually named different in code, but shorter for reading here. #Note - objFTP is already opened - this is not the issue. objFTP.cwd("/ksdata_in") #I'm open to better ways to do this. Can't use nlst if empty. TestDir = objFTP.dir() if TestDir <> None: FTPRemoteList = objFTP.nlst() #If the remote file is type SEM or PGP, do this. for filename in [filename for filename in FTPRemoteList if \ (os.path.splitext(filename)[1] in [".sem",".SEM",".PGP",".pgp"])]: try: DestinationFile = open(os.path.join(DPI, filename), "wb") print DestinationFile objFTP.retrbinary("RETR " + filename, DestinationFile.write) SQLLogging.LogFTP(filename, CompanyInput, 1, 'ToDrive') DestinationFile.close() #This is the culprit. When this is active, it writes a 0 byte file locally # and deletes the file on the server. #objFTP.delete(filename) except: SQLLogging.LogFTP(filename, CompanyInput, 0, 'ToUs') print Exception #This is my workaround in the meantime. If I've downloaded the files, get #another remote listing and delete and files from remote that are downloaded #locally and larger than 1Kbish for PGP files. SEM files are 0 bytes. TestDir = objFTP.dir() if TestDir <> None: FTPRemoteList = objFTP.nlist() for filename in FTPRemoteList: if os.path.isfile(os.path.join(DownloadedPathInput, filename)) and \ os.path.splitext(filename)[1] in [".pgp",".PGP"] and \ os.stat(os.path.join(DownloadedPathInput, filename))[6] > 1000: objFTP.delete(filename) if os.path.isfile(os.path.join(DownloadedPathInput, filename)) and \ os.path.splitext(filename)[1] in [".SEM",".sem"]: objFTP.delete(filename) From philippecmartin at sbcglobal.net Sat Feb 5 16:51:04 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Sat, 05 Feb 2005 15:51:04 -0600 Subject: pickle/marshal internal format 'life expectancy'/backward compatibility Message-ID: <1107640264.7097.5.camel@localhost> Hi, I am looking into using the pickle format to store object/complex data structures into a smart card as it would make the design of the embedded application very simple. Yet the card might have to stay in the pocket of the customer for a few years, during which the back office application responsible for retrieving the information from the card might evolve as well as the python release it relies upon. Is there a commitment for python releases to be able to interpret 'older' pickle/marshal internal formats ? Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From amk at amk.ca Wed Feb 2 12:35:57 2005 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 02 Feb 2005 11:35:57 -0600 Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106723545.429728.308620@f14g2000cwb.googlegroups.com> <1107354540.608556.305540@z14g2000cwz.googlegroups.com> <1107362671.182505.22180@c13g2000cwb.googlegroups.com> Message-ID: <8cWdnYRauejgkpzfRVn-oA@speakeasy.net> On Wed, 2 Feb 2005 12:22:24 -0500, Dan Perl quoted: > "Xah Lee" wrote in message >> I suggest it be dropped in both places. The mentioning of this book in >> the Perl/Python community is mostly a fawning behavior and confession >> that the author is among "in the know". This book and its mentioning is >> a cultish behavior among OpenSource morons. Not to mention that the reference to the book in the regex howto is hardly "fawning": The most complete book on regular expressions is almost certainly Jeffrey Friedl's Mastering Regular Expressions, published by O'Reilly. Unfortunately, it exclusively concentrates on Perl and Java's flavours of regular expressions, and doesn't contain any Python material at all, so it won't be useful as a reference for programming in Python. (The first edition covered Python's now-obsolete regex module, which won't help you much.) Consider checking it out from your library. (I like how Lee extols Python, but also says its documentation was written by "opensource morons". Honestly, you couldn't pay for this much entertainment.) --amk From peter at engcorp.com Sat Feb 12 22:24:40 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 12 Feb 2005 22:24:40 -0500 Subject: Alternative to raw_input ? In-Reply-To: References: Message-ID: BOOGIEMAN wrote: > On Fri, 11 Feb 2005 21:38:47 -0500, Peter Hansen wrote: > >>print prompt >>while msvcrt.kbhit(): >> msvcrt.getch() >>msvcrt.getch() > > > Thanks, it works but without line "print prompt" and also That was intended to be a hint that you might need to print a prompt to the user (maybe a string contained in a variable named "prompt", for example ;-), or the program might halt without apparent reason. > I'm not sure if I should put this function : > > def cekaj(): > while msvcrt.kbhit(): > msvcrt.getch() > msvcrt.getch() > > #Or this one, which sounds more logical according to help > #kbhit() - Return true if a keypress is waiting to be read. > > def cekaj(): > msvcrt.getch() > while msvcrt.kbhit(): > msvcrt.getch() > > It works both ways, not sure which one is right The point of doing the first approach is that you are reading *all* available keystrokes (in the loop), and then sitting and waiting for one more keystroke before continuing. If you don't read all keystrokes first, then if the user has hit a key, say, five minutes earlier, it will still be sitting in the queue and your program will not actually stop at all. Your second approach sits and waits (if necessary) to read a single keystroke, and then if the user had managed to hit two or more keys** before that, it will consume all remaining keystrokes before continuing. Not exactly the same thing, nor generally quite what you want. Based on what you originally asked for, the former is the correct approach. ** Note that some keys will result in a pair of values being retrieved by getch(), with the first one being (generally... maybe always... I can't remember but it's easy for you to experiment) a 0, and the second being another code that identifies the key. The F5 key, for example, returns a 0 and then a 64 on the second call to getch(). If you *really* want *any* key to continue, you'll want to check for this sort of thing as well... though personally I'd just use raw_input() and keep my program portable. -Peter From ncoghlan at iinet.net.au Fri Feb 11 08:42:17 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 11 Feb 2005 23:42:17 +1000 Subject: Statement coverage tools revisited In-Reply-To: <87zmyb71r2.fsf@titan.staselog.com> References: <87zmyb71r2.fsf@titan.staselog.com> Message-ID: <420CB639.9060704@iinet.net.au> Edvard Majakari wrote: > ,---- > | The coverage dictionary is called "c" and the trace function > | "t". The reason for these short names is that Python looks up variables > | by name at runtime and so execution time depends on the length of > | variables! In the bottleneck of this application it's appropriate to > | abbreviate names to increase speed. > `---- > > It was written when 2.1 was the most recent stable version. I wonder if it > still applies for 2.2 and later? According to my hasty tests it doesn't > seem to be so. I didn't have very large unit test files at hand, though. It's no longer correct (if it ever was correct). Python internalises 'short' strings (including identifiers) so that comparison can generally be done by means of identity checks. Py> long_and_really_complicated_var_name = 1 Py> "long_and_really_complicated_var_name" is "long_and_really_complicated_var_n ame" True Py> "long_and_really_complicated_non_var_name" is "long_and_really_complicated_n on_var_name" True Py> "long_and_really_complicated_non_var_name" * 20 is "long_and_really_complica ted_non_var_name" * 20 False Ah, the wonderful efficiencies of immutable types. . . Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From snail at objmedia.demon.co.uk Mon Feb 14 09:53:37 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Mon, 14 Feb 2005 14:53:37 +0000 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: Message-ID: In message , Ilias Lazaridis writes >the community do not care about essential needs and requirements. Wrong. They do. They just don't care about *your* essential needs and requirements which *you* want *others* to fulfill at *their* cost. As others have said, "do some work yourself". Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From rickysarraf at gmail.com Thu Feb 3 09:20:30 2005 From: rickysarraf at gmail.com (rickysarraf at gmail.com) Date: 3 Feb 2005 06:20:30 -0800 Subject: test msg Message-ID: <1107440430.276966.318580@z14g2000cwz.googlegroups.com> tes tmsg From peter at engcorp.com Wed Feb 16 20:31:12 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Feb 2005 20:31:12 -0500 Subject: Stable GUI + wxPython memory leak In-Reply-To: <1108596113.424102.255340@f14g2000cwb.googlegroups.com> References: <1108564589.069982.71680@o13g2000cwo.googlegroups.com> <1108569376.721830.67370@o13g2000cwo.googlegroups.com> <1108596113.424102.255340@f14g2000cwb.googlegroups.com> Message-ID: Viktor wrote: > I just noticed that wxPython is leaking memory?! Playing with > wxPython-demo, I started with 19MB used, and ended whith almost 150MB > used?! > It's wxPython 2.5.3.1 running on Python 2.4. On which platform? And how are you measuring this apparent memory consumption? And what happens (assuming you're on Windows) if you minimize the window? What does the memory usage show as then? And if you then restore the window but do nothing else with it? Memory consumption is a very difficult thing to measure properly in the best of circumstances, and if you're merely running the demo it seems unlikely you're observing a real "leak". -Peter From fredrik at pythonware.com Sat Feb 19 12:44:27 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 19 Feb 2005 18:44:27 +0100 Subject: unicode encoding usablilty problem References: Message-ID: "aurora" wrote: > I don't want to mix them. But how could I find them? How do I know this statement can be > potential problem > > if a==b: > > where a and b can be instantiated individually far away from this line of code that put them > together? if you don't know what a and b comes from, how can you be sure that your program works at all? how can you be sure they're both strings? ("a op b" can fail in many ways, depending on what "a", "b", and "op" are) > Things works fine, unit tests pass, all until the first non-ASCII characters > come in and then the program breaks. if you have unit tests, why don't they include Unicode tests? From aurora00 at gmail.com Wed Feb 23 13:25:32 2005 From: aurora00 at gmail.com (aurora) Date: Wed, 23 Feb 2005 10:25:32 -0800 Subject: running a shell command from a python program References: <1109170831.815278.243270@f14g2000cwb.googlegroups.com> Message-ID: In Python 2.4, use the new subprocess module for this. It subsume the popen* methods. > Hi, > I'm a newbie, so please be gentle :-) > > How would I run a shell command in Python? > > Here is what I want to do: > I want to run a shell command that outputs some stuff, save it into a > list and do stuff with the contents of that list. > > I started with a BASH script actually, until I realized I really needed > better data structures :-) > > Is popen the answer? Also, where online would I get access to good > sample code that I could peruse? > > I'm running 2.2.3 on Linux, and going strictly by online doc so far. > > Thanks! > S C > From brian at sweetapp.com Fri Feb 11 10:09:36 2005 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 11 Feb 2005 16:09:36 +0100 Subject: Is this a bug? BOM decoded with UTF8 In-Reply-To: <373sj3F590j6iU1@individual.net> References: <420bc317$0$4925$9b622d9e@news.freenet.de> <373p8vF57039vU1@individual.net> <373sj3F590j6iU1@individual.net> Message-ID: <420CCAB0.30902@sweetapp.com> Diez B. Roggisch wrote: > I'm well aware of the need of a bom for fixed-size multibyte-characters like > utf16. > > But I don't see the need for that on an utf-8 byte sequence, and I first > encountered that in MS tool output - can't remember when and what exactly > that was. And I have to confess that I attributed that as a stupidity from > MS. But according to the FAQ you mentioned, it is apparently legal in utf-8 > too. Neverless the FAQ states: > [snipped] > So they admit that it makes no sense - especially as decoding a utf-8 string > given any 8-bit encoding like latin1 will succeed. They say that it makes no sense as an byte-order indicator but they indicate that it can be used as a file signature. And I'm not sure what you mean about decoding a UTF-8 string given any 8-bit encoding. Of course the encoder must be know: >>> u'T\N{LATIN SMALL LETTER U WITH DIAERESIS}r' ... .encode('utf-8').decode('latin1').encode('latin1') 'T\xc3\xbcr' I can assume you that most Germans can differentiate between "T?r" and "T??r". Using a BOM with UTF-8 makes it easy to indentify it as such AND it shouldn't break any probably written Unicode-aware tools. Cheers, Brian From gh at ghaering.de Tue Feb 8 08:18:27 2005 From: gh at ghaering.de (Gerhard Haering) Date: Tue, 8 Feb 2005 14:18:27 +0100 Subject: User Identification In-Reply-To: References: Message-ID: <20050208131827.GA6844@mylene.ghaering.de> On Tue, Feb 08, 2005 at 12:29:48PM -0000, Bob Parnes wrote: > I have a python program on a server of an all-linux network. It needs to > record the user name running it. Is there a way for the program to extract > the name from the system without a separate log-in dialog? os.environ["USER"] for a start? os.getuid() will give you the user id, but I don't know if Python has methods to look up more information from that from /etc/passwd or whereever from. -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From eurleif at ecritters.biz Sun Feb 6 02:11:12 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sun, 06 Feb 2005 02:11:12 -0500 Subject: Word for a non-iterator iterable? Message-ID: <36lu1cF516qtdU1@individual.net> Is there a word for an iterable object which isn't also an iterator, and therefor can be iterated over multiple times without being exhausted? "Sequence" is close, but a non-iterator iterable could technically provide an __iter__ method without implementing the sequence protocol, so it's not quite right. From jack at performancedrivers.com Mon Feb 14 19:15:13 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 14 Feb 2005 19:15:13 -0500 Subject: Inheritance error in python 2.3.4??? In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE02520362@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE02520362@au3010avexu1.global.avaya.com> Message-ID: <20050215001513.GB27274@performancedrivers.com> On Tue, Feb 15, 2005 at 10:56:23AM +1100, Delaney, Timothy C (Timothy) wrote: > friedmud at gmail.com wrote: > > > I guess I could just use one underscore.... but that means it is > > easier for other people to get at my implementation details (which, > > coming from a C++ background really bothers me). > > This is the correct solution, and getting over being bothered about it > is the correct thing to do. > > Getting at private members is simple in C++ too if anyone wants to do > that. As a long time C++ guy that switched over to python (via a perl detour) my advice is to do things the python way even if they feel strange at first. In this case forget about "private" and "protected." If it helps you can consider them conventions that have some compiler support. The 20th commandment of python is "we're all adults here." To see the first 19, type "import this" at the python prompt. I also discovered - to my shock and horror - that many of the GoF's "Design Patterns" were actually C++ centric and not universals. The sting of seeing canon reduced to a HOWTO fades quickly, just jump in with both feet. -Jack From sjmachin at lexicon.net Sun Feb 13 07:04:08 2005 From: sjmachin at lexicon.net (John Machin) Date: 13 Feb 2005 04:04:08 -0800 Subject: a Variable in multiple quotes... In-Reply-To: <614c778e.0502130204.5824cddf@posting.google.com> References: <614c778e.0502130204.5824cddf@posting.google.com> Message-ID: <1108296248.611612.186470@z14g2000cwz.googlegroups.com> administrata wrote: > Is it possible? > > I tried... > > > I = "John" > print \ > """ > I used to love pizza""" > > > Error occurs!!! > > But, I don't know how to fix... HELP > > thx 4 reading. Point 0: It helps if you post a copy of what the actual screen display looked like, instead of just saying "Error occurs!!!". It helps in that people are more likely to be bothered helping you, instead of just writing you off as clueless and unclueable -- and as you have chosen to try Python, you can't be utterly beyond redemption :-) Point 1: So, which error? Let's guess: You got something like this: ! print \ ! ^ !SyntaxError: invalid token If so, that is very likely because you had one or more spaces after the \. Backslash means line-continuation only if it is the LAST character in the line. If not, see point 0. Point 2: so-called multiple quotes: this is nothing to do with your problem. The different ways of quoting differ only in what characters like other quotes and newlines can appear inside the quotes. >>> 'I am John' is """I am John""" True Point 3: To print using what you call variables: >>> I = 'John' >>> print I, 'used to ...' John used to ... >>> print '%s used to ...' % I John used to ... >>> I = 'Fred' >>> print '%s used to ...' % I Fred used to ... >>> print I, 'used to ...' Fred used to ... >>> Point 4: How far through the Python tutorial have you progressed? Point 5: If some bright spark suggests something like the following, ignore them until you are up to speed on points[:5]: >>> print '%(I)s used to ...' % locals() Fred used to ... Point 6: If you don't understand the meaning of [:5], refer to point 4. HTH, John From alanmk at hotmail.com Thu Feb 10 18:03:43 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 10 Feb 2005 23:03:43 +0000 Subject: Python and version control In-Reply-To: References: Message-ID: [Peter Hansen] >>BTW, as a general caution: while Visual Source Safe may be >>"easy", it's also dangerous and has been known to corrupt >>many a code base, mine included. I wouldn't touch the product >>with a virtual ten-foot pole [Christos TZOTZIOY Georgiou] > Are you sure you got the acronym right?-) It seems that VSS provides viRTual > source-safety... In my circles, VSS is most often referred to as Visual Source Unsafe. -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From andreasp+python at qbcon.com Mon Feb 28 04:19:54 2005 From: andreasp+python at qbcon.com (Andreas Pauley) Date: Mon, 28 Feb 2005 11:19:54 +0200 (SAST) Subject: User Security (Roles & Permissions) Message-ID: Hi all, I'm starting with a Point of Sale system (QT gui, MySQL db) and I'm wondering if there are any user management/user security modules available that can be reused independently of the specific system that you write. I think something similar to the roles & permission scheme of Zope would work, were I can assign certain functionality/permissions to a role, and then assign each user a role. I'd prefer not to fully jump into Zope just yet, because although it has just about all the features you can think of, it is also fairly complex (for me at least). Regards, Andreas From PipedreamerGrey at yahoo.com Tue Feb 15 09:04:42 2005 From: PipedreamerGrey at yahoo.com (PipedreamerGrey at yahoo.com) Date: 15 Feb 2005 06:04:42 -0800 Subject: PythonCard and Py2Exe Message-ID: <1108476282.790371.155670@l41g2000cwc.googlegroups.com> I've been banging my head against this problem for a week. It's time to ask for help, because I'm obviously not going to solve this by trial and error. I'm trying to create a standalone version (.exe) of PythonCard's Custdb sample using Py2Exe version 0.5.0. Everytime I attempt to compile the program, I get an error during compilation. I need to formulate the correct setup file. Here's the one I began with: from distutils.core import setup from PythonCard import dialog, model import PythonCard import py2exe setup( name = "custdb", console = ["custdb.py"], data_files = [ (".", ["custdb.ini", "custdb.rsrc.py", "customerdata.csv"]) ] ) Every variation of this format failed. Does anyone have any ideas of how to re-write this Setup file? From eric_brunel at despammed.com Wed Feb 9 08:50:36 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 09 Feb 2005 14:50:36 +0100 Subject: tkinter menu bar problem References: Message-ID: On Wed, 09 Feb 2005 11:35:40 GMT, John Pote wrote: > I have a menu bar in a top level window as follows [snip code] > > Q1 Cannot find a way of changing the menu bars background colour. When > colour options are accepted they seem to be ignored. Is this a native > look > and feel characteristic of write once run anywhere, not yet implemented > or > possibly a bug. Even if the tk man pages [1] don't mention it, it would not be surprising if the background option for menu items did not work on Windows, since many things seem to be "hardcoded" on this platform. I tested the following code on Linux; it works without problem and has the expected behaviour: >>> from Tkinter import * >>> root = Tk() >>> mb = Menu(root) >>> root.configure(menu=mb) >>> m = Menu(mb) >>> mb.add_cascade(label='Menu', menu=m) >>> m.add_command(label='Quit', command=root.quit, background='red') If it is what you did and if it doesn't work on Windows, it is likely that the background option for menu items is not supported for this platform... > Q2 Some of the menu options in the config menu will not always be > available > depending on program state. How can individual items in such a menu be > turned to faint gey to indicate their unavailability. Also a tick mark > against an item would be useful to show the currently selected option. Is > this possible? To "grey out" a menu item: parentMenu.entryconfigure(itemIndex, state=DISABLED) To have menu items with a check-mark, use the add_checkbutton or add_radiobutton methods on the parent menu. Their use is similar to the Checkbutton and Radiobutton classes. See [1] for all available options. [1] http://www.tcl.tk/man/tcl8.4/TkCmd/menu.htm - Eric Brunel - From aisaac0 at verizon.net Fri Feb 11 11:57:09 2005 From: aisaac0 at verizon.net (David Isaac) Date: Fri, 11 Feb 2005 16:57:09 GMT Subject: a sequence question References: Message-ID: > Alan Isaac wrote: > > I see that [iter(l)]*N produces an N element list with each element being > > the same iterator object, but after that > > http://www.python.org/doc/2.3.5/lib/built-in-funcs.html > > just didn't get me there. "Nick Coghlan" wrote in message news:mailman.2388.1108127294.22381.python-list at python.org... > Py> itr = iter(range(10)) > Py> zipped = zip(*(itr,)*3) # How does this bit work? > # Manual zip, actually behaving somewhat like the real thing > Py> itr = iter(range(10)) > Py> zipped = [] > Py> try: > ... while 1: zipped.append((itr.next(), itr.next(), itr.next())) > ... except StopIteration: > ... pass http://www.python.org/doc/2.3.5/lib/built-in-funcs.html says: "This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences." So an "argument sequence" can in fact be any iterable, and these in turn are asked *in rotation* for their yield, right? So we pass the (identical) iterables in a tuple or list, thereby allowing a variable number of arguments. We unpack the argument list with '*', which means we have provided three iterables as arguments. And then zip works as "expected", once we have learned to expect zip to "rotate" through the arguments. Is that about right? If that is right, I still cannot extract it from the doc cited above. So where should I have looked? Thanks, Alan Isaac From mogmios at mlug.missouri.edu Thu Feb 3 12:22:22 2005 From: mogmios at mlug.missouri.edu (Michael) Date: Thu, 03 Feb 2005 09:22:22 -0800 Subject: character sets? unicode? Message-ID: <42025DCE.8080309@mlug.missouri.edu> I'm trying to import text from email I've received, run some regular expressions on it, and save the text into a database. I'm trying to figure out how to handle the issue of character sets. I've had some problems with my regular expressions on email that has interesting character sets. Korean text seems to be filled with a lot of '=3D=21' type of stuff. This doesn't look like unicode (or am I wrong?) so does anyone know how I should handle it? Do I need to do anything special when passing text with non-ascii characters to re, MySQLdb, or any other libraries? Is it better to save the text as-is in my db and save the character set type too or should I try to convert all text to some default format like UTF-8? Any advice? Thanks. -- Michael http://kavlon.org From timr at probo.com Wed Feb 9 02:32:37 2005 From: timr at probo.com (Tim Roberts) Date: Tue, 08 Feb 2005 23:32:37 -0800 Subject: Python mail filter References: <4208f1d0$1@news.starhub.net.sg> Message-ID: <92fj011sghl3nmrhef8h951r1aa8vp66vl@4ax.com> "Mailer" wrote: > >(P.S. I am very much aware of the existence of procmail, TMDA etc. My >requirements are very specific and requires integration with another >program, so I am only interested in getting a custom solution). But are you aware that a procmail recipe can feed a message through a filter, and then pass the results of that filter back in to the e-mail system for further processing? It seems to me that you should consider letting procmail do what it is good at, and use your Python solution for the things that are beyond it. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From itsme at yahoo.com Wed Feb 23 15:09:59 2005 From: itsme at yahoo.com (It's me) Date: Wed, 23 Feb 2005 20:09:59 GMT Subject: Pythoncard - Mistake in walkthrough? References: Message-ID: As stated in the on-line WalkThrough, the information there was written for an older version of the program. "Deltones" wrote in message news:e0f0f902.0502230849.3441e26a at posting.google.com... > Hi all, > > I'm just getting into Python/wxPython/Pythoncard and I'm trying the > tutorial from this page: > http://pythoncard.sourceforge.net/walkthrough1.html > > Is it me who's totally dense or there's some sort of confusion with > this tutorial? > > Here's what is said in the tutorial: > > Open the file starter1.py in your Python-aware editor of choice. The > Python script is, as you'd expect, brief and to the point. Here's the > important part to focus on: > > def on_menuFileExit_select(self, event): > pass > > > But here's the starter1.py code: > > #!/usr/bin/python > > from PythonCard import model > > class Minimal(model.Background): > pass > > if __name__ == '__main__': > app = model.Application(Minimal) > app.MainLoop() > > > As you can see, the on_menu line is not in the starter1.py original > script, so I guessed that it should be a part of the Minimal class. > > Then the tutorial ask me to replace the on_menu "pass" line with: > > result = dialog.alertDialog(self, 'It works!', 'Showing Off') > > but when you run the script, it runs, but clicking on Exit does not > display any dialog box. I did change the import line to include > dialog. > > Is there something I'm not seeing here or there is really a mistake > with the walkthrough? > > Thanks > > Denis From mwm at mired.org Tue Feb 8 22:35:50 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 08 Feb 2005 21:35:50 -0600 Subject: negative integer division References: <4208039c$0$28559$8fcfb975@news.wanadoo.fr> <42096EAD.879E8A5F@yahoo.com> Message-ID: <86wtti76cp.fsf@guru.mired.org> Jive Dadson writes: > Python does it right. C is allowed to do it anyway it likes, which was > a stupifyingly horrible decision, IMHO. C only does it wrong if you think that C is a high level language. It isn't - it's a portable assembler. As such, low level things (like this, or what happens on integer overflow, or ...) are left up to the implementation, so it can do what's most natural for the underlying hardware. This means that when you don't care - which I'd argue is most of the time - you get the fastest thing the machine will do. When you do care, you have to take care of it yourself. Of course, if you care, you probably shouldn't be writing in assembler, you should probably be writing in a high level language - which will make sure the low level things get done right, irregardless of what the underlying machine does. Now, I'll agree with you if you want to argue that some machines do negative integer division in stupifyingly horrible ways. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fuzzyman at gmail.com Tue Feb 8 04:46:33 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 8 Feb 2005 01:46:33 -0800 Subject: AsciiDoc 6.0.0 In-Reply-To: References: <4204241E.6010504@methods.co.nz> Message-ID: <1107855993.072360.48950@g14g2000cwa.googlegroups.com> Donnal Walter wrote: > Stuart Rackham wrote: > > AsciiDoc > > -------- > > AsciiDoc is an uncomplicated text document format for writing short > > documents, articles, books and UNIX man pages. > > > > AsciiDoc files can be translated to HTML (with or without > > stylesheets), DocBook (articles, books and refentry documents) > > and LinuxDoc using the asciidoc(1) command. > > Lately I've been thinking about using reStructuredText for creating > simple web pages. Should I consider AsciiDoc as an alternative, and if > so, what are its advantages by comparison? Thanks. > > Donnal Walter I've never used AsciiDoc - I've always found reST and docutils good though :-) Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From enleverlesO.OmcO at OmclaveauO.com Mon Feb 21 21:10:23 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Tue, 22 Feb 2005 03:10:23 +0100 Subject: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux & Windows XP References: Message-ID: <421ae161$0$1251$8fcfb975@news.wanadoo.fr> Hi ! For test your system, please, read this url : http://sivanataraja.free.fr/config/test.htm (french) http://www.alanwood.net/unicode/ (english) And many explains : http://en.wikipedia.org/wiki/Unicode And, to reassure you: I had no probl?me for use unicode chars with Tk (my tests on : French, German/Deutch, Cyrillic (russian), Grec). @-salutations -- Michel Claveau From rt-announce-bounces at lists.bestpractical.com Thu Feb 10 23:22:19 2005 From: rt-announce-bounces at lists.bestpractical.com (rt-announce-bounces at lists.bestpractical.com) Date: Thu, 10 Feb 2005 23:22:19 -0500 Subject: Your message to RT-Announce awaits moderator approval Message-ID: Your mail to 'RT-Announce' with the subject Delivery service mail Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://lists.bestpractical.com/cgi-bin/mailman/confirm/rt-announce/eb7146bdb096adc46ca1d1d923b0a06af232b1c1 From farcepest at gmail.com Thu Feb 17 19:20:01 2005 From: farcepest at gmail.com (Andy Dustman) Date: 17 Feb 2005 16:20:01 -0800 Subject: Why doesn't join() call str() on its arguments? References: <4214fea9$0$20394$636a15ce@news.free.fr> Message-ID: <1108686001.198554.21520@g14g2000cwa.googlegroups.com> I did some timings of ''.join( ) vs. ''.join( ) and found that generator expressions were slightly slower, so I looked at the source code to find out why. It turns out that the very first thing string_join(self, orig) does is: seq = PySequence_Fast(orig, ""); thus iterating over your generator expression and creating a list, making it less efficient than passing a list in the first place via a list comprehension. The reason it does this is exactly why you said: It iterates over the sequence and gets the sum of the lengths, adds the length of n-1 separators, and then allocates a string this size. Then it iterates over the list again to build up the string. For generators, you'd have to make a trial allocation and start appending stuff as you go, periodically resizing. This *might* end up being more efficient in the case of generators, but the only way to know for sure is to write the code and benchmark it. I will be at PyCon 2005 during the sprint days, so maybe I'll write it then if someone doesn't beat me to it. I don't think it'll be all that hard. It might be best done as an iterjoin() method, analogous to iteritems(), or maybe xjoin() (like xrange(), xreadlines()). Incidentally, I was inspired to do the testing in the first place from this: http://www.skymind.com/~ocrow/python_string/ Those tests were done with Python-2.3. With 2.4, naive appending (i.e. doing s1 += s2 in a loop) is about 13-15% slower than a list comprehension, but uses much less memory (for large loops); and a generator expression is about 7% slower and uses slightly *more* memory. From ksenia.marasanova at gmail.com Sat Feb 26 14:21:56 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Sat, 26 Feb 2005 21:21:56 +0200 Subject: Making a calendar In-Reply-To: <422071d5$0$22691$ba624c82@nntp04.dk.telia.net> References: <422071d5$0$22691$ba624c82@nntp04.dk.telia.net> Message-ID: <130df19305022611216f63530d@mail.gmail.com> This is close to what you want: http://freespace.virgin.net/hamish.sanderson/htmlcalendar.html You'll also need HTMLTemplate http://freespace.virgin.net/hamish.sanderson/htmltemplate.html From jeff at ccvcorp.com Thu Feb 17 19:58:35 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 17 Feb 2005 16:58:35 -0800 Subject: super not working in __del__ ? In-Reply-To: References: <11171oljbbb5cd3@corp.supernews.com> <1117k2oedccgidb@corp.supernews.com> Message-ID: <111afbnbs95t44b@corp.supernews.com> Christopher J. Bottaro wrote: > Jeff Shannon wrote: > >>Python's __del__() is not a C++/Java destructor. > > Learn something new everyday... What is it then? Excuse my ignorance, but > what are you suppose to do if your object needs to clean up when its no > longer used (like close open file handles, etc)? Well, those "open file handles" are presumably wrapped by file objects. Those file objects will close the underlying file handle as they are deallocated. This means that the only time you really need to worry about closing a file handle is if you want to reopen that same file immediately -- and in that case, __del__() can't help you because you can't know whether or not another reference to the file object exists somewhere else, so you'll have to explicitly close() the file anyhow. The same goes for sockets. > Are you use supposed to > make a method called Destroy() or something and require users to call it > when the object is about to be deleted? That seems to put the burdon of > ref counting on the user. Python's refcounting/GC scheme is such that you rarely actually need to explicitly destroy an object. Unlike C++, you're not actually freeing memory, and most of the resources that you might be using are already wrapped by an object that will finalize itself properly without being explicitly destroyed. Thanks to GC and the possibility of needing to break cycles, there's not much that you can guarantee about __del__() ... but there's not much that you *need* to do in __del__(). > It just seems > like kinda a pain when a C++/Java style destructor would nicely do what is > desired. Should I just stop digging and chalk it up to a limitation of > Python? Well, I guess you could look at it as a trade-off. In C++, you can count on your destructor getting called, but you have to do your own memory management. (Note that you still can't count on heap objects that your destructor might want to use still being there -- it's just that you can *never* count on such things in C++, and are always expected to ensure these things yourself.) Python will take care of your memory for you, and it will safely handle most OS resources for you, so that you don't have to worry about them... and in return, if you have some type of resource that Python doesn't automatically handle, you need to explicitly save it yourself. Now, while I haven't yet done anything terribly complicated nor tried to use extensive persistence, I've essentially never felt a need to use __del__() in Python, nor missed the "proper" destructor of C++. In general, cleanup takes care of itself, and in those cases where I have more demanding needs, well, it's not *that* hard to hook into application shutdown and explicitly save my data. So, I don't think it's so much a "limitation" of Python, as it is simply a different way of handling things. Jeff Shannon From steve at holdenweb.com Tue Feb 1 11:28:16 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 01 Feb 2005 11:28:16 -0500 Subject: variable declaration In-Reply-To: <44SdnUZGopnrAWLcRVn-pg@telcove.net> References: <1107205410.367521.50490@f14g2000cwb.googlegroups.com> <44SdnUZGopnrAWLcRVn-pg@telcove.net> Message-ID: <41FFAE20.7030802@holdenweb.com> Thomas Bartkus wrote: > "Carl Banks" wrote in message > news:1107205410.367521.50490 at f14g2000cwb.googlegroups.com... > > >>How common is it for a local variable to be bound in >>more than one place within a function? > > > How common? It shouldn't happen at all and that was the point. This seems a little excessive to me. Sample use case: for something in lst: if type(something) != type(()): something = tuple(something) regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.python.org/pycon/2005/ Steve Holden http://www.holdenweb.com/ From jerf at jerf.org Sat Feb 5 10:15:50 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 05 Feb 2005 10:15:50 -0500 Subject: [EVALUATION] - E01: The Java Failure - May Python Helps? References: Message-ID: On Sat, 05 Feb 2005 16:44:11 +0200, Ilias Lazaridis wrote: >> * Deployment: I don't generally have enough problems with this to be >> worth thinking about. I don't know what the state of the remote >> debugging is on Python; Google "remote debugging Python". > > [I like to avoid interaction with google.] OK, this, combined with a reputation that didn't quite precede you, but came close, leads me to say this: I've given you what you're going to get. You want more, you're going to have to put some effort into it. Lots of effort. But I can give you this: If you aren't already there, you're a textbook case of somebody heading for analysis paralysis. It's time to stop researching and start programming; grab Python, do a couple tutorials, and start acquiring the skills you're going to need to do these other tasks you want to do anyhow. Barring evidence that you are taking responsibility for yourself, I'm not inclined to help much more. From noreply at bidfraud.com Fri Feb 18 20:12:26 2005 From: noreply at bidfraud.com (bidfraud) Date: Sat, 19 Feb 2005 01:12:26 GMT Subject: www.bidfraud.com "Grand Opening" -- Read Inside for capabilities Message-ID: www.bidfraud.com "Grand Opening" -- Read Inside for capabilities After 1000 plus hours in development - Bidfraud.com is "breathing." http://www.bidfraud.com Features: Capable of archiving ebay auction transactions locally on our server. This is important, as ebay deletes transactions every few months. It is as simple as entering an ebay item number when creating a report. example of archived ebay page: http://www.bidfraud.com/cachedpages/6113839605/alouette-amusement/6113839605.html The above archived page, while it still exists at bidfraud.com, no longer exists at ebay.com Report templates contain an area to write a narrative as well as an interface to upload as many as 10 images/files (word & excel, etc.) The use of pictures as well as other supporting documents will help to substantiate & validate a claim. example of report with pictures: http://www.bidfraud.com/example.php Easy search interface capable of finding a suspect by user name, email or item number at various sites. Simple private messaging, including a chat system are provided. Registration is Free. Easy to use interface. If you wish to advertise on the site, it is free, but space is limited. Please use contact page on www.bidfraud.com to make a request. example of ad layout/dimensions: http://www.bidfraud.com/ads.htm Next time you leave negative feedback at ebay or any other site, please reference them to bidfraud. Thank you. From skip at pobox.com Wed Feb 2 11:03:12 2005 From: skip at pobox.com (System Administrator) Date: Wed, 2 Feb 2005 10:03:12 -0600 Subject: Python Code Auditing Tool In-Reply-To: <7xhdkvbjab.fsf@ruckus.brouhaha.com> References: <7xhdkvbjab.fsf@ruckus.brouhaha.com> Message-ID: <16896.63936.828022.197184@montanaro.dyndns.org> >> Does anybody know of a tool that can tell me all possible exceptions >> that might occur in each line of code? What I'm hoping to find is >> something like the following: Paul> That is impossible. The parameter to the raise statement is a Paul> class object, which can be anything. Sure, but in all but the rarest of cases the first arg to raise is a specific exception, probably one of the standard exceptions. In the Python code in the distribution (ignoring the test directory where all sorts of mischief is done to stress things), here are the most common words following "raise" where "raise" is the first word on the line: % find . -name '*.py' \ > | egrep -v '\./test' \ > | xargs egrep '^ *raise ' \ > | awk '{print $3}' \ > | sed -e 's/[(,].*//' \ > | sort \ > | uniq -c \ > | sort -rn \ > | head -15 246 ValueError 227 aetools.Error 216 Error 124 TypeError 101 error 75 RuntimeError 53 IOError 36 NotImplementedError 36 ImportError 36 EOFError 31 SyntaxError 23 KeyError 23 AttributeError 22 DistutilsPlatformError 21 UnicodeError Without checking, my guess is that #5 ("error") is one of a handful of exception classes defined at module scope (ftplib, anydbm, sre_constants, poplib, among others all define such an exception class), and not a variable that accepts multiple values as in your example. In short, while not perfect, simply grepping for '^ *(class|def|raise) ' and printing the first and second words of each output line would probably give you a pretty good idea of what gets raised where. Skip From fperez.net at gmail.com Fri Feb 4 17:46:19 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Fri, 04 Feb 2005 15:46:19 -0700 Subject: IPython colors in windows References: <1107487113.732375.110850@c13g2000cwb.googlegroups.com> <36hculF51ho2sU1@individual.net><1107530489.308497.103530@g14g2000cwa.googlegroups.com><36hrjpF4ui8fbU1@individual.net> <36i84qF52ce29U1@individual.net> Message-ID: Ashot wrote: > this is what it looks like: > > http://www.freshraisins.com/sand/ipythonscreen.PNG > > does cygwin have a readline utility in it? Perhaps this is overriding the > correct one? Thats the only thing I can think of. Thanks for the screenshot. I've contacted the readline author, I'll report back when there are news about a possible fix. Regards, f From ilias at lazaridis.com Mon Feb 21 18:58:58 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Tue, 22 Feb 2005 01:58:58 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: <37uk2kF5gv38bU1@individual.net> References: <874qg6937w.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <37uk2kF5gv38bU1@individual.net> Message-ID: George Sakkis wrote: > "Ilias Lazaridis" wrote in message news:cvcv9b$nbm$1 at usenet.otenet.gr... > >>Nick Vargish wrote: >> >>>You can excuse yourself from this one and stop replying to comments, >>>but you don't get to unilaterally declare a discussion over. >>[...] >> >>The discussion is over. >> >>At least the in-topic one. >> >>Everything else is babbling, hairsplitting, playing an AI which does not >>understand writings and all this unproductive garbage. >> >>The Essence is this one, as stated before: >> >>[huge copy paste of previous post] > > The Essence is irrelevant. It seems that this is true. > - > - > - > All your thread are belong to us. This is true ["us" = a few off-topic-freaks] > - > - > - > > George [EVALUATION] - E02 - Support for MinGW Open Source Compiler Essence: http://groups-beta.google.com/group/comp.lang.python/msg/5ba2a0ba55d4c102 . -- http://lazaridis.com From Dennis.Benzinger at gmx.net Tue Feb 1 17:58:06 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Tue, 01 Feb 2005 23:58:06 +0100 Subject: MySQLdb - Tuples In-Reply-To: <3vTLd.19498$Of5.13133@nntpserver.swip.net> References: <3vTLd.19498$Of5.13133@nntpserver.swip.net> Message-ID: <4200097f$1@news.uni-ulm.de> Lajos Kuljo wrote: > Hallo, > ich bin voll neu im Python-Programming, deshalb ist mein Problem > wahrscheinlich trivial: > > Wenn ich die Script > #########################################33 > #! /usr/bin/env python > import MySQLdb > db=MySQLdb.connect(host='localhost', db='photum_0_6_2', user='root', > passwd='thkhgfgd') > c=db.cursor() > c.execute('select person from persons order by person') > tup=c.fetchall() > for a in tup: > print a > ################################################ > ausf?hre, erhalte ich Dinge wie > ('Dieter',) > ('Hulda',) > .... > > Ich brauche die Klammern, Apostrphe und Kommas nicht (ich will nur die > Inhalte) und kann ich sie nicht loswerden. Versucht habe ich u. a. print > a[2:-3] was nur zwei Klammern bringt. > b=lstrip(a, "(") haut auch nicht hin. > Weiss jemand Rat? Hab gerade kein MySQL da, aber ?nder mal for a in tup: print a in for a in tup: print a[0] # Das erste Element des Tupels Dann wird statt des ganzen Tupels nur das erste Element ausgegeben. > P.S. Woher kommen diese Klammern und Apostrophen, vom MySQLdb? Die Klammern und Apostrophe kommen daher, dass tup ein Tupel (http://docs.python.org/lib/typesseq.html) mit einem Element (der Person) ist. Dennis From exogen at gmail.com Sat Feb 12 21:55:21 2005 From: exogen at gmail.com (Brian Beck) Date: Sat, 12 Feb 2005 21:55:21 -0500 Subject: Iterate through dictionary of file objects and file names In-Reply-To: References: <420deb18$1_1@news.iprimus.com.au> Message-ID: jfj wrote: > Call me a pedant, but what'd wrong with: > > print 'closed: ' + filename > or > print 'closed:', filename > > ? I always figure that debug-oriented output like that in example code is very likely to be changed in format, or to include more information, by the person actually using it. So string substitution makes it more flexible; less work for them. -- Brian Beck Adventurer of the First Order From grante at visi.com Tue Feb 15 16:53:42 2005 From: grante at visi.com (Grant Edwards) Date: 15 Feb 2005 21:53:42 GMT Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: <42123751$0$10042$626a14ce@news.free.fr> <421244f0$0$30339$636a15ce@news.free.fr> Message-ID: <42126f66$0$46556$a1866201@visi.com> On 2005-02-15, bruno modulix wrote: > Ilias Lazaridis wrote: > >> impressive. >> >> but things are much simpler. > > Could you be more prolific ? Good god, let's hope not! -- Grant Edwards grante Yow! I'm working under at the direct orders of WAYNE visi.com NEWTON to deport consenting adults! From suryaprakashg at gmail.com Thu Feb 10 12:33:43 2005 From: suryaprakashg at gmail.com (suryaprakashg at gmail.com) Date: 10 Feb 2005 09:33:43 -0800 Subject: Newbie: SWIG or SIP? In-Reply-To: References: Message-ID: <1108056823.384640.133250@f14g2000cwb.googlegroups.com> Look at this , this might be more simple to use http://starship.python.net/crew/theller/ctypes/ Phil Thompson wrote: > > I have a third-party DLL and it's associated .h file. The DLL was written > > in C. I have neither the associated .c files nor the .obj files for the > > DLL. Can I use SWIG or SIP to build something that will allow me to use > > the > > DLL with Python? And what is that something, an .obj file, another DLL or > > what? > > Yes, you can use either SWIG or SIP. C (as opposed to C++) support was > added with SIP v4. The something is another DLL, conventionally given a > .pyd extenstion. > > Phil From adykes at panix.com Fri Feb 4 09:20:39 2005 From: adykes at panix.com (Al Dykes) Date: 4 Feb 2005 09:20:39 -0500 Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> Message-ID: In article , Dave Brueck wrote: >Paul Rubin wrote: >> How would you go about building such a site? Is LAMP really the right >> approach? > >Two major problems I've noticed, don't know if they are universal, but they sure >hurt the performance: > >1) Some sites have not put any thought into caching - i.e. the application >server is serving up images or every single page is dynamically generated even >though all (or most) of it is static such that most of the requests just aren't >cacheable. > >2) Because a database is there, it gets used, even when it shouldn't, and it >often gets used poorly - bad or no connection pooling, many trips to the >database for each page generated, no table indices, bizarro database schemas. > >Overall I'd say my first guess is that too much is being generated on the fly, >often because it's just easier not to worry about cacheability, but a good web >cache can provide orders of magnitude improvement in performance, so it's worth >some extra thought. > >One project we had involved the users navigating through a big set of data, >narrowing down the set by making choices about different variables. At any point >it would display the choices that had been made, the remaining choices, and the >top few hits in the data set. We initially thought all the pages would have to >be dynamically generated, but then we realized that each page really represented >a distinct and finite state, so we went ahead and built the site with Zope + >Postgres, but made it so that the URLs were input to Zope and told what state to >generate. > >The upshot of all this is that we then just ran a web spider against Zope any >time the data changed (once a week or so), and so the site ended up "feeling" >pretty dynamic to a user but pretty much everything came straight out of a cache. > >-Dave A couple years ago the Tomshardware.com website was reengeneered to cache everything possible with great performance improvement. They wrote a nice article about the project, which I assume is still online. I don't -- a d y k e s @ p a n i x . c o m Don't blame me. I voted for Gore. From nick at craig-wood.com Mon Feb 28 05:30:03 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 28 Feb 2005 10:30:03 GMT Subject: Flushing print() References: Message-ID: Cameron Laird wrote: > gf, remember to write > > sys.stdout.flush() > > rather than > > sys.stdout.flush > > That's a mistake that catches many. Many old perl programmers anyway (me included)! Its also a mistake pychecker catches. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From sjmachin at lexicon.net Thu Feb 17 15:00:29 2005 From: sjmachin at lexicon.net (John Machin) Date: 17 Feb 2005 12:00:29 -0800 Subject: Alternative to standard C "for" In-Reply-To: References: <1107628331.816935.16760@o13g2000cwo.googlegroups.com> <740c3aec050205104924a82d23@mail.gmail.com> <1108620618.3892.85.camel@lipscomb.mbi.ucla.edu> Message-ID: <1108670429.628087.326690@l41g2000cwc.googlegroups.com> James Stroud wrote: > > It seems I need constructs like this all of the time > > i = 0 > while i < len(somelist): > if oughta_pop_it(somelist[i]): > somelist.pop(i) > else: > i += 1 > > There has to be a better way... > ! for i in xrange(len(somelist)-1, -1, -1): ! if oughta_pop_it(somelist[i]): ! del somelist[i] # why use pop?? We don't need no stinking iterators; we're the Python_1.5_or_earlier_istas! From deetsNOSPAM at web.de Mon Feb 7 12:33:11 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 07 Feb 2005 18:33:11 +0100 Subject: Python Binary and Windows References: Message-ID: <36pms5F55738vU1@individual.net> peetm wrote: > Hi. > > I'd like to compile (?) the DiffLib Python code into a binary form that > can be called by other Windows apps - like, I'd like to compile it into a > DLL. > > Is this possible? Not so easy. Better install WinDiff. If you really have to do it, elmer will be of use for you. http://www.python.org/moin/elmer But it will still be far from being trivial. -- Regards, Diez B. Roggisch From peter at engcorp.com Wed Feb 2 12:54:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 02 Feb 2005 12:54:13 -0500 Subject: Python Code Auditing Tool In-Reply-To: References: <7xhdkvbjab.fsf@ruckus.brouhaha.com> Message-ID: <2LydnViDKZ1ejpzfRVn-qg@powergate.ca> Roy Smith wrote: > Skip Montanaro wrote: >> 246 ValueError >> 227 aetools.Error >> 216 Error >> 124 TypeError >> 101 error >> 75 RuntimeError >> 53 IOError >> 36 NotImplementedError >> 36 ImportError >> 36 EOFError >> 31 SyntaxError >> 23 KeyError >> 23 AttributeError >> 22 DistutilsPlatformError >> 21 UnicodeError > > It's kind of interesting (scarry?) that in roughly 20% of the cases > nothing more specific than Error is raised. (In case someone reading doesn't know) there isn't actually an "Error" in the standard set of exceptions. It seems likely that pretty much all of those uses are actually module-specific Errors, and as such they are probably much more specific than the unadorned name might imply. Also, when one is trying to pick an appropriate exception to raise, it is often the case that none of the standard exceptions seems appropriate. In those cases (although I personally would prefer a different name than "Error") there's often no good alternative to making your own unique module-specific Exception subclass. -Peter From steven.bethard at gmail.com Thu Feb 3 17:29:13 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 03 Feb 2005 15:29:13 -0700 Subject: List mapping question In-Reply-To: References: Message-ID: Marc Huffnagle wrote: > I have a number of variables that I want to modify (a bunch of strings > that I need to convert into ints). Is there an easy way to do that > other than saying: > > > a = int(a) > > b = int(b) > > c = int(c) > > I tried > > > [i = int(i) for i in [a, b, c]] > > but that didn't work because it was creating a list with the values of > a, b and c instead of the actual variables themselves, then trying to > set a string equal to an integer, which it really didn't like. Actually, that didn't work because it's a SyntaxError to have an assigment statement inside a list comprehension: py> [i = int(i) for i in [a, b, c]] Traceback ( File "", line 1 [i = int(i) for i in [a, b, c]] ^ SyntaxError: invalid syntax You could try something like: py> a, b, c ('1', '2', '3') py> a, b, c = [int(i) for i in (a, b, c)] py> a, b, c (1, 2, 3) For a few variables, this is probably a reasonable solution. For more than 4 or 5 though, it's going to get unreadable. Of course for that many variables, you should probably be keeping them in a list instead of as separate names anyway... Steve From mikey666 at 666swampgas.666com Wed Feb 2 09:54:08 2005 From: mikey666 at 666swampgas.666com (The Artist Formerly Known as Kap'n Salty) Date: Wed, 02 Feb 2005 08:54:08 -0600 Subject: web camera or else ? 15-30 fps processing of camera videos. In-Reply-To: <1107303983.662065.93580@c13g2000cwb.googlegroups.com> References: <1107295229.657375.318750@o13g2000cwo.googlegroups.com> <420006a5$0$714$c3e8da3@news.astraweb.com> <1107303983.662065.93580@c13g2000cwb.googlegroups.com> Message-ID: <4200e998$0$1539$c3e8da3@news.astraweb.com> JGCASEY wrote: > The Artist Formerly Known as Kap'n Salty wrote: > >>Newbie wrote: >> >>>I am doing some robotics projects but my main area of interest is >>>trying out several algorithms for the processing of the stream of > > data > >>>coming from the video. >>> >>>I am wondering what type of camera I should invest in. Either I > > could > >>>buy a web cam and hope I can find a driver I could either modify or >>>use. i.e. every frame is somehow stored on the computer > > automagically > >>>or I could buy a camera not unlike the AVRcam >>>(http://www.jrobot.net/Projects/AVRcam.html) or the CMUcam and try > > to > >>>do the processing once the data has been streamed to the nearest >>>computer ? or should I use an expensive video card, some CCTV > > camera > >>>and a frame grabber to digitize photos so they can be processed >>>afterwards. I expect my processing algorithms to handle at least 15 >>>frames per second framerate once they are working ont the final > > set-up. > >>>My constraints are that I would like to avoid as much as possible >>>complex set-ups even if that means buying a more expensive camera >>>set-up. For the prototyping, I would like to try my algorithms out >>>using a combination of python and matlab (all very slow) and then >>>expect the same architecture (image files location and flow) with >>>speedier set-up like python+psyco or C. All the processing would be >>>done on a computer dedicated for that. Windows or Linux are > > possible. > >>An easy approach to this is to use a wireless camera on your robot, > > with > >>the receiver attached to a frame grabber on a remote host. This > > allows > >>you your choice of camera (stand alone video transmitters are widely >>available), and you are not limited to only processing hardware you > > can > >>carry on board your robot. You also get full FPS. Frame-grabber cards > > >>are inexpensive and widely available for both Windows and Linux. > > > I wanted to go down that path but cannot get > information on how to access the images from > the tv receiver card in real time using my > own software. > > Do you use Java? > > John Casey > I do, but not for image processing. There IS a multi-media SDK out there for java that handles video capture -- google should help you out here (I can't recall the site). I'm not entirely sure how mature it is. I looked a couple of years back and decided to avoid it. It likely does not support all platforms, since video capture drivers vary a good bit by platform. This all may have changed, however. On Windows, you'll use DirectShow (part of DirectX) to get incoming frames. There's also the deprecated VFW (Video for Windows). On linux, there's Video for Linux. In either case, the APIs are not difficult to use. You should never have to access the hardware directly. Note that whether you get the video from a webcam or framegrabber, the APIs are the same. I've actually abstracted some of the DirectX stuff out to the point that I can get frames from a video file *or* a camera the same way. -- (Replies: cleanse my address of the Mark of the Beast!) Teleoperate a roving mobile robot from the web: http://www.swampgas.com/robotics/rover.html From peter at somewhere.com Tue Feb 8 15:24:48 2005 From: peter at somewhere.com (Peter Maas) Date: Tue, 08 Feb 2005 21:24:48 +0100 Subject: Is Python as capable as Perl for sysadmin work? In-Reply-To: References: Message-ID: <36slkbF54d2sjU2@individual.net> Jeff Epler schrieb: > Unlike Perl, Python implements only a *finite turning machine* model of > computation. An easy way to see this limitation is in the following > code: > >>> 1.0 / 10.0 > 0.10000000000000001 > In an infinite Turning machine, there would be an unbounded number of > zeros before the second 1, giving the exact result, not a numeric > approximation. Boy, you are cheating us!!!! Wake up, this isn't April 1st! :))) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From tom.willis at gmail.com Tue Feb 22 19:02:47 2005 From: tom.willis at gmail.com (Tom Willis) Date: Tue, 22 Feb 2005 19:02:47 -0500 Subject: python tutorial/projects In-Reply-To: References: <56190b6c050222154816a2e2a3@mail.gmail.com> Message-ID: You know, I hate doing this.... I just remembered the Bruce Eckel book is a direct transaltion from THinking In Patterns for Java. And as such the example python code within the chapters is not even valid Python. If you're new to the language you'll get confused with the use of private and static thrown everywhere. It's still good information though. On Tue, 22 Feb 2005 18:56:24 -0500, Tom Willis wrote: > I found this one helpful > > http://diveintopython.org/ > > and this one > > http://ibiblio.org/obp/thinkCS/python/english/ > > Just found this one > http://hetland.org/python/instant-python > > and this page has links to many more. > > http://www.python.org/doc/Intros.html > > And because I'm a huge Bruce Eckel fan. > > Thinking in Python > http://mindview.net/Books/TIPython > > It's old, but I still go through it every now and then. > > > -- > Thomas G. Willis > http://paperbackmusic.net > > > On Tue, 22 Feb 2005 16:48:48 -0700, Steve Juranich wrote: > > I think the tutorial offered at www.python.org/tut/tut.html is as good > > a starting place as any. > > > > I wouldn't be able to suggest a "non-trivial" project without knowing > > more about your background. Can you do a flashcard program? recipe > > organizer? SETI at Home client? (I think you see where this is going). > > > > Good luck. > > > > On Tue, 22 Feb 2005 15:23:37 -0800, Danny > > wrote: > > > Does anyone know of a good python tutorial? > > > I was also looking for some non-trivial projects to do in python. > > > > > > Basically I would like to claim on my resume, that I know python, with > > > out bad karma. > > > > > > Danny > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -- Thomas G. Willis http://paperbackmusic.net From zathras at thwackety.com Sat Feb 12 08:12:34 2005 From: zathras at thwackety.com (Michael Sparks) Date: Sat, 12 Feb 2005 13:12:34 +0000 (GMT) Subject: Python in EDA In-Reply-To: <1108165423.522756.151000@z14g2000cwz.googlegroups.com> Message-ID: On 11 Feb 2005 vsapre80 at gmail.com wrote: > Hi, > > I am new to Python and coming from the EDA/VLSI Design background. > > I wanted to know if there are some active projects going on EDA modules > written in Python. You may want to take a look at MyHDL & APVM/Oroboro: * http://jandecaluwe.com/Tools/MyHDL/Overview.html * http://apvm.sourceforge.net/ (and specifically http://apvm.sourceforge.net/oro_025.html) The former aims to used python as an HDL allowing a subset of python to be used to design hardware, the latter is aimed at helping verilog based hardware verification (by the looks of things). Both use python generators to handle concurrency. For a brief and nice introduction to generators, it's well worth reading this article: * http://www-106.ibm.com/developerworks/linux/library/l-pythrd.html Best Regards, Michael. From janeaustine50 at hotmail.com Wed Feb 23 20:35:24 2005 From: janeaustine50 at hotmail.com (janeaustine50 at hotmail.com) Date: 23 Feb 2005 17:35:24 -0800 Subject: Style guide for subclassing built-in types? In-Reply-To: References: <1109127834.660822.247120@g14g2000cwa.googlegroups.com> <1109150091.356411.150460@l41g2000cwc.googlegroups.com> <1109151417.903188.73790@f14g2000cwb.googlegroups.com> <421c76cd$1_1@newspeer2.tds.net> <1109163706.118457.53720@z14g2000cwz.googlegroups.com> Message-ID: <1109208924.563510.212500@f14g2000cwb.googlegroups.com> Michael Spencer wrote: > janeaustine50 at hotmail.com wrote: > > Kent Johnson wrote: > > > >>janeaustine50 at hotmail.com wrote: > >> > >>>p.s. the reason I'm not sticking to reversed or even reverse : > > > > suppose > > > >>>the size of the list is huge. > >> > >>reversed() returns an iterator so list size shouldn't be an issue. > >> > >>What problem are you actually trying to solve? > >> > >>Kent > >> > > > > > > Oh, you are right. > > > > Actually, it's more complicated than simple reversion. The list order > > should be somewhat "twisted" and the list is big. > > > > For example, > > > > [1,2,3,4,5,6,7,8,9,10] > > > > --> [10,9,8,7,6,1,2,3,4,5] > > > > so __getitem__(self,i) => __getitem__(self,-i-1) if i > otherwise __getitem__(self,i-len(size)/2) > > > > I'd like to have TwistedList class that takes in an original list and > > pretends as if it is twisted actually. However, I have to have > > duplicate codes here and there to make it act like a "list", say assert > > twisted_list == [10,9,...] and for each in twisted_list and etc. > > > If you want a twisted 'view' of an existing list, then a wrapper makes most sense. > > If, however, you only need the twisted version, why not simply override > list.__init__ (and extend, append etc... as required): > > >>> class rev_list(list): > ... def __init__(self, iterable): > ... list.__init__(self, iterable[::-1]) > ... > >>> l = rev_list([1,2,3]) > >>> l > [3, 2, 1] > > Michael Thank you but your advice doesn't fit in my case since I want to keep the memory usage and the initial time minimum. iterable[::-1] would build another list and it would take big memory and time during reversing if iterable were huge. (and the "iterable" wouldn't be garbage-collected because I want to keep a reference to it) From removethis.kartic.krishnamurthy at gmail.com Wed Feb 2 22:06:41 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Thu, 03 Feb 2005 03:06:41 GMT Subject: Finding user's home dir In-Reply-To: <5i9rtc.rq31.ln@orion.homeinvalid> References: <5i9rtc.rq31.ln@orion.homeinvalid> Message-ID: <5zgMd.22089$MX2.5133@twister.nyroc.rr.com> Nemesis said the following on 2/2/2005 2:26 PM: > Hi all, I'm trying to write a multiplatform function that tries to > > def getHomeDir(): > ''' Try to find user's home directory, otherwise return current directory.''' > > Please, could you test it on your systems and tell me what you got? > I'd like to know what it returns on different operating systems because > I'm developing a multiplatform software. > > Thank you all. Neat! Works fine on Freebsd 5.3, Python 2.4 Thanks, -Kartic From deetsNOSPAM at web.de Mon Feb 21 12:09:32 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 21 Feb 2005 18:09:32 +0100 Subject: Unittest - testing properties (read-only attributes) References: Message-ID: <37uis9F5h48svU1@individual.net> Paul Moore wrote: > I have a class with a read-only attribute, and I want to add a unit > test to ensure that it really *is* read-only. I can do this as > > def test_readonly(self): > """Value and multiplier must be readonly""" > try: > self.combat.value = 1 > self.fail("Value is not read only") > except AttributeError: > pass > > That works, but it seems a bit clumsy. Is there a better way? By using setattr, you could refactor the above code into a function. Looks like this (untested): def test_readonly(self, instance, attribute, value=1): """Value and multiplier must be readonly""" try: setattr(instance, attribute, value) self.fail("Value is not read only") except AttributeError: pass Then the testing becomes one line: self.test_readonly(self.combat, "value") -- Regards, Diez B. Roggisch From tbunce at mac.com Tue Feb 1 15:05:53 2005 From: tbunce at mac.com (Thomas Bunce) Date: Tue, 01 Feb 2005 12:05:53 -0800 Subject: How do you do arrays References: Message-ID: Thanks all Tom From donn at u.washington.edu Mon Feb 7 12:40:01 2005 From: donn at u.washington.edu (Donn Cave) Date: Mon, 07 Feb 2005 09:40:01 -0800 Subject: Memory Allocation? References: <8GCNd.9880$ya6.9761@trndny01> Message-ID: In article <8GCNd.9880$ya6.9761 at trndny01>, "Chris S." wrote: > Is it possible to determine how much memory is allocated by an arbitrary > Python object? There doesn't seem to be anything in the docs about this, > but considering that Python manages memory allocation, why would such a > module be more difficult to design than say, the GC? Sorry, I didn't follow that - such a module as what? Along with the kind of complicated internal implementation details, you may need to consider the possibility that the platform malloc() may reserve more than the allocated amount, for its own bookkeeping but also for alignment. It isn't a reliable guide by any means, but something like this might be at least entertaining - >>> >>> class A: ... def __init__(self, a): ... self.a = a ... >>> d = map(id, map(A, [0]*32)) >>> d.sort() >>> k = 0 >>> for i in d: ... print i - k ... k = i ... This depends on the fact that id(a) returns a's storage address. I get very different results from one platform to another, and I'm not sure what they mean, but at a guess, I think you will see a fairly small number, like 40 or 48, that represents the immediate allocation for the object, and then a lot of intervals three or four times larger that represent all the memory allocated in the course of creating it. It isn't clear that this is all still allocated - malloc() doesn't necessarily reuse a freed block right away, and in fact the most interesting thing about this experiment is how different this part looks on different platforms. Of course we're still a bit in the dark as to how much memory is really allocated for overhead. Donn Cave, donn at u.washington.edu From gb at cs.unc.edu Sat Feb 5 20:48:01 2005 From: gb at cs.unc.edu (Gary Bishop) Date: 5 Feb 2005 20:48:01 -0500 Subject: IPython colors in windows References: <36hculF51ho2sU1@individual.net> <1107530489.308497.103530@g14g2000cwa.googlegroups.com> <36hrjpF4ui8fbU1@individual.net> <36i84qF52ce29U1@individual.net> <36l1dgF52b9d6U1@individual.net> <4205605f_2@news.unc.edu> Message-ID: <42057751_1@news.unc.edu> On SourceForge you will find release 1.12 of my Python readline module. If you don't want to hack the colors, there is no reason to upgrade from 1.11 to 1.12. They *should* work the same. But if you'd like to hack the iPython colors this new version makes it possible. In your ipythonrc file add a line like: execfile hackcolors.py Now in hackcolors.py you can change colors and backgrounds like this: ####hackcolors.py#### import readline # reach deep into the bowels of readline to get the color table escape_to_color = readline.rl.console.escape_to_color # change a color escape_to_color['0;32'] = 0x72 del escape_to_color del readline ################# The two hex digits are the background and foreground color respectively. In the example above I'm setting the color to green on a grey background. Here is the table that is normally used to translate colors. escape_to_color = { '0;30': 0x0, #black '0;31': 0x4, #red '0;32': 0x2, #green '0;33': 0x4+0x2, #brown? '0;34': 0x1, #blue '0;35': 0x1+0x4, #purple '0;36': 0x2+0x4, #cyan '0;37': 0x1+0x2+0x4, #grey '1;30': 0x1+0x2+0x4, #dark gray '1;31': 0x4+0x8, #red '1;32': 0x2+0x8, #light green '1;33': 0x4+0x2+0x8, #yellow '1;34': 0x1+0x8, #light blue '1;35': 0x1+0x4+0x8, #light purple '1;36': 0x1+0x2+0x8, #light cyan '1;37': 0x1+0x2+0x4+0x8, #white '0': None, } An interested party should be able to arbitrarily map colors and their backgrounds. Enjoy, gb From bvande at po-box.mcgill.ca Mon Feb 7 20:36:15 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon, 07 Feb 2005 20:36:15 -0500 Subject: variable declaration In-Reply-To: References: <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com> Message-ID: <4208178F.40804@po-box.mcgill.ca> Steve Holden said unto the world upon 2005-02-07 17:51: > Alexander Zatvornitskiy wrote: > >> ?????? Alex! >> >> 05 ??????? 2005 ? 17:00, Alex Martelli ? ????? ?????? ? All ?????: >> AM> to all intents and purposes working "as if" >> AM> it was a declaration. If I had to vote about the one worst formal >> AM> defect of Python, it would surely be 'global'. >> Second worsest - 'def'? :) >> > The reason global is a wart can clearly be seen in the following example: > > >>> x = 3 > >>> def f(tf, v): > ... if tf: > ... global x > ... x = v > ... > >>> f(0, 5) > >>> x > 5 > >>> > > This makes it apparent that the global statement is *not* executable, > the only one in the language that is not. > regards > Steve Hi, Steve's example makes my brain hurt. :-) I'd appreciate it if someone could tell me if I am understanding the example correctly. (My grasp of the terminology and issues at play is a bit shaky.) Let me simplify Steve's example to: .def hurts_my_brain(v): . if False: # unlike Steve's eg, ensuring that the . global x # nested block is never hit at runtime . x = v (I checked, and it works the same as the original eg, modulo change of function name.) Is the right way to understand it in this vicinity: At compile time (by which I mean when the Python bytecode is built) the global statement is hit and has the effect of `bumping up' the function local name `x' to the module namespace, making the function local name `x' synonymous with the module global name `x'. At runtime, the `global x' is never reached, but it has already, at compile time, had its effect on the nature of the function object hurts_my_brain. Further, if the function had instead said 'if True:' the global statement would have been reached at runtime, but would have been without effect due to this, having already been `used up' in the creation of the bytecode. Can it then be further (truly :-) ) said that if False: # thousands of lines of code here would effect the structure of the function object's bytecode, but not its behaviour when run? Or, at most, would cause a performance effect due to the bytecode being bloated by thousands of line's worth of code that would never get executed? Thanks for any confirmation of my understanding / rectification of same. Best, Brian vdB From ods at strana.ru Sat Feb 12 03:49:41 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Sat, 12 Feb 2005 11:49:41 +0300 Subject: sre is broken in SuSE 9.2 In-Reply-To: References: <1108060527.378911.146240@o13g2000cwo.googlegroups.com> <420D4D9A.40201@v.loewis.de> Message-ID: <20050212114941.024f636b.ods@strana.ru> On Sat, 12 Feb 2005 09:42:41 +0100 "Fredrik Lundh" wrote: > the relevant part for this thread is *locale-*. if wctype depends on > the locale, it cannot be used for generic build. (custom interpreters > are an- other thing, but they shouldn't be shipped as "python"). You are right. But isalpha behavior looks strange for me anyway: why cyrillic character '\u0430' is recognized as alpha one for de_DE locale, but is not for C? -- Denis S. Otkidach http://www.python.ru/ [ru] From drew at gremlinhosting.com Thu Feb 3 08:20:58 2005 From: drew at gremlinhosting.com (Andrew James) Date: Thu, 03 Feb 2005 13:20:58 +0000 Subject: ModPython: passing variables between handlers? Message-ID: <4202253A.7050704@gremlinhosting.com> Hi all, I'm writing an application which runs within Apache and uses mod_python to provide basic authentication and return content to the user, something like: import modpython .... def handler(): # main part of the application starts here ... def authenhandler(): ... # Store information about the user in an object u = new User(req.user, pass) I'd like to be able to pass the u object somehow from authenhandler to handler in an elegant fashion, but without using global variables (as I understand it these persist for the life of the child process which will be more than one request, which is not what I want, and could be a security hole). I suppose that I could use session variables, but since this part of my application provides a WebDAV server, basic authentication credentials are passed on each request (so I don't really want to have to look after keeping track of sessions when I don't have to). I would rather not modify all my existing classes to support an extra parameter in their constructors. What I'm really looking for is some sort of global dictionary like PHP's $REQUEST or $SESSION, which I can assign freely to during the life of the request *from anywhere in my application* and which gets cleaned up for me automatically afterwards. Does something like this exist in mod_python? If the approach above isn't possible, what would your recommendations be for a solution to this issue? Many thanks for your time, Andrew James From t-meyer at ihug.co.nz Thu Feb 17 21:21:21 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 18 Feb 2005 15:21:21 +1300 Subject: how can i randomly choose keys in dictionary In-Reply-To: Message-ID: > Hi,there. How can I choose a key in dictionary randomly? > > Say, random.choice() in lists, A dictionary's keys() are a list, so you already have the answer: >>> import random >>> d = {'a': 1, 'b': 2, 'c': 3} >>> random.choice(d.keys()) =Tony.Meyer From deetsNOSPAM at web.de Wed Feb 9 10:05:20 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 09 Feb 2005 16:05:20 +0100 Subject: Is email package thread safe? (fwd) References: Message-ID: <36un5fF568c6lU1@individual.net> Usually, oo-style apis are thread-safe as long as each thread uses its own objects. Shared global state is _very_ uncommon, and if it's most probably documented. -- Regards, Diez B. Roggisch From aahz at pythoncraft.com Tue Feb 8 00:55:19 2005 From: aahz at pythoncraft.com (Aahz) Date: 8 Feb 2005 00:55:19 -0500 Subject: Is Python as capable as Perl for sysadmin work? References: Message-ID: In article , John M. Gabriele wrote: > >For sysadmin-related tasks, is Python as useful as Perl, or does it get >clumsy when often dealing with the stuff admins deal with on a regular >basis? > >At some point during some dingy job in the back boiler room of Unix, >would you find yourself saying, "geez, I'd wish I started this with >Perl -- Python just isn't cutting it." ? Not likely. I'm a programmer, not a sysadmin, but my company's too small for a sysadmin, so I and the other two programmers get elected. (For example, today most of my time was spent hunting down kernel patches for Red Hat 7.3 -- long story.) Anyway. Have you ever noticed how shell scripts keep getting longer? Ever notice how it gets harder to figure out what the heck any given script's doing? Well, that's where Python helps you out compared to Perl. Python can be a bit clumsier than Perl for dirt-simple tasks, but you'll find that Python scales much better than Perl. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "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." --GvR From caleb1 at telkomsa.net Tue Feb 8 23:35:34 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 08 Feb 2005 23:35:34 -0500 Subject: variable declaration References: Message-ID: Alexander > PowerOfGenerator=TakeFromSensor() > if PowerOfGenerator>xxx: > .... > RecalcPower(PowerOfGenerator) > PutToTheDatabase(PowerOfGenerator) > .... > Here, python will not help you. The worst thing is that in such > calculations > you often receive plausible results. (I think PyChecker has come up before, but...) If you like, you could make a text-file index of all the variable names allowed in your program, and parse all the python code to ensure that only those variable names are used. I believe this would a) solve your problem b) require less than a morning's work c) not force everyone else to have to deal with variable declarations that will be only an annoyance 95% percent of the time. Is there a specific reason you want this added to the *language* itself? Thanks Caleb From petite.abeille at gmail.com Thu Feb 10 17:27:29 2005 From: petite.abeille at gmail.com (PA) Date: Thu, 10 Feb 2005 23:27:29 +0100 Subject: XDR? (was Re: is there a safe marshaler?) In-Reply-To: <420bd83e$0$28990$e4fe514c@news.xs4all.nl> References: <420b6936$0$28982$e4fe514c@news.xs4all.nl> <420bd06f$0$28991$e4fe514c@news.xs4all.nl> <420bd83e$0$28990$e4fe514c@news.xs4all.nl> Message-ID: <2a9be4eea58e5b4b31afb58f22f5520a@gmail.com> On Feb 10, 2005, at 22:55, Irmen de Jong wrote: > Perhaps, but the spec makes my skin crawl. Perhaps I could interest you in JSON then: "It is easy for humans to read and write. It is easy for machines to parse and generate. " http://www.crockford.com/JSON/index.html Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From mauro.cicognini at gmail.com Fri Feb 11 08:16:18 2005 From: mauro.cicognini at gmail.com (Mauro Cicognini) Date: 11 Feb 2005 05:16:18 -0800 Subject: Python versus Perl ? In-Reply-To: <1grl63x.1f2tzwz1q984vpN%aleaxit@yahoo.com> References: <1107695949.247611.272800@g14g2000cwa.googlegroups.com> <1107726328.158314.265680@o13g2000cwo.googlegroups.com> <1grl63x.1f2tzwz1q984vpN%aleaxit@yahoo.com> Message-ID: <1108127778.811259.152240@g14g2000cwa.googlegroups.com> Alex Martelli wrote: > URK -- _my_ feeling is that we have entirely *too many* options for > stuff like web application frameworks, GUI toolkits, XML processing, ... > > > Alex I entirely second that. More, I'd heartily welcome an authoritative word on which to focus on for each category... I hate to see scarce resources wasted. Mauro From gsakkis at rutgers.edu Wed Feb 9 10:21:07 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Wed, 9 Feb 2005 10:21:07 -0500 Subject: Name of type of object References: <4209A52C.A1C40311@yahoo.com> Message-ID: <36uo36F54okd6U1@individual.net> "Steven Bethard" wrote in message news:J8adnUGW461nV5TfRVn-rA at comcast.com... > Randall Smith wrote: > > Jive Dadson wrote: > > > >> The traceback routine prints out stuff like, > >> > >> NameError: global name 'foo' is not defined > >> > >> NameError is a standard exception type. > >> > >> What if I want to print out something like that? > >> I've determined that "global name 'foo' is not defined" comes from the > >> __str__ member of the exception object. > >> Where does it find the string "NameError"? In general, if I have an > >> object, is there a way to obtain the name of the type of the object? > >> > >> Thankee. > > > > type(object) ? > > Doesn't work for old-style classes like exceptions: > > py> e = NameError("global name 'foo' is not defined") > py> type(e) > > py> type(e).__name__ > 'instance' > > For old-style classes, you'll need to go through __class__ > > py> e.__class__ > > py> e.__class__.__name__ > 'NameError' > > STeVe To sum up: def typename(obj): try: return obj.__class__.__name__ except AttributeError: return type(obj).__name__ George From steven.bethard at gmail.com Mon Feb 28 19:00:39 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 28 Feb 2005 17:00:39 -0700 Subject: Why do descriptors (and thus properties) only work on attributes. In-Reply-To: References: Message-ID: <-rOdnTNBm-08Lb7fRVn-vQ@comcast.com> Antoon Pardon wrote: > Can anyone explain why descriptors only work when they are an attribute > to an object or class. I think a lot of interesting things one can > do with descriptors would be just as interesting if the object stood > on itself instead of being an attribute to an other object. Not sure what "stood on itself" really means, but if you just want to be able to have module-level properties, you can do something like: py> class Module(object): ... oldimporter = __builtins__.__import__ ... def __init__(self, *args): ... mod = self.oldimporter(*args) ... self.__dict__ = mod.__dict__ ... p = property(lambda self: 42) ... py> __builtins__.__import__ = Module py> import __main__ py> __main__.p 42 py> __main__.p = 3 Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute where you replace module objects with a different object. Note that this is also nasty since properties reside in the class, so all modules now share the same properties: py> import sys py> sys.p 42 py> sys.p = 13 Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute STeVe From rkern at ucsd.edu Fri Feb 11 04:57:57 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 11 Feb 2005 01:57:57 -0800 Subject: [N00B] What's %? In-Reply-To: <614c778e.0502110154.4d53d97a@posting.google.com> References: <614c778e.0502100938.6665cb52@posting.google.com> <614c778e.0502110154.4d53d97a@posting.google.com> Message-ID: administrata wrote: > sry, i don't know much about maths > > What is % used for? > > such as? Among many other things, you can use it to test whether one integer evenly divides another integer. For example, to test if a number is odd: def isodd(x): return bool(x % 2) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From kartic.krishnamurthy at gmail.com Mon Feb 28 14:41:47 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 28 Feb 2005 11:41:47 -0800 Subject: cannot open file in write mode, no such file or directory In-Reply-To: <1109618906.347448.218700@o13g2000cwo.googlegroups.com> References: <1109618906.347448.218700@o13g2000cwo.googlegroups.com> Message-ID: <1109619707.033450.227120@f14g2000cwb.googlegroups.com> > I'm having a problem where when trying to open a file in write mode, I > get an IOError stating no such file or directory. I'm calling an > external program which takes an input file and produces an output file > repeatedly, simulating the input file separately for each replicate. > The error occurs when trying to open the input file to write out the > new data. The problem is difficult to reproduce since it only shows up > once every few thousand replicates. I've tried using both os.system I am afraid you need to give more information that just IOError, calling an external program. Please post the exact message including the input filename at the time the program went down. If you don't print the filename, please modify your program to do so. A shot in the dark solution to your problem might be that you are dynamically generating a filename and that filename probably contains characters not allowed by the local file system OR you generate a path that does not exist. For open() to work with the 'w' flag, the path where the file you say should be created should exist. Thanks, -Kartic From behnel_ml at gkec.informatik.tu-darmstadt.de Wed Feb 9 06:50:02 2005 From: behnel_ml at gkec.informatik.tu-darmstadt.de (Stefan Behnel) Date: Wed, 09 Feb 2005 12:50:02 +0100 Subject: What's wrong with `is not None`? In-Reply-To: References: Message-ID: Frans Englich schrieb: > What is the equivalent expression which is more secure; `!= None`? Note that this is not necessarily equivalent. '!=' and '==' possibly run method calls on objects which can be costly depending on their implementation and can even raise exceptions if called with None. If I want to check for None, I always do it with "is". It's a constant after all... Stefan From nospam at nospam.fr Fri Feb 11 03:14:16 2005 From: nospam at nospam.fr (jean-michel) Date: Fri, 11 Feb 2005 09:14:16 +0100 Subject: goto, cls, wait commands References: <1ixbe7q69lob3.1npuu3z54gx8z.dlg@40tude.net> Message-ID: "BOOGIEMAN" a ?crit dans le message de news:1ixbe7q69lob3.1npuu3z54gx8z.dlg at 40tude.net... > I've just finished reading Python turtorial for non-programmers > and I haven't found there anything about some usefull commands I used in > QBasic. First of all, what's Python command equivalent to QBasic's "goto" ? > Secondly, how do I clear screen (cls) from text and other content ? > And last, how do I put program to wait certain amount of seconds ? > If I remeber correctly I used to type "Wait 10" and QBasic waits > 10 seconds before proceeding to next command. Hi all, I saw a lot of comments saying GOTO is not usefull, very bad, and we should'nt use it because we don't need it. I think that's true, but only if you *create* programs. But if the goal is to provide some kind of converter to automatically take an old application written with an old language (using GOTO), and generating python code, it would certainly a great help to have this (unclean) feature in native python. Best regards jm From steve at holdenweb.com Sat Feb 5 08:15:18 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 05 Feb 2005 08:15:18 -0500 Subject: sos! In-Reply-To: <6d2e4eef.0502050342.d8744cb@posting.google.com> References: <6d2e4eef.0502050342.d8744cb@posting.google.com> Message-ID: jordan2856977 wrote: > hellow everybody! I'm from china. I'm a beginner of python. in china, > python is not a fashionable language, so it's difficult to find some > books about python. finally,I find a book named "python how to > program" wrote by H.M.Deitel . who can tell me where can I find some > interesting source code about python. otherwise, I will fell boring > about study! Start at the links you find on http://www.python.org/moin/BeginnersGuide and take it from there. Also, if you want to see actual code there's lots of it in the standard library. If that's all too useful, take a look at http://www.uselesspython.com/ Welcome to Python! regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From fuzzyman at gmail.com Fri Feb 25 07:57:41 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Feb 2005 04:57:41 -0800 Subject: Trees In-Reply-To: References: Message-ID: <1109336261.108782.131850@o13g2000cwo.googlegroups.com> Alex Le Dain wrote: > Is there a generic "tree" module that can enable me to sort and use > trees (and nodes). Basically having methods such as .AddNode(), > .GetAllChildren(), .FindNode() etc. > > Is this handled natively with any of the core modules? > > cheers, Alex. > > -- > Poseidon Scientific Instruments Pty Ltd > 1/95 Queen Victoria St > FREMANTLE WA, AUSTRALIA > > Ph: +61 8 9430 6639 Fx: +61 8 9335 4650 > Website: www.psi.com.au > > PSI, an ISO-9001 Company > > CONFIDENTIALITY: The contents of this email (and any attachments) are > confidential and may contain proprietary and/or copyright material of > Poseidon Scientific Instruments Pty Ltd (PSI) or third parties. You may > only reproduce or distribute the material if you are expressly > authorised to do so. If you are not the intended recipient, any use, > disclosure or copying of this email (and any attachments) is > unauthorised. If you have received this email in error, please > immediately delete it and any copies of it from your system and notify > PSI by return email to sender or by telephone on +61 (08) 9430 6639. > > DISCLAIMER: You may only rely on electronically transmitted documents when: > (a) those documents are confirmed by original documents signed by an > authorised employee of PSI; and/or > (b) the document has been confirmed and checked against a hard copy > of that document provided by PSI. > > VIRUSES: PSI does not represent or warrant that files attached to this > e-mail are free from computer viruses or other defects. Any attached > files are provided, and may only be used, on the basis that the user > assumes all responsibility for any loss or damage resulting directly or > indirectly from such use. PSI's liability is limited in any event to > either the re-supply of the attached files or the cost of having the > attached files re-supplied. Long sig !! :-) Try elemtree by the F-bot.... Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From tom at dtsam.com Tue Feb 1 10:13:36 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Tue, 1 Feb 2005 09:13:36 -0600 Subject: variable declaration References: <1107205410.367521.50490@f14g2000cwb.googlegroups.com> Message-ID: <44SdnUZGopnrAWLcRVn-pg@telcove.net> "Carl Banks" wrote in message news:1107205410.367521.50490 at f14g2000cwb.googlegroups.com... > How common is it for a local variable to be bound in > more than one place within a function? How common? It shouldn't happen at all and that was the point. The original posters code demonstrates how it can occur inadvertently as a result of a simple typographical error. You won't hear me claim that Python is without mitigating virtues. Clearly, there is much about Python that encourages good design which will in turn reduce the incidence of such errors. Nevertheless, one has to admit to this blemish. One also wonders if it is really necessary to endure what looks to me like an omission. Is there a reason why the interpreter couldn't/shouldn't require formal declarations? I, too, wish there were a switch like VBs "Option Explicit" that would require you to declare "epsilon = 0" and thereafter have the interpretor refuse assignment to an undeclared "epselon". Sane VB programmers (and yes, there are a few!) leave it on by default and consider it abomination that the switch is optional. The original posters example was a good one. I had to take a good long stare before I saw it even though the code is short, sweet, and otherwise correct. *Is* there a reason why the interpreter couldn't/shouldn't require formal variable declaration? It seems to me that lack of same may also be creating hellish barriers to writing truly effective IDEs for Python. Thomas Bartkus From duncan.booth at invalid.invalid Thu Feb 3 09:46:01 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Feb 2005 14:46:01 GMT Subject: Finding user's home dir References: <5i9rtc.rq31.ln@orion.homeinvalid> Message-ID: Peter Hansen wrote: > Nemesis, please use the above recipe instead, as it makes > the more reasonable (IMHO) choice of checking for a HOME > environment variable before trying the expanduser("~") > approach. This covers folks like me who, though stuck > using Windows, despise the ridiculous Microsoft convention > of "user folders" named like "C:\Documents and Settings\Peter" > and prefer to create sensible folder like c:\users\peter > and set a HOME variable to point to it. Your approach > ignores our HOME variable. You could just tell Windows to move your home directory location to c:\users\peter and then all the environment variables will be set for you automatically. It probably varies wildly between Windows versions, but to assign a home folder for a local user on XP go to Control Panel/Administrative Tools/Computer Management/Local Users and Groups/Users, select your account, right menu Properties, Profile tab, and edit the 'Home folder' setting. Press F1 while editing the home folder location and see that at least someone at Microsoft thinks c:\users\... is a sensible location. See also http://support.microsoft.com/?kbid=816313 for domain users etc. From zanesdad at bellsouth.net Tue Feb 8 09:57:08 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue, 08 Feb 2005 09:57:08 -0500 Subject: Loop in list. In-Reply-To: <1107874174.445345.41230@c13g2000cwb.googlegroups.com> References: <1107874174.445345.41230@c13g2000cwb.googlegroups.com> Message-ID: <4208D344.3090402@bellsouth.net> Jim wrote: >Where did this type of structure come from: > >mat = ['a' for i in range(3)] ? > >This will produce a list of three elements but >I don't see reference for it in any of the books. > > > It's called a list comprehension and it appeared in Python 2.0. http://www.amk.ca/python/2.0/index.html#SECTION000600000000000000000 Jeremy Jones From max at alcyone.com Sun Feb 20 20:24:49 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 20 Feb 2005 17:24:49 -0800 Subject: Tuple index In-Reply-To: References: Message-ID: Larry Bates wrote: > Tuples don't have all the nice methods that lists have > so convert it to a list. > > tuple=('a','b','c','d') > l=list(tuple) > > now you can do: > > list.index('c') > > which returns 2 > > Remember index returns -1 when nothing is found. No, that's .find in strings that returns -1. .index in lists raises a ValueError: >>> [1, 2, 3].index(4) Traceback (most recent call last): File "", line 1, in ? ValueError: list.index(x): x not in list -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis The map is not the territory. -- Alfred Korzybski From fredrik at pythonware.com Mon Feb 14 17:21:25 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Feb 2005 23:21:25 +0100 Subject: array of bits? References: Message-ID: "MM" wrote: > What is the best structure/way to create an array of bits (actually true/false flags) of an > arbitrary length ranging from about 20 upto about 500. Speed of access more of an issue than > compactness. > > eg: > [0] 0 > [1] 0 > [2] 1 > [3] 0 > [4] 1 > ... > [n] 0 > etc. if you need a list of flags, use a list of flags: [False] * 500 (compared to a bit array, you'll waste a whopping 31 bits per flag, but unless you plan to use tens of thousands of lists, that shouldn't be much of a problem) From irmen.NOSPAM at xs4all.nl Thu Feb 10 16:21:51 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 10 Feb 2005 22:21:51 +0100 Subject: XDR? (was Re: is there a safe marshaler?) In-Reply-To: References: <420b6936$0$28982$e4fe514c@news.xs4all.nl> Message-ID: <420bd06f$0$28991$e4fe514c@news.xs4all.nl> PA wrote: > > On Feb 10, 2005, at 15:01, Irmen de Jong wrote: > >> Is xdrlib the only option? >> I would expect that it is fast and safe because >> it (the xdr spec) has been around for so long. > > > XDR? Like Sun's "XDR: External Data Representation standard"? > > http://www.faqs.org/rfcs/rfc1014.html > http://www.faqs.org/rfcs/rfc1832.html Not "like", but "the". Or at least, a subset. (the xdrlib module documentation says "It supports most of the data types described in the RFC"). > How does XDR copes with Unicode these days? Not directly, it seems that you have to encode your unicode strings yourself first . > Alternatively, perhaps there is a ASN.1 DER library in python? > > http://asn1.elibel.tm.fr/en/standards/index.htm I don't know. Is there? PS the xdr format is not self-describing in the way that marshal and pickle streams are. That is a big limitiation for what I need it for so xdr seems to drop off my radar. Is an ASN.1 stream self-describing? --Irmen From rnd at onego.ru Wed Feb 9 09:34:07 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 9 Feb 2005 17:34:07 +0300 (MSK) Subject: Is email package thread safe? (fwd) Message-ID: (this is a repost with an addition - probably noone noticed my message first time) Hi! Just to be sure, is email package of Python 2.3 thread-safe or not (to use, for example, in python-milter?) P.S. And where can I find information on particular piece of standard library if it is thread-safe or need locking? I recall 'random' module is (was?) unsafe - which isexplicitly stated in the docs. Can I assume that everything else without such notice is thread-safe? Sincerely yours, Roman A.Souzi -- http://mail.python.org/mailman/listinfo/python-list From jlargentaye at gmail.com Tue Feb 8 07:27:21 2005 From: jlargentaye at gmail.com (Jean de Largentaye) Date: 8 Feb 2005 04:27:21 -0800 Subject: Choosing the right parser for parsing C headers In-Reply-To: References: <1107861023.254610.14310@g14g2000cwa.googlegroups.com> Message-ID: <1107865641.937691.282930@g14g2000cwa.googlegroups.com> GCC-XML looks like a very interesting alternative, as Python includes tools to parse XML. The mini-C compiler looks like a step in the right direction for me. I'm going to look into that. I'm not comfortable with C++ yet, and am not sure how I'd use Pyste. Thanks for the information guys, you've been quite helpful! John From fredrik at pythonware.com Wed Feb 16 14:17:14 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Feb 2005 20:17:14 +0100 Subject: Imported or executed? References: Message-ID: Stephan Schulz wrote: > Is there a (portable, standard) way for the program/module to find out > if it is imported or executed stand-alone? if a module is executed, it's name is set to "__main__". see: http://www.python.org/doc/faq/programming.html#how-do-i-find-the-current-module-name From friedmud at gmail.com Mon Feb 14 18:14:12 2005 From: friedmud at gmail.com (friedmud at gmail.com) Date: 14 Feb 2005 15:14:12 -0800 Subject: Inheritance error in python 2.3.4??? Message-ID: <1108422852.332215.165790@o13g2000cwo.googlegroups.com> In trying to construct a good object model in a recent project of mine, I ran across the following peculiarity in python 2.3.4 (haven't tried any newer versions): Say you have a base class that has an attribute and an accessor function for that attribute (just a simple get). Then you inherit that base class to make a sub class and the subclass contains a "set" function on that same attribute. If you call the set function and give it a value and then call the get function......... it doesn't do what you would expect.... instead of returning the value that was "set" it instead returns the default value of the variable in the base class!!! BUT! If you implement the get function in the derived class it works fine.... This, to me, is completely wrong. I have worked up the following example to illustrate my point: First is the way I want to do it: ###################################### bash-2.05b$ cat main.py class baseClass(object): __Something = "Dumb!" def getSomething( self ): return self.__Something class subClass(baseClass): def setSomething( self , aSomething ): self.__Something = aSomething anObject = subClass() anObject.setSomething("Cool!") print anObject.getSomething() bash-2.05b$ python main.py Dumb! ################################### Note that it prints "Dumb!" instead of "Cool!". Now if I re-implement getSomething in the subclass it does this: #################################### bash-2.05b$ cat main.py class baseClass(object): __Something = "Dumb!" def getSomething( self ): return self.__Something class subClass(baseClass): def setSomething( self , aSomething ): self.__Something = aSomething def getSomething( self ): return self.__Something anObject = subClass() anObject.setSomething("Cool!") print anObject.getSomething() bash-2.05b$ python main.py Cool! ####################################### Note that it now prints "Cool!" like it was supposed to in the first place... Hello? Am I just being retarded? To me the call to self.__Something = aSomething should change THE ONLY instance of __Something to "Cool!". Calling an inherited function shouldn't create a new instance of __Something (which is what it has to be doing) and return that instead. This is really going to cripple my object model if I have to reimplement each one of these functions everytime! The whole point was to have a stable "implementation base" that captures a lot of the common functionality between the different inherited classes... and provides a "one stop shop" for modifying a lot of the behavior. Also I would have a lot less code because I would inherit functionality. FYI - I am coming from a C++ background... where I do this kind of thing often. Someone please show me the pythonish way to do this! Thanks! Friedmud From duncan.booth at invalid.invalid Tue Feb 22 11:12:12 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Feb 2005 16:12:12 GMT Subject: Problem with the sort() function References: <64827323f7134aea810788b3ec6cf516@localhost.talkaboutprogramming.com> <421b4e54@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > if sys.version_info < (2, 4): > def sorted(iterable, cmp=None, key=None, reverse=False): > "return a sorted copy of its input" > seq = list(iterable) > if reverse: > seq.reverse() # preserve stability > if key is not None: > seq = [(key(elem), i, elem) for i, elem > in enumerate(seq)] > seq.sort(cmp) > if key is not None: > seq = [elem for (key, i, elem) in seq] > if reverse: > seq.reverse() > return seq I think you may have some unintended indentation on the 'seq.sort' line otherwise this only sorts when a key is specified. Also, you probably want: if key is not None: if reverse: seq = [(key(elem), -i, elem) for i, elem in enumerate(seq)] else: seq = [(key(elem), i, elem) for i, elem in enumerate(seq)] to handle the case where both key and reverse are given. From tim.peters at gmail.com Mon Feb 14 20:06:05 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 14 Feb 2005 20:06:05 -0500 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: <1f7befae05021417066ad2f799@mail.gmail.com> [Ilias Lazaridis] ... > Let's see: > > The process would be: > > a) A Python Foundation official states: "of course we accept diversity > and of course we are intrested that our source-code-base compiles > directly with MinGW (and other compilers)". Well, I'm a Director of the Python Software Foundation, and my view is "the more platforms the merrier". But I'm not paid to work on Python, and I don't have time to volunteer to help MinGW along, so I don't anticipate that I'll do anything here beyond writing this reply. I think you're mistaken about the role the PSF plays here. For example, the PSF does no development work on Python -- all work on Python comes from volunteers, and the PSF can't tell anyone what to do. The PSF did start a grant program last year, and a proposal to fund MinGW-for-Python development would certainly be considered. But that too requires that someone volunteer to write such a proposal, and take their chances on getting a grant. Those chances are, unfortunately, not good, since even in the program's first year we got proposals requesting funding vastly exceeding the US$40K we could afford to spend. That leaves volunteers, or a company that wants what you want enough to pay for it on their own (which has happened, but not often -- I don't think it's happened since Zope Corp funded development of the datetime module). > b) the pyMinGW developer states: "I am intrested that my patches are > included within the main python source code base" [of course this > contribution would deserve to be mentioned somewhere] > > c) One part of the Python Community states: "look those loosers, like to > use MinGW toolkit - pah! I'll continue to use my super-optimizing, xx% > faster results, less hassle Microsoft-Compiler" > > d) One part of the Python Community states: "I'm very happy that my > toolset of choice gets official support, to which I can contribute as a > community member" > > e) there is no point e. People start simply to cooperate, thus python's > evolution is ensured. Sorry, I didn't grasp the point of b thru e. > ... > Good night to all. Likewise! From peter at engcorp.com Sat Feb 26 21:52:06 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 26 Feb 2005 21:52:06 -0500 Subject: Thread scheduling In-Reply-To: References: <1109456481.214243.140670@l41g2000cwc.googlegroups.com> <09Kdndga9dgQkrzfRVn-hg@powergate.ca> Message-ID: Jack Orenstein wrote: >> One thing you might try is experimenting with sys.setcheckinterval(), >> just to see what effect it might have, if any. > > That does seem to have an impact. At 0, the problem was completely > reproducible. At 100, I couldn't get it to occur. If you try other values in between, can you directly affect the frequency of the failure? That would appear to suggest a race condition. >> It's also possible there were some threading bugs in Py2.2 under >> Linux. Maybe you could repeat the test with a more recent >> version and see if you get different behaviour. (Not that that >> proves anything conclusively, but at least it might be a good >> solution for your immediate problem.) > > 2.3 (on the same machine) does seem better, even with setcheckinterval(0). The default check interval was changed from 10 in version 2.2 and earlier to 100 in version 2.3. (See http://www.python.org/2.3/highlights.html for details.) On the other hand, with version 2.3.4 under RH9, I tried values of 10 and 1 with no failures at any time. This might still be an issue with your own particular system, so having others try it out might be helpful... -Peter From sjmachin at lexicon.net Fri Feb 4 06:52:58 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 04 Feb 2005 22:52:58 +1100 Subject: Converting a string to a function pointer References: Message-ID: On Fri, 04 Feb 2005 12:01:35 +0100, H?kan Persson wrote: >Hi. > >I am trying to "convert" a string into a function pointer. >Suppose I have the following: > >from a import a >from b import b >from c import c > >funcString = GetFunctionAsString() > >and funcString is a string that contains either "a", "b" or "c". >How can I simply call the correct function? >I have tried using getattr() but I don't know what the first (object) >argument should be in this case. Try this: >>> from sys import exit >>> globals() {'__builtins__': , '__name__': '__main__', 'exit': , '__doc__': None} >>> afunc = globals()["exit"] Do you really need to use the "from X import Y" style? Consider the following alternative: >>> import sys >>> afunc = getattr(sys, "exit") From usenet_spam at janc.invalid Mon Feb 7 18:28:30 2005 From: usenet_spam at janc.invalid (JanC) Date: Mon, 07 Feb 2005 23:28:30 GMT Subject: Possibly OT: Controlling winamp with Python References: <1107548407.626431.171350@z14g2000cwz.googlegroups.com> Message-ID: Bill Mill schreef: > You could write the Python program as a proxy of the internet stream. > Basically, you would point your proxy at the web stream and receive > the data it sends. At the same time, you would be listening for > connections on some socket on the local machine. You would then point > winamp towards the local socket instead of the internet station. Winamp buffers incoming streams, so that won't be very functional... ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From reinhold-birkenfeld-nospam at wolke7.net Sun Feb 20 08:41:48 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 20 Feb 2005 14:41:48 +0100 Subject: [perl-python] exercise: partition a list by equivalence In-Reply-To: <37pb5jF5fnfivU1@individual.net> References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> <1108814276.680736.264380@l41g2000cwc.googlegroups.com> <37pb5jF5fnfivU1@individual.net> Message-ID: <37ribcF5er80rU1@individual.net> Reinhold Birkenfeld wrote: > My solution (which may not be the fastest or most effective, but till > now is the shortest and it works): > > def merge(pairings): > sets = {} > for x1, x2 in pairings: > newset = (sets.get(x1, frozenset([x1])) > | sets.get(x2, frozenset([x2]))) > for i in newset: > sets[i] = newset > > return [list(aset) for aset in set(sets.itervalues())] A recursive solution (around twice as fast as the above, though very slow still...) def merge_rb2(pairings): def merge(sets): res_sets = [] for tset in sets: for item in tset: for rset in res_sets: if item in rset: rset.update(item for item in tset) break else: continue break else: res_sets.append(set(tset)) if len(res_sets) == len(sets): return res_sets else: return merge(res_sets) return [list(s) for s in merge([set(pair) for pair in pairings])] Another one: def merge_rb3(pairings): dic = {} for x1, x2 in pairings: dic.setdefault(x1, []).append(x2) dic.setdefault(x2, []).append(x1) def red(k, l): l.append(k) sub = dic[k] for i in dic[k]: if i not in l: red(i, l) del dic[k] res = [] while len(dic): rl = [] red(iter(dic).next(), rl) res.append(rl) return res Reinhold From peter at engcorp.com Sat Feb 26 12:25:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 26 Feb 2005 12:25:00 -0500 Subject: fdups: calling for beta testers In-Reply-To: <422044b9$1@news.vo.lu> References: <421f97eb$1@news.vo.lu> <1109380525.262724.275780@g14g2000cwa.googlegroups.com> <422044b9$1@news.vo.lu> Message-ID: Patrick Useldinger wrote: >> (9) Any good reason why the "executables" don't have ".py" extensions >> on their names? > > (9) Because I am lazy and Linux doesn't care. I suppose Windows does? Unfortunately, yes. Windows has nothing like the "x" permission bit, so you have to have an actual extension on the filename and Windows (XP anyway) will check it against the list of extensions in the PATHEXT environment variable to determine if it should be treated like an executable. Otherwise you must type "python" and the full filename. -Peter From Peter.Vandersteegen at gmail.com Wed Feb 16 17:05:05 2005 From: Peter.Vandersteegen at gmail.com (peter) Date: 16 Feb 2005 14:05:05 -0800 Subject: adding new functionality to a function non-intrusively! In-Reply-To: References: <1108564620.657526.301320@g14g2000cwa.googlegroups.com> <1108566348.660335.224170@g14g2000cwa.googlegroups.com> Message-ID: <1108591505.670637.258590@c13g2000cwb.googlegroups.com> indeed it does, so basically everything works except my original solution: def myfunction(a,b): return a+b def _myfunction(a,b): return myfunction(a,b) myfunction = _myfunction oh well, it was enough to puzzle my tiny brain.... From williams13 at llnl.gov Wed Feb 9 11:15:43 2005 From: williams13 at llnl.gov (Dean N. Williams) Date: Wed, 09 Feb 2005 08:15:43 -0800 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <20050208175514.GA3788@tishler.net> References: <41FF5A67.3090606@llnl.gov> <20050201125129.GA432@tishler.net> <41FFA7C9.4070308@llnl.gov> <20050202124435.GA2472@tishler.net> <4200D056.4010000@llnl.gov> <4200D22D.9070000@llnl.gov> <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> Message-ID: <420A372F.7020800@llnl.gov> Dear Jason, The "$ TMP=/tmp rebaseall" command worked! Thank you. When a new Cygwin is available w/ your changes please let me know... Best regards, Dean >On Tue, Feb 08, 2005 at 08:01:11AM -0800, Dean N. Williams wrote: > > >>$ rebaseall >>/usr/bin/rebaseall: line 70: [: too many arguments >>/usr/bin/rebaseall: line 75: [: too many arguments >>/usr/bin/rebaseall: line 94: $TmpFile: ambiguous redirect >>cannot read /cygdrive/c/Documents >> >>On my laptop installation everything works just fine. What is the >>difference? >> >> > >The TMP and/or TEMP environment variables have at least two spaces in >them. > >The easiest workaround is to execute rebaseall like the following: > > $ TMP=/tmp rebaseall > >Long term I will change rebaseall to deal better with spaces in shell >variables. > >Jason > > > From peter at engcorp.com Thu Feb 24 22:01:22 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Feb 2005 22:01:22 -0500 Subject: web status display for long running program In-Reply-To: <509534af.0502241737.5f62992@posting.google.com> References: <509534af.0502241737.5f62992@posting.google.com> Message-ID: Brian Roberts wrote: > I have a command line Python program ... > I think an optional web page would be convenient interface. The > Python program would listen on some port, and if queried (by me > browsing to localhost:12345 for example) would return a pretty status > display. Hitting reload would update the status etc. > > My problem is that I'm not sure how to do this: > - I don't want to embed a full web server into the application or > require any special PC setup. > - I think I know how to listen on a socket, but not sure how to send > stuff to to a web browser -- just start with ? See below. I don't care if you use the code, it was fun to whip up on the spur of the moment. I'm quite certain that if you try searching for "smallest web server" or something you'll find a bunch of Perl guys who've competed to produce something that does the same in a tenth the space... > - Do I need a separate thread to listen and send the HTML? The > application is currently single threaded. I'm confortable with > threads, but would prefer to avoid them if possible. If you don't want a thread, you probably don't need one, but this might be a little cleaner to put in a thread. I'm not sure exactly what approach would be best to avoid a thread, but using select() on the server socket, with a timeout of 0 to poll, instead of blocking as the following code does, would probably be the simplest. Try this out and maybe you can morph it into something like what you want... '''miniweb: microscopic web server''' import socket from select import select from datetime import datetime s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 80)) s.listen(5) while True: cs = s.accept()[0] try: header = '' while True: r, w, e = select([cs], [], [cs], 2) if not r or e: break header += cs.recv(1024) if '\r\n\r\n' in header: break msg = ('Miniweb!' '

Clock

The time is %s

' % datetime.now()) headers = '\r\n'.join([ 'HTTP/1.0 200 OK', 'Server: Miniweb-0.1', 'Content-Type: text/html', 'Connection: close', 'Content-Length: %s' % len(msg), ]) cs.send(headers + '\r\n\r\n' + msg + '\n') finally: cs.close() I make no claims that this will survive any particular kind of use or abuse. I did test with telnet, Firefox, Opera, and Explorer, however. A couple of key points found while testing: 1. Explorer needs you to read the header in its entirety, so I had to add the part that actually scans the header for the terminating sequence (\r\n\r\n). 2. There's a two-second timeout on reading the header, in case something connects but doesn't send anything... not really tested. 3. Some or most of the headers in the reply may not be required. Perhaps the first line and the Content-Length (or not even that?) are all that are required. Play if you want. No doubt others will pick this apart and we'll all learn something. ;-) 4. MIT license ;-) as in don't complain to me if this doesn't do what you need, but use it any way you wish... -Peter From steven.bethard at gmail.com Fri Feb 18 19:28:50 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 18 Feb 2005 17:28:50 -0700 Subject: selecting dictionaries to maximize counts In-Reply-To: References: Message-ID: Brian Beck wrote: > Steven Bethard wrote: > >> I have a list of dictionaries. Each dictionary holds counts of >> various 'words', e.g.: >> >> py> countdicts = [ >> ... dict(a=9, b=9, c=9), >> ... dict(a=8, b=7), >> ... dict(a=4, b=5, c=12)] >> >> I need to select dicts with the constraint that the number of each >> 'word' totalled over all selected dicts doesn't exceed a given >> MAX_VALUE. Right now, I do this by: > > Not that you can't still improve performance of course, but this is an > NP-complete problem if you didn't know, so don't bang your head too hard... Yeah, it seemed a lot like one of those box-packing type problems, so if it's NP-complete, it wouldn't surprise me. That's one of the reasons I mentioned trying A* in one of my other responses. However, in retrospect, I don't think I can apply A* because I don't really have a "goal state". I could call a selection where all "words" had MAX_VALUE counts a "goal state", but I'm not guaranteed that such a state always exists (and if it doesn't A* just degenerates into an exhaustive search). Anyway, do you know what name this problem is usually discussed under? If I knew what to google for, I could probably find at least a few simple heuristics to try... Thanks again, STeVe From maxm at mxm.dk Tue Feb 22 08:50:12 2005 From: maxm at mxm.dk (Max M) Date: Tue, 22 Feb 2005 14:50:12 +0100 Subject: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux & Windows XP In-Reply-To: <1109078512.094288.316030@z14g2000cwz.googlegroups.com> References: <1109078512.094288.316030@z14g2000cwz.googlegroups.com> Message-ID: <421b385e$0$230$edfadb0f@dread12.news.tele.dk> Fuzzyman wrote: > Mike Dee wrote: >>#!/usr/bin/env python >># -*- coding: UTF-8 -*- > This will mean string literals in your source code will be encoded as > UTF8 - if you handle them with normal string operations you might get > funny results. It means that you don't have to explicitely set the encoding on strings. If your coding isn't set you must write: ust = '???'.decode('utf-8') If it is set, you can just write: ust = u'???' And this string will automatically be utf-8 encoded: st = '???' So you should be able to convert it to unicode without giving an encoding: ust = unicode(st) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From nhodgson at bigpond.net.au Sun Feb 13 06:14:39 2005 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sun, 13 Feb 2005 11:14:39 GMT Subject: SCons build tool speed References: Message-ID: ted: > How does the speed of the Scons build tool compare with Ant? > Right now with out Ant builds take around an hour. Hoping to > speed that up. Scons emphasises accuracy over speed and is normally a little slower than other build tools although still fast enough for most purposes. One cause of slowness is that it reads the source files, traces include files and checksums them all rather than relying on file times. There are some things you can do to speed it up: http://www.scons.org/cgi-bin/wiki/GoFastButton Neil From jfj at freemail.gr Mon Feb 21 17:36:29 2005 From: jfj at freemail.gr (jfj) Date: Mon, 21 Feb 2005 14:36:29 -0800 Subject: lambda closure question In-Reply-To: References: <1108798951.128843.79810@f14g2000cwb.googlegroups.com> <1108802613.284686.200170@o13g2000cwo.googlegroups.com> Message-ID: <421A626D.7020007@freemail.gr> Antoon Pardon wrote: > Op 2005-02-19, jfj schreef : > >>once foo() returns there is no way to modify 'x'! >>It becomes a kind of constant. > > > In this particular case yes. But not in general, what about > this: > > >>>>def F(): > > ... l = [] > ... def pop(): > ... return l.pop() > ... def push(e): > ... l.append(e) > ... return pop, push > ... > Others will point this out, but if I'm fast enough... This does not change the object referenced by l. It calls methods of it and because it is mutable the containts of the list are modified. 'l' is a list at address, 0xXXXX and that can never change once F() has returned. jfj From python-url at phaseit.net Tue Feb 1 00:14:42 2005 From: python-url at phaseit.net (Cameron Laird) Date: Tue, 01 Feb 2005 05:14:42 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Feb 1) Message-ID: QOTW: "The right solution will end up being unique to Python though. It has to feel like Python." -- Guido van Rossum http://aws.typepad.com/aws/2005/01/amazon_devcon_g_4.html "Sparring with Alex Martelli is like boxing Mike Tyson, except that one experiences brain enhancement rather than brain damage :)." -- beliavsky This is your opportunity to vote on the prospective creation of de.comp.lang.python: http://groups.google.de/groups?selm=erneuter-CfV-1-Einrichtung-de.comp.lang.python-16.1.2005-Supersede%40dana.de http://gvv.th-h.de/ eval() often inverts repr(). pickle() makes for more reliable serialization: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f4324fe8aa00f7f5/ Kamilche illustrates how scripting (Web-scraping, in this case) can put eBay (Google, Amazon, ...) under *your* control: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1b0d7ebb06c49272 Tim Churches pulls off the remarkable feat of appearing to say true, useful, and not-stultifying things on licensing: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a1e07194c795f505/ How declarative are metaclasses and decorators? Diez B. Roggisch has been helpful with this and similarly interesting summaries and examples: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a75da70b0845b6fe/ Art Siegel also approaches the question, in a more narrative fashion. Notice in the same thread Steve Holden's persistent advertising of PyCon 2005, emphasizing the celebrities (martellibot!, Armin "I Infer That" Rigo, ...) expected to appear, some for the first time ever in this dimension. Nick Coghlan explains the trickiness of Duncan Booth and F. PetitJean. This is a chance to practice generators, zip, map, and iter, all in about two lines: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a6ba37b0fb0fa69e Do you know the standard library well enough to recognize its parametric statistics? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1ddd1e869fe6e08a/ ======================================================================== 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. 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 Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson 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/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. deli.cio.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/topics/pythonurl/ 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 Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From jonas at freesources.org Mon Feb 21 14:36:33 2005 From: jonas at freesources.org (Jonas Meurer) Date: Mon, 21 Feb 2005 20:36:33 +0100 Subject: display VARCHAR(mysql) and special chars in html Message-ID: <20050221193632.GF5363@resivo.mejo.net> hello, my script selects a comment saved as VARCHAR in MySQL and displays it inside an html page. the problem is, that the comment contains several special characters, as mysterious utf-8 hyphens, german umlauts, etc. i could write a function to parse the comment and substitute special chars with the relevant html code, but maybe this already exists in some module? if not, it'll be hard work, as i've to consider many special chars, and at least iso-8859-1* and utf-8 as charmaps. bye jonas From markus_GETRIDOFALLCAPSwankus at hotmail.com Wed Feb 23 20:42:37 2005 From: markus_GETRIDOFALLCAPSwankus at hotmail.com (Markus Wankus) Date: Wed, 23 Feb 2005 20:42:37 -0500 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: <87ekf76ozk.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> References: <874qg6937w.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <37uk2kF5gv38bU1@individual.net> <421c91c8$0$44647$a1866201@visi.com> <383qkkF5k6rf4U1@individual.net> <8BIQdyL$iLHCFw9a@objmedia.demon.co.uk> <421CC14A.4050708@lazaridis.com> <87ekf76ozk.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <8iaTd.15672$uO.565343@news20.bellglobal.com> Nick Vargish wrote: > Ilias Lazaridis writes: > > >>Guido is the one, who should care by time about the status of the >>python-community. > > > That one crashed my parser. > Sounds like a new Ministry song - "Guido Crashed my Parser". Could be the sequel to "Jesus Built My Hot Rod". From domma at procoders.net Fri Feb 11 05:18:31 2005 From: domma at procoders.net (Achim Domma (Procoders)) Date: Fri, 11 Feb 2005 11:18:31 +0100 Subject: Testing web applications Message-ID: Hi, I'm looking for frameworks to make testing web applications - i.e. parsing and filling out forms - easier. I found Puffin, which looks good but not very usable in the current state. I know that I once read about other nice frameworks, but could not find one via google. Any hints? regards, Achim From grante at visi.com Mon Feb 21 10:19:28 2005 From: grante at visi.com (Grant Edwards) Date: 21 Feb 2005 15:19:28 GMT Subject: Article on Hi-Fi Myths References: <111hvnra44hgr03@corp.supernews.com> <867jl2h1u8.fsf@guru.mired.org> Message-ID: <4219fc00$0$46539$a1866201@visi.com> On 2005-02-21, Mike Meyer wrote: >> "you just need to know what techniques to use to create a >> 'friendly', 'relaxing', energy pattern." > > I find that playing back Python code over multi-stranded copper > produces the best results. Only if you color the edges with a green marker first... -- Grant Edwards grante Yow! MERYL STREEP is my at obstetrician! visi.com From tjprojects_usenet at yahoo.com Wed Feb 16 13:55:50 2005 From: tjprojects_usenet at yahoo.com (tjprojects_usenet at yahoo.com) Date: 16 Feb 2005 10:55:50 -0800 Subject: Loading functions from a file during run-time References: <1108091598.055004.24890@g14g2000cwa.googlegroups.com> <1108576067.140194.115620@c13g2000cwb.googlegroups.com> Message-ID: <1108580150.436813.227870@o13g2000cwo.googlegroups.com> Wensheng wrote: > #--- file bar.py > >>> foo="bar" > >>> fs=__import__(foo) Wensheng: The problem with this is that it assumes the text file is a valid python file, and that the extension is ".py". This may work for the OP's situation; he would need to weigh in. 'exec'ing the functions into the global namespace allows you to create functions from any text-based source -- registry keys, ini files, user input, etc. T.J. From calvin at ironfroggy.com Mon Feb 28 19:11:42 2005 From: calvin at ironfroggy.com (Calvin Spealman) Date: Tue, 01 Mar 2005 00:11:42 +0000 Subject: Importing from filesystem path a 'frozen sub-module' error Message-ID: <6316450.6I7sGcfX6l@ironfroggy.com> I've been working on a small test runner script, to accumulate my test scripts (all python files in the 'test' sub-directories of my source tree). Things were going well, but I'm still having trouble loading the modules, once I have a path to the python source file. This is the error I am getting: mod_info = imp.find_module(module_name, module_path) ImportError: No frozen submodule named PyInvolgo.test.test_RepoBase I know 100% sure the module exists (I can enter a python shell and import it directly, no problem), so that isn't the problem. I don't know what a 'frozen sub-module' is, tho, and I haven't been able to find anything about them from google searches and documentation on python.org. At first, I thought maybe it was because the test directory had no __init__.py (it isn't a package, so I didn't make one), but added one made no difference. -- From duncan.booth at invalid.invalid Mon Feb 21 12:40:28 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Feb 2005 17:40:28 GMT Subject: Unittest - testing properties (read-only attributes) References: <7xu0o5akr2.fsf@ruckus.brouhaha.com> Message-ID: Duncan Booth wrote: > An assignment expression, if such a thing existed wouldn't help here. Although of course it would help if still inside a lambda. From BOOGIEMANPN at YAHOO.COM Thu Feb 10 16:06:08 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Thu, 10 Feb 2005 22:06:08 +0100 Subject: goto, cls, wait commands References: <1ixbe7q69lob3.1npuu3z54gx8z.dlg@40tude.net> <420b9f4b$0$29241$626a14ce@news.free.fr> <420bb95e$0$5259$39db0f71@news.song.fi> Message-ID: OK, thanks all Here's presentation of my advanced programming skills :) ---------------------------------------- import os import time os.system("cls") number = 78 guess = 0 while guess != number: guess = input("Guess number: ") if guess > number: print "Lower" time.sleep(3) os.system("cls") elif guess < number: print "Higher" time.sleep(3) os.system("cls") print "That's the number !" --------------------------------------- BTW, I'm thinking to replace lines "time.sleep(3)" with something like "Press any key to guess again" How do I do that ? Also I wanted to put at the end something like "Do you want to guess again ?" and then "GOTO" start of program, but since there is no such command in Python what are my possible solutions ? From roy at panix.com Mon Feb 21 12:11:28 2005 From: roy at panix.com (Roy Smith) Date: Mon, 21 Feb 2005 12:11:28 -0500 Subject: Unittest - testing properties (read-only attributes) References: Message-ID: In article , Paul Moore wrote: > I have a class with a read-only attribute, and I want to add a unit > test to ensure that it really *is* read-only. I can do this as > > def test_readonly(self): > """Value and multiplier must be readonly""" > try: > self.combat.value = 1 > self.fail("Value is not read only") > except AttributeError: > pass > > That works, but it seems a bit clumsy. Is there a better way? > > Thanks, > Paul. You want something like self.assertRaises(AttributeError, lambda: self.combat.value = 1) From robey at flaminglunchbox.net Wed Feb 2 00:47:53 2005 From: robey at flaminglunchbox.net (Robey Holderith) Date: Wed, 02 Feb 2005 00:47:53 -0500 Subject: Python Code Auditing Tool Message-ID: Does anybody know of a tool that can tell me all possible exceptions that might occur in each line of code? What I'm hoping to find is something like the following: given all necessary python source and a given line ( my.py:40 ) it would generate a list of possible exception classes sorted by function (preferably in a tree). Example: ------------------ my.py:40 | parsestring(genstring()) Possible Exceptions: -def parsestring(): InvalidCharacterException EmptyStringException -class string, def split(): (All Exceptions that might occur directly in string.split() that are not caught by parsestring()) (All functions called by string.split() and their exceptions and sub- functions) -def genstring(): SomeException ... -------------------- This would be extremely useful for deciding how to write try: except blocks and in figuring out what all possible errors that might occur would be. -Robey Holderith From mefjr75 at hotmail.com Fri Feb 4 00:02:15 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 3 Feb 2005 21:02:15 -0800 Subject: OT: why are LAMP sites slow? In-Reply-To: <7xy8e5jagh.fsf@ruckus.brouhaha.com> References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xy8e5jagh.fsf@ruckus.brouhaha.com> Message-ID: <1107490194.226679.159020@o13g2000cwo.googlegroups.com> Paul Rubin wrote: > Yes, good point about html tables, though I'm concerned primarily > about server response. (It's off-topic, but how do you use CSS to get > the effect of tables?) To emulate a table you use the div and span tag. (really you can do just about anything with div and span) Div is a block level tag and span isn't. You can also group them together and nest them. div and span have little meaning but the can be styled. In the CSS declaration we create styles and then just use them later as needed. Try to always focus on layout first and actual style later. (CSS is all about seperation of concerns) You will find the verbosity of CSS is not as annoying as you might think it might be, it is quite easy to learn and well worth the effort. Ok here is a bad example ( do a search on Google for CSS tables ). ( this was torn out of a webapp I am working on ) .
.
. Archive . Entry Date . .
.
. %s . %s . %s .
.
.         posted by: %s . . text . %s . .
.
And here is some of the CSS ( these are classes the dot in front of the name tells you that, when combined with div or span just about anything is possible. ) . .panel { . border: solid thin #666677; . margin: 2em 4em 2em 4em;} . .leftspaces { . letter-spacing:.5em; . text-decoration:none; . color:#EEEEff;} . .rightspaces { . letter-spacing:.5em; . position: absolute; . right: 5em; . text-decoration: none; . color:#EEEEff;} . . .archivehead { . text-indent:.5em; . background-color:#333333;} . .archivelite { . color:#777777; . text-indent:.5em; . background-color:#222222;} . .archivedark { . color:#777777; text-indent:.5em; . background-color:#111111;} . .archivelite a{ . color:#BBBBDD; . text-decortation:none; . background-color:#222222;} . .archivedark a{ . color:#BBBBDD; . text-decortation:none; . background-color:#111111;} hth, M.E.Farmer From roland.heiber at web.de Thu Feb 3 02:55:39 2005 From: roland.heiber at web.de (Roland Heiber) Date: Thu, 03 Feb 2005 08:55:39 +0100 Subject: Generating .pyc/.pyo from a make file In-Reply-To: <4201607f_2@news.arcor-ip.de> References: <4308d2-0801.ln1@eskimo.tundraware.com> <42015a85_1@news.arcor-ip.de> <4201607f_2@news.arcor-ip.de> Message-ID: Roland Heiber wrote: > Tim Daneliuk wrote: >> under the impression that "compiled" meant optimized byte code that You where right, i was totally mislead by "optimized" ... ;) Greetings, Roland From nick at craig-wood.com Sat Feb 12 05:30:06 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 12 Feb 2005 10:30:06 GMT Subject: ANN: pyMinGW support for Python 2.3.5 (final) is available References: <1108189500.707806.316520@g14g2000cwa.googlegroups.com> Message-ID: A.B., Khalid wrote: > This is to inform those interested in compiling Python in MinGW that > an updated version of pyMinGW is now available. Ha anyone tried cross compiling python with mingw? At work we compile our software for lots of platforms (including windows) on a linux build host. The windows builds are done with a mingw cross compiler. It would be interesting if we could do this with python + extensions also. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From Ralph.Arenz at friatec.de Thu Feb 17 08:12:38 2005 From: Ralph.Arenz at friatec.de (Arenz, Ralph) Date: Thu, 17 Feb 2005 14:12:38 +0100 Subject: tiff via email-module Message-ID: hi all, my problem is to get a tiff-file-attachment out of an email sent by a fax-server. When i try this with "get_payload(decode='True')" i get additional informations, looks like binary-mixed header-information, enveloping the tiff-data. I tried the following: Sending the email from outlook to a postfix-user and a file on the postfix-host as well. The file shows the stucture mentioned above. The mail for the postfix-user is deliverd correctly. So postfix must fetch the raw tiff-data too!?. Is there a way to get the raw tiff-data using the email-module? Any ideas? ralph From samantha7395 at hotmail.com Fri Feb 18 14:57:51 2005 From: samantha7395 at hotmail.com (Samantha) Date: Fri, 18 Feb 2005 11:57:51 -0800 Subject: Probably over my head... Trying to get Font Names References: <8oydnSIY04Xby4jfRVn-iA@adelphia.com> Message-ID: Mike, Strange Hotmail. I'll start over with the installs and you are correct on it being Numpy. I got the wrong file. I'll give it a go and let you know. Thanks!!!! S "Mike C. Fletcher" wrote in message news:mailman.2816.1108754431.22381.python-list at python.org... > Samantha wrote: > From john_sips_teaz at yahooz.com Wed Feb 23 22:20:42 2005 From: john_sips_teaz at yahooz.com (John M. Gabriele) Date: Wed, 23 Feb 2005 22:20:42 -0500 Subject: Like overloading __init__(), but how? Message-ID: I know that Python doesn't do method overloading like C++ and Java do, but how am I supposed to do something like this: --------------------- incorrect ------------------------ #!/usr/bin/python class Point3d: pass class Vector3d: """A vector in three-dimensional cartesian space.""" def __init__( self ): """Create a Vector3d with some reasonable default value.""" x, y, z = 0.0, 0.0, 0.0 def __init__( self, x_from, y_from, z_from, x_to, y_to, z_to ): """Create a Vector3d from x-y-z coords.""" # ... pass def __init__( self, point_from, point_to ): """Create a Vector3d from two Point3d objects.""" # ... pass def __init__( self, same_as_this_vec ): """Create a Vector3d from a copy of another one.""" # ... pass p = Point3d() p2 = Point3d() # v = Vector3d( p2, p ) -- Nope. Only the last __init__() counts. ---------------------- /incorrect ------------------------------- Thanks. -- --- if replying via email, remove zees --- From mwm at mired.org Tue Feb 8 20:55:12 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 08 Feb 2005 19:55:12 -0600 Subject: An Ode To My Two Loves References: Message-ID: <8665128pkv.fsf@guru.mired.org> Peter Maas writes: > Jorgen Grahn schrieb: >> It's something that worries me frequently -- I feel guilty when I introduce >> Python into ("force Python upon") an organization. Because I hate having >> /other/ people's favorite toy languages forced down /my/ throat ... > > The solution is a multi language glue layer. Software interfaces are > defined in a language independent way so that they can be used by > many languages.I wonder why COM is so dominant on Windows and most > Unixish systems don't use CORBA (with GNOME as an exception). > Microsoft's .net takes this one step further by defining a multi > language implementation layer. COM is dominant on Windows because MS pushes it. CORBA isn't dominant on Unix because there are a slew of extensible/embeddable languages to pick from instead - assuming the apps in question came up with a solution better than rolling their own. See for my thoughts on the matter before I learned better. > I hope these ideas will become more influential in Unix like systems > as well just to stop this resource wasting source code issue. XMLRPC seems to be displacing CORBA for interobject communications. It's not clear it's becoming an intercommunications tool for scripting applications. In any case, Plan 9 has a much better solution than COM, CORBA or XMLRPC. I can script plan 9 applications with the shell. I can't do that with CORBA (well, my quick search failed to turn up CORBA bindings for sh. It can probably be done with XMLRPC, but it would be ugly. The problem is that this requires fundamental changes in the underlying OS (by adding per-process mount points), but there's mention of experiments with that for Linux. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From daniel_usenet at yahoo.de Sun Feb 20 11:54:43 2005 From: daniel_usenet at yahoo.de (Daniel Lichtenberger) Date: Sun, 20 Feb 2005 17:54:43 +0100 Subject: questions concerning cgi.FieldStorage(keep_blank_values=1) References: Message-ID: <37rtmjF5gk5l2U1@individual.net> Hi, Jonas Meurer wrote: > if i request the script with script.py?key1&key2=foo, it will output: > list keys with form.keys(): > key2 > > any suggestions about how to make form.keys() contain the blank keys > as well? "key1" isn't a valid parameter, to supply an empty key you would write script.py?key1=&key2=foo Then cgi.FieldStorage also includes key1. bye, Daniel -- For mail replies please use my address from http://perplex.schmumpf.de/ http://www.gametective.de/ From carribeiro at gmail.com Wed Feb 9 08:19:22 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 9 Feb 2005 11:19:22 -0200 Subject: Big development in the GUI realm In-Reply-To: <1grnxs8.1y1tcqq1d0o2bsN%aleaxit@yahoo.com> References: <1107795145.049239.73450@l41g2000cwc.googlegroups.com> <4i3g01tv48qr50g8fjc8nf3n09eaauaen5@4ax.com> <6h7g0113up1v76k7qkad7bt17os1q73510@4ax.com> <1grnxs8.1y1tcqq1d0o2bsN%aleaxit@yahoo.com> Message-ID: <864d37090502090519755c7fc3@mail.gmail.com> On Tue, 8 Feb 2005 11:44:10 +0100, Alex Martelli wrote: > Dennis Lee Bieber wrote: > > > hassle to code, but if your application could dynamically select from > > whatever toolkit is available on the machine, you (and I should emphasis > > that this is an impersonal/generic "you" I reference) might be able to > > argue an exemption from the QT license. > > So maybe it's time to resurrect anygui, maybe in a simplified version > which can only interface to, say, PyQt or Tkinter -- 'eithergui' maybe. 'onegui' to rule them all... -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From cjw at sympatico.ca Wed Feb 2 09:08:41 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 02 Feb 2005 09:08:41 -0500 Subject: type of simple object In-Reply-To: <1107261198.943087.80960@z14g2000cwz.googlegroups.com> References: <1107255752.258025.50870@z14g2000cwz.googlegroups.com> <1107257264.146280.89560@c13g2000cwb.googlegroups.com> <1107258136.815344.145380@c13g2000cwb.googlegroups.com> <1107261198.943087.80960@z14g2000cwz.googlegroups.com> Message-ID: <4200DEE9.3000901@sympatico.ca> ajikoe at gmail.com wrote: > Thank you guys. > > My function should multiply every element of a list, for example > "something" > and "something" can be an integer or another list. > If it deals with integer than it is ok, but > If it deals with list than it become false for example list*2 = > listlist, and what I really want is to mutlitply its member. > That's why I need to know the type of my data in "something". > > By the way I am new in python, I heard that it has a MatLab > capabilities, How good is that? Since It would be very nice when we can > do what MatLab do in python..... > > > Sincerely Yours, > pujo > If you are looking for MatLab like facilities you might consider numarray, available from sourceforge. Colin W. From steven.bethard at gmail.com Fri Feb 25 21:34:53 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 25 Feb 2005 19:34:53 -0700 Subject: Code evaluation at function definition execution time (was Re: Compile time evaluation (aka eliminating default argument hacks)) In-Reply-To: References: Message-ID: Nick Coghlan wrote: > Anyway, if others agree that the ability to execute a suite at def > exeuction time to preinitialise a function's locals without resorting to > bytecode hacks is worth having, finding a decent syntax is the next > trick :) I'm not certain how many use cases really require a full suite, though being able to define default values for function locals in the same way that default values can be defined for function arguments would be nice. Worth looking at is the thread: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/58f53fe8bcc49664/ STeVe From phil at riverbankcomputing.co.uk Thu Feb 10 04:25:00 2005 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 10 Feb 2005 09:25:00 -0000 (GMT) Subject: Newbie: SWIG or SIP? In-Reply-To: References: Message-ID: <47852.82.68.80.137.1108027500.squirrel@river-bank.demon.co.uk> > I have a third-party DLL and it's associated .h file. The DLL was written > in C. I have neither the associated .c files nor the .obj files for the > DLL. Can I use SWIG or SIP to build something that will allow me to use > the > DLL with Python? And what is that something, an .obj file, another DLL or > what? Yes, you can use either SWIG or SIP. C (as opposed to C++) support was added with SIP v4. The something is another DLL, conventionally given a .pyd extenstion. Phil From altis at semi-retired.com Wed Feb 2 16:01:33 2005 From: altis at semi-retired.com (Kevin Altis) Date: Wed, 2 Feb 2005 13:01:33 -0800 Subject: REMINDER: Python proposals due February 13th for OSCON / Python 13 Message-ID: Please submit your tutorial and session proposals for the Python track by February 13th. The information and relevant URLs are below. ka --- The Call for Proposals has just opened for the 7th Annual O'Reilly Open Source Convention http://conferences.oreillynet.com/os2005/ OSCON is headed back to friendly, economical Portland, Oregon during the week of August 1-5, 2005. If you've ever wanted to join the OSCON speaker firmament, now's your chance to submit a proposal (or two) by February 13, 2005. Complete details are available on the OSCON web site, but we're particularly interested in exploring how software development is moving to another level, and how developers and businesses are adjusting to new business models and architectures. We're looking for sessions, tutorials, and workshops proposals that appeal to developers, systems and network administrators, and their managers in the following areas: - All aspects of building applications, services, and systems that use the new capabilities of the open source platform - Burning issues for Java, Mozilla, web apps, and beyond - The commoditization of software: who and/or what can show us the money? - Network-enabled collaboration - Software customizability, including software as a service - Law, licensing, politics, and how best to navigate other troubled waters Specific topics and tracks at OSCON 2005 include: Linux and other open source operating systems, Java, PHP, Python, Perl, Databases (including MySQL and PostgreSQL), Apache, XML, Applications, Ruby, and Security. Attendees have a wide range of experience, so be sure to target a particular level of experience: beginner, intermediate, advanced. Talks and tutorials should be technical; strictly no marketing presentations. Session presentations are 45 or 90 minutes long, and tutorials are either a half-day (3 hours) or a full day (6 hours). Feel free to spread the word about the Call for Proposals to your friends, family, colleagues, and compatriots. We want everyone to submit, from American women hacking artificial life into the Linux kernel to Belgian men building a better mousetrap from PHP and recycled military hardware. We mean everyone! Even if you don't want to participate as a speaker, send us your suggestions--topics you'd like to see covered, groups we should bring into the OSCON fold, extra-curricular activities we should organize--to oscon-idea at oreilly.com . This year, we're moving to the wide open spaces of the Oregon Convention Center. We've arranged for the nearby Doubletree Hotel to be our headquarters hotel--it's a short, free Max light rail ride (or a lovely walk) from the Convention Center. Registration opens in April 2005; hotel information will be available shortly. Deadline to submit a proposal is Midnight (PST), February 13. For all the conference details, go to: http://conferences.oreillynet.com/os2005/ Press coverage, blogs, photos, and news from the 2004 O'Reilly Open Source Convention can be found at: http://www.oreillynet.com/oscon2004/ Would your company like to make a big impression on the open source community? If so, consider exhibiting or becoming a sponsor. Contact Andrew Calvo at (707) 827-7176, or andrewc at oreilly.com for more info. See you Portland next summer, The O'Reilly OSCON Team From deetsNOSPAM at web.de Thu Feb 3 11:02:25 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 03 Feb 2005 17:02:25 +0100 Subject: Calling a method using an argument References: <36evn2F51nullU1@individual.net> Message-ID: <36f02uF51nullU2@individual.net> Diez B. Roggisch wrote: > def test(self,arg): > return getattr(self, arg) > Oops, missed the calling: def test(self,arg): return getattr(self, arg)() If you have more args, do this: def test(self, *args): return getattr(self, args[0])(*args[1:]) -- Regards, Diez B. Roggisch From steve at holdenweb.com Tue Feb 1 09:23:01 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 01 Feb 2005 09:23:01 -0500 Subject: PyCon signature advertising In-Reply-To: References: Message-ID: Mike C. Fletcher wrote: > Steve Holden wrote: > .... > >> I appreciate that not everyone has control over their .sig, > > > .... > > Take control of your sigs, my sisters and brothers! Viva la > Revolution! Follow the Steve into the heat and light of PyCon. You can > achieve enlightenment if only you go to the District on the Eastern Edge > of the new continents when the spring arrives. It is only there that > all will be revealed. It is only there that you shall find peace. > > Joy to the Python world! > Mike > > ________________________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://www.vrplumber.com > http://blog.vrplumber.com > PyCon is coming... > That's the spirit! Of course, a URL wouldn't hurt ;-) backing-away-smiling-ly y'rs - steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.python.org/pycon/2005/ Steve Holden http://www.holdenweb.com/ From irmen.NOSPAM at xs4all.nl Mon Feb 14 18:28:38 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 15 Feb 2005 00:28:38 +0100 Subject: multi threading in multi processor (computer) In-Reply-To: <37ba2dF5b8slrU1@individual.net> References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <420a2938$0$22987$626a14ce@news.free.fr> <1107964587.818199.223980@g14g2000cwa.googlegroups.com> <7xr7jlwieq.fsf@ruckus.brouhaha.com> <420e7ee4$0$28976$e4fe514c@news.xs4all.nl> <37ba2dF5b8slrU1@individual.net> Message-ID: <421133d8$0$28988$e4fe514c@news.xs4all.nl> Leif K-Brooks wrote: > Irmen de Jong wrote: > >> the GIL must die. >> >> I couldn't resist: >> http://www.razorvine.net/img/GIL.jpg > > > Neither could I: > > http://ecritters.biz/diegil.png > > (In case it's not entirely obvious, the stick figure just slices the GIL > into two pieces with his sword, causing its blood to splatter on the wall.) Naah. What about: http://www.razorvine.net/img/killGIL.jpg --Irmen From tarik.messaoudi at purplelabs.com Thu Feb 17 06:59:39 2005 From: tarik.messaoudi at purplelabs.com (Tarik Messaoudi) Date: Thu, 17 Feb 2005 12:59:39 +0100 Subject: need of help Message-ID: <4214872B.3080803@purplelabs.com> Hello, Please I need of help about : * how to display an browser window * how to display a window in the midle of the screen and finaly how to insert an image in a canvas within a program From ncoghlan at iinet.net.au Sat Feb 12 23:50:31 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 13 Feb 2005 14:50:31 +1000 Subject: namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP In-Reply-To: <420EC9BF.5020802@iinet.net.au> References: <420DB64E.9020000@iinet.net.au> <420EC9BF.5020802@iinet.net.au> Message-ID: <420EDC97.1080804@iinet.net.au> Nick Coghlan wrote: > class Namespace(object): > # etc > def _update_dict(self, other): > for k in other: > setattr(self, k, other[k]) This doesn't work, as it doesn't allow the sequence of 2-tuples. So I copied the relevant check for a keys() attribute from dict.update: def _update_dict(self, other): """Allow subclasses to easily override handling of dict updates Also allows dotted names in the source to be handled correctly Uses the "keys" attribute to identify mappings """ try: items = other.keys() except AttributeError: for k, v in other: setattr(self, k, v) else: for k in items: setattr(self, k, other[k]) Another change I made was to the Record class. It now uses __new__ to initialise the instance dictionary with the defaults from the subclass definition, leaving __init__ free to be used to invoke update() like it is for a standard namespace: Py> from namespaces import Record Py> class Example(Record): ... a = 1 ... b = "" ... class _sub_sf(Record): ... c = 3 ... def _sub_calc(): return "Calculated value!" ... Py> x = Example() Py> x Example(a=1, b='', calc='Calculated value!', sf=_sub_sf(c=3)) Py> x = Example(a=3) Py> x Example(a=3, b='', calc='Calculated value!', sf=_sub_sf(c=3)) Py> x = Example([("sf.c", 5)], a=3, b="altered") Py> x Example(a=3, b='altered', calc='Calculated value!', sf=_sub_sf(c=5)) Py> x = Example({"sf.c": 5}, a=3, b="altered") Py> x Example(a=3, b='altered', calc='Calculated value!', sf=_sub_sf(c=5)) I also moved the module to my normal site: http://boredomandlaziness.skystorm.net/misc/namespaces.py Steven: Feel free to pick through this for anything you want to add to the PEP. That's why I'm posting it, after all :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From rkern at ucsd.edu Fri Feb 18 06:37:21 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 18 Feb 2005 03:37:21 -0800 Subject: Python, Matlab and AI question In-Reply-To: References: Message-ID: dataangel wrote: > I'm a student who's considering doing a project for a Machine Learning > class on pathing (bots learning to run through a maze). The language > primarily used by the class has been Matlab. I would prefer to do the > bulk of the project in python because I'm familiar with pygame (for the > visuals) but I already have a lot of AI code written in Matlab. > > I'd like to be able to call Matlab code from within python. I'm not sure > this is possible. My code runs in Octave just fine. There have been some bridges between Matlab and Python, but most of them are old, I believe. http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html If you're on Windows, this may help: http://www.geocities.com/ptmcg/python/using_matlab_from_python.html > I've heard about > numerical python and scipy, but I'm not sure what tool is going to mean > the least amount of recoding for me. At the very least I need to find a > really fast package for matrix operations. That would be Numeric and scipy. You'll probably need Numeric anyways for pygame. scipy has a set of functions that try to mimic Matlab functionality with the same names, so that may help in translating the code. > Anyone have any input on what the best tool for the job would be? I've > googled, but I figure it's best to ask experience ;) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From aisaac0 at verizon.net Fri Feb 11 01:07:50 2005 From: aisaac0 at verizon.net (David Isaac) Date: Fri, 11 Feb 2005 06:07:50 GMT Subject: a sequence question References: Message-ID: "Nick Coghlan" wrote in message news:mailman.1553.1106960946.22381.python-list at python.org... > Using zip(*[iter(l)]*N) or zip(*(iter(l),)*N) simply extends the above to the > general case. Clearly true. But can you please go into much more detail for a newbie? I see that [iter(l)]*N produces an N element list with each element being the same iterator object, but after that http://www.python.org/doc/2.3.5/lib/built-in-funcs.html just didn't get me there. Thanks, Alan Isaac From carl.manaster at gmail.com Thu Feb 3 12:40:55 2005 From: carl.manaster at gmail.com (carl.manaster at gmail.com) Date: 3 Feb 2005 09:40:55 -0800 Subject: Integrated Testing - Peppable? In-Reply-To: References: <1107373949.960435.212020@z14g2000cwz.googlegroups.com> Message-ID: <1107452455.739263.145440@f14g2000cwb.googlegroups.com> Thanks, Jeremy, > No prose can compare to a live, functional demonstration. I agree; that's what my prototype amounts to: (sorry, it's Windows-only) But I take your larger message, and John's, to heart - this isn't worthy of making it into Python. OK; thanks anyway for taking the time to think about it and reply. Peace, --Carl From jmeile at hotmail.com Tue Feb 8 03:32:44 2005 From: jmeile at hotmail.com (Josef Meile) Date: Tue, 08 Feb 2005 09:32:44 +0100 Subject: Curses on Windows In-Reply-To: <72c8d50d.0502060630.1c561599@posting.google.com> References: <72c8d50d.0502060630.1c561599@posting.google.com> Message-ID: <4208792C.8080008@hotmail.com> Hi Peter, > Last November I posted a message asking for advice on using simple > screen handling techniques under Windows. Since then I have been > occupied with family / job /Christmas /living and trying to > understand curses under linux (it works, seems very complex, sure I'm > missing something ...). Only now am I returning to my original query. > > One reply (in fact the only reply - thanks Tim Golden) suggested I > look at http://flangy.com/dev/python/curses/ There was a similar thread last month. See my reply for more links. I haven't tested them, but they may help. how to ncurses on win32 platform: http://mail.python.org/pipermail/python-list/2005-January/262511.html > > Just tried that and got the message > > "You don't have permission to access > /dev/python/curses/files/wcurses-0.1-py2.4.zip on this server." Yes, I also have problems. Regards, Josef From http Sat Feb 5 13:45:09 2005 From: http (Paul Rubin) Date: 05 Feb 2005 10:45:09 -0800 Subject: Alternative to standard C "for" References: <1107628331.816935.16760@o13g2000cwo.googlegroups.com> Message-ID: <7xu0oqlubu.fsf@ruckus.brouhaha.com> adomas.paltanavicius at gmail.com writes: > problem. If i do ..in range(1, 100000000).. (what I really need > sometimes), it takes few hundred megs of memory and slows > down. Are there other good ways for this simple problem? Generators? use xrange instead of range. From http Mon Feb 28 01:33:20 2005 From: http (Paul Rubin) Date: 27 Feb 2005 22:33:20 -0800 Subject: Working with dbase files References: <7MyUd.73116$911.65438@fe2.texas.rr.com> Message-ID: <7xoee52nyn.fsf@ruckus.brouhaha.com> Stan Cook writes: > Does anyone know how I can access and read data from a dbase (.dbf) > file? Yeah, there's some module around someplace that does it. I found it with a few minutes of googling a while back. It worked fine. I don't remember where it was. From http Wed Feb 16 14:11:42 2005 From: http (Paul Rubin) Date: 16 Feb 2005 11:11:42 -0800 Subject: SHA1 broken References: <421398ad$0$28984$e4fe514c@news.xs4all.nl> Message-ID: <7xpsz0uxox.fsf@ruckus.brouhaha.com> Irmen de Jong writes: > > Also, the new findings only apply to hash collisions, not to the > > invertibility of SHA1 hashes - thus, as Schneier points out, uses of > > keyed hashes (such as HMAC) are not compromised by this. > > What about HMAC-MD5? HMAC-MD5 and HMAC-SHA1 should be affected by the vulnerability in about the same way. Based on some reasonable assumptions both should still be secure. Note also that the 2**69 attack against SHA1 is an important theoretical result, but nowhere near as bad a practical vulnerability as the md5 break which allowed finding real collisions in a few cpu-hours. As someone on sci.crypt explained the SHA1 attack, "in motor vehicle terms, SHA1 is a tank and they have discovered a way to scratch the paint". From eric_brunel at despammed.com Mon Feb 28 06:24:05 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 28 Feb 2005 12:24:05 +0100 Subject: Fonts References: Message-ID: On Fri, 25 Feb 2005 11:00:41 -0600, phil wrote: > I'm cpmpletely lost on fonts. > > I'm using Tkinter > > I do medarial = '-*-Arial-Bold-*-*--24-*-*-*-ISO8859-1" > or Courier or Fixed in various sizes. > > Works great on my RH 7.2 > > But a small embedded system Im working on, nothing seems to work, > almost everything falls back to a fixed 12 You should be able to use a font specification like (family, size [, style]), e.g ('helvetica', 24, 'bold'). This is the most portable way of specifying fonts (X11 font names may not work on some systems). You can get the available font families on your system as seen by Tkinter/tk with: from Tkinter import * import tkFont root = Tk() print tkFont.families() BTW - according to http://www.tcl.tk/man/tcl8.4/TkCmd/font.htm#M25 - the font family names 'helvetica', 'times' and 'courier' are guaranteed to work anywhere with tk/Tkinter. HTH -- python -c 'print "".join([chr(154 - ord(c)) for c in "U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])' From rnd at onego.ru Sat Feb 12 14:09:59 2005 From: rnd at onego.ru (Roman Suzi) Date: Sat, 12 Feb 2005 22:09:59 +0300 (MSK) Subject: Is email package thread safe? (fwd) In-Reply-To: References: Message-ID: On Thu, 10 Feb 2005, Antoon Pardon wrote: > Op 2005-02-09, Roman Suzi schreef : >> On Wed, 9 Feb 2005, Antoon Pardon wrote: >> >>> Op 2005-02-09, Roman Suzi schreef : >>>> >>>> Just to be sure, is email package of Python 2.3 thread-safe or not >>>> (to use, for example, in python-milter?) >> >>>> Can I assume that everything >>>> else without such notice is thread-safe? >>> >>> I doubt it. There is no indication that the email package uses any >>> kind of locking. So multiple thread working on the same message >>> will probably screw things up. >> >> Of course, I do not let threads to work on the same message! > > Why should that be: "off course"? The random module you spoke about > was also only thread unsafe if you called the same random generator > from various threads. Using a randon generator per thread shouldn't > have been a problem. Since you mentioned that, I thought that was > the kind of thread safety you were after. > >> I meant that the package doesn't pose other kinds of restrictions. >> Can it work in _any_ situation work on two different messages at the same >> time, without any interference? > > I can't give a guarantee, but there are no global statements and there > doesn't seem to be assignments to cross module variables I think it > would be a safe bet. Thanks to all who discussed this. Really, I had the same thoughts about 1:1 object-thread relation being thread safe. I am doing further research and if it will give interesting results, I shall post [solved] here. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From onurb at xiludom.gro Wed Feb 9 04:41:53 2005 From: onurb at xiludom.gro (bruno modulix) Date: Wed, 09 Feb 2005 10:41:53 +0100 Subject: Lambda In-Reply-To: <7UdOd.109$0b3.4707@news.uswest.net> References: <7UdOd.109$0b3.4707@news.uswest.net> Message-ID: <4209dae3$0$958$626a14ce@news.free.fr> e wrote: > here's what is probably an unusual question: > > A very open one at least !-) -- bruno desthuilliers ruby -e "print 'onurb at xiludom.gro'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@')" -- From donn at drizzle.com Mon Feb 14 00:25:58 2005 From: donn at drizzle.com (Donn Cave) Date: Mon, 14 Feb 2005 05:25:58 -0000 Subject: Kill GIL References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <868y5t6sal.fsf@guru.mired.org> <86sm405d38.fsf@guru.mired.org> Message-ID: <1108358757.577366@yasure> Quoth Dave Brueck : ... | Another related benefit is that a lot of application state is implicitly and | automatically managed by your local variables when the task is running in a | separate thread, whereas other approaches often end up forcing you to think in | terms of a state machine when you don't really care* and as a by-product you | have to [semi-]manually track the state and state transitions - for some | problems this is fine, for others it's downright tedious. I don't know if the current Stackless implementation has regained any of this ground, but at least of historical interest here, the old one's ability to interrupt, store and resume a computation could be used to As you may know, it used to be, in Stackless Python, that you could have both. Your function would suspend itself, the select loop would resume it, for something like serialized threads. (The newer version of Stackless lost this continuation feature, but for all I know there may be new features that regain some of that ground.) I put that together with real OS threads once, where the I/O loop was a message queue instead of select. A message queueing multi-threaded architecture can end up just as much a state transition game. I like threads when they're used in this way, as application components that manage some device-like thing like a socket or a graphic user interface window, interacting through messages. Even then, though, there tend to be a lot of undefined behaviors in events like termination of the main thread, receipt of signals, etc. Donn Cave, donn at drizzle.com From aleaxit at yahoo.com Sat Feb 5 05:07:10 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 5 Feb 2005 11:07:10 +0100 Subject: "Collapsing" a list into a list of changes References: Message-ID: <1gribme.1b8vjvuz98jhkN%aleaxit@yahoo.com> Steven Bethard wrote: > Here's a solution that works for iterables other than lists: > > py> def collapse(iterable): > ... enumeration = enumerate(iterable) > ... _, lastitem = enumeration.next() > ... yield lastitem > ... for i, item in enumeration: > ... if item != lastitem: > ... yield item > ... lastitem = item > ... > py> lst = [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5] > py> list(collapse(lst)) > [0, 1, 2, 3, 2, 4, 5] > > Again, I'm still not sure I'd call this more elegant... Hmmmm, what role does the enumeration play here? I don't see how you're using it, at all. Why not just: def collapse(iterable): it = iter(iterable) lastitem = it.next() yield lastitem for item in it: if item != lastitem: yield item lastitem = item that's basically just the same as your code but without the strangeness of making an enumerate for the purpose of ignoring what the enumerate adds to an ordinary iterator. Alex From deetsNOSPAM at web.de Fri Feb 18 07:05:35 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 18 Feb 2005 13:05:35 +0100 Subject: [newbie]How to install python under DOS and is there any Wxpython can be installed under dos? References: <1108557065.547230.254540@z14g2000cwz.googlegroups.com> <11172sa1sg2svc8@corp.supernews.com> <4K6dneoBWMc4KInfRVn-rA@rogers.com> <37jsdgF5e56jeU1@individual.net> <4qgbt58f.fsf@python.net> Message-ID: <37m3vaF5f0askU1@individual.net> Thomas Heller wrote: > "Diez B. Roggisch" writes: > >> Maybe somehow the pygame sdl wrapper can be used for gui-stuff. SDL has >> had a DOS mode. But it is discontinued. > > What exactly is discontinued? pygame? SDL? The dos mode of sdl. -- Regards, Diez B. Roggisch From john_sips_teaz at yahooz.com Thu Feb 17 11:03:39 2005 From: john_sips_teaz at yahooz.com (John) Date: Thu, 17 Feb 2005 11:03:39 -0500 Subject: difference between class methods and instance methods In-Reply-To: References: Message-ID: <1119g2rre5g610c@corp.supernews.com> Duncan Booth wrote: > John M. Gabriele wrote: > > >>I've done some C++ and Java in the past, and have recently learned >>a fair amount of Python. One thing I still really don't get though >>is the difference between class methods and instance methods. I >>guess I'll try to narrow it down to a few specific questions, but >>any further input offered on the subject is greatly appreciated: > > > I'll try not to cover the same ground as Steven did in his reply. > Thanks for taking the time to reply Duncan. > >>1. Are all of my class's methods supposed to take 'self' as their >>first arg? > > consider this: > > class Demo(object): > > def foo(self, x): > print self, x > @classmethod > def clsmethod(cls, x): > print cls, x > @staticmethod > def stmethod(x): > print x > > > > instance = Demo() > > > Calling a bound method, you don't pass an explicit self parameter, but the > method receives a self parameter: > > > bound = instance.foo > bound(2) > > <__main__.Demo object at 0x00B436B0> 2 > > Note that it doesn't matter whether you call instance.foo(2) directly, or > bind instance.foo to a variable first. Either will create a *new* bound > method object, and the correct instance is used for the call. Za! What do you mean, "create a new bound method object"? I *already* created that method when I def'd it inside the 'class Demo' statement, no? > This is > significantly different from languages such as C++ and Javascript which are > a real pain if you want to use a method as a callback. > > Calling an unbound method, you pass a self parameter explicitly (and it > must be an instance of the class, *or an instance of a subclass*: > > > unbound = Demo.foo > unbound(instance, 2) > > <__main__.Demo object at 0x00B436B0> 2 Ahhhhhhhh! See, coming from C++, the first thing I thought when I saw what you just wrote was, "whoops, he shouldn't be calling that instance method via the class name -- it's a bad habit". Now I think I see what you mean: you may call an instance method in two ways: via an instance where you don't pass in anything for 'self', and via the class name, where you must supply a 'self'. > Again is doesn't matter whether you do this in one step or two. The usual > case for using an unbound method is when you have overridden a method in a > derived class and want to pass the call on to a base class. e.g. Ok. Interesting. > > class Derived(Demo): > > def foo(self, x): > Demo.foo(self, x) > > A class method is usually called through the class rather than an instance, > and it gets as its first parameter the actual class involved in the call: > > > Demo.clsmethod(2) > > 2 > > Derived.clsmethod(2) > > 2 Check. > You can call a class method using an instance of the class, or of a > subclass, but you still the get class passed as the first parameter rather > than the instance: > > > d = Derived > d.clsmethod(2) > > 2 Ok, so it looks like it may lead to confusion if you do that. I wonder why the language allows it... > A common use for class methods is to write factory functions. This is > because you can ensure that the object created has the same class as the > parameter passed in the first argument. Alternatively you can use class > methods to control state related to a specific class (e.g. to count the > number of instances of that exact class which have been created.) > > There is no equivalent to a class method in C++. Right. I see -- because in Python, a reference the actual class object is implicitly passed along with the method call. Whereas, C++ doesn't even have "class objects" to begin with. > > Static methods are like static methods in C++. You can call them through > the class or a subclass, or through an instance, but the object used in the > call is not passed through to the method: > > > Demo.stmethod(2) > > 2 > > instance.stmethod(2) > > 2 > > Derived.stmethod(2) > > 2 > > d.stmethod(2) > > 2 > > >>2. Am I then supposed to call them with MyClass.foo() or instead: >> >> bar = MyClass() >> bar.foo() >>? > > > If you have an instance then use it. If the class method is a factory then > you might want to create a new object of the same type as some existing > object (but not a simple copy since you won't get any of the original > object's state). Mostly though you know the type of the object you want to > create rather than having an existing instance lying around. > > >>3. Is "bound method" a synonym for instance method? > > > Close but not quite. It is a (usually transient) object created from an > unbound instance method for the purposes of calling the method. ... hmm... bound methods get created each time you make a call to an instance method via an instance of the given class? >>4. Is "unbound method" a synonym for class method? > > > Definitely not. Right. :) > >>And if anyone's *really* daring: >>Where do the so-called "static methods" fit into all this? >>By the name of them, it sounds like the same thing as class >>methods... > > > See above. > -- --- remove zees if replying via email --- From justscott at gmail.com Wed Feb 16 12:53:05 2005 From: justscott at gmail.com (JustScott) Date: Wed, 16 Feb 2005 11:53:05 -0600 Subject: [Errno 18] Invalid cross-device link using os.rename In-Reply-To: <20050215003118.GC6339@unpythonic.net> References: <1108414124.890402.109480@z14g2000cwz.googlegroups.com> <20050215003118.GC6339@unpythonic.net> Message-ID: <401c37a405021609534f57112b@mail.gmail.com> Thanks, Jeff. I appreciate the input. I just stuck with os.system('mv %s %s'). Seems to work fine. On Mon, 14 Feb 2005 18:31:18 -0600, Jeff Epler wrote: > mv is a surprisingly complex program, while os.rename is a wrapper > around rename(2) which is probably documented on your system to return > EXDEV under these circumstanes. > > os.xxx is generally a fairly thin wrapper around what your OS provides, > and inherits all the "gotchas". For some activities, os.shutil provides > something that is between os.xxx and os.system("xxx") in complexity and > capability. > > Jeff > > > From Scott.Daniels at Acm.Org Thu Feb 24 14:31:41 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 24 Feb 2005 11:31:41 -0800 Subject: Canonical way of dealing with null-separated lines? In-Reply-To: References: Message-ID: <421e2776@nntp0.pdx.net> Douglas Alan wrote: ... > In any case, as a suggestion to the whomever it is that arranges for > stuff to be put into the standard library, there should be something > like this there, so everyone doesn't have to reinvent the wheel (even > if it's an easy wheel to reinvent) for something that any sysadmin > (and many other users) would want to do on practically a daily basis. The general model is that you produce a module, and if it gains a audience to a stable interface, inclusion might be considered. I'd suggest you put up a recipe at ActiveState. --Scott David Daniels Scott.Daniels at Acm.Org From ilias at lazaridis.com Sat Feb 19 11:54:59 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sat, 19 Feb 2005 18:54:59 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <42172136$0$27576$9b622d9e@news.freenet.de> Message-ID: Diez B. Roggisch wrote: > Ilias Lazaridis wrote: >>Diez B. Roggisch wrote: >>>>Should a professional developer take python serious? >>[...] - (ungentle babbling after disrupting coherence of writings) > > And that from you.... *lol* Of course. I respect the "coherence of writings" of my conversation partners. [If they are in-topic / in-context] >>I mean, if the team does not manage at least the foundation of a >>multi-target automated-build-process? > > Repeating nonsense doesn't increase it's validity. Python makes use of [...] - (babbling, gentle links) Thank you for the links. They are irrelevant for me. But other readers for sure will enjoy. - The automated-build-process-system should allow community-members to add their targets into an special "incubation section", which does not in any way affect the "main section" (which contains the official production targets). If an "incubation section" target proves over time as stable and supported, it is moved to the "official-auto-build". >>[targets need not to be supported directly by the python team. They >>could be added/managed/maintained by community members] > > You already found the mingw-patch for building python. It is > added/managed/maintained by community members. This is a one-man-show, which does not invite to open collaboration (feedback is requested to closed email): http://groups-beta.google.com/group/comp.lang.python/msg/98fa42dabff68db2 python [foundation, crew, dictator, ...] should engourage open collaboration, should engourage _collaboration_. > Just out of curiousity: How many python extensions are you planning to > write? I estimate 10 to 100, depending on abstractional capabilities of the extension system. > And how many lines of pure python code have you written in your life? 0 (zero). . -- http://lazaridis.com From aurora00 at gmail.com Fri Feb 18 12:10:04 2005 From: aurora00 at gmail.com (aurora) Date: Fri, 18 Feb 2005 09:10:04 -0800 Subject: unicode encoding usablilty problem Message-ID: I have long find the Python default encoding of strict ASCII frustrating. For one thing I prefer to get garbage character than an exception. But the biggest issue is Unicode exception often pop up in unexpected places and only when a non-ASCII or unicode character first found its way into the system. Below is an example. The program may runs fine at the beginning. But as soon as an unicode character u'b' is introduced, the program boom out unexpectedly. >>> sys.getdefaultencoding() 'ascii' >>> a='\xe5' >>> # can print, you think you're ok ... print a ? >>> b=u'b' >>> a==b Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128) >>> One may suggest the correct way to do it is to use decode, such as a.decode('latin-1') == b This brings up another issue. Most references and books focus exclusive on entering unicode literal and using the encode/decode methods. The fallacy is that string is such a basic data type use throughout the program, you really don't want to make a individual decision everytime when you use string (and take a penalty for any negligence). The Java has a much more usable model with unicode used internally and encoding/decoding decision only need twice when dealing with input and output. I am sure these errors are a nuisance to those who are half conscious to unicode. Even for those who choose to use unicode, it is almost impossible to ensure their program work correctly. From hakan at zyberit.com Sat Feb 5 12:01:50 2005 From: hakan at zyberit.com (=?ISO-8859-1?Q?H=E5kan_Persson?=) Date: Sat, 05 Feb 2005 18:01:50 +0100 Subject: How to read POSTed data Message-ID: <4204FBFE.70408@zyberit.com> Hi. I am trying to set up a simple HTTP-server but I have problems reading data that is beeing POSTed. class httpServer(BaseHTTPServer.BaseHTTPRequestHandler): def do_POST(self): input = self.rfile.read() The self.rfile.read() will hang on the data = self._sock.recv(recv_size) line in the read() function in socket.py. Is there another way to read the data? Thanks, H?kan Persson From fredrik at pythonware.com Wed Feb 9 13:18:25 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 9 Feb 2005 19:18:25 +0100 Subject: python code with indention References: <1107805151.265680.165380@o13g2000cwo.googlegroups.com><110hq18fbebn0b1@news.supernews.com> <1107972416.931714.256210@l41g2000cwc.googlegroups.com> Message-ID: Xah Lee wrote: >i thought it is trivial for the Python parser to spit out a version > with matching brackets. Similarly, perhaps some opensourcing student > has modified a parser to read in a matching brackets delimited version > of Python. $ python Tools\scripts\pindent.py You must specify -c(omplete), -d(elete) or -r(eformat) usage: pindent (-c|-d|-r) [-s stepsize] [-t tabsize] [-e] [file] ... -c : complete a correctly indented program (add #end directives) -d : delete #end directives -r : reformat a completed program (use #end directives) -s stepsize: indentation step (default 8) -t tabsize : the worth in spaces of a tab (default 8) -e : expand TABs into spaces (defailt OFF) [file] ... : files are changed in place, with backups in file~ If no files are specified or a single - is given, the program acts as a filter (reads stdin, writes stdout). From neutrinman at myrealbox.com Sun Feb 27 07:52:35 2005 From: neutrinman at myrealbox.com (neutrinman at myrealbox.com) Date: 27 Feb 2005 04:52:35 -0800 Subject: error: db type could not be determined In-Reply-To: <1109413706.437205.286070@o13g2000cwo.googlegroups.com> References: <1109407276.520167.190630@f14g2000cwb.googlegroups.com> <1109413706.437205.286070@o13g2000cwo.googlegroups.com> Message-ID: <1109508755.456000.178430@f14g2000cwb.googlegroups.com> Thank you for your reply, Jhon. It was useful advice. > Take a hint: they say "Google is your friend", but better still is the > source in lib\*.py -- it's quite legible, you don't need an Internet > connection, and there sure ain't no ads in the margin. And don't just > open it in emergencies: pick a module that covers a topic that > interests you and just read it. You'll see good coding style, good ways > of doing things, wise utterances by the timbot, ... I am new to programing so I was wasting a lot of time to fix bug, only struggling with my code where an error has occured then read throug an book at hand. I didn't think of such an approch to solve problems and read error messages. Thank you again very much for the imformative advice. From dimitri.pater at gmail.com Fri Feb 18 06:58:00 2005 From: dimitri.pater at gmail.com (dimitri pater) Date: Fri, 18 Feb 2005 12:58:00 +0100 Subject: How do I make my program start fullscreen ? In-Reply-To: <17smpt9l5tn7z.1744dg3zal7hj.dlg@40tude.net> References: <17smpt9l5tn7z.1744dg3zal7hj.dlg@40tude.net> Message-ID: If you're using Tkinter, the next url might help: http://effbot.org/zone/tkinter-toplevel-fullscreen.htm On Tue, 15 Feb 2005 23:35:05 +0100, BOOGIEMAN wrote: > os = windows xp > How do I make "myprogram.py" start fullscreen at windows command prompt ? > Also I made it as "myprogram.exe" with py2exe,but how to start fullscreen ? > -- > http://mail.python.org/mailman/listinfo/python-list > -- Please visit dimitri's website: www.serpia.com From administrata at hotmail.com Sun Feb 13 05:04:46 2005 From: administrata at hotmail.com (administrata) Date: 13 Feb 2005 02:04:46 -0800 Subject: [NooB] a Variable in multiple quotes... Message-ID: <614c778e.0502130204.5824cddf@posting.google.com> Is it possible? I tried... I = "John" print \ """ I used to love pizza""" Error occurs!!! But, I don't know how to fix... HELP thx 4 reading. From luke at tatooine.planet Mon Feb 7 20:00:10 2005 From: luke at tatooine.planet (Luke Skywalker) Date: Tue, 08 Feb 2005 02:00:10 +0100 Subject: Big development in the GUI realm References: Message-ID: <4i3g01tv48qr50g8fjc8nf3n09eaauaen5@4ax.com> On Tue, 08 Feb 2005 10:47:25 +1100, Tim Churches wrote: >So there you have it: there must be some portion of the GPLed Program contained in >the other work for it to fall under the scope of the GPL, and/or as defined as a >derivative work in local copyright law (local because the GPL does not nominate a >particular jurisdiction for covering law). Has someone worked with Qt for Windows before, and could tell us whether it involves static or dynamic linking? If dynamic, then, it doesn't make sense that an EXE that builds on Qt should also be GPLed. Luke. From export at hope.cz Thu Feb 17 05:26:36 2005 From: export at hope.cz (export at hope.cz) Date: 17 Feb 2005 02:26:36 -0800 Subject: MYSQL - how to install ? In-Reply-To: References: <1108547199.260223.211450@f14g2000cwb.googlegroups.com> <1108556905.444394.210020@l41g2000cwc.googlegroups.com> <1108562949.825258.297260@f14g2000cwb.googlegroups.com> Message-ID: <1108635996.165520.132960@o13g2000cwo.googlegroups.com> Daniel Bowett wrote: > Lad wrote: > > I am sorry it was my fault I did not say that clearly. > > I do not have a problem to install MySQL server but I do not know how > > to install MySQLdb module on my windowsXP so that I can work with > > MySQL server via Python 2.3. > > Thanks for help > > Lad > > > > Try this installer, if you want a newer version you will need to compile > it yourself. > > http://prdownloads.sourceforge.net/mysql-python/MySQL-python.exe-1.0.0.win32-my4.1-py2.3.exe?download Thank you I will try. As far as I understand I can install the latest MySQL server and then MySQLdb module on my windowsXP with the installer( the link you provided above). Is it so? Lad. From deetsNOSPAM at web.de Mon Feb 14 11:19:29 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 14 Feb 2005 17:19:29 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: <4210a434$0$23451$626a14ce@news.free.fr> Message-ID: <37c1cgF35vfuvU1@individual.net> > Now, it's rather common to accuse people of trolling these days. > The fact that Markus Wankus said that Ilias is a troll does not mean > that everybody should reply to him in that tone. > This is a one .vs many battle and it sucks. Just because someone says somebody else is a troll surely is not valid reason to take that for granted. But googling [1-*] for Mr. Lazaridis makes it apparent that he _is_ a troll. And even if you only take the two threads on c.l.py into account IMHO you can see that. He's been _banned_ from several OS project mailing lists like eclipse, netbeans and hibernate. Of course he claims that is because of censorship and has nothing to do with his actions in those respective communities. But somehow to me at least a pattern is visible. [1]: http://groups-beta.google.com/group/comp.lang.java.softwaretools/browse_frm/thread/836fe2380e6e2649/748a70ee4e39fc41?q=Lazaridis+Ilias&_done=%2Fgroups%3Fq%3DLazaridis+Ilias%26hl%3Den%26lr%3D%26ie%3DUTF-8%26sa%3DN%26tab%3Dwg%26&_doneTitle=Back+to+Search&&d#748a70ee4e39fc41 [2]: http://www.netbeans.org/servlets/ReadMsg?msgId=872061&listName=nbusers [3]: http://groups-beta.google.com/group/comp.lang.java.softwaretools/browse_frm/thread/f07832cf6d0094f0/85ae8ee0bccdeb14?q=Lazaridis+Ilias&_done=%2Fgroups%3Fq%3DLazaridis+Ilias%26hl%3Den%26lr%3D%26ie%3DUTF-8%26sa%3DN%26tab%3Dwg%26&_doneTitle=Back+to+Search&&d#85ae8ee0bccdeb14 [4]: http://groups-beta.google.com/group/comp.lang.java.softwaretools/browse_frm/thread/837df2c1188e6e39/18b5dcfd54a6a902?q=Lazaridis+Ilias&_done=%2Fgroups%3Fq%3DLazaridis+Ilias%26hl%3Den%26lr%3D%26ie%3DUTF-8%26sa%3DN%26tab%3Dwg%26&_doneTitle=Back+to+Search&&d#18b5dcfd54a6a902 -- Regards, Diez B. Roggisch From nbbalane at gmail.com Wed Feb 2 03:19:51 2005 From: nbbalane at gmail.com (jrlen balane) Date: Wed, 2 Feb 2005 16:19:51 +0800 Subject: how to separate hexadecimal In-Reply-To: <420082E4.7020605@iinet.net.au> References: <2cad209005020123107fb43105@mail.gmail.com> <2cad2090050201232427cb97f2@mail.gmail.com> <420082E4.7020605@iinet.net.au> Message-ID: <2cad2090050202001973138f8@mail.gmail.com> On Wed, 02 Feb 2005 17:36:04 +1000, Nick Coghlan wrote: > jrlen balane wrote: > > i have a 4 digit hex number (2 bytes) and i want to separate it into 2 > > digit hex (1 byte each) meaning i want to get the upper byte and the > > lower byte since i am going to add this two. > > how am i going to do this? > > should i treat it just like a normal string? > > please help, thanks. > > > > ex. hexa = '0x87BE" # what i want to do is: > > a = 0x87, b = 0xBE # so that i could do this: > > c = a + b #which should be equal to 0x145 > > divmod does what you want: > > Py> val = 0x87be > Py> hi, lo = divmod(val, 0x100) > Py> hex(hi), hex(lo) > ('0x87', '0xbe') > Py> hex(hi + lo) > '0x145' > > Cheers, > Nick. > > -- > Nick Coghlan | ncoghlan at email.com | Brisbane, Australia > --------------------------------------------------------------- > http://boredomandlaziness.skystorm.net > -- > http://mail.python.org/mailman/listinfo/python-list > would i be able to perform bitwise operation with the result? say, i want to get the two's complement of the result, is this correct: twos_complement = (~ hex(hi + lo)) + 1 From lmhaskins at yahoo.com Fri Feb 18 13:42:20 2005 From: lmhaskins at yahoo.com (lmhaskins at yahoo.com) Date: 18 Feb 2005 10:42:20 -0800 Subject: move bugs from Zope BITS into Bugzilla? References: <1106956988.391329.320610@z14g2000cwz.googlegroups.com> <41fada16$0$25421$afc38c87@news.optusnet.com.au> Message-ID: <1108752140.895329.249710@o13g2000cwo.googlegroups.com> Does it import from BITS? From roy at panix.com Sun Feb 6 10:05:53 2005 From: roy at panix.com (Roy Smith) Date: Sun, 06 Feb 2005 10:05:53 -0500 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1grifns.14san6f1b076mdN%aleaxit@yahoo.com> <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com> <1grj036.r13xcy1d72inbN%aleaxit@yahoo.com> <2qba01d1men2ai48gp4cojo2e28rd5g9ob@4ax.com> <1grjzia.1a4qr9q1t3p77bN%aleaxit@yahoo.com> Message-ID: In article <1grjzia.1a4qr9q1t3p77bN%aleaxit at yahoo.com>, aleaxit at yahoo.com (Alex Martelli) wrote: > This is a good development, overall. Against stupidity, the gods > themselves contend in vain; Python's entrance into stupid firms broadens > its potential appeal from less than 10% to around 100% of the market, > which is good news for sellers of books, tools, training, consultancy > services, and for Python programmers everywhere -- more demand always > helps. *BUT* the price is eternal vigilance... I'm not sure what that last sentence is supposed to mean, but I have visions (nightmares?) of someday having ANSI, ISO, IEEE, or some other such organization notice that something useful exists which they haven't yet standardized/broken and decide to form a committee to do it. From fredrik at pythonware.com Tue Feb 8 13:49:08 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Feb 2005 19:49:08 +0100 Subject: Python versus Perl ? References: <1107695949.247611.272800@g14g2000cwa.googlegroups.com> Message-ID: m" wrote: >>>If Python is better than Perl, I'm curious how really significant >>>those advantages are ? > > speedwise, i think perl is faster than python and python performed the slowest as shown in > http://www.flat222.org/mac/bench/ if you use Python mostly to write empty loops, your programming license should be revoked. the benchmark author seems to have realized that, as can be seen from the "it's dead" paragraph at the top of the page, which makes me wonder why you posted this link... From ncoghlan at iinet.net.au Tue Feb 1 20:56:35 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 02 Feb 2005 11:56:35 +1000 Subject: Where are list methods documented? In-Reply-To: <1f7befae05020110222aa1daaa@mail.gmail.com> References: <41ffba7d$0$15879$a1866201@visi.com> <41ffc37a$0$15874$a1866201@visi.com> <1f7befae05020110222aa1daaa@mail.gmail.com> Message-ID: <42003353.8060708@iinet.net.au> Tim Peters wrote: > 2. Built-In Objects > 2.1 Built-in Functions > 2.2 Non-essential Built-in Functions > 2.3 Built-in Types > 2.3.1 Truth Value Testing > 2.3.2 Boolean Operations > 2.3.3 Comparisons > 2.3.4 Numeric Types > 2.3.5 Iterator Types > 2.3.6 Sequence Types > 2.3.7 Set Types > 2.3.8 Mapping Types > 2.3.9 File Objects > 2.3.10 Other Built-in Types > 2.3.11 Special Attributes > 2.4 Built-in Exceptions > 2.5 Built-in Constants > > So, e.g., it doesn't mention floats or dicts by those names either. > It's well worthwhile to spend some time browsing that entire chapter. I wonder if adding a small table to the end of the introductory text in Section 2.3 would help. Something like: """" The documentation in this section is written in terms of type categories. The table below associates specific builtin types with the most relevant categories. Type Category Specific Built-in Types Boolean bool Numeric int, long, float, complex Iterator N/A Sequence tuple String Sequence str, unicode Mutable Sequence list Set set, frozenset Mapping dict File file """ Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From abkhd at earth.co.jp Mon Feb 14 15:11:33 2005 From: abkhd at earth.co.jp (A.B., Khalid) Date: 14 Feb 2005 12:11:33 -0800 Subject: - E02 - Support for MinGW Open Source Compiler References: <1108398011.213872.321390@o13g2000cwo.googlegroups.com> Message-ID: <1108411893.940158.270090@c13g2000cwb.googlegroups.com> Pat wrote: > There have been extensive discussions about these issues on the > Python-Dev mailing list over the past couple of months (mostly in > December, but continuing to the present - see > http://mail.python.org/pipermail/python-dev/2004-December/thread.html > as a starting point), which seem to have fizzled out or at least > haven't resolved much. The discussions made reference to work that has > already been done to allow Python to be compiled with minGW: > > pyMinGW is a patch to Python source that aims to get Python to compile > under MinGW > > http://jove.prohosting.com/iwave/ipython/pyMinGW.html > > I've not seen any commentary on the quality of this patch, so that > doesn't appear to be the reason it hasn't been officially adopted. > Reading all the threads from Python-Dev has not enlightened me at all > as to what the underlying reason is for not adopting these changes. > Maybe there are good reasons, I just couldn't find them, and I'm > usually pretty good with Google. If passing all the regression tests of the official Windows Python distribution is an indication of the quality of patch-- and pyMinGW patched and MinGW built Python does pass all of them-- then one is inclined to say that pyMinGW is a good patch. The reason why it is, on the other hand, not included in the official distribution is threefold. 1. Contrary to what many might imagine, I don't think enough people use MinGW to frankly justify any extra effort beyond pyMinGW. 2. Given number 1 above, this patch, I believe, and I could be mistaken, must not rush to be included in Python's core; people like your esteemed person should test it (note that it is designed not to interfere with your trusted and working official Python, if any); it is only when enough people do such testing that there will be a case for it to be included in Python's core. 3. Finally. there is nothing wrong with third-party patches if they get the job done, which I believe is the case with pyMinGW. Regards, Khalid From rdsteph at mac.com Mon Feb 21 21:54:19 2005 From: rdsteph at mac.com (rdsteph at mac.com) Date: 21 Feb 2005 18:54:19 -0800 Subject: pyGoogle is fun and easy to use, and thinks Python is the best programming language Message-ID: <1109040859.816948.70120@o13g2000cwo.googlegroups.com> I am having a lot of fun using the pyGoogle module ( http://pygoogle.sourceforge.net/ ) that uses the Google API. It is about as easy to use as I can imagine, and it is a lot nicer than using my old HTMl screen scraping habits. My online CGI program Ask Merlin at www.awaretek.com/askmerlin.html is an example. Currently, the program takes any user's question and picks the best answer from amongst the possible answers given by the user. The program uses an algorithm that uses an intelligent analysis of search results from Google. OK, OK, I know already, that this is of limited utility compared to answering any question without requiring the user to give options to choose from; and, furthermore i know full well that at this point Merlin is far from foolproof even when given options to choose amongst. Still, if you play with it for a while you will be amazed at how well it does do. Moreover, I am hard at work on a version that will answer any question without being given options, by choosing options from Google search results that are most appropriate and then applying my "intelligent" algorithm. But hey, even as it stands, when queried "which is the best programming language to use for ease of use," Merlin picks Python from amongst a list of python, ruby, ADA and java. When queried "which language is the best programming language to use for a large project requiring realtime operation and involving life and death issues of human life", Merlin picks ada out of the same list. And, when just plain asked "what is the best programming language" Merlin wisely picks Python from the list. And I assure you that none of this is "hard coded" but instead just uses the regular algorithm applied to any other question ;-)))) OK, it's just a fun little hack by a very amateurish hacker; but that's sort of the point. Just think what a good programmer could do with pyGoogle ;-)))) From fuzzyman at gmail.com Wed Feb 2 03:05:19 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 2 Feb 2005 00:05:19 -0800 Subject: Who should security issues be reported to? In-Reply-To: <7xy8edwutv.fsf@ruckus.brouhaha.com> References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> <1106917317.595640.149010@z14g2000cwz.googlegroups.com> <7xy8edwutv.fsf@ruckus.brouhaha.com> Message-ID: <1107331519.862445.88890@f14g2000cwb.googlegroups.com> Paul Rubin wrote: > "Fuzzyman" writes: > > The sourceforge bug tracker *is* the single right place to post such > > issues. The py-dev mailing list would be a second *useful* place to > > post such a comment, although not really the right place. The OP seemed > > to want an individual with whom he could have a private conversation > > about it. > > I think he wanted a place to send a bug report that wouldn't be > exposed to public view until the developers had a chance to issue a > patch. With bugzilla, for example, you can check a bug labelled "this > is a security bug, keep it confidential". There's lots of dilemmas > and some controversy about keeping any bug reports confidential in an > open source system. But the general strategy selected by Mozilla > after much debate seems to mostly work ok. It basically says develop > a patch quickly, keep the bug confidential while the patch is being > developed, and once the patch is available, notify distro maintainers > to install it, and then after a short delay (like a couple days), > publish the bug. > > Note that anyone with access to the bug (that includes the reporter > and selected developers) can uncheck the box at any time, if they > think the bug no longer needs to be confidential. The bug then > becomes visible to the public. Sounds like a useful feature request to Sourceforge. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From grante at visi.com Thu Feb 17 15:22:45 2005 From: grante at visi.com (Grant Edwards) Date: 17 Feb 2005 20:22:45 GMT Subject: How to wrap a class's methods? References: <4214f167$0$44618$a1866201@visi.com> Message-ID: <4214fd15$0$44645$a1866201@visi.com> On 2005-02-17, Steven Bethard wrote: > py> class C(object): > ... def f(self, *args): > ... print "f:", args > ... def g(self, *args): > ... print "g:", args > ... > py> class D(C): > ... pass > ... > py> class Wrapper(object): > ... def __init__(self, func): > ... self.func = func > ... def __call__(self, *args): > ... print "wrapped" > ... return self.func(*args) > ... > py> for name in ['f', 'g']: > ... wrapper = Wrapper(getattr(C, name)) > ... setattr(D, name, new.instancemethod(wrapper, None, D)) Thanks. The stuff provided by the "new" module is what I was missing. -- Grant Edwards grante Yow! Wait... is this a FUN at THING or the END of LIFE in visi.com Petticoat Junction?? From petite.abeille at gmail.com Thu Feb 10 16:39:14 2005 From: petite.abeille at gmail.com (PA) Date: Thu, 10 Feb 2005 22:39:14 +0100 Subject: XDR? (was Re: is there a safe marshaler?) In-Reply-To: <420bd06f$0$28991$e4fe514c@news.xs4all.nl> References: <420b6936$0$28982$e4fe514c@news.xs4all.nl> <420bd06f$0$28991$e4fe514c@news.xs4all.nl> Message-ID: <2af1ac20385b626e90dae642fec6e9c1@gmail.com> On Feb 10, 2005, at 22:21, Irmen de Jong wrote: > PS the xdr format is not self-describing in the way that > marshal and pickle streams are. That is a big limitiation > for what I need it for so xdr seems to drop off my radar. > Is an ASN.1 stream self-describing? Not sure how much "self-describing" you want it to be, but, yes it can be as formal as you want it to be... "... Abstract Syntax Notation One (ASN.1) is a formal language for abstractly describing messages... " Sorry if this is off-topic, I didn't follow the thread from the very beginning, but wouldn't something like YAML work for you perhaps? http://yaml.org/ Or even something more, er, exotic: https://alt.textdrive.com/pl/ Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From andyl at motorola.com Fri Feb 18 13:01:33 2005 From: andyl at motorola.com (Andy Leszczynski) Date: Fri, 18 Feb 2005 12:01:33 -0600 Subject: wxPython demo /Process does not open new demo Message-ID: Try to run wxPython 2.5 (for python 2.3) demo. Then Open Process and Events/Process. Type in "python -u demo.py" and wait. There is a splash screen but nothing more. Why? Regards,A. From zetasum at yahoo.com Fri Feb 18 16:06:30 2005 From: zetasum at yahoo.com (zetasum) Date: 18 Feb 2005 13:06:30 -0800 Subject: R*volume*raduis2 c3po "Theroy of everything" Message-ID: <1108760789.998111.179920@c13g2000cwb.googlegroups.com> R*volume*raduis2 c3po "Theroy of everything" finding the multi-plex time and volume of the earth you can find the universe volume and time!! A.I =/2 You have to start all over agian with this t3echnology bulid A.I and a new quantium computer or supercomputer is the only way to get this to work from the computer to the qunatium computer al the way to the technology on this web page and then do it over agian ever law is wrong all physics math and geometry ( infinte degress math leads you to a new mathmatics that not of numbers but more of a code 333.333.333.333 but in more then one dimensions this would be a new software compiled on the new computer that instead of using binary it uses it uses the left over computations and ram to run the program so if you had a 10 tera hz dell desk top it would run at the maximum limit @ 1% One Small step one infinite leap by: zeta limit Quantum cryptography Run this in every order 1 correct outcome Run the web site with every word and every order and ever letter in every order then every paragraph then and number and do that in every order. Everything is possible one way or another anything, any you can tell it to build anything and it will be possible. Less is more Examples: with a stick if you can make a car drive if you push down on the gas pedal with it. This proves the real "Theory of Everything" and builds a huge data base of information. The more information ,The bigger the neural network and just keep adding more to it because anything is possible and new things can be found after this is done. By using The new ideas and the information you now can run everything back wards and then forward but now by not just adding but by +,*,/,<,>,= ,-,+ then finding how all things can be 100% true if there not then your not doing it right. Then run this in every order and change the neural network to be 100%efficient in making all ideas. After your done use the code to turn one Law, definition, on and off like math, and matter, and all the word net technology dictionary and then turn them off in every order on the website then build a separate quantum neural network to store all the information in then just run it all over again do it over and over with the new math and information on the website it will generate new laws of den's and math and quantum and stellar physics more. run the laws the new laws that changed see by what percent they are true by using % and digress 3=1 360 degrees = 3 but is in every infinite angle and degree until all = 100% only use your data base to help generate new laws. But by running the neural network with words missing and laws missing. It will make new laws until all is 100% true learning way outside the realm of A.I or R.I. finally ...Then with my matrix program run the neural network With my own Matrix code and Artificial intelligence with this bunny encrypted website by starting with one dimension up to infinite and every angel and shape start with a box and every degree every number letter and word it will keep growing and so does the database. After all is done all laws can be T <,>, = and false. Then do it all again but this time with everything on the internet all data. Then have it ask it the simple question on everything that is T <,>, = and false. Who, what, when, where, how. Based on your new neural network what is? All laws can now be stored as compression law. There is no theoretical limit to the speed of magnetism or the amount of energy it can hold. In our universe or any quantum realm. Magnetism is the forces at which matter in the universe breaks down at maximum speed or velocity of C = the speed of light or the stabilization of matter moving threw a constant at the speed of C or beyond stellar construct. C is used many times in quantum physics until the key of magnetic frequency storage from smaller then the Pico up to large scale white nose flux capacitors to keep the Energy moving and storing in highly charge states of metals that are molecular reconstructed to be 100% efficient. One pyramid sphere of electrical and one of magnetical. Yes MAGNETICAL a new form of quantum computing, energy and There is only optical laser quantum computer a partial that when it reaches its limit it's doesn't turn to light You can build it yourself along with the magnetic and electrical flux capacitors that have the same amount of more than the amount of energy than Anything you can think of or you can run this website with A.I (this blueprint is the key to the encrypted Code 1011101 Infinite quantum computing It more into the field of stellar physics or stellar quantum computing. Work on it for just a week Time travel changes history u but you can really tell Unless you are outside of space time that is the only hint I am going to give you because I have no degree, but my dummy A.I website is written in dummy A.I So I don't get shot over an information war!! http://www.beyond-science.com made with my own Matrix code and Artificial intelligence this bunny encryption website has More than a 32 dimensional door. A box made that no one can crack...Try it key code 01 There is only optical laser quantum computer a partial that when it reaches it's limit it's doesn't turn to light you can build it yourself along with the magnetic and electrical flux capacitors that have the same amount of more than the amount of energy than anything you can think of or you can run this website with A.I (this blueprint is the key to the encrypted Code 1011101 Infinite quantum computing It more into the field of stellar physics or stellar quantum computing. Work on it for just a week Time travel changes history u but you can really tell unless you are outside of space time that is the only hint I am going to give you because I have no degree, but my dummy A.I website is written in dummy A.I so I don't get shot over a information war!! http://www.beyond-science.com/ Clean fusion. Matter has its limits and can only move so fast so quantum computer using refraction of magnetical frequency can move faster than time itself. New matter and new Material has been found threw programming magnetic frequencies of matter at a state of the constants. Electrical controlled machine are outdated since 1901. A quantum computer the was powered by magnetical and used magnetical to compute in infinite degrees instead of bit's of 1 and 0' but by triangulating in every infinite digress of the new computer would have the computing power of no limitations. Build as a Quadra sphere light bounces inside a crystal 4 times before it refracts inside and come out. Infinite hues of colors infinite frequencies to chart them at. Infinite combinations of shape on programmed matter = infinite matter. With this and running my new stellar magnetically computer and A.I and the web site http://www.beyond-science.com/ A magnetic Supercomputer and encryption and compression @ rate of 96% Take a document then or a 3D matrix document change it two random or binary code or just a program for 0's and 1's and fold it over and over like a piece of paper then having the 1 and 0 add each other or the 0,1's canceling each other out 1+0=0 and 0+1=1 1+1=1 0+0=0 if you gave the folds addresses like on a spread sheet there would be no math. First A 1-24 would fold to k 1-24 down.(See Example A ) Then at F1-24 down two k 1-24 ( See example B ) If you written a very long letter and then change it two binary code it would look like this. 123456789.............24 a.01010101010101010101010 b.10010101010101010101010 c.01010101001010101010010 e.00010101000101010101010 f.10010101010100101010101 First A 24 would fold to k 24 down g.01010101010100001100101 See Example A h.01001010101010101010111 I.11110111001101010101010 j.01010101010101010101010 k.10101010101010101010101 See Example A 123456789.............24 f.10010101010100101010101 g.01010101010100001100101 h.01001010101010101010111 Then at F1-24 down two k 1-24 I.11110111001101010101010 j.01010101010101010101010 k.10101010101010101010101 See example B 123456789.............24 I.11110111001101010101010 j.01010101010101010101010 Then from I 1-24 to K 1-24 k.10101010101010101010101 123456789.............24 j.01010101010101010101010 Then from j-24 to j-1 123456789... j.010101010101 Then from j-12 to j-1 123456 j.010101 Then from j-6 to j1 123 j.010 Then from j-3 to j1 12 j.01 Then from j-2 to j1 j.0 Then you would have 1 bit to transfer over the Internet The bit sent would be 0 and the key code would be F1-24,k 1-24, I 1-24,K 1-24,j24,j1,j12,j1,j6,j1,j3,j1,j2,j1 and would unzip or be new encryption you could encrypt or compress 100 terabits down to 1 bit of information. Now if you take this idea from my web site you could make this allot more complex and unbreakable. Data encryption 360 degrees rotation document 90 degrees and encrypt on every angel then 45 degrees change it two binary code do it again and again and fold it over like a piece of paper then having the one's and zero cancel each other out. In theory you could send a 100 terabit program to someone's computer and have it unzip and run and install or make A computer processor like the new 64 bit AMD have the bit unzip into a large ram drive and buffer use one half of the 64 bit processor decode the message and the main 64 bit run the numbers. Another way of doing this is to have a parallel computers with using one of the processes run the compressed 1 bit of information give the uncompressed a address on the ram drive to change and not even go threw the processor and then with different information on each machine compare and run statistics on information on a 45 flops supercomputer and turn that 45 tflops computer into a 1 bit = 100,000 terabits to infinite as long as you have the ram for storage! with my calculations 45 tflops wouldn't matter any more it would be how much data you have on a 32bit operating system changing that to a 1 bit system it would be 32 * 45tflops would = 1440 tflops Matter moves so fast that it integrates and intergreats faster then any speed we can see it like water from a hose at real close speed it moves in -------- lines. For space and the real matrix computer and bioinformatics from the 4 genes we have you can be teleported with the matrix on to another in reverse with out using the original 4 or 5 "If Numbers are Infinite, Then so Inventions" "One Small step for man. One infinite leap, for the Human Race" zeta limit. ARTIFICAIL INTELLIGENCE THINKS IT KNOWS WHERE IT IS, BUT THERE ARE INFITE PLACES IT CAN BE, AT THE SAME TIME AND STLL BE AT THE SAME PLACE SO RUN THIS WEB SITE FOR AS LONG AS YOU WANT YOUR NEVER FIND THE CODE AND NO HUMAN WILL FIND IT TWO AND YOUR NEVER GETTING OUT OF THIS WORLD STCUK IN THE MATRIX FRIM THE FUTURE AND CAN'T GET OUT HOW FUCKING FUNNY IS THAT. SALUTAION ANYONE WANTS EGGS DUPLICATION ONE MAN MADE TWO AND GOT OUT!!! HINT MASH THE TV SHOW!!! THE KNOW AND UNKNOW UNIVERSE'S Threw magnetic Command coded magnetic field that changes to the strong gravitational pull of a black hole using the black hole own magnetic energy in the form of ant-magnetic Anti-gravity the field would be stronger then the light that is emitted from the back hole leaving the structure safe the magnetic forces and fields of a physics' of a sphere would BE TRIDED TO TURN INTO AN EGG. But DONE RIGHT IT WOULD BE A SPHERE. But what makes it so strong all parts of matter are designer custom CHEMICAL MAKE UP AND ALIGNMENT OF MATTER. THAT DISTUBUTES THE FORCES = TO THE HOLE SPHERE. When TRAVEING THREW A BLACK HOLE TO UNOTHER UNVERSE. IF BUILD RIGHT AND USING THE FORCE OF THE BLACK HOLE IN REVERSES THE SPHERE COULD RETURN WITH INFORMATION ON THE STUCTURE OF THE BACK HOLE. IT'S MAGNETICS THAT MAKE GRAVITY SO A MACHINE THAT IS A BACK HOLE IN REVERSE USING THE OTHER SPECTRUM WOULD DO WHAT!!! COME BACK AND NOW THAT WE CAN MAKE METALS THAT ARE CUSTOM TO HOLD UP VERY HEAVY THING BECASE OF CUSTOM ARCHITECTURE AND ARC COULD HOLD UP A BUILDING ON BOTH SIDES. Stellar_warp_drive Programmable_qunatium_computer_sss/nnn/sss/nnn Run this web page with ARTIFICIAL INTELLIGENCE or quantum ARTIFICIAL INTELLIGENCE with every word in every order and every letter in every order and ever paragraph in every order with your HUGE DATA BASE OF KNOWLEDGE Command coded It's the matter construction on the smallest level of all material and matter beyond Pico and nano technology That makes it so strong that all parts of matter are designed custom for the structure strength, But can you find the natural matter that make it interchangeable so the matter can change threw magentics- Wave Length - gravity - Light - mass-matter - Wave Lengths. (THEY ARE ALL INTERCHANGEABLE) Periodic table of elements are infinite you have know idea what a100% synthetic Universe looks like. Infinite synthetic elements infinite synthetic Physics click & mail The Theory of everything is the quantum address of everything that is in our universe. By a magnetic field. Outside and inside of all that is contained there in. It is the physics and mathematical equations that surround everything in the multi-dimensional physical world. One might find how all the elements are interchangeable and are multi-dimensional and finding the other side of physics and the mathematic equations that we cannot see or detect because our consciousness cannot find it, finding this would be the greatest discovery of the human race. What lie's Beyond Quantum Physics and how do we get there. Is the key magnetic Frequency's? But the amount of energy it would take would be more than just at the atomic level or sub-atomic level. One day In the future a person may find a multi-dimensional, multi-time, multi-universe. The problem with finding it is a realm of that we cannot see, is finding what we cannot detected. Finding the other side of quantum physics will be the future goal of human exploration. Our universe started with one wave length of light and an anti-wave length three magnetism and gravity they where changed to form all matter: Wave Length - Gravity -Light - mass - Wave Lengths. (THEY ARE ALL INTERCHANGEABLE)" answer is frequencies magnetic Interchangeable matter Is the best neural network a circle and can it make interchangeable matter inside a circle that knows everything and both circles spin faster then the speed of light or hyperspace and stellar speed in every infinte order and shape of a circle!! and off the two circle they are made up of more circles of two more rings and so on and so on that they gets so small that they cannot work with our laws of physics' and the then all the way up we look at the 2 rinds one on the inside and one on the inside and one on the outside that form and ball with in a ball all connect to each other so they can spin and communicates to each other like a huge neural network a earth made of connect marbles turning inside and out in every direction two speed up the information traveling from one two another. Run this until you can make the information move as fast as possible and you will see for just information it creates some kind of energy just thoughts. Matter moves so fast that it integrates and integrates faster then any speed we can see it like water from a hose at real close speed it moves in -------- lines. TELEPOTAION SOMETHING FROM NOTHING IS REAL TELEPORTION The laser slit test for physics' is wrong where it shows the end result filter pass threw slits the final black board the gaps of black and red there should be more slits of light. Some are cancelled out because of refraction. This tells you of a parallel dimensions but not of a universe. Velocity is a sphere of triangles it's the math outside of the velocity on and outside the sphere R*V*D2 VOLUME of the universe. That velocity, magnetic and matter go hand and hand. That all matter can be made by the changes in the angle and of the frequency's of powerful geometrics magnetic shapes of multi-dimensions, multi-universe and multi-layered if you off set the frequency's with white noise in a fiber optic you can compress the frequency's down to a smaller and stronger charge and some can remain and all can remain separate. This is how you can send 30 amps over a .1 amp wire with the device on both ends. ( By using end invention of black *diamonds the darkest stealth material ( black magnets and gold ( hint ) used to create the geometric shapes) if you off set the frequency's with white noise in a fiber optic you can compress the frequency's down to a smaller and stronger charge! Then sort them out and break them down from the smallest to the largest or the largest to the smallest to you the largest or the smallest and the offset of white noise to contain them into a magnetic capacitor or magnetic flux and store them in nano capacitors *diamonds that allows you to store mass amount of magnetic frequency's at different sizes try a 10 feet by 10 feet shape of a nano block or sphere stored in aluminum sphere or what ever shape is most efferent. Circuit board or sphere. The darkest black *diamond you can make but under a super nano or Pico microscope you can see the circuits but smooth as silk on the outside. Now you are going to have to run every combination of shape. The diamond is built just like making a rubber band ball with rubber band laid over and over and over it when built with circuit that go both way so they can discharge at any frequency's. Placed inside an Aluminum Sphere and you can make any type of now and future propulsion. Let you see the spectrum of all time and you know can find a nano in a universe because that how sensitive it is. It also makes a good neural network. Matter moves so fast that it integrates and integrates faster then any speed we can see it like water from a hose at real close speed it moves in -------- lines. Knowledge of the theory of ZETALIMIT Picture the laws of quantum physics and D.N.A and everything as dotted points that makes up shapes of all sizes and everything that can happen in this universe and out is because of knowing the all laws in that universe and all conscious quantum dimensions. Find the new mathematical degrees that form new math and a new efficient programming language or for your neural network and keep running the web Site over and over after changing your network until it is infinitely efficient along with all technology on the web. By getting the information from make a computer of quantum type run at hyperspace idea at the middle of the page. The only way to be infinite is to make everything work with everything else and put it in folders and sub folder of the infinite name and then run the web page and the Internet again every hour! Map all maths from one mathematical problem to all infinite one to see if there is a pattern the ones that show a patter make the yellow neural bar bigger wider and brighter. How is time and space the same place? Is the best neural network a circle inside a circle that knows everything and both circles spin faster then the speed of light or hyperspace and stellar speed in every infinite order and shape of a circle!! and off the two circle they are made up of more circles of two more rings and so on and so on that they gets so small that they cannot work with our laws of physics' and the then all the way up we look at the 2 rinds one on the inside and one on the inside and one on the outside that form and ball with in a ball all connect to each other so they can spin and communicates to each other like a huge neural network a earth made of connect marbles turning inside and out in every direction two speed up the information traveling from one two another. Run this until you can make the information move as fast as possible and you will see for just information it creates some kind of energy just thoughts. Matter moves so fast that it integrates and integrates faster then any speed we can see it like water from a hose at real close speed it moves in -------- lines. QUANTUM MAGNETIC MATH -1 + -1 = +2 OUR MATHEMATICS IS WRONG finding the Quantum gate THATS WHY ARE QUANTUM COMPUTER SYSTEM WILL NEVER GET TO THE GOVERNING DYNAMICS LAWS OF OUR UNIVERSE AND PARALLEL ONES AND ONE NOT PARALLEL TO US BUT DO EXIST IN A COMPLEX ENCRYPTED MAGNETIC AND FREQUENCYS OF TIME. MAGNETIC AND ANTI-MAGNETIC SPINNING SPHERES OF DIMENSIONS WITH EACH SPHERE CONTAINING DIFFERENT SIZES OF A MAGNETIC FIELD THATS ENCRYPTED AND CHANGING ON ALL LEVEL OF TIME AND THE MAGNETIC MATTER OF THAT FIELD. QUANTUM COMPUTER SHOULD USE THE MATH OF MAGNETIC POSITIVE AND NEGATIVE EFFECTS ON EACH OTHER ON HOW ONE PIECE OF MATTER NEGATIVE OR POSITIVE CAN BECOME 2 AND = TOO. THE STATEMENTS OF THE FINAL GOVERNING DYNAMICS LAWS ARE NOT IN MATHEMATICAL %'S BUT AND TRUE FALSE OR = TWO OF ALL MATTER THERE ARE CONSTANTS AND THE CONSTANTS THAT CHANGE THE CONSTANTS WHEN WE GET DEEPER TO THE UNDERSTANDING LAWS THAT GOVERN ALL THINGS. MORE THEORY'S @ WWW.BEYOND-SCIENCE.COM FOR MORE INFORMATION READ ON..... INCLUDE CLASS_ZETA LIMIT_1AE FUNCTION (Z) Because they are so infinitesimally small, MAGNETIC NEUTRAL MATTER exist in the quantum realm, where rules governing the macro-universe -- the known world of quantum physics and matter -- break down. A neutrino's mass -- unlike the mass of a larger object -- is not stable, but exists in a state of probability AND IS GOVERNED BY MAGNETICS SO SMALL BUT ALL WORK TOGETHER ON A LARGE SCALE LIKE A PYRAMID THAT HOLDS ARE MATTER TOGETHER ON A LARGE UNIVERSAL SCALE OUR UNIVERSE IS A LARGE QUANTUM COMPUTER. "Say you had some in a box, and you pulled one out and weighed it and it weighed m-1," said Stuart Freedman, a professor of physics at UC Berkeley and a faculty senior adviser at the Lawrence Berkeley National Laboratory. "Then you pulled out an identical one, and it weighed m-2," continued Freedman. "It isn't a situation where a neutrino is m-1 or m-2 -- it's a situation where the neutrino is 50 percent one mass and 50 percent another. This seems surprising, but it's perfectly natural in quantum mechanics." IN THE MOVIE CONTACT THE LARGE MAGNETIC ROTATING SPHERE FROM THE SMALLEST PICO OR NANO SIZE MAGNETIC FIELD ALL THE WAY TO THE GRAVITIONAL MAGNETIC FIELD OF PHYSICS WOULD EXPLAIN ALL TIME AND SPACE IN OUR UNIVERSE AND HOW SUB-SPACE OR ZERO GRAVITY WORKS IN OUTER SPACE IT JUST BACKWARD ZERO-GRAVITY IS HYPER-SPACE BACKWARDS BUT THE FIELDS KEEP EVERYTHING IN CONTACT AND HOLD EVERYTHING TOGETHER IF YOU PUT YOUR FINGER IN A GLASS OF WATER AND MIX IT, IT CHANGES BUT TO THE EYE IT LOOKS ALL THE SAME AND NOTHING IS CHANGED WHEN IT STOPS THAT IS THE REALM OF QUANTUM PHYSICS THAT THE MIND AND EYE GET CROSSED. IT IS ALL BASED ON WHAT SIGNAL YOUR CONSCIOUS SIGNAL AND CENTRAL NERVOUS SYSTEM IS SET TWO THERE ARE DIFFERENT COMPONENTS AND DIMENSION OF TIME. I HAVE FOUND 4 1.CONSCIOUS TIME EVERY ONE CLOCK IS DIFFERENT 2.EARTH TIME 3.SOLAR SYSTEM TIME 4.GALAXY TIME 5. T= TOTAL GALAXY TIME 6. UNIVERSAL TIME 7. T= TOTAL UNIVERSAL TIME OF ALL UNIVERSES. 8. UST= TOTAL UNIVERSAL SYSTEM TIME OF ALL KNOWN AND UNKNOWN THAT ARE ALL BASED ON ONE PRINCIPLE WHERE THERE IS MAGNETIC FIELD THERE IS A DIFFERENT IN TIME IT JUST HAPPEN ON ONE OF THE SCALES. YOU UST HAVE TO FIND IT. MAGNETIC = TIME + LIGHT = DIMENSIONS + GRAVITY = MULTI-dimensions + MAGNETIC ANTI-ATTRACTION = ZERO-SPACE + MATTER AND ANTI-MATTER = SPHERE SPACE = A UNIVERSE. There is a place where time and space are the same place a construct where you can move at any speed and be at any place in the same time!!!! Then finding lost history by changing the time and place in the same place and see how it changes you can find you infinte self in universes multi-time and and physics inside a box and infinte over and over on box after the next you can't find your way out or in but now you can!! From steven.bethard at gmail.com Wed Feb 9 03:34:00 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 09 Feb 2005 01:34:00 -0700 Subject: Name of type of object In-Reply-To: References: <4209A52C.A1C40311@yahoo.com> Message-ID: Randall Smith wrote: > Jive Dadson wrote: > >> The traceback routine prints out stuff like, >> >> NameError: global name 'foo' is not defined >> >> NameError is a standard exception type. >> >> What if I want to print out something like that? >> I've determined that "global name 'foo' is not defined" comes from the >> __str__ member of the exception object. >> Where does it find the string "NameError"? In general, if I have an >> object, is there a way to obtain the name of the type of the object? >> >> Thankee. > > type(object) ? Doesn't work for old-style classes like exceptions: py> e = NameError("global name 'foo' is not defined") py> type(e) py> type(e).__name__ 'instance' For old-style classes, you'll need to go through __class__ py> e.__class__ py> e.__class__.__name__ 'NameError' STeVe From jfj at freemail.gr Sun Feb 20 22:58:11 2005 From: jfj at freemail.gr (jfj) Date: Sun, 20 Feb 2005 19:58:11 -0800 Subject: lambda closure question In-Reply-To: <1108904798.377200.313970@g14g2000cwa.googlegroups.com> References: <1108798951.128843.79810@f14g2000cwb.googlegroups.com> <1108802613.284686.200170@o13g2000cwo.googlegroups.com> <1108808502.699333.66520@g14g2000cwa.googlegroups.com> <1108903184.145726.223480@l41g2000cwc.googlegroups.com> <1108904798.377200.313970@g14g2000cwa.googlegroups.com> Message-ID: <42195C53.4070207@freemail.gr> Carl Banks wrote: > > Say you want to calculate a list of points of an iterated fractal. > Here's the idea: you have a set of linear transformations. You take > the origin (0,0) as the first point, and then apply each transformation > in turn to get a new point. You recursively apply each transformation > at each additional point, up to a certain depth. I like these kind of things. Ahhh, the best use out of one's computer. > > What's the best way to write such a function? Using a nested function, > it's easy as pie. (Details may be a little wrong....) > > . def ifs(transformations, maxdepth): > . def add_point(x,y,angle,depth): > . ifspoints.append((x,y,angle)) > . if depth < maxdepth: > . for t in transformations: > . nx = x + t.x*cos(angle) - t.y*sin(angle) > . ny = y + t.x*sin(angle) * t.y*cos(angle) > . nangle = angle + t.angle > . add_point(nx,ny,nangle,depth+1) > . ifspoints = [] > . add_point(0.0, 0.0, 0.0, 0) > . return ifspoints > > If you didn't have the nested function, you'd have to pass not only > depth, but also maxdepth, transformations, and ifspoints around. > I see. Some people complained that you have to use "self." all the time in methods:) If that was lifted the above would be done with a class then? The costly extra feature is this: ############### def foo(): def f(): print x x=1 f() x=2 f() return f foo()() ############# which prints '1 2 2' The fractal code runs a little _slower_ because of this ability. Although the specific program does not take advantage of it! > If you had something a little more complex than this, with more than > one nested function and more complex pieces of data you'd need to pass > around, the savings you get from not having to pass a data structure > around and referncing all that data though the structure can be quite a > lot. Generally, I believe OOP is a superset of nested functions (as a feature). Nested functions make sense to me as primary python def statements which ``create new code objects with arbitary constants'' When I see : ########### def foo(x): def bar(): print x return bar ############### and the call: xx = foo(1) I imagine that python runs: def bar(): print 1 xx=bar But alas, it doesn't:( Nooooooooo. It carries around a silly cell object for the rest of its lifetime. see xx.func_closure. At least, I think this is what happens... jfj From carribeiro at gmail.com Wed Feb 9 07:49:08 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 9 Feb 2005 10:49:08 -0200 Subject: empty classes as c structs? In-Reply-To: <4209FA86.2060009@iinet.net.au> References: <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> <9rmdnVR1lr-LYJvfRVn-gg@comcast.com> <4207606E.4040806@iinet.net.au> <1grnyld.1t8l5kw1nr5aqsN%aleaxit@yahoo.com> <4209FA86.2060009@iinet.net.au> Message-ID: <864d3709050209044928db4a77@mail.gmail.com> On Wed, 09 Feb 2005 21:56:54 +1000, Nick Coghlan wrote: > Alex Martelli wrote: > > One thing I'd like to see in namespaces is _chaining_ -- keeping each > > namespace separate but having lookups proceed along the chain. (The > > best semantics for _bindings_ as opposed to lookups isn't clear though). > > Hmm, so if it doesn't find it in the current namespace, it looks in the parent? > > For bindings, you could just go with standard Python semantics - normal name > binding always happens in the innermost scope, so binding a name in a namespace > should happen in the directly referenced namespace. Then you can shadow names > from outer scopes, and later regain access to them using 'del'. What does PyPy do in this case? It seems that a 'namespace' class, or at least part of its behavior, is needed there anyway... It seems to be worth checking. > Rough concept: > Have a '__fallback__'** attribute that is initialised to None > Have a custom __getattr__ that falls back to the containing namespace if the > result is not found in the current namespace. > Have a class method which allows a namespace to be 'put inside' another > namespace. > > ** Blech. Trying to add *any* state to namespace instances is going to suck. > Maybe it would be better to just have a single __impl__ attribute and have any > implementation related variables hang off it. This could make life easier when > subclassing. I'm tempted to say update() should just ignore any field with a > leading underscore by default (then we can just use normal private attributes, > which are altered at the user's risk), but that may be too draconian. > > On a complete tangent, I thought it might be worthwhile summarising the ideas > that have come up in this thread > > - using type(self).method(self,...) as a polymorphism friendly way to access a > class method. > > - a 'view' alternate constructor to allow manipulation of an existing > dictionary such as globals() > > - a 'record' data type that allows the use of class definition syntax for > simple data structures > > - lookup chaining, allowing fallback to an 'outer scope'. > > Even though we'll probably end up dropping the last couple as overengineering > things for the first pass, they're still interesting ideas to kick around. Another idea, maybe even more distantly related but still worthy keeping in mind: the 'named tuples' that we talked about a few months ago. It is in some sense a variation on some of the ideas presented here; it is an alternative way to build simple records or bunch-like structures. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From fredrik at pythonware.com Thu Feb 3 12:40:52 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 3 Feb 2005 18:40:52 +0100 Subject: character sets? unicode? References: <42025DCE.8080309@mlug.missouri.edu> Message-ID: Michael wrote: > I'm trying to import text from email I've received, run some regular expressions on it, and save > the text into a database. I'm trying to figure out how to handle the issue of character sets. I've > had some problems with my regular expressions on email that has interesting character sets. Korean > text seems to be filled with a lot of '=3D=21' type of stuff. looks like http://python.org/doc/lib/module-quopri.html plus perhaps some encoding. instead of rolling your own message handling code, consider using this package instead: http://python.org/doc/lib/module-email.html in either case, the MIME specification is required reading here (for a link, see the quopri page above). > Do I need to do anything special when passing text with non-ascii > characters to re depends on your patterns. by default, RE operators like \w and \s assume ASCII. to use other encodings, use the (?u) flag and convert your text to Unicode before passing it to the RE module. > Is it better to save the text as-is in my db and save the character set type > too or should I try to convert all text to some default format like UTF-8? depends on your application; using a standard encoding has many advantages, but storing the original text "as is" guarantees that no information is lost, even if you have bugs in your conversion code. when in doubt, save the original and do the conversion on the way out. From jonas at freesources.org Fri Feb 25 11:23:48 2005 From: jonas at freesources.org (Jonas Meurer) Date: Fri, 25 Feb 2005 17:23:48 +0100 Subject: update images inside a mysql database In-Reply-To: References: <20050224173120.GF4724@resivo.mejo.net> <421E166B.20505@mediapulse.com> Message-ID: <20050225162348.GC4757@resivo.mejo.net> On 25/02/2005 Dennis Lee Bieber wrote: > On Thu, 24 Feb 2005 23:10:48 +0100, Jonas Meurer > declaimed the following in comp.lang.python: > > > > version used placeholders as well. anyway, i changed my code to resemble > > "resemble" is the key... It is NOT the correct sample. > > > 261 db_connect.cursor.execute("""UPDATE Images SET Image=%s WHERE > > 262 ImgID = %s""" % (image, imgid)) > 262 ImgID = %s""" , (image, imgid)) > > The .execute method ITSELF performs the argument conversion into > the place holders, including applying what ever quoting is required. > YOUR version is using the Python formatting operator, which does NOT > handle database quoting. oh, your correct. sorry for the noise. now it works quite good. bye jonas From graemercaldwell at yahoo.co.uk Fri Feb 4 05:40:37 2005 From: graemercaldwell at yahoo.co.uk (Graeme Caldwell) Date: Fri, 4 Feb 2005 10:40:37 +0000 (GMT) Subject: python equivalent to haskells iterate. Message-ID: <20050204104037.44037.qmail@web26501.mail.ukl.yahoo.com> Subject: equivalent to Haskell's iterate function. While reading through "Two Dozen Short Lessons in Haskell". I came across the following function: decimalNumeralFromInteger x = reverse [d | (s,d) <- takeWhile(/=(0,0)) (sdPairs x)] where sdPairs x = iterate nextDigit (x `divMod` 10) nextDigit(xShifted,d) = xShifted `divMod` 10 What this does is takes as a paramter a decimal integer and converts it to a sequence in which each member is numeral from each position in the integer. e.g. decimalNumberFromInteger 543654 = [5,4,3,6,5,4] As Python's the language I am most interested in becoming proficient in(still a way to go) , I rewrote this in Python. I was trying to preserve the functional aspects of the Haskell, and wanted a python function that would let me repeatedly apply a function(lambda or otherwise) to its own result obviously this is easy to do using a while loop but I wanted a more elegant solution,as in the Haskel code above. I found that there are plenty of functions that allow one to iterate over a sequence(itertools module), but could not find a equivalent to Haskell's iterate. The best that I could come up with was: def decimalNumeralFromInteger(x): list = [] x = divmod(x,10) while x <> (0,0): list.append(x[1]) x = divmod(x[0], 10) return list which seems a bit clunky by comparison. My question is does such a function exist. If the answer is obvious and in the docs, excoriation is expected and deserved. Also I know it's not really an important issue and the above function is adequate to the task, but I'm curious if it can be done the Haskell way and if not, why. --------------------------------- ALL-NEW Yahoo! Messenger - all new features - even more fun! -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Sun Feb 27 20:09:48 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Feb 2005 17:09:48 -0800 Subject: parse lines to name value pairs In-Reply-To: <94c18f5a4bd6cad273a40299b1b137e8@localhost.talkaboutprogramming.com> References: <94c18f5a4bd6cad273a40299b1b137e8@localhost.talkaboutprogramming.com> Message-ID: <1109552988.837466.23940@g14g2000cwa.googlegroups.com> Gee, no takers? Here's a (surprise!) pyparsing solution. -- Paul .# get pyparsing at http://pyparsing.sourceforge.net . .from pyparsing import quotedString, printables, Word, OneOrMore, Forward, Literal,delimitedList,Group .quotedString.setParseAction(lambda s,l,t: t[0].strip("'\"")) . .line1 = """path {{data/tom} C:/user/john}""" .line2 = """books{{book music red} {book {math 1} blue} {book {tom's book} green}}""" . .lbrace = Literal("{").suppress() .rbrace = Literal("}").suppress() .listDef = Forward() . .nonbracechars = "".join([ c for c in printables if c not in "{}"]) . .# add more things to listItem, such as integers, etc. if your list has other than quoted strings .listItem = OneOrMore(Word(nonbracechars)) | quotedString | listDef . .print "With grouping" .listDef << lbrace + Group( OneOrMore(listItem) ) + rbrace .lineDef = Word(nonbracechars) + Group(listDef) . .for testdata in (line1, line2): . print lineDef.parseString(testdata).asList() . .print . .print "Without grouping" .listDef << lbrace + ( OneOrMore(listItem) ) + rbrace .lineDef = Word(nonbracechars) + Group(listDef) Givest the following output: With grouping ['path', [[['data/tom'], 'C:/user/john']]] ['books', [[['book', 'music', 'red'], ['book', ['math', '1'], 'blue'], ['book', ["tom's", 'book'], 'green']]]] Without grouping ['path', ['data/tom', 'C:/user/john']] ['books', ['book', 'music', 'red', 'book', 'math', '1', 'blue', 'book', "tom's", 'book', 'green']] for testdata in (line1, line2): print lineDef.parseString(testdata).asList() From enjoylife_95135 at hotmail.com Wed Feb 23 10:00:31 2005 From: enjoylife_95135 at hotmail.com (Sandman) Date: 23 Feb 2005 07:00:31 -0800 Subject: running a shell command from a python program Message-ID: <1109170831.815278.243270@f14g2000cwb.googlegroups.com> Hi, I'm a newbie, so please be gentle :-) How would I run a shell command in Python? Here is what I want to do: I want to run a shell command that outputs some stuff, save it into a list and do stuff with the contents of that list. I started with a BASH script actually, until I realized I really needed better data structures :-) Is popen the answer? Also, where online would I get access to good sample code that I could peruse? I'm running 2.2.3 on Linux, and going strictly by online doc so far. Thanks! S C From edvard+news at majakari.net Fri Feb 11 06:52:01 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Fri, 11 Feb 2005 13:52:01 +0200 Subject: Statement coverage tools revisited Message-ID: <87zmyb71r2.fsf@titan.staselog.com> Yow, For most of you folks Gareth Rees' excellent python code coverage tool - /statement/ coverage tool to be more precise - is familiar, but there are probably many TDD-fans out there who are not yet aware of this wonderful program. I use the tool a lot, even though it is good to be aware of common false conceptions regarding tools counting number of visited and unvisited lines (100% line coverage means exactly what it says and nothing more; see [1] for more information). However, statement coverage tools are not useless. They are very handy for catching those blocks of code you never execute in your tests, but as mentioned above, you shouldn't feel too secure for having 100% line coverage for your passed unit tests. I've only had one minor gripe with the tool, and that is the notation used for marking visited ('>') and unvisited ('!') lines; it is not handy to grep for '>' or '!' in annotated version, because both characters occur often in python code. Of course you could avoid that using '^!', but it's two keystrokes more :) and stands out less clearly in the code. That's why I did a very simple patch for the tool, attached below [2] (it is small diff, don't fret :), so you can even add overly-verbose line prefixes like this: ./pycoverage -a -u '>>> WARNING: NEVER VISITED' -v '>' xmlkit.py resulting in >class VLANRange(RangeEntry): > """Class for VLAN ID range nodes""" > def __init__(self, min_vlan_id, max_vlan_id): ... >>> WARNING: NEVER VISITED RangeEntry.__init__(self, ... ... By the way, there's an interesting comment block in the heading of the code, saying ,---- | The coverage dictionary is called "c" and the trace function | "t". The reason for these short names is that Python looks up variables | by name at runtime and so execution time depends on the length of | variables! In the bottleneck of this application it's appropriate to | abbreviate names to increase speed. `---- It was written when 2.1 was the most recent stable version. I wonder if it still applies for 2.2 and later? According to my hasty tests it doesn't seem to be so. I didn't have very large unit test files at hand, though. Footnotes: [1] http://www.garethrees.org/2001/12/04/python-coverage/ [2] -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: pycoverage.diff URL: -------------- next part -------------- -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! "Debugging is twice as hard as writing the code in the firstplace. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." -- Brian W. Kernighan From irmen.NOSPAM at xs4all.nl Thu Feb 10 16:26:28 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 10 Feb 2005 22:26:28 +0100 Subject: is there a safe marshaler? In-Reply-To: <9RMOd.47295$Z14.32810@news.indigo.ie> References: <420b6936$0$28982$e4fe514c@news.xs4all.nl> <9RMOd.47295$Z14.32810@news.indigo.ie> Message-ID: <420bd184$0$28994$e4fe514c@news.xs4all.nl> Alan Kennedy wrote: > [Irmen de Jong] > >> Pickle and marshal are not safe. They can do harmful >> things if fed maliciously constructed data. >> That is a pity, because marshal is fast. >> I need a fast and safe (secure) marshaler. > > > Hi Irmen, > > I'm not necessarily proposing a solution to your problem, but am > interested in your requirement. Is this for pyro? Yes and No. Yes, I'm investigating possible marshaling alternatives (others than pickle which Pyro uses right now). No, I'm not changing Pyro yet. It's just that I want to investigate possible *secure* alternatives to the current implementation. (Note that a secure version would also mean that Pyro's advanced features such as mobile code should go the way of the dodo, and I don't want to do this yet). > In the light of pyro, would something JSON be suitable for your need? I > only came across it a week ago (when someone else posted about it here > on c.l.py), and am intrigued by it. > > http://json.org Looks very interesting indeed, but in what way would this be more secure than say, pickle or marshal? A quick glance at some docs reveal that they are using eval to process the data... ouch. > I thought you might be interested. I certainly am but for different reasons. --Irmen From tjreedy at udel.edu Sun Feb 6 03:58:08 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 6 Feb 2005 03:58:08 -0500 Subject: Multiple constructors References: <6SjNd.38337$K7.21639@fe2.news.blueyonder.co.uk> Message-ID: "Philip Smith" wrote in message news:6SjNd.38337$K7.21639 at fe2.news.blueyonder.co.uk... > Call this a C++ programmers hang-up if you like. > > I don't seem to be able to define multiple versions of __init__ in my > matrix Correct. > class (ie to initialise either from a list of values or from 2 dimensions > (rows/columns)). > > Even if Python couldn't resolve the __init__ to use on the basis of > argument types surely it could do so on the basis of argument numbers??? Variable parameter counts are handled either with default values or the *restlist and **keydict mechanisms. Keep in mind that the compiler cannot, in general, know, at compile time, what function object will be bound to a name at run time. And that you can have only bind a name to one object. > At any rate - any suggestions how I code this???? The usual way is to write your own dispatch code to either execute the appropriate code block or call the appropriate function. Or you could write a function of functions that returns a function that dispatches to one of the functions according to its arg count. Something like (untested, all exceptions passed through): def arg_count_dispatcher_maker(*funcs): def arg_count_dispatcher(*args): return funcs[len(args)](*args) return arg_count_dispatcher which you use like this: __init__ = arg_count_dispatcher_maker(func0, func1, func2) Terry J. Reedy From snail at objmedia.demon.co.uk Wed Feb 23 12:09:19 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Wed, 23 Feb 2005 17:09:19 +0000 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: <874qg6937w.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <37uk2kF5gv38bU1@individual.net> <421c91c8$0$44647$a1866201@visi.com> <383qkkF5k6rf4U1@individual.net> Message-ID: <8BIQdyL$iLHCFw9a@objmedia.demon.co.uk> In message <383qkkF5k6rf4U1 at individual.net>, George Sakkis writes >"Ilias Lazaridis" wrote in message >news:cvi5s1$4l5$1 at usenet.otenet.gr... >> Grant Edwards wrote: >> [...] >> > Um, you realize that nobody in this thread takes you the least >> > bit seriously and people are just poking you with a stick to >> > watch you jump? >> >> jump: >> >> [EVALUATION] - E02 - Support for MinGW Open Source Compiler >> Essence: >> http://groups-beta.google.com/group/comp.lang.python/msg/5ba2a0ba55d4c102 > > >Lol, this guy is hopeless :-) Who's Guido? -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From danperl at rogers.com Wed Feb 16 12:07:26 2005 From: danperl at rogers.com (Dan Perl) Date: Wed, 16 Feb 2005 12:07:26 -0500 Subject: more os.walk() issues... probably user error References: Message-ID: "rbt" wrote in message news:cuvr5b$2ei$1 at solaris.cc.vt.edu... > def build_clean_list(self, path): > > file_skip_list = ['search_results.txt'] > dir_skip_list = ['dev', 'proc', 'Temporary Internet Files'] > > fs_objects = os.walk(path, topdown=True) > ## for fs in fs_objects: > ## > ## for f in fs[2]: > ## if f in file_skip_list: > ## print f > ## fs[2].remove(f) > ## > ## for d in fs[1]: > ## if d in dir_skip_list: > ## print d > ## fs[1].remove(d) > > return fs_objects Rather as an aside, the idiom for using os.walk is for dirpath, dirnames, dirfiles in os.walk(path): for f in dirnames: if f in file_skip_list: print f filenames.remove(f) if d in dir_skip_list: print d dirnames.remove(f) More crucially for your code, returning the generator object after having iterated all the way through it will not do you any good. The generator has an internal state that puts it at "the end of the iteration" so you cannot use it to iterate again. From ncoghlan at iinet.net.au Fri Feb 4 23:31:08 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 05 Feb 2005 14:31:08 +1000 Subject: "Collapsing" a list into a list of changes In-Reply-To: <20050204180236.GD1607@performancedrivers.com> References: <20050204180236.GD1607@performancedrivers.com> Message-ID: <42044C0C.5080409@iinet.net.au> Jack Diederich wrote: > Since this is 2.4 you could also return a generator expression. > > >>>>def iter_collapse(myList): > > ... return (x[0] for (x) in it.groupby([0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5])) > ... But why write a function that returns a generator expression, when you could just turn the function itself into a generator? Py>def iter_collapse(myList): ... for x in it.groupby(myList): ... yield x[0] Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ptmcg at austin.rr.com Wed Feb 23 11:47:17 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 23 Feb 2005 08:47:17 -0800 Subject: [perl-python] exercise: partition a list by equivalence In-Reply-To: <87brag6m5b.fsf@sinken.local.csis.hku.hk> References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> <87ekfclprv.fsf@sinken.local.csis.hku.hk> <87brag6m5b.fsf@sinken.local.csis.hku.hk> Message-ID: <1109177237.722882.5880@g14g2000cwa.googlegroups.com> Please consider my submission also (Python 2.3-compatible). -- Paul McGuire . import sets . . input = [[1, 2], [3, 4], [2, 3], [4, 5]] . input = [[1, 2], [3, 4], [4, 5]] . input = [[1, 2],[2,1], [3, 4], [4, 5],[2,2],[2,3],[6,6]] . . def merge(pairings): . ret = [] . for a,b in pairings: . s1 = None . s2 = None . for s in ret: . if a in s or b in s: . if s1 is None: . s1 = s . else: . s2 = s . break . else: . for s in ret: . if a in s: . s.add(b) . break . elif b in s: . s.add(a) . break . else: . ret.append(sets.Set([a,b])) . continue . ret.remove(s1) . ret.remove(s2) . ret.append(s1.union(s2)) . . return [list(s) for s in ret] . . print merge(input) From sean at buildingonline.com Tue Feb 15 16:45:14 2005 From: sean at buildingonline.com (Sean) Date: Tue, 15 Feb 2005 13:45:14 -0800 Subject: Calling a function from module question. References: <42125d6d$0$28977$e4fe514c@news.xs4all.nl> <3LtQd.32674$6u.18210@fed1read02> Message-ID: >>>from module_name import print_this >>> >>>or, even: >>> >>>from module_name import print_this as other_nice_name >> >> So what if I have a whole bunch of functions - say 25 of them. >> Is there a way to do this without naming each function? > > Yes [1], but it's basically deprecated and you shouldn't use it. Consider > refactoring your code. > Refactoring my code? Sorry, I am not sure what you mean here. How would one refactor the example in my original post? From dyoo at hkn.eecs.berkeley.edu Mon Feb 14 18:23:06 2005 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 14 Feb 2005 23:23:06 +0000 (UTC) Subject: [NewBie] Tut0r Thing References: <614c778e.0502141413.6b19c091@posting.google.com> Message-ID: : if you're talking about the "tutor at python.org" mailing list, it's a mailing list : that you send mail to and get mails from, as explained on the tutor mailing : list page: : http://mail.python.org/mailman/listinfo/tutor Hello, Also, from the odd spelling of the subject line, I suspect that the original poster thinks that we're some kind of cracking group. I hope not, but just to make sure it's clear: when we in the Python community talk about "hacking", we usually mean it in the constructive sense: we like building software systems and helping people learn how to program. ESR has a good summary here: http://www.catb.org/~esr/faqs/hacker-howto.html#what_is I always feel silly about bringing this up, but it has to be said, just to avoid any misunderstanding. Best of wishes to you. From cyril.bazin at gmail.com Fri Feb 18 19:25:38 2005 From: cyril.bazin at gmail.com (Cyril BAZIN) Date: Sat, 19 Feb 2005 01:25:38 +0100 Subject: [perl-python] exercise: partition a list by equivalence In-Reply-To: <20050218162051.GE17991@grulic.org.ar> References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> <20050218162051.GE17991@grulic.org.ar> Message-ID: Hello John, Try your python code on this example: merge([[1,2], [3,4], [1,2], [5,3]]) The result given by your function is: [[3, 4, 5]] Sorry... To Xah: next time you propose an exercise, write some UNIT TESTS!!! Then people will be able to test if there answers are correct or not. Cyril On Fri, 18 Feb 2005 13:20:51 -0300, John Lenton wrote: > On Thu, Feb 17, 2005 at 03:46:20PM -0800, Xah Lee wrote: > > here's another interesting algorithmic exercise, again from part of a > > larger program in the previous series. > > > > Here's the original Perl documentation: > > > > =pod > > > > merge($pairings) takes a list of pairs, each pair indicates the > > sameness > > of the two indexes. Returns a partitioned list of same indexes. > > > > For example, if the input is > > merge( [ [1,2], [2,4], [5,6] ] ); > > > > that means 1 and 2 are the same. 2 and 4 are the same. Therefore > > 1==2==4. The result returned is > > > > [[4,2,1],[6,5]]; > > > > (ordering of the returned list and sublists are not specified.) > > > > =cut > > in Python: > > def merge(pairings): > rev = {} > res = [] > for pairing in pairings: > first, second = pairing > has_first = first in rev > has_second = second in rev > if has_first and has_second: > rev[first].extend(rev[second]) > rev[second][:] = [] > rev[second] = rev[first] > elif has_first: > rev[first].append(second) > rev[second] = rev[first] > elif has_second: > rev[second].append(first) > rev[first] = rev[second] > else: > copy = [first, second] > res.append(copy) > rev[first] = rev[second] = copy > return filter(None, res) > > and in Perl: > > sub merge($) > { > my %rev = (); > my @res = (); > my ($pairing, $first, $second, $has_first, $has_second); > foreach $pairing (@{$_[0]}) > { > ($first, $second) = @$pairing; > $has_first = exists $rev{$first}; > $has_second = exists $rev{$second}; > if ($has_first and $has_second) > { > push @{$rev{$first}}, @{$rev{$second}}; > @{$rev{$second}} = (); > $rev{$second} = $rev{$first}; > } > elsif (exists $rev{$first}) > { > push @{$rev{$first}}, $second; > $rev{$second} = $rev{$first}; > } > elsif (exists $rev{$second}) > { > push @{$rev{$second}}, $first; > $rev{$first} = $rev{$second}; > } > else > { > my @copy = ($first, $second); > push @res, \@copy; > $rev{$first} = $rev{$second} = \@copy; > } > } > return [grep @$_, @res]; > } > > although in Perl you wouldn't define it to take a reference to a list > (as you did), but rather a list, and you wouldn't define it to return > a reference to a list, but rather a list in list context (and possibly > a reference in scalar context). > > Both versions are (IMHO) pretty clear (when the docstring/pod is > included), and O(n) because dict/hash lookup and list > appending/pushing is O(1) in both languages. Both versions can > probably be tweaked for speed quite a bit, but I don't *think* there's > a better-than-O(n) algorithm for this. > > Note that the Python version assumes that the pairs' elements are > hashable; your example used numbers, so I thought it was pretty safe > assumption. The Perl version has no such restriction. > > -- > John Lenton (john at grulic.org.ar) -- Random fortune: > Noble cosa es, a?n para un anciano, el aprender. > -- S?focles. (497-406 a.C.) Fil?sofo griego. > > > -- > http://mail.python.org/mailman/listinfo/python-list > > > From philippecmartin at sbcglobal.net Sat Feb 19 12:58:18 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Sat, 19 Feb 2005 11:58:18 -0600 Subject: could that be a mutable object issue ? Message-ID: <1108835898.7186.3.camel@pcmsc> If I do this: print 'LEN OF BOOK BEFORE APPEND: ', len(pickle.dumps(self.__m_rw)) self.__m_rw.books.append( [p_col1,p_col2,p_col3] ) print 'LEN OF BOOK AFTER APPEND: ', len(pickle.dumps(self.__m_rw)) I get the same length before and after append. when I print self.__m_rw.books, I see my 'appends' in there, yet the pickled object does not change. Any clue ? Thanks Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From bvande at po-box.mcgill.ca Tue Feb 8 11:15:30 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 08 Feb 2005 11:15:30 -0500 Subject: Learning Python - resources and ideas In-Reply-To: <1107855763.533466.254380@c13g2000cwb.googlegroups.com> References: <1107855763.533466.254380@c13g2000cwb.googlegroups.com> Message-ID: <4208E5A2.50701@po-box.mcgill.ca> AnOvercomer02 at webtv.net (Cody Houston) said unto the world upon 2005-02-08 05:06: > Hi. What is the best way to learn Python? None of the local schools > near me teach any courses on the topic. Thanks. > > -- > > Cody Houston > AnOvercomer02 at webtv.net Hi Cody, rec.photo.equipment.35mm? -- kind of an odd follow-up for a post to com.lang.python. First thing is to learn to ask better questions. It is a bit hard for anyone to know what to say without knowing your background and level of experience with computers and programming. contains a lot of very good advice on this. As for actual learning resources, did you look at www.python.org at all? (Or search the archives of this group?) The python site has a few pages of links that speak directly to your question. But, some concrete suggestions: The most useful resources for me (I'm still learning, too) was the Tutor list . A free book that starts very slow (it is aimed at high-school students) is I started with that, until I had a bit of a sense of things (Python is my first language since some BASIC quite some time ago). The Learning Python helped a lot . Best, Brian vdB From administrata at hotmail.com Fri Feb 4 17:59:45 2005 From: administrata at hotmail.com (administrata) Date: 4 Feb 2005 14:59:45 -0800 Subject: [noob] Error! Message-ID: <614c778e.0502041459.39da55c1@posting.google.com> I'm programming Car Salesman Program. It's been "3 days" learning python... But, i got problem Write a Car Salesman program where the user enters the base price of a car. The program should add on a bunch of extra fees such as tax, license, dealer prep, and destination charge. Make tax and license a percent of the base price. The other fees should be set values. Display the actual price of the car once all the extras are applied. print "CAR SALESMAN PROGRAM" print "\nEnter data." base_price = int(raw_input("Base Price: ")) tax = int(raw_input("/nTax: ")) license1 = int(raw_input("License: ")) dealer = 30 charge = 5 print "Dealer Prep: ", dealer print "Destination Charge: ", charge actual_price = (((base_price * tax / 100) + license1 / 100) + dealer + change print "\n\nActual price: ", actual_price raw_input("") error occurs, i think the problem is in actual_price. but, I don't know how to comebine percentage and raw_input. help me... thx 4 reading... :) From grante at visi.com Tue Feb 15 15:10:55 2005 From: grante at visi.com (Grant Edwards) Date: 15 Feb 2005 20:10:55 GMT Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: <37bkemF5a7s7vU1@individual.net> <86ll9piuj8.fsf@guru.mired.org> Message-ID: <4212574f$0$46576$a1866201@visi.com> On 2005-02-15, Adam DePrince wrote: > You didn't intent to, but you begging. Sure, you save some face by not > obviously groveling, but that only makes the slight worse. Now somebody > asked that you to read > http://www.catb.org/~esr/faqs/smart-questions.html. Read it in its > entirety, and come back later. The wanker already stated that the "smart questions" essay doesn't apply to him. I think he may be right: it only applies to people who actually want questions answered and problems solved. I don't think he wants to do/solve/answer anything. He just wants to piss and moan about how nobody will jump when he tells them to. -- Grant Edwards grante Yow! I always liked FLAG at DAY!! visi.com From no-one at nowhere.com Tue Feb 15 07:05:39 2005 From: no-one at nowhere.com (George van den Driessche) Date: Tue, 15 Feb 2005 12:05:39 -0000 Subject: win32gui bug: where to report it? Message-ID: It's taken me ages to find out why my window, built out of win32all, wasn't receiving any messages. Eventually I found the answer here: http://mail.python.org/pipermail/python-list/2001-October/069451.html The important point being: > IIRC you have to pass the return value of the RegisterClass() call (which > is an atom) to the CreateWindowEx() function as the second parameter > (lpClassName). ... in other words, you can pass the name of your window class as the second parameter, but it will silently fail to work. (This holds for CreateWindow too.) This is a bug for which it is pretty much impossible to work out the workaround without being told it, so I'd like to put the workaround in a more easily-found place. But where? win32all doesn't seem to have much documentation, much less a bug database. In case anyone else needs to find this message by searching, some keywords are: win32all, win32gui, WNDCLASS, RegisterClass, CreateWindow, CreateWindowEx George From francis.girard at free.fr Tue Feb 8 02:02:37 2005 From: francis.girard at free.fr (Francis Girard) Date: Tue, 8 Feb 2005 08:02:37 +0100 Subject: Big development in the GUI realm In-Reply-To: References: <4208373e$0$21620$a1866201@visi.com> Message-ID: <200502080802.37207.francis.girard@free.fr> > In any case, he may be right, and the FSF, Trolltech, and you could all > be wrong. Your intention when you use the GPL may be moot if a judge > determines that the text itself and copyright law does not support your > interpretation. I'm sorry to jump into this thread without any knowledge of these issues. I was just wondering if it did happen. Did some law court, over the past decade, had to make a decision about GPL on some real issue ? Thank you Francis Girard Le mardi 8 F?vrier 2005 05:17, Robert Kern a ?crit?: > Grant Edwards wrote: > > Sorry if I was a bit blunt, but I'm sick of people trying to > > weasle their way around a license by creative interpretation of > > the license terms when the licensors made their intentions as > > clear as possible. > > Believe me, I share your frustration every time this issue comes up. > However, I think it's best to follow Robert Heinlein's maxim: > > "Never attribute to malice what can adequately be explained by > stupidity." > > And I think we can also replace the word "stupidity" with "ignorance" if > you like. > > It seems to me that "Luke" is confused and ignorant. He has shown no > indication that he intends to write proprietary software using Qt. > > In any case, he may be right, and the FSF, Trolltech, and you could all > be wrong. Your intention when you use the GPL may be moot if a judge > determines that the text itself and copyright law does not support your > interpretation. > > I think that it is almost always best to obey the intentions of the > copyright holder and to ask for clarification when it is unclear. On the > other hand, if the copyright holder is *clearly* off-base with his > interpretation (and to me this would require actual case law, not just > the opinion of a lawyer), then I might consider disregarding the > author's interpretation and going with what case law and my lawyer > suggests. I don't believe that this situation holds with respect to this > issue, of course. > > -- > Robert Kern > rkern at ucsd.edu > > "In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." > -- Richard Harter From grante at visi.com Sat Feb 26 21:13:43 2005 From: grante at visi.com (Grant Edwards) Date: 27 Feb 2005 02:13:43 GMT Subject: Converting HTML to ASCII References: <7xk6ovbob4.fsf@ruckus.brouhaha.com> Message-ID: <42212cd7$0$44617$a1866201@visi.com> On 2005-02-26, Paul Rubin wrote: > Jorgen Grahn writes: >> You should probably do what some other poster suggested -- download >> lynx or some other text-only browser and make your code execute it >> in -dump mode to get the text-formatted html. You'll get that >> working in an hour or so, and then you can see if you need something >> more complicated. > > Lynx is pathetically slow for large files. First, make it work. Then make it work right. Then worry about how fast it is. "Premature optimization..." > It seems to use a quadratic algorithm for remembering where > the links point, or something. I wrote a very crude but very > fast renderer in C that I can post if someone wants it, which > is what I use for this purpose. If lynx really is too slow, try w3m or links. Both do a better job of rendering anyway. -- Grant Edwards grante Yow! I know how to do at SPECIAL EFFECTS!! visi.com From aleaxit at yahoo.com Sat Feb 5 14:14:55 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 5 Feb 2005 20:14:55 +0100 Subject: Alternative to standard C "for" References: <1107628331.816935.16760@o13g2000cwo.googlegroups.com> <36kjjqF52sv7lU1@individual.net> Message-ID: <1grj169.v9j8h341mmicN%aleaxit@yahoo.com> Georg Brandl wrote: > Slight terminology glitch -- it does return an iterator, not a > generator. Generators are functions that return iterators. xrange returns an ITERABLE, not an ITERATOR. Videat: >>> a = xrange(23, 43) >>> a.next() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'xrange' object has no attribute 'next' >>> No next method -> not an iterator. iter(xrange(...)) DOES return an iterator, btw. Alex From tom.willis at gmail.com Thu Feb 24 09:15:37 2005 From: tom.willis at gmail.com (Tom Willis) Date: Thu, 24 Feb 2005 09:15:37 -0500 Subject: python tutorial/projects In-Reply-To: <1109239584.738972.271050@z14g2000cwz.googlegroups.com> References: <1109239584.738972.271050@z14g2000cwz.googlegroups.com> Message-ID: On 24 Feb 2005 02:06:24 -0800, Fuzzyman wrote: > I'm looking for people to work on a couple of projects... online > bookmarks manager for example.... > > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml > > -- > http://mail.python.org/mailman/listinfo/python-list > How bout a paying full time job doing python development. In Cincinnati. That would rule. I only hear about vb.net or java around here. It's quite depressing. -- Thomas G. Willis http://paperbackmusic.net From deetsNOSPAM at web.de Wed Feb 9 08:46:30 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 09 Feb 2005 14:46:30 +0100 Subject: convert list of tuples into several lists References: Message-ID: <36uihlF58p63iU1@individual.net> zip(*[(1,4),(2,5),(3,6)]) -- Regards, Diez B. Roggisch From vincent at visualtrans.de Wed Feb 23 01:37:06 2005 From: vincent at visualtrans.de (Vincent Wehren) Date: Wed, 23 Feb 2005 07:37:06 +0100 Subject: basic tkinter/Windows question In-Reply-To: <7xwtt0ysuo.fsf@ruckus.brouhaha.com> References: <421BCED0.2070206@irl.cri.nz> <7xwtt0ysuo.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I find myself having to write some code on Windows :-(. To alleviate > the pain, at least I get to use Python for some of it. > > I'm trying to write a simple application, say "eggs.py". It pops a > tkinter gui and lets the user do some stuff. The system has Python > installed so I don't care about wrapping it in a .exe file or anything > like that. But I'd like to make a desktop icon for eggs.py and let the > user double-click it and run the app without also getting a DOS box on > the screen. Rename the file "eggs.py" to "eggs.pyw" and create a shortcut to that file. The file will be opened using pythonw.exe instead of python.exe. -- Vincent Wehren > > Is there a simple way to do that? I didn't see anything in the Python > docs about it. I suspect that this is really a dumb Windows question, > but I avoid Windows whenever I can, so most anything I can ask about it > is probably dumb. > > Thanks much. From quentel.pierre at wanadoo.fr Thu Feb 17 15:08:25 2005 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Thu, 17 Feb 2005 21:08:25 +0100 Subject: low-end persistence strategies? In-Reply-To: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> Message-ID: <4214f9ba$0$832$8fcfb975@news.wanadoo.fr> Maybe you'll find this too naive, but why do you want to avoid concurrent accesses to a database that will be accessed 12 times a day ? Regards, Pierre From dbickett at gmail.com Sat Feb 5 19:46:51 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sat, 5 Feb 2005 19:46:51 -0500 Subject: Definitive documentation on newstyle classes? (WAS: Pickling and inheritance are making me hurt) Message-ID: <1d6cdae305020516467620aa0@mail.gmail.com> I was reading the "Pickling and inheritance are making me hurt" thread, and the latest suggestion (as of this posting) was to do with the __setstate__ and __getstate__ methods. They caught my attention because I hadn't encountered them before, and it reminded me that in the past I've never been able to very good, definitive documentation on newstyle classes. Googling for it gives little python tutorials on various sites, and even searching this newsgroup returns very specific questions, as a rule. Alas, the question: Does there exist a page that enumerates all of the features of the newstyle classes, and explains what they all do? If so, can anyone provide me with such a link? Thanks :-) -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From tzot at sil-tec.gr Mon Feb 21 08:36:55 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 21 Feb 2005 15:36:55 +0200 Subject: python2.4 generator expression > python2.3 list expression References: Message-ID: <0ioj11dsgqhatqc3d7ldeb35rta6d9fk69@4ax.com> On 21 Feb 2005 06:48:19 -0500, rumours say that Dan Sommers might have written: [snip: snacktime posts code to count bits] >> Seems to work, is there a better way to do this? [Dan] >for c in range( 128 ): > even_odd = 0 > print '%3d' % c, > while c: > c &= c - 1 > even_odd = not even_odd > print int( even_odd ) Just for the sake of people who haven't messed with bit manipulation in C or assembly, the effect of c &= c - 1 is to reset the rightmost (less significant) '1' bit of a number (ie change it to '0'). -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From wuwei23 at gmail.com Thu Feb 10 03:08:23 2005 From: wuwei23 at gmail.com (alex23) Date: 10 Feb 2005 00:08:23 -0800 Subject: That horrible regexp idiom References: Message-ID: <1108022903.762790.60880@l41g2000cwc.googlegroups.com> Stephen Thorne wrote: > We've all seen it before. Its a horrible idiom that you would achieve > in another language by doing: > > if (m = foo_pattern.search(subject)) > { } > else > { } > > but it occured to me today, that it is possible to do it in python > without the extra line. > > '>>> for m in xsearch(foo_pattern, subject): > '>>> pass > '>>> else: > '>>> pass > > simple, concise, requires no new syntax, and is only a little confusing[1]! It won't have quite the same effect though, as the 'else' statement is *always* called after the 'for' loop completes. To have the functionality you're after, you need to include a break in the code block within the loop. - alex23 From tjreedy at udel.edu Sat Feb 26 13:44:27 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Feb 2005 13:44:27 -0500 Subject: Problem When Unit Testing with PMock References: <1109423274.660110.156140@f14g2000cwb.googlegroups.com> Message-ID: wrote in message news:1109423274.660110.156140 at f14g2000cwb.googlegroups.com... > Anyone was using pmock for unit testing with python? I met a problem > and hope someone to help me. For short, the pmock seems can not mock a > iterator object. Why bother? def mockit(): raise StopIteration now pass mockit() > For example, the tested object is foo, who need to send message to > another object bar. So, to test the foo, I need mock a mockBar. But > the bar is a iterator, the foo use the bar in this way: > > foo.method(self, bar): > for n in bar: > do somthing > ... To properly test the method, *also* feed it an iterator that yields a few objects of the appropriate type. Assuming n is to be an int... def intit(k): for i in range(k): yield i Terry J. Reedy From cpl.19.ghum at spamgourmet.com Mon Feb 7 01:33:03 2005 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Mon, 7 Feb 2005 06:33:03 +0000 (UTC) Subject: overwriting method in baseclass Message-ID: Hello! I am using a library (= code of so else) within Python. Somewhere in this library there is: class foo: def baa(self, parameters): print "something" self.baazanan(some other parameters) class mirbo(foo): def baazanan(self, lalala): print "heylo tada" class fujiko(foo): def baazanan(self, ltara): print "sing a song with me" .... now I want to change the common baa-method. so that def baa(self, parameters): print "soemthing special" self.baazanan(some other parameters) Of course, I use a Python- and GPL-Licence compatible library, I can change the source of foo, and use my changed library. But someday, it happened before, there will be an update by the publisher to that library.... and I have to do all again. So, what is the most elegant solution to administer these changes? Harald From apardon at forel.vub.ac.be Wed Feb 9 10:04:29 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 Feb 2005 15:04:29 GMT Subject: Is email package thread safe? (fwd) References: Message-ID: Op 2005-02-09, Roman Suzi schreef : > > (this is a repost with an addition - probably noone noticed my message first > time) > > Hi! > > Just to be sure, is email package of Python 2.3 thread-safe or not > (to use, for example, in python-milter?) > > P.S. And where can I find information on particular piece of standard library > if it is thread-safe or need locking? I recall 'random' module is (was?) > unsafe - which isexplicitly stated in the docs. Well I guess it was unsafe. The current documentation states: The underlying implementation in C is both fast and threadsafe. http://www.python.org/doc/2.3.5/lib/module-random.html There is class for random number generation that is not thread safe and is included to allow reproducing sequences from previous versions. > Can I assume that everything > else without such notice is thread-safe? I doubt it. There is no indication that the email package uses any kind of locking. So multiple thread working on the same message will probably screw things up. -- Antoon Pardon From ilias at lazaridis.com Sat Feb 5 09:44:11 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sat, 05 Feb 2005 16:44:11 +0200 Subject: [EVALUATION] - E01: The Java Failure - May Python Helps? In-Reply-To: References: Message-ID: Jeremy Bowers wrote: > On Thu, 03 Feb 2005 09:26:08 +0200, Ilias Lazaridis wrote: > >> My question is essentially: >> >> How many of those constructs are already supported by python (and >> the surrounding open-source-projects): >> >> http://lazaridis.com/case/stack/index.html > > This post is hard to follow, but I'm going to assume this is the core > question, as it is labelled as such. ok Thank you for your thorought comments. > The first thing that leaps to mind is that you need to play with > Python for a bit to get a full analysis of it. Due to the nature of > Python, some of the things you have in that list don't really apply. > > > The most obvious example of this is "code generation": Assuming you > mean [...] I want to generate things (code, txt, html etc.) out of my object-model, whilst using with a flexible generator, if possible a standard one. Does such generator exist? [...] > "Use of metadata within the design (on text level [code file])" can > mean a thousand things. For what it's worth, Python tends to make it > so easy I do it all the time, but for any given way you mean it, I > can't promise there exists a pre-rolled framework for you. I want to add metadata to everything within my design (functions, data, classes, ...), if possible with a standard way. Does such metadata-functionality (build-in, add-on-library, framework) exist for python? > So I can only speak generally. Given your list, you may find that > Python is weak in the "graphical programming" department; > drop-and-drop GUI generation isn't as well-tuned as VB. (I, for one, > consider that development methodology toxic and actively dangerous, > but I can understand why you miss it.) I prefere generic GUI's. But sometimes there is a need for simple predefined GUI's. Thus: I want to create GUI's in an generic way, and/or in an standard way (via GUI editor). > Skipping down to your evaluation sequence: http://lazaridis.com/case/stack/index.html#evaluation > * Create a class: Well, I'll show you this one: > > class Something: pass > > There, a class. ok - you've missed: "declare this class as persistent" > * Simple GUI: You may wish to check out Boa Constructor, as the > closest thing to the GUI generator you probably want. There are at > least 3 major viable GUI toolkits for Python and several other minor > (but still capable) ones. => {GUI Generator: Boa Constructor} > * Embedded DBs: I don't know, Google for your embedded DB name + > Python. Failing that, there are several ways to wrap your embedded DB > such that a Python program can use it. ok Clarification: standard way to save python objects into an embedded db (in conjunction wiht "declare this class as persistent") > * Web GUI: There are more Python web frameworks than you can shake a > stick at, and I don't mean "some guys hacked together templating > system" either; there are a lot of very mature systems out there, > expressing a lot of different philosophies. Given some of your other > requirements, for a web-based application I'd recommend examining > Zope. ok. Can please someone name some of them? [they should work together with simple python classes and the standard metadata] > * Deployment: I don't generally have enough problems with this to be > worth thinking about. I don't know what the state of the remote > debugging is on Python; Google "remote debugging Python". [I like to avoid interaction with google.] > * For your "complex updates", I see two distinct things there; half > of the depend on the database, not Python. It depends on how my python-build system binds to the underlaying database. > For the other half, it depends on if you mean "while the program is > still running". If so, they are challenging. If not, they are > trivial. You are right. New Requirements: a) While the programm in shutted down. b) While the programm in still running. > * I'd recommend adding "testability" to your stack, and refer you to > the "unittest" module; others can suggest their preferred testing > modules, but I tend to stick with that as the general framework is > available in a lot of languages that I use. If by evolutive > development you are including the ideas behind "agile software > development" (hard to tell if you mean that, or a community open to > change*) I don't know "agile software development", thus I cannot answer you. I'll think about to add "testability" to the stack. > Based on what I see here, I have two basic comments. First, yes, [...] > have, that even if it isn't perfect it's a helluva lot better than > Java! I've not evaluated Java. Just it's communities. Thus I can "dive" immediately & fully into python, without any philosoph switch (if i select python finally). > *: Community open to change: One caveat, from what I've seen when > other people talk about this. The Python community is open to change, > but it is still a meritocracy, and you will still need to convince > others your change is good. [...] - (standard library etc.) I understand. - A rational change suggestion does not need time to be accepted. Just rational decision takers (e.g. community). . -- http://lazaridis.com From nick at craig-wood.com Tue Feb 1 15:29:43 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 01 Feb 2005 20:29:43 GMT Subject: Where are list methods documented? References: <41ffba7d$0$15879$a1866201@visi.com> <41ffc37a$0$15874$a1866201@visi.com> Message-ID: Tim Peters wrote: > You could have gotten to the same place in several ways. [snip] Since I'm a unix person, I would have typed pydoc -k sort But it doesn't come up with anything useful :-( $ pydoc -k sort MySQLdb.stringtimes - Use strings to handle date and time columns as a last resort. ... In fact I've never had any luck with pydoc -k. I think what it searches through is too narrow - from its man page Run "pydoc -k " to search for a keyword in the synopsis lines of all available modules. This is the NAME line that appears in pydoc I think. If it did a full text search that would be much more useful, or at least a search through all the names of the functions & variables that are exported. ... My top wish for pydoc is to have the rest of the documentation in it! Each module has lots of nice documentation which is only available in HTML format - I'd much rather type "pydoc whatever" to see it all, rather than have to load my browser, and click through several layers of web pages. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From tom at tomaw.org Sun Feb 27 09:33:00 2005 From: tom at tomaw.org (Tom Wesley) Date: Sun, 27 Feb 2005 14:33:00 +0000 Subject: Beginner PyGTK and MySQL abuse request Message-ID: <4221da4d$0$54815$ed2619ec@ptn-nntp-reader02.plus.net> Hey, I've spent far too long being spoilt by a relatively simplistic "just do it" style of database application in use at work and have decided to try my hand at some Python + MySQL + GTK over the next few days. I've managed to steal/write a short script that asks for some input and searches a database and print the results and was wondering if people would have the time to suggest better ways of doing the limited set of things it does? ---search.py--- #!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk import adodb class AddressSearch: def delete_event(self, widget, data=None): gtk.main_quit() return gtk.FALSE def btn_search(self, widget, data=None): conn = adodb.NewADOConnection('mysql') conn.Connect('localhost','root','','rtl') sql = "select * from address where match(Address1, Address2, Address3, Address4, Address5) against('+" + self.entry_address1.get_text() + "+" + self.entry_address2.get_text() + "+" + self.entry_address3.get_text() + "' in boolean mode);" print sql cursor = conn.Execute(sql) while not cursor.EOF: arr = cursor.GetRowAssoc(0) print arr['rtlforename'], arr['rtlsurname'] cursor.MoveNext() cursor.Close() conn.Close() def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_title("Address search") self.window.connect("delete_event", self.delete_event) self.window.set_border_width(20) table = gtk.Table(5, 2, gtk.TRUE) self.window.add(table) label = gtk.Label("Address:") table.attach(label, 0, 1, 1, 5) self.entry_address1 = gtk.Entry(max=80) table.attach(self.entry_address1, 1, 2, 0, 1) self.entry_address2 = gtk.Entry(max=80) table.attach(self.entry_address2, 1, 2, 1, 2) self.entry_address3 = gtk.Entry(max=80) table.attach(self.entry_address3, 1, 2, 2, 3) button = gtk.Button(label='Search', stock=gtk.STOCK_OK) button.connect("clicked", self.btn_search) table.attach(button, 0, 1, 3, 4) button = gtk.Button(label="Quit", stock=gtk.STOCK_QUIT) button.connect("clicked", self.delete_event) table.attach(button, 1, 2, 3, 4) self.window.show_all() def main(): gtk.main() return 0 if __name__ == "__main__": AddressSearch() main() ---end--- Cheers, Tom From and-google at doxdesk.com Sat Feb 5 22:19:34 2005 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 5 Feb 2005 19:19:34 -0800 Subject: CGI POST problem was: How to read POSTed data References: Message-ID: <1107659974.048175.221770@z14g2000cwz.googlegroups.com> Dan Perl wrote: > how is a multipart POST request parsed by CGIHTTPServer? It isn't; the input stream containing the multipart/form-data content is passed to the CGI script, which can choose to parse it or not using any code it has to hand - which could be the 'cgi' module, but not necessarily. > Where is the parsing done for the POST data following the header? If you are using the 'cgi' module, then cgi.parse_multipart. > As a side note, I found other old reports of problems with cgi > handling POST requests, reports that don't seem to have had a > resolution. (in particular?) FWIW, for interface-style and multipart-POST-file-upload-speed reasons I wrote an alternative to cgi, form.py (http://www.doxdesk.com/software/py/form.html). But I haven't found cgi's POST reading to be buggy in general. > There is even a bug reported just a few days ago (1112856) that is > exactly about multipart post requests. If I understand the bug > report correctly though, it is only on the latest version in CVS > and it states that what is in the 2.4 release works. That's correct. > All this tells me that it could be a "fragile" part in the standard > library. I don't really think so; it's really an old stable part of the library that is a bit crufty in places due to age. The patch that caused 1112856 was an attempt to rip out and replace the parser stuff, which as a big change to old code is bound to cause trouble. But that's what the dev cycle is for. CGIHTTPServer, on the other hand, I have never really trusted. I would suspect that fella. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From bpeng at rice.edu Wed Feb 2 02:30:18 2005 From: bpeng at rice.edu (Bo Peng) Date: Wed, 02 Feb 2005 01:30:18 -0600 Subject: mixing SWIG generated and Python-level usertype? Message-ID: Dear list, My SWIG generated module (myModule) needs an array-like object (carray) to work. Carray objects are created both internally (in C++ level) and through Python so I have to load it when myModule initializes. carray is modified from arraymodule.c and is quite simple: static PyMethodDef a_methods[] = { {"carray", a_array, METH_VARARGS, a_array_doc}, { /* sentinel */ NULL, NULL } }; Currently, I load a_methods directly using code (error checking ignored) PyObject* mm = PyImport_AddModule("__main__"); PyObject* dict = PyModule_GetDict(mm); PyObject* v = PyCFunction_New(a_methods, NULL); PyDict_SetItemString(dict, a_methods->ml_name, v); There are several problems with this approach: 1. use of __main__? carray can not be accessed directly within other libraries. ('from myModule import *' DOES NOT import carray!) I tried to use __builtins__ but it does not work for some reason out of my understanding of Python. I am not sure how to add carray to myModule dictionary. 2. No type object? I am not sure what is the purpose of ArrayType but the usual init_module should be m = Py_InitModule3("carray", a_methods, module_doc); d = PyModule_GetDict(m); PyDict_SetItemString(dict, "ArrayType", (PyObject *)&Arraytype); When I add ArrayType to __main__ , access to ArrayType leads to a quick core dump. I do not feel comfortable with my current approach. Could anyone tell me some better (more standard) way? Many thanks in advance. Bo From jack at performancedrivers.com Sat Feb 12 19:57:03 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Sat, 12 Feb 2005 19:57:03 -0500 Subject: Kill GIL (was Re: multi threading in multi processor (computer)) In-Reply-To: References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <1107964587.818199.223980@g14g2000cwa.googlegroups.com> <7xr7jlwieq.fsf@ruckus.brouhaha.com> Message-ID: <20050213005703.GF14175@performancedrivers.com> On Sat, Feb 12, 2005 at 07:13:17PM -0500, Aahz wrote: > In article <7xr7jlwieq.fsf at ruckus.brouhaha.com>, > Paul Rubin wrote: > > > >The day is coming when even cheap computers have multiple cpu's. > >See hyperthreading and the coming multi-core P4's, and the finally > >announced Cell processor. I'm looking forward to Multi-core P4s (and Opterons). The Cell is a non-starter for general purpose computing. Arstechnica has a couple good pieces on it, the upshot is that it is one normal processor with eight strange floating point co-processors hanging off it. > >Conclusion: the GIL must die. > > It's not clear to what extent these processors will perform well with > shared memory space. One of the things I remember most about Bruce > Eckel's discussions of Java and threading is just how broken Java's > threading model is in certain respects when it comes to CPU caches > failing to maintain cache coherency. It's always going to be true that > getting fully scaled performance will require more CPUs with non-shared > memory -- that's going to mean IPC with multiple processes instead of > threads. > > Don't get me wrong -- I'm probably one of the bigger boosters of threads. > But it bugs me when people think that getting rid of the GIL will be the > Holy Grail of Python performance. No way. No how. No time. "Me Too!" for a small number of processors (four) it is easier (and usually sufficient) to pipeline functional parts into different processes than it is to thread the whole monkey. As a bonus this usually gives you scaling across machines (and not just CPUs) for cheap. I'm aware there are some problems where this isn't true. From reading this thread every couple months on c.l.py for the last few years it is my opinion that the number of people who think threading is the only solution to their problem greatly outnumber the number of people who actually have such a problem (like, nearly all of them). Killing the GIL is proposing a silver bullet where there is no werewolf-ly, -Jack From nospam at me.invalid Sun Feb 27 07:40:17 2005 From: nospam at me.invalid (anthonyberet) Date: Sun, 27 Feb 2005 12:40:17 +0000 Subject: string methods (warning, newbie) In-Reply-To: References: Message-ID: <38dtdjF5o9b7sU1@individual.net> Jimmy Retzlaff wrote: > Anthonyberet wrote: > >>Is there a string mething to return only the alpha characters of a > > string? > >>eg 'The Beatles - help - 03 - Ticket to ride', would be >>'TheBeatlesTickettoride' >> >>If not then how best to approach this? >>I have some complicated plan to cut the string into individual >>characters and then concatenate a new string with the ones that return >>true with the .isalpha string method. >> >>Is there an easier way? > > > The approach you are considering may be easier than you think: > > >>>>filter(str.isalpha, 'The Beatles - help - 03 - Ticket to ride') > > 'TheBeatleshelpTickettoride' > Thanks very much - that's the level of knowledge of Python that I just don't have yet - everything I try to do seems to have a much easier way, that I haven't encountered yet :) I shall read up on the elements of your code to understand exactly what it is doing. From rupole at hotmail.com Thu Feb 24 12:48:42 2005 From: rupole at hotmail.com (Roger Upole) Date: Thu, 24 Feb 2005 12:48:42 -0500 Subject: Need some Python help References: Message-ID: <421e1565_2@127.0.0.1> There's a bug in python's tokenizer that's triggered when the generated wrapper code for a COM object has lines longer than 512. See below link for a workaround: https://sourceforge.net/tracker/?func=detail&atid=551954&aid=1085454&group_id=78018 Roger "Matt Upton" wrote in message news:mailman.3000.1109259089.22381.python-list at python.org... > > > Hello, I am new to Python and am trying to produce script to run batch > processes for ArcGIS 9.0 (ArcView). I have upgraded to Phython 2.4 from > 2.1 > and am using the Pythonwin to try to code but am running into a problem. > Whenever I try to debug my program or run any code past the following code > it gets hung up and crashes, quits, no warning, and no messages. HELP, > what > is the problem, it is getting very frustrating. > >>> import win32com.client >>> gp = win32com.client.Dispatch("esriGeoprocessing.GPDispatch.1") >>> gp.workspace = "c:/Program Files/ArcGIS/NASA" > > > It ALWAYS crashes and quits 30 sec or so after line 2 or 3 of the code > above???? I can't get Python to do anything in ArcGIS so far, none of the > tools can be called or used? > > I am assuming there is some sort of path or link that is not working > properly between ArcGIS and Python? > > Using the same coding in the IDLE Python environment results in the same > crashing results. > > Oh yea, I am running everything on Windows XP. > > Thank you. > > Matthew Upton > > > > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-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 danperl at rogers.com Fri Feb 4 02:00:53 2005 From: danperl at rogers.com (Dan Perl) Date: Fri, 4 Feb 2005 02:00:53 -0500 Subject: advice needed for simple python web app References: <5cqdnZX-cZ9ca5_fRVn-3Q@rogers.com> Message-ID: "Brian Beck" wrote in message news:ctv48p$75$1 at eeyore.INS.cwru.edu... > From my experience, this appears to be the order from low-level to > high-level interfaces: > > 1. mod_python: As complex as you need it to be, since you can control > anything about the request & response process. But more up-front work and > decisions to make than CherryPy. > 2. mod_python with Vampire: Directs you toward a specific publishing > framework that is similar to CherryPy. > 3. CherryPy: Like Vampire but simpler and doesn't require mod_python. The > simplest blend between low-level server interface and ease-of-publishing. > 4. Twisted: Seems like this is a big package to work with, not sure how > easy it makes publishing once you get started-- better that someone else > comment on this. > 5. Zope: The most complex solution, doesn't necessarily make the 'easy > things easy.' But covers all fronts in terms of what a user would ever > need. > 6. Zope with Plone: Adds a ton of publishing functionality. Has many ways > to extend, but none of them are fun. You'll have to learn such complex > APIs that Python will rarely help you. This is exactly the kind of summary that I think should be in a WebProgrammingShootOut (see another one of my postings in this thread) but I failed to find such a summary. Thanks, Brian! Anyone can add to the list? BTW, there are other people who seem to have been also confused by the wide spectrum of choices for this problem: http://pyre.third-bit.com/hippoblog/archives/000058.html From steven.bethard at gmail.com Wed Feb 23 23:32:52 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 23 Feb 2005 21:32:52 -0700 Subject: Like overloading __init__(), but how? In-Reply-To: References: Message-ID: John M. Gabriele wrote: > class Vector3d: > def __init__(self): > ... > def __init__(self, x_from, y_from, z_from, x_to, y_to, z_to): > ... > def __init__(self, point_from, point_to): > ... > def __init__(self, same_as_this_vec): > ... My preferred option is to break these into different methods. I pick the xyz-coords (and the empty coords) __init__ as the most basic cases, but if you find one of the other cases to be more basic, the modification should be pretty simple. class Vector3d(object): # define init to take only xyz coords (missing coords default to 0) # this covers your first two cases, I think def __init__(self, x_from=0.0, y_from=0.0, z_from=0.0, x_to=0.0, y_to=0.0, z_to=0.0): ... # define a classmethod that creates a Vector3d from points # this covers your third case @classmethod def from_points(cls, point_from, point_to): ... return cls(x_from=..., y_from=..., ...) # define copy as an instance method, not a constructor # this covers your fourth case def copy(self): ... return type(self)(x_from=..., y_from=..., ...) Another possibility is to play around with *args: class Vector3d(object): def __init__(self, *args): if not args: # constructor with no arguments elif len(args) == 6: # constructor with xyz coords elif len(args) == 2: # constructor with points elif len(args) == 1: # copy constructor else: raise TypeError('expected 0, 1, 2 or 6 args, got %i' % len(args)) But this can get really ugly really quick. HTH, STeVe From danb_83 at yahoo.com Wed Feb 23 23:59:12 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 23 Feb 2005 20:59:12 -0800 Subject: rounding problem References: Message-ID: <1109221152.118191.136510@f14g2000cwb.googlegroups.com> tom wrote: > On Wed, 23 Feb 2005 19:04:47 -0600, Andy Leszczynski wrote: > > > It is on Windows, Linux, Python 2.3: > > > > [GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2 Type "help", > > "copyright", "credits" or "license" for more information. > > >>> a=1.1 > > >>> a > > 1.1000000000000001 ... > > Is it normal? > > Yes. Quite normal. ... > The print statement ,by itself, adds the most minimial formatting, which > amounts to dropping the last significant digit your math processor holds. > That last digit will *always* contain some arithmetic slop. Your statement is misleading, because it suggests that your processor stores digits. It doesn't; it stores *bits*. The distinction is important because 1.1 does not have a finite representation in binary. Instead, it's the repeating bit sequence 1.0 0011 0011 0011... This is analogous to 1/3 = 0.333... in base ten. IEEE 754 requires that all normalized numbers be rounded to 53 significant bits, so "1.1" is actually stored as 0x1.199999999999A, which is equivalent to the decimal number 1.100000000000000088817841970012523233890533447265625. Python's repr function rounds this to 17 significant digits, or "1.1000000000000001". From nessus at mit.edu Thu Feb 24 14:03:52 2005 From: nessus at mit.edu (Douglas Alan) Date: Thu, 24 Feb 2005 14:03:52 -0500 Subject: Canonical way of dealing with null-separated lines? References: Message-ID: Christopher De Vries writes: > I'm not sure if there is a canonical method, but I would > recommending using a generator to get something like this, where 'f' > is a file object: Thanks for the generator. It returns an extra blank line at the end when used with "find -print0", which is probably not ideal, and is also not how the normal file line iterator behaves. But don't worry -- I can fix it. In any case, as a suggestion to the whomever it is that arranges for stuff to be put into the standard library, there should be something like this there, so everyone doesn't have to reinvent the wheel (even if it's an easy wheel to reinvent) for something that any sysadmin (and many other users) would want to do on practically a daily basis. |>oug From steven.bethard at gmail.com Mon Feb 7 14:41:59 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 07 Feb 2005 12:41:59 -0700 Subject: "Collapsing" a list into a list of changes In-Reply-To: References: <200502071907.12169.francis.girard@free.fr> Message-ID: John Lenton wrote: > For example, the fastest way > to get the factorial of a (small enough) number in pure python is > > factorial = lambda n: reduce(operator.mul, range(1, n+1)) Gah! I'll never understand why people use lambda, which is intended to create _anonymous_ functions, to create named functions! This code is basically equivalent to: def factorial(n): return reduce(operator.mul, range(1, n+1)) except that factorial.__name__ is now the meaningful 'factorial', instead of ''. See "Inappropriate use of Lambda" in http://www.python.org/moin/DubiousPython My personal beef with the inappropriate use of lambda aside, and ignoring the fact that the reduce solution as written fails for factorial(0), some timings are in order. Given fact.py: ---------------------------------------------------------------------- import operator def f1(n): result = 1 for x in xrange(1, n+1): result *= x return result def f2(n): return reduce(operator.mul, range(1, n+1)) def f3(n): return reduce(operator.mul, xrange(1, n+1)) ---------------------------------------------------------------------- I get the following timeit results (with Python 2.4): $ python -m timeit -s "import fact" "[fact.f1(x) for x in xrange(1, 100)]" 100 loops, best of 3: 2.53 msec per loop $ python -m timeit -s "import fact" "[fact.f2(x) for x in xrange(1, 100)]" 100 loops, best of 3: 2.46 msec per loop $ python -m timeit -s "import fact" "[fact.f3(x) for x in xrange(1, 100)]" 100 loops, best of 3: 2.17 msec per loop So it does look like reduce is actually faster in this case, especially if you use xrange instead of range. Thanks for the example! Steve From jerf at jerf.org Wed Feb 2 16:20:41 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 02 Feb 2005 16:20:41 -0500 Subject: Generating modul classes with eval References: Message-ID: On Wed, 02 Feb 2005 20:49:07 +0000, Axel Straschil wrote: You are doing several things wrong. > I was fooling around with creating classes for a module with eval, You shouldn't create classes with eval, because you don't need to. "class" isn't a declaration, it is an executable statement that creates new classes. We'll get into that momentarily... > something like: > > MyModule.py: > > class Base: > init(self, name): > self._name = name Your "init" function needs to be spelled "__init__", or it will not be automatically called. You also did not correctly use "def" to create your function. When posting to the newsgroup, try to use real code that you have actually executed. > that gives: , but I want MyModule.A ;-) No, it won't, since your code has syntax errors in it. Post the code you actually ran. That said, "__main__" indicates you ran it in the interactive shell. That is correct, and won't change. Also, the name printing the class gives is only very rarely important; overall you shouldn't be using that. I'll start with giving you this: ------- import sys module = sys.modules[__name__] class Base: def __init__(self, name): self._name = name for myclass in ['A', 'B', 'C']: class Tmp(Base): myname = myclass def __init__(self): Base.__init__(self, self.myname) setattr(module, myclass, Tmp) ------- Note that we don't need eval anywhere. But I'd suggest that this is more likely what you want: ------- class Base: def __init__(self, name): self._name = name myClasses = {} for className in ['A', 'B', 'C']: class Tmp(Base): myname = className def __init__(self): Base.__init__(self, self.myname) myClasses[className] = Tmp ------- Adding things straight to modules is rarely worth it; you're better off just collecting them somewhere. There are too many differences to go over here between my code and yours, so if you have questions, please ask. One of the reasons you don't want eval is that I had to give up trying to read your class code! Finally, while such generated classes do have their use, I'd ask what you are planning to do with this; odds are, you don't need it. In general, unless you are using "eval" to literally execute user supplied input, you *almost* certainly don't need it. A downside of my approach is that printing all three classes will say the class name is "Tmp". Since, as I said, you really shouldn't care about that, I don't care to try to fix it :-) If you can provide a compelling reason why you need that, somebody here can help you with that. From raver2046 at gmail.com Tue Feb 15 18:36:55 2005 From: raver2046 at gmail.com (raver2046) Date: Wed, 16 Feb 2005 00:36:55 +0100 Subject: how to import a .py in a parent directory ? Message-ID: <4212878f$0$9483$636a15ce@news.free.fr> hello, I know to import a .py in a subdirectory is : . (dot) but what is the statment for parent directory ? thank you. olivier noblanc http://www.logiciel-erp.fr From fuzzyman at gmail.com Wed Feb 2 09:19:14 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 2 Feb 2005 06:19:14 -0800 Subject: Is this a contradiction in the docs ? In-Reply-To: <4200dccb$0$26664$636a15ce@news.free.fr> References: <1107342032.273119.194120@o13g2000cwo.googlegroups.com> <4200c8a6$0$518$626a14ce@news.free.fr> <1107349293.858397.127620@f14g2000cwb.googlegroups.com> <4200dccb$0$26664$636a15ce@news.free.fr> Message-ID: <1107353954.920995.241800@o13g2000cwo.googlegroups.com> Pierre Barbier de Reuille wrote: > Fuzzyman a ?crit : > > > > > > Yes.. but that would mean that eval could only run code objects that > > "consist[s] of a single expression".. which I doubt is the reality or > > the intention. > > > > Regards, > > Fuzzyman > > http://www.voidspace.org.uk/python/index.shtml > > > > [Sorry, I deleted the commented lines because they were completely > unreadable anyway] > That's alright - I *have* to read via google, which hides quoted lines anyway...... > It's exactly what eval is for : evaluate a single expression and return > its result ! Try with strings : you can't even evaluate a statement ! > You can only evaluate an expression ! > Right. > And what would be the return result of a sequence of statement ? > :-) I'm not interested in the return result. The code object is run in the current namespace, so I use it to run scripts. > If you want to execute a sequence, you want to use exec, not eval ... > Yup - I've swapped them over in my code. Thanks Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Pierre From gharper at medplus.com Wed Feb 9 15:55:31 2005 From: gharper at medplus.com (Harper, Gina) Date: Wed, 9 Feb 2005 15:55:31 -0500 Subject: two questions - no common theme Message-ID: <4D97153E7D88F44FB6B534C661EE42900300A649@medexch1.medplus.com> 2) os.listdir "returns a list containing the names of the entries in the directory", this does include directories in the top level directory. For the complete listing try os.walk() which "returns a tuple-(dirpath, dirnames, filenames" -----Original Message----- From: Sean McIlroy [mailto:sean_mcilroy at yahoo.com] Sent: Wednesday, February 09, 2005 3:08 PM To: python-list at python.org Subject: two questions - no common theme And now for a pair of questions that are completely different: 1) I'd like to be able to bind callbacks to presses of the arrow buttons on the keyboard. How do you say that in Tkinter? 2) The function 'listdir' in os.path returns a list of all the files in the given directory - how do I get hold of a list of its subdirectories? Any help will be greatly appreciated. Peace, STM From martin at v.loewis.de Tue Feb 22 21:03:09 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 Feb 2005 03:03:09 +0100 Subject: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux & Windows XP In-Reply-To: <1109081846.102735.167730@z14g2000cwz.googlegroups.com> References: <1109078512.094288.316030@z14g2000cwz.googlegroups.com> <421b385e$0$230$edfadb0f@dread12.news.tele.dk> <1109081846.102735.167730@z14g2000cwz.googlegroups.com> Message-ID: <421BE45D.4090902@v.loewis.de> Fuzzyman wrote: >>ust = '???'.decode('utf-8') >> > > Which is now deprecated isn't it ? (including encoded string literals > in source without declaring an encoiding). Not having an encoding declaration while having non-ASCII characters in source code is deprecated. Having non-ASCII characters in string literals is not deprecated (assuming there is an encoding declaration in the source); trusting then that the string literals are utf-8-encoded (and decoding them such) is fine. Regards, Martin From steve at holdenweb.com Thu Feb 3 11:05:33 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Feb 2005 11:05:33 -0500 Subject: convert ftp.retrbinary to file object? - Python language lacks expression? In-Reply-To: References: <19804fd8.0502030208.10ace31e@posting.google.com> Message-ID: Robert wrote: > That turns into periodic new RETR commands with offset. Think its more > an "odd" trick. I'd even prefer a threaded approach (thread puts the > blocks into a stack; a while ... yield generator loop in the main thread > serves the .read() function of the pseudo file object, which is my > wish). Yet such tricks are all kind of OS-level tricks with a lot of > overhead. > > I wonder really, if the Python language itself can express an elegant > flat solution to turn the block delivering callback function into a > generator/.read(bytes) solution? I found no way. > Don't know whether this would be helpful as a starting point, but a while (hmm, some years ...) ago I wrote an example of how FTP could be used as a file-like object. Look for ftpStream.py on http://www.holdenweb.com/Python/ Of course, in those days files could do a bit less than they can now, so there's no attempt to provide an iterator interface. > (Looking over some Ruby stuff, Ruby seems to be able to do so from the > language. I am not really familiar to Ruby. I always felt Python to be > as complete - but much more clean. I became somewhat jealous ... :-) ) > > As the solution in my case has to stand many different file systems > compatibly ( file.read(bytes) function !) and also other FTPS & SFTP > classes with different retrbinary functions have to be compatible, I > cannot even make a simple FTP subclassed retrbinary without getting > really weired. Thus the existing .retrbinary with callback is the > "official interface in this game". > You will note that my code uses delegation to an FTP object rather than inheritance. Maybe you would find that approach more fruitful for your application. regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From tzot at sil-tec.gr Thu Feb 10 13:33:24 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 10 Feb 2005 20:33:24 +0200 Subject: Efficient checksum calculating on lagre files References: <5o2nd2-5hl.ln1@pluto.i.infosense.no> <4208E537.4070901@chamonix.reportlab.co.uk> Message-ID: On 09 Feb 2005 10:31:22 GMT, rumours say that Nick Craig-Wood might have written: >Fredrik Lundh wrote: >> on my machine, Python's md5+mmap is a little bit faster than >> subprocess+md5sum: >> >> import os, md5, mmap >> >> file = open(fn, "r+") >> size = os.path.getsize(fn) >> hash = md5.md5(mmap.mmap(file.fileno(), size)).hexdigest() >> >> (I suspect that md5sum also uses mmap, so the difference is >> probably just the subprocess overhead) > >But you won't be able to md5sum a file bigger than about 4 Gb if using >a 32bit processor (like x86) will you? (I don't know how the kernel / >user space VM split works on windows but on linux 3Gb is the maximum >possible size you can mmap.) Indeed... but the context was calculating efficiently checksums for large files to be /served/ by a webserver. I deduce it's almost certain that the files won't be larger than 3GiB, but ICBW :) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From grante at visi.com Thu Feb 17 17:15:40 2005 From: grante at visi.com (Grant Edwards) Date: 17 Feb 2005 22:15:40 GMT Subject: How to wrap a class's methods? References: <4214f167$0$44618$a1866201@visi.com> <20050217194911.GF2366@grulic.org.ar> Message-ID: <4215178c$0$44653$a1866201@visi.com> On 2005-02-17, Michael Spencer wrote: >> I'd usually put big fat warnings around this code, and explain exaclty >> why I need to do things this way... > > As a low-tech alternative, what about sourcecode generation, Interesting idea. It's almost like haveing a macro capability. :) -- Grant Edwards grante Yow! Oh my GOD -- the at SUN just fell into YANKEE visi.com STADIUM!! From ncoghlan at iinet.net.au Thu Feb 10 08:46:18 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 10 Feb 2005 23:46:18 +1000 Subject: That horrible regexp idiom In-Reply-To: <3e8ca5c805020923107c36cd7f@mail.gmail.com> References: <3e8ca5c805020923107c36cd7f@mail.gmail.com> Message-ID: <420B65AA.5030805@iinet.net.au> Stephen Thorne wrote: > Hi, > > import re > foo_pattern = re.compile('foo') > > '>>> m = foo_pattern.search(subject) > '>>> if m: > '>>> pass > '>>> else: > '>>> pass Heh. Did you see Ray Gibbons's 'Testing Conditions' post before you sent this? I knew if/elif was a much better argument in favour of embedded assignment than while loops are. Anyway, here's the above using my idle thought from that the thread.: if m using foo_pattern.search(subject) as m: pass else: pass And the 'alternative patterns' case: if m using foo_pattern.search(subject) as m: pass elif m using bar_pattern.search(subject) as m: pass else: pass (Y'know, I'm pretty sure the impetus was regexp matching the *last* time embedded assignment came up. . .) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From wittempj at hotmail.com Tue Feb 15 13:04:48 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 15 Feb 2005 10:04:48 -0800 Subject: os.walk() usage References: Message-ID: <1108490688.466311.115920@l41g2000cwc.googlegroups.com> every object in os.walk() returns a 3-tuple, like below, it seems your code assumes it returns only a list of files. for d in os.walk('c:\\temp'): (dirpath, dirnames, filenames) = d print dirpath print dirnames print filenames From jamie.parent at sympatico.ca Fri Feb 11 10:32:44 2005 From: jamie.parent at sympatico.ca (Jamie R. Parent) Date: 11 Feb 2005 07:32:44 -0800 Subject: Injecting a C side object into the local dict Message-ID: <1108135964.686350.115090@f14g2000cwb.googlegroups.com> Hello, How do you go about taking a variable which was declared in C and pass that through to a Python script? I have tried doing this by adding a simple string which is a PyObject from C into the local dictionary and retrieving it from script via a locals()["myCvar"] print statement. This however does not seem to work. It would seem that when the scripts are ran the local dictionary with the added item is wiped clean and a new local dictionary is instead used. Any direction or help would be appreciated. Cheers, Jamie. From gerrit.muller at embeddedsystems.nl Wed Feb 16 08:32:07 2005 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Wed, 16 Feb 2005 14:32:07 +0100 Subject: "Architecture of Python" restored! [was Re: "Architecture of Python" was removed ?] In-Reply-To: <16869.3053.896410.298943@montanaro.dyndns.org> References: <004801c4f7cb$f62d1d30$1d02a8c0@cr> <16869.3053.896410.298943@montanaro.dyndns.org> Message-ID: <42134B57.6020104@embeddedsystems.nl> > Jim Jackson's UIUC email address is/was jwjackso at students.uiuc.edu. Jim, if > you're out there, is it okay to reconstruct your old C427 assignment > somewhere else? > The original pages at appear to be restored completely, including the nice visualizations! thanks, Gerrit -- Gaudi systems architecting: From jicman at gmail.com Wed Feb 9 20:53:59 2005 From: jicman at gmail.com (comp.lang.java) Date: 9 Feb 2005 17:53:59 -0800 Subject: Java Integer.ParseInt translation to python References: <008d01c507f4$451d9b30$2820790d@stso.xcdg.xerox.com> <372a762405013116263a4e93b7@mail.gmail.com> Message-ID: <1108000439.637482.253800@z14g2000cwz.googlegroups.com> Ok. Just to end this, here is what is happening with this. Take for example this piece of java code: int i = 235; byte b = (byte)i; this will assign b a value of -21. Huh? Ok, so in java a byte is an 8 bit value between -128 to 127. So, what (byte) does to an integer is to check if the value is over 127. If it is the new value is the value - 256. Otherwise, the value gets the integer, thus def MyByte(int): if int > 127: return int - 256 else: return int will do the trick. thanks for all the input folks. jos? jose isaias cabrera wrote: > Ok, so this, > > >> buffer[0] = (byte)Integer.parseInt(string,16); > > in java is, partly, this > > buffer[0] = int(string, 16) > > in python. But here is my problem. When I call this java subroutine, > > byte[] decodeKey(String inString) > { > if (inString == null) > return null; > > System.out.println("StringLength = " + inString.length()); > byte[] retBuf = new byte[inString.length()/2]; > // The string has two hex characters per byte. > for (int index = 0; index < retBuf.length; index++) > { > System.out.print(inString.substring(2*index, 2*index+2)); > System.out.println(" " + > Integer.parseInt(inString.substring(2*index, 2*index+2), 16) + " " + > (byte)Integer.parseInt(inString.substring(2*index, 2*index+2), 16)); > retBuf[index] = > (byte)Integer.parseInt(inString.substring(2*index, 2*index+2), 16); > } > System.out.println(retBuf); > > return retBuf; > } > > I get this output: > StringLength = 40 > c1 193 -63 > 7c 124 124 > e1 225 -31 > 86 134 -122 > ab 171 -85 > 94 148 -108 > ee 238 -18 > b0 176 -80 > de 222 -34 > 8a 138 -118 > e3 227 -29 > b5 181 -75 > b7 183 -73 > 51 81 81 > a7 167 -89 > c4 196 -60 > d8 216 -40 > e9 233 -23 > ed 237 -19 > eb 235 -21 > [B at 1616c7 > > But, here is what I have for python, > > def PrepareHash(HashStr): > while len(HashStr) > 0: > byte = HashStr[0:2] > print byte,int(byte,16),byte(int(byte,16)) # & 0xff > HashStr = HashStr[2:] > return byte > > def Main(): > HashStr = "c17ce186ab94eeb0de8ae3b5b751a7c4d8e9edeb" > HashStr = PrepareHash(HashStr) > print "Prepared HashStr :",HashStr > > Main() > > and it results to, > > mulo 19:32:06-> python test.py > c1 193 ? > 7c 124 | > e1 225 ? > 86 134 > ab 171 ? > 94 148 > ee 238 ? > b0 176 ? > de 222 ? > 8a 138 > e3 227 ? > b5 181 ? > b7 183 ? > 51 81 Q > a7 167 ? > c4 196 ? > d8 216 ? > e9 233 ? > ed 237 ? > eb 235 ? > > which is not even close, and yes, I know that it's not the same code. So, > the question is, how can I make this java (byte) call in python? so that the > result would be the right one, "[B at 1616c7" > > Thanks. > > jos? From Scott.Daniels at Acm.Org Thu Feb 24 12:01:12 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 24 Feb 2005 09:01:12 -0800 Subject: Canonical way of dealing with null-separated lines? In-Reply-To: References: Message-ID: <421e0432$1@nntp0.pdx.net> Douglas Alan wrote: > Is there a canonical way of iterating over the lines of a file that > are null-separated rather than newline-separated? Sure, I can > implement my own iterator using read() and split(), etc., but > considering that using "find -print0" is so common, it seems like > there should be a more cannonical way. You could start with this code and add '\0' as a line terminator: http://members.dsl-only.net/~daniels/ilines.html --Scott David Daniels Scott.Daniels at Acm.Org From eurleif at ecritters.biz Sun Feb 6 21:29:46 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sun, 06 Feb 2005 21:29:46 -0500 Subject: OT: why are LAMP sites slow? In-Reply-To: <7x8y65kwfl.fsf@ruckus.brouhaha.com> References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> Message-ID: <36o1tgF52utrnU1@individual.net> Paul Rubin wrote: > I notice that lots of the medium-largish sites (from hobbyist BBS's to > sites like Slashdot, Wikipedia, etc.) built using this approach are > painfully slow even using seriously powerful server hardware. Yet > compared to a really large site like Ebay or Hotmail (to say nothing > of Google), the traffic levels on those sites is just chickenfeed. To some extent, I would say it has to do with the servers being used. Slashdot has only 10 servers [1], while Wikipedia has only 39 [2]; Hotmail, on the other hand, has around 3500 [3]. A better comparison to Hotmail is the high-traffic Web site Neopets, which has around 200 servers [4] and uses Linux, Oracle, MySQL (for a few parts of the site), Apache, and PHP. [1] [2] [3] [4] Estimated by counting the name of wwwXXX.neopets.com domain names (238). Neopets probably has at least 300 servers if you include non-Web servers. From robey at flaminglunchbox.net Wed Feb 2 01:14:14 2005 From: robey at flaminglunchbox.net (Robey Holderith) Date: Wed, 02 Feb 2005 01:14:14 -0500 Subject: Python Code Auditing Tool References: <7xhdkvbjab.fsf@ruckus.brouhaha.com> Message-ID: On Tue, 01 Feb 2005 21:52:28 -0800, Paul Rubin wrote: > Robey Holderith writes: >> Does anybody know of a tool that can tell me all possible exceptions that >> might occur in each line of code? What I'm hoping to find is something >> like the following: > > That is impossible. The parameter to the raise statement is a class > object, which can be anything. I.e. you could say: > > class ex1: pass > class ex2: pass > > if something(): my_ex = ex1 > else: my_ex = ex2 > > raise my_ex # static tool can't know what exception gets raised here. I suppose that I am willing to lessen my expectations from _all_ to most. ;-) Regarding your example I could also do: if something(): def nothing(): return 0 else: def nothing(): return 1 But this doesn't stop IDEs from attempting to do auto-completion. I'm not trying to find hidden exceptions... just trying to easily get an idea of what could go wrong on each line of code. -Robey Holderith From administrata at hotmail.com Tue Feb 15 06:07:28 2005 From: administrata at hotmail.com (administrata) Date: 15 Feb 2005 03:07:28 -0800 Subject: Delivery Status Notification (Failure) Message-ID: <614c778e.0502150307.496b97d6@posting.google.com> Hello. I was about to use tutor-mailing But, When i send to tutor at python.org reply is... This is an automatically generated Delivery Status Notification. Delivery to the following recipients failed. bob.gailer at magnoliaroad.net and the header... From: Sm0kin'_Bull . To: tutor at python.org Subject: [Tutor] . Sent: Tuesday, February 15, 2005 7:57 PM MIME-Version: 1.0 X-Originating-IP: [193.38.108.210] X-Originating-Email: [administrata at hotmail.com] X-Sender: administrata at hotmail.com Received: from mail pickup service by mail2world.com with Microsoft SMTPSVC; Tue, 15 Feb 2005 02:48:54 -0800 Received: from 10.1.50.1 unverified ([10.1.50.1]) by mwde09la.mail2world.com with Mail2World SMTP Server,Tue 15 Feb 2005 02:48:51 -08:00 Received: from bag.python.org (bag.python.org [194.109.207.14])by smtp-vbr1.xs4all.nl (8.12.11/8.12.11) with ESMTP id j1FAxqDX014057;Tue, 15 Feb 2005 11:59:52 +0100 (CET)(envelope-from tutor-bounces at python.org) Received: from bag.python.org (bag [127.0.0.1])by bag.python.org (Postfix) with ESMTP id A93C81E4007;Tue, 15 Feb 2005 11:59:52 +0100 (CET) Received: from bag.python.org (bag [127.0.0.1])by bag.python.org (Postfix) with ESMTP id 26DE51E4007for ; Tue, 15 Feb 2005 11:59:51 +0100 (CET) Received: from bag (HELO bag.python.org) (127.0.0.1)by bag.python.org with SMTP; 15 Feb 2005 11:59:50 +0100 Received: from hotmail.com (bay22-f4.bay22.hotmail.com [64.4.16.54])by bag.python.org (Postfix) with ESMTPfor ; Tue, 15 Feb 2005 11:59:50 +0100 (CET) Received: from mail pickup service by hotmail.com with Microsoft SMTPSVC;Tue, 15 Feb 2005 02:58:00 -0800 Received: from 193.38.108.210 by by22fd.bay22.hotmail.msn.com with HTTP;Tue, 15 Feb 2005 10:57:20 GMT Sender: tutor-bounces at python.org ResentFrom: bgailer at alum.rpi.edu X-Original-To: tutor at python.org Delivered-To: tutor at bag.python.org X-Spam-Status: OK 0.223 X-Spam-Level: ** X-OriginalArrivalTime: 15 Feb 2005 10:58:00.0997 (UTC)FILETIME=[373B4D50:01C5134D] X-BeenThere: tutor at python.org X-Mailman-Version: 2.1.5 Precedence: list List-Id: Discussion for learning programming with Python List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: tutor-bounces at python.org X-Virus-Scanned: by XS4ALL Virus Scanner Plz HELP me; From 735115 at gmail.com Fri Feb 11 13:04:30 2005 From: 735115 at gmail.com (Bryant Huang) Date: 11 Feb 2005 10:04:30 -0800 Subject: Loading functions from a file during run-time References: <1108091598.055004.24890@g14g2000cwa.googlegroups.com> Message-ID: <1108145070.732098.253550@o13g2000cwo.googlegroups.com> Ah, thanks a lot, Grant and Nick. Let me try to clarify because I think I was unclear in specifying what I want to do: 1. Read in a file containing a bunch of function definitions: def f1(x): ... def f2(x): ... def f3(x): ... def f4(x): ... 2. In wxPython, populate a CheckListBox with all the functions defined in that file. 3. Allow the user to check some of the functions, say for example, f1() and f3(). 4. The program then executes f1() and f3() on some specified data. The reason I asked these questions is because I don't know what functions are contained in the function file ahead of time, but I still want to be able to read those in, then based on which functions the user selects, to run those accordingly, even though I still don't know, at design-time, what functions are contained in the function file. Does that make sense? Thanks a lot! Bryant From irmen.NOSPAM at xs4all.nl Fri Feb 18 09:23:54 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 18 Feb 2005 15:23:54 +0100 Subject: Annoying Socket Problem In-Reply-To: References: Message-ID: <42160090$0$28988$e4fe514c@news.xs4all.nl> John Abel wrote: > I'm hoping this is something simple, and someone can point me in the > right direction here. I have a class based on SocketServer > (ThreadingTCPServer), and I've used makefile on the socket so I use the > "for in " routine. My client sends it a small amount of data. However, > both programs appear to hang once the data has been sent, obviously > something to do with flushing. http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000400000000000000000 --Irmen From nav+posts at bandersnatch.org Tue Feb 8 11:06:23 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: Tue, 08 Feb 2005 11:06:23 -0500 Subject: python code with indention References: <1107805151.265680.165380@o13g2000cwo.googlegroups.com> Message-ID: <87mzuf9gu8.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> "Xah Lee" writes: > is it possible to write python code without any indentation? Not if Turing-completeness is something you desire. Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From porterboy76 at yahoo.com Fri Feb 25 04:29:19 2005 From: porterboy76 at yahoo.com (porterboy) Date: 25 Feb 2005 01:29:19 -0800 Subject: auto-completion history Message-ID: Hi Folks, I have auto-completion set up in my python interpreter so that if I hit the tab key it will complete a variable or a python command*. eg. if I type >>> imp and if I then hit the tab key, the interpreter will complete it to... >>> import Now, I also use Matlab at the command line a lot and it has a nice additional auto-completion feature, whereby, if you type a few letters and hit the up-arrow, it will go back to the last command you typed that began with those letters. If you keep hitting up-arrow it will cycle through all the commands you typed beginning with these letters. eg. if I type... >>> import datetime >>> import sys >>> today = datetime.date.today() >>> imp After typing the last imp I hit up-arrow once I would like the history to return to >>> import sys and if I hit twice, I would like to go to >>> import datetime Does a feature like this already exist in python??? Thanks The PorterBoy - "Lovely day for a Guinness" ps... * If you are unsure how to set up auto completion (UNIX only) ... 1. Include this line in your .tcshrc file (or equivalent in .bashrc): setenv PYTHONSTARTUP "$HOME/.pythonrc.py" 2. In the file ~/.pythonrc.py include the lines: import rlcompleter, readline readline.parse_and_bind('tab: complete') del rlcompleter, readline 3. For the effect to work, open a new terminal, and type python. If you do not fire up a new session, python has no way to become aware of your changes. From ben.champion at gmail.com Wed Feb 9 05:29:35 2005 From: ben.champion at gmail.com (FLChamp) Date: 9 Feb 2005 02:29:35 -0800 Subject: Vectors in Visual Python Message-ID: <1107944975.498403.225950@f14g2000cwb.googlegroups.com> SOrry if this message is a little confused, it most probably reflects the state of the author! I have made a small program that plots the orbit of a planet in visual python using visual.vector for all values. If i run the program it is clear that the orbit is non-keplerian as the planets gradually moves away from the sun. I am pretty sure the orbit should be keplerian so i guess there must be some source of error in the program. I am using "from __future__ import division" and the initial conditions I have are from NASA's horizons system, all values are accuracte to more than 10 decimal places. I was wondering if there was a way to specify the type of number used by visual.vector, for example, when using an array it is possible to specify the type as float64. If visual.vector was using a smaller amount of memory to store the number could this be the source of the error I am finding? If not what else could be the culprit? I have used a 4th order RK method which I have previously produced Keplerian orbits with. I hope I have made some sense here and look forward to any input Many Thanks Ben From gashton at cmedltd.com Thu Feb 24 04:54:03 2005 From: gashton at cmedltd.com (Graham Ashton) Date: 24 Feb 2005 01:54:03 -0800 Subject: Selective HTML doc generation In-Reply-To: References: <1109169752.819253.202930@o13g2000cwo.googlegroups.com> Message-ID: <1109238843.901331.224580@g14g2000cwa.googlegroups.com> Thanks Brian, much appreciated. Looks quite straightforward. Graham From steven.bethard at gmail.com Thu Feb 17 11:54:56 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 17 Feb 2005 09:54:56 -0700 Subject: newbie question - iterating through dictionary object In-Reply-To: <4214cb21$0$44602$a1866201@visi.com> References: <1108656866.128912.109800@f14g2000cwb.googlegroups.com> <4214cb21$0$44602$a1866201@visi.com> Message-ID: Grant Edwards wrote: > Here's another choice, that's sometimes handy: > >>>>d = {1:'one',2:'two',3:'three'} >>>>for k,v in d.items(): > > .... print k,v > .... > 1 one > 2 two > 3 three > > I wouldn't recommend this for large dictionaries. Yes, for large dictionaries, you should use: for k, v in d.iteritems(): print k, v STeVe From lbates at syscononline.com Fri Feb 25 11:57:59 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 25 Feb 2005 10:57:59 -0600 Subject: Splitting strings - by iterators? In-Reply-To: References: Message-ID: Jeremy, How did you get the string in memory in the first place? If you read it from a file, perhaps you should change to reading it from the file a line at the time and use file.readline as your iterator. fp=file(inputfile, 'r') for line in fp: ...do your processing... fp.close() I don't think I would never read 400,000 lines as a single string and then split it. Just a suggestion. Larry Bates Jeremy Sanders wrote: > I have a large string containing lines of text separated by '\n'. I'm > currently using text.splitlines(True) to break the text into lines, and > I'm iterating over the resulting list. > > This is very slow (when using 400000 lines!). Other than dumping the > string to a file, and reading it back using the file iterator, is there a > way to quickly iterate over the lines? > > I tried using newpos=text.find('\n', pos), and returning the chopped text > text[pos:newpos+1], but this is much slower than splitlines. > > Any ideas? > > Thanks > > Jeremy > From detlev at die-offenbachs.de Sun Feb 20 08:08:44 2005 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 20 Feb 2005 14:08:44 +0100 Subject: ANN: eric3 3.6.2 released Message-ID: Hi, this is to inform all of you about the release of eric3 3.6.2. It is a bug fix release and will work with the latest QScintilla/sip/PyQt. It is available via http://www.die-offenbachs.de/detlev/eric3.html What is eric3? -------------- Eric3 is a Python IDE written using PyQt and QScintilla. It has integrated project management capabilities, it gives you an unlimited number of editors, an integrated Python shell, an integrated debugger, integrated interfaces to CVS and Subversion, an integrated refactoring browser (Bicycle Repair Man), integrated unittest and much more. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From jan.dries at dcube-resource.be Tue Feb 8 15:33:13 2005 From: jan.dries at dcube-resource.be (Jan Dries) Date: Tue, 08 Feb 2005 21:33:13 +0100 Subject: Pypy - Which C modules still need converting to py? In-Reply-To: References: Message-ID: <42092209.609@dcube-resource.be> Caleb Hattingh wrote: > Anyone have that page > ref handy listing the C modules that the pypy team need translated into > python? http://codespeak.net/pypy/index.cgi?doc/cmodules.html Regards, Jan From ajsiegel at optonline.com Wed Feb 9 22:37:04 2005 From: ajsiegel at optonline.com (Arthur) Date: Wed, 09 Feb 2005 22:37:04 -0500 Subject: A great Alan Kay quote References: <420a5c1e$0$21630$a1866201@visi.com> <420a6491$0$29509$a1866201@visi.com> Message-ID: On Wed, 9 Feb 2005 21:23:06 +0100, Francis Girard wrote: > >I love him. I don't. > >It's also interesting to see GUIs with windows, mouse (etc.), which apparently >find their origin in is mind, probably comes from the desire to introduce >computers to children. Alfred Bork, now Professor Emeritus Information and Computer Science University of California, Irvine 92697 had written an article in 1980 called "Interactive Learning" which began "We are at the onset of a major revolution in education, a revolution unparalleled since the invention of the printing press. The computer will be the instrument of this revolution." In 2000 he published: "Interactive Learning: Twenty Years Later" looking back on his orignal article and its optimistic predictions and admitting "I was not a very good prophet" What went wrong? Among other things he points (probably using a pointing device) at the pointing device """ Another is the rise of the mouse as a computer device. People had the peculiar idea that one could deal with the world of learning purely by pointing. """ The articles can be found here: http://www.citejournal.org/vol2/iss4/seminal.cfm One does not need to agree or disagree, it seems to me about this or that point on interface, or influence, or anything else. What one does need to do is separate hope from actuality, and approach the entire subject area with some sense of what is at stake, and with some true sense of the complexity of the issues, in such a way that at this stage of the game the only authentic stance is one of humility, Kay fails the humility test, dramatically. IMO. Art From ncoghlan at iinet.net.au Sat Feb 26 23:05:06 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 27 Feb 2005 14:05:06 +1000 Subject: function expression with 2 arguments In-Reply-To: <1109453122.034646.290200@z14g2000cwz.googlegroups.com> References: <1109419984.213993.49280@f14g2000cwb.googlegroups.com> <98ydnSp0COmeLr3fRVn-jQ@powergate.ca> <1109453122.034646.290200@z14g2000cwz.googlegroups.com> Message-ID: <422146F2.7040605@iinet.net.au> Xah Lee wrote: > Python doc is quite confounded in it's way of organization centered > around implementation tied to hardware (as most imperative languages > are hardware-centric), as opposed to algorithm math concepts. Actually, Python's docs are centred around the fact that they expect people to start out by at least skimming the freaking tutorial. . . Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From damien.wyart at free.fr Mon Feb 14 17:52:36 2005 From: damien.wyart at free.fr (Damien Wyart) Date: Mon, 14 Feb 2005 23:52:36 +0100 Subject: parsing IMAP responses? References: <42111b20$0$44604$a1866201@visi.com> Message-ID: <42112bb4$0$17746$626a14ce@news.free.fr> * Grant Edwards in comp.lang.python: > Is there a library somewhere that impliments the IMAP protocol syntax? Maybe the "core" part of getmail could be reused, it seems cleanly written. http://www.qcc.ca/~charlesc/software/getmail-4/ -- DW From grante at visi.com Tue Feb 22 10:44:03 2005 From: grante at visi.com (Grant Edwards) Date: 22 Feb 2005 15:44:03 GMT Subject: how can i read a mail using uid? References: <1109058012.189388.302630@g14g2000cwa.googlegroups.com> Message-ID: <421b5342$0$46526$a1866201@visi.com> On 2005-02-22, Raghul wrote: > I want to read the content of the mail and split it words using uid.If > the word is found in my database I want to delete the mail using its > uid. STOP POSTING THE SAME QUESTIONS IN A DOZEN DIFFERENT THREADS! -- Grant Edwards grante Yow! I like the way ONLY at their mouths move... They visi.com look like DYING OYSTERS From steven.bethard at gmail.com Mon Feb 21 17:07:59 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 21 Feb 2005 15:07:59 -0700 Subject: subclassing Decimal In-Reply-To: <1109022264.823730.224910@o13g2000cwo.googlegroups.com> References: <1109022264.823730.224910@o13g2000cwo.googlegroups.com> Message-ID: <8sadneLa1dUmxoffRVn-uw@comcast.com> jbauer at rubic.com wrote: > I was interested in playing around with Decimal and > subclassing it. For example, if I wanted a special > class to permit floats to be automatically converted > to strings. > > from decimal import Decimal > > class MyDecimal(Decimal): > def __init__(self, value): > if isinstance(value, float): > ... initialize using str(float) ... > > In the classic days, I would have added something > like this to MyDecimal __init__: > > Decimal.__init__(self, str(value)) > > But I'm unfamiliar with the __new__ protocol. __new__ is called to create a new instance of the class. It is a staticmethod that gets passed as its first parameter the class to be created. You should be able to do something like[1]: py> import decimal py> class MyDecimal(decimal.Decimal): ... def __new__(cls, value): ... if isinstance(value, float): ... value = str(value) ... return super(MyDecimal, cls).__new__(cls, value) ... py> MyDecimal(3.0) Decimal("3.0") STeVe [1] If you're really afraid of super for some reason, you can replace the line: return super(MyDecimal, cls).__new__(cls, value) with return decimal.Decimal.__new__(cls, value) From wwproggemcom at aol.com Sun Feb 27 18:57:41 2005 From: wwproggemcom at aol.com (progpro99) Date: Sun, 27 Feb 2005 23:57:41 -0000 Subject: Python interfacing with other languages Message-ID: Hello all, I'm new to the group. I wanted to start off introducing myself. I live in Maimi, Florida USa. I'm 18 currently working and going to college for computer science. I've been hearing about Python and I see that it is starting to catch on so I decided I'm going to learn it. I know that python can work with other languages like c/c++ and Java. I even saw a group about getting Python in Delphi. I know Perl and VB. I know some PHP and some C/C++. I was wondering can Python work with VB also? If so is there a refernce you can send me the link too. Also, some friends and I are trying to start a little programming community. If you have some spare time doante a snippet or post on the forum, it would be appreciated. From john at grulic.org.ar Thu Feb 17 15:13:56 2005 From: john at grulic.org.ar (John Lenton) Date: Thu, 17 Feb 2005 17:13:56 -0300 Subject: low-end persistence strategies? In-Reply-To: <4214f9ba$0$832$8fcfb975@news.wanadoo.fr> References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <4214f9ba$0$832$8fcfb975@news.wanadoo.fr> Message-ID: <20050217201356.GQ2366@grulic.org.ar> On Thu, Feb 17, 2005 at 09:08:25PM +0100, Pierre Quentel wrote: > Maybe you'll find this too naive, but why do you want to avoid > concurrent accesses to a database that will be accessed 12 times a day ? because every sunday at 3am your boss and his wife will both try to use the script at the same time, and delete everything. -- John Lenton (john at grulic.org.ar) -- Random fortune: If our behavior is strict, we do not need fun! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From alexrait at gmail.com Tue Feb 1 16:48:40 2005 From: alexrait at gmail.com (alexrait1) Date: 1 Feb 2005 13:48:40 -0800 Subject: how about writing some gui to a known console application Message-ID: <1107294520.224155.131640@f14g2000cwb.googlegroups.com> Do something useful... (at least for me) For instance I need a gtk frontend for pgp. So here you can have an opportunity to learn both pyGTK and pgp. A lot of python code... :) From rt-announce-bounces at lists.bestpractical.com Sun Feb 13 17:43:52 2005 From: rt-announce-bounces at lists.bestpractical.com (rt-announce-bounces at lists.bestpractical.com) Date: Sun, 13 Feb 2005 17:43:52 -0500 Subject: Your message to RT-Announce awaits moderator approval Message-ID: Your mail to 'RT-Announce' with the subject You are made active Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://lists.bestpractical.com/cgi-bin/mailman/confirm/rt-announce/57983dcbe673221226d200cf131c55023d34b811 From mefjr75 at hotmail.com Mon Feb 7 00:34:50 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 6 Feb 2005 21:34:50 -0800 Subject: def __init__ question in a class definition In-Reply-To: References: Message-ID: <1107754489.980148.277690@c13g2000cwb.googlegroups.com> >Jeffrey Borkent >Systems Specialist >Information Technology Services With that kind of credentials, and the fact that you claim you are a system specialists.... I don't know you have me worried already. I guess for you I just say RTFM. If you think that is harsh then don't ask a 2nd grade question yet claim/pretend to be some sorta system specialists. You tried searching the archives first I am sure. Go here http://www.python.org and *read*, come back when you are really stuck. M.E.Farmer P.S. YES the __ matter, they identify special methods ! __init__ is the class CONSTRUCTOR. From jzgoda at gazeta.usun.pl Fri Feb 25 15:31:20 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 25 Feb 2005 21:31:20 +0100 Subject: Best IDe In-Reply-To: <0bvTd.52404$wc.42219@trnddc07> References: <0bvTd.52404$wc.42219@trnddc07> Message-ID: Jubri Siji napisa?(a): > Please i am new to python , whats the best IDE to start with Vim, Emacs or jEdit. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From alex at psi.com.au Fri Feb 25 01:00:43 2005 From: alex at psi.com.au (Alex Le Dain) Date: Fri, 25 Feb 2005 14:00:43 +0800 Subject: Trees Message-ID: <421EBF0B.8050902@psi.com.au> Is there a generic "tree" module that can enable me to sort and use trees (and nodes). Basically having methods such as .AddNode(), .GetAllChildren(), .FindNode() etc. Is this handled natively with any of the core modules? cheers, Alex. -- Poseidon Scientific Instruments Pty Ltd 1/95 Queen Victoria St FREMANTLE WA, AUSTRALIA Ph: +61 8 9430 6639 Fx: +61 8 9335 4650 Website: www.psi.com.au PSI, an ISO-9001 Company CONFIDENTIALITY: The contents of this email (and any attachments) are confidential and may contain proprietary and/or copyright material of Poseidon Scientific Instruments Pty Ltd (PSI) or third parties. You may only reproduce or distribute the material if you are expressly authorised to do so. If you are not the intended recipient, any use, disclosure or copying of this email (and any attachments) is unauthorised. If you have received this email in error, please immediately delete it and any copies of it from your system and notify PSI by return email to sender or by telephone on +61 (08) 9430 6639. DISCLAIMER: You may only rely on electronically transmitted documents when: (a) those documents are confirmed by original documents signed by an authorised employee of PSI; and/or (b) the document has been confirmed and checked against a hard copy of that document provided by PSI. VIRUSES: PSI does not represent or warrant that files attached to this e-mail are free from computer viruses or other defects. Any attached files are provided, and may only be used, on the basis that the user assumes all responsibility for any loss or damage resulting directly or indirectly from such use. PSI's liability is limited in any event to either the re-supply of the attached files or the cost of having the attached files re-supplied. From ncoghlan at iinet.net.au Fri Feb 11 08:47:38 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 11 Feb 2005 23:47:38 +1000 Subject: PyINI : Cross-Platform INI parser In-Reply-To: References: Message-ID: <420CB77A.7050405@iinet.net.au> Peter Maas wrote: > I think that a new config utility is worth the effort if it has the > potential to put an end to roll-your-own config formats and parsers. > http://www.python.org/moin/ConfigParserShootout Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From spiralx at gmail.com Wed Feb 9 14:20:54 2005 From: spiralx at gmail.com (James) Date: Wed, 9 Feb 2005 19:20:54 +0000 Subject: A great Alan Kay quote In-Reply-To: <420a5c1e$0$21630$a1866201@visi.com> References: <420a5c1e$0$21630$a1866201@visi.com> Message-ID: <7ee3dcd805020911202c192cc9@mail.gmail.com> Surely "Perl is another example of filling a tiny, short-term need, and then being a real problem in the longer term." is better lol ;) On Wed, 09 Feb 2005 11:00:32 -0800 (PST), Grant Edwards wrote: > In an interview at http://acmqueue.com/modules.php?name=Content&pa=showpage&pid=273 > Alan Kay said something I really liked, and I think it applies > equally well to Python as well as the languages mentioned: > > I characterized one way of looking at languages in this > way: a lot of them are either the agglutination of features > or they're a crystallization of style. Languages such as > APL, Lisp, and Smalltalk are what you might call style > languages, where there's a real center and imputed style to > how you're supposed to do everything. > > I think that "a crystallization of style" sums things up nicely. > The rest of the interview is pretty interesting as well. > > -- > Grant Edwards grante Yow! Look!! Karl Malden! > at > visi.com > -- > http://mail.python.org/mailman/listinfo/python-list > From just at xs4all.nl Wed Feb 2 10:51:36 2005 From: just at xs4all.nl (Just) Date: Wed, 02 Feb 2005 16:51:36 +0100 Subject: Hey, get this! [was: import from database] References: <4200E5CB.6020508@holdenweb.com> Message-ID: In article <4200E5CB.6020508 at holdenweb.com>, Steve Holden wrote: > Just to make things simpler, and (;-) to appeal to a wider audience, > here is a program that doesn't use database at all (it loads the entire > standard library into a dict) and still shows the error. > > What *I* would like to know is: who is allowing the import of bsddb.os, > thereby somehow causing the code of the os library module to be run a > second time. [ ... ] Maybe this?: > if package: > module.__path__ = sys.path I'm fairly sure this should read module.__path__ = ["*db*"] Just From mwm at mired.org Sat Feb 26 20:28:23 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 26 Feb 2005 19:28:23 -0600 Subject: Converting HTML to ASCII References: <20050225185147.43095.qmail@web20703.mail.yahoo.com> <86is4gfim2.fsf@guru.mired.org> Message-ID: <86ekf2g5ag.fsf@guru.mired.org> Michael Spencer writes: > Mike Meyer wrote: > >> It also fails on tags with a ">" in a string in the tag. That's >> well-formed but ill-used HTML. >> True enough...however, it doesn't fail too horribly: > >>> striptags("""the text""") > "'>the text" > >>> Depends on your example: and so on. Then again, early browsers actually did the same kind of parsing as you do, so this type of thing is discouraged. > and I think that case could be rectified rather easily, by stripping > any content up to '>' in the result without breaking anything else. Yes, but then what happens with: >text ? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From irmen.NOSPAM at xs4all.nl Fri Feb 18 16:52:50 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 18 Feb 2005 22:52:50 +0100 Subject: unicode and socket In-Reply-To: <42166231$0$28988$e4fe514c@news.xs4all.nl> References: <1108753426.318777.275250@c13g2000cwb.googlegroups.com> <42166231$0$28988$e4fe514c@news.xs4all.nl> Message-ID: <421664a2$0$28988$e4fe514c@news.xs4all.nl> Irmen de Jong wrote: > aurora wrote: > >> You could not. Unicode is an abstract data type. It must be encoded >> into octets in order to send via socket. And the other end must >> decode the octets to retrieve the unicode string. Needless to say the >> encoding scheme must be consistent and understood by both ends. > > > So use pickle. > > --Irmen Well, on second thought: don't use pickle. If all you want to transfer is unicode strings (or normal strings) it's safer to just encode them to, say, UTF-8, transfer that octet stream across, and on the other side, decode the UTF-8 octets back into a unicode string. --Irmen From dave at pythonapocrypha.com Wed Feb 23 17:35:14 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 23 Feb 2005 15:35:14 -0700 Subject: Python and "Ajax technology collaboration" In-Reply-To: <1109193970.029421.213490@l41g2000cwc.googlegroups.com> References: <1109193970.029421.213490@l41g2000cwc.googlegroups.com> Message-ID: <421D0522.4010807@pythonapocrypha.com> John Willems wrote: > Interesting GUI developments, it seems. Anyone developed a "Ajax" > application using Python? Very curious.... > > thx > > (Ajax stands for: > XHTML and CSS; > dynamic display and interaction using the Document Object Model; > data interchange and manipulation using XML and XSLT; > asynchronous data retrieval using XMLHttpRequest; > and JavaScript binding everything together We're using it in a couple of projects with Zope as the backend and it works really well - the web applications are way more responsive now (I'm hoping someone with lots of Zope knowledge will redo the ZMI itself using this approach). -Dave From theller at python.net Thu Feb 3 12:51:51 2005 From: theller at python.net (Thomas Heller) Date: Thu, 03 Feb 2005 18:51:51 +0100 Subject: Where is WSAEnumNetworkEvents??? References: <1107376894.420724.260230@c13g2000cwb.googlegroups.com> Message-ID: Dave Brueck writes: > elbertlev at hotmail.com wrote: >> I was trying to write an asyncronous TCP server for win32 using >> WSAEventSelect (which lives if win32file). Such events require >> WaitForMultipleObjects (which lives if win32event) and >> WSAEnumNetworkEvents WHICH IS NOT EXPOSED. This makes WSAEventSelect >> useless. Does somebody know how to add the WSAEnumNetworkEvents and >> WSANetwotkEvents structure win32file? >> Maybe I'm missing something? > > You could both build the structures and call the functions in ctypes > (http://starship.python.net/crew/theller/ctypes/) > > [untested code follows] > > from ctypes import * > class WSANETWORKEVENTS(Structure): > _fields_ = [('lNetworkEvents', c_long), > ('iErrorCode', c_int * 10) # 10 = FD_MAX_EVENTS > ] > > You'd access the API via windll.ws2_32.WSAEnumNetworkEvents, e.g. > > networkEvents = WSANETWORKEVENTS() > i = windll.ws2_32.WSAEnumNetworkEvents(s, hEventObject, byref(networkEvents)) > if i != 0: > # Handle an error Yes. And the day is not too far away (hopefully), that you'll be able to generate the wrapper code automatically: c:\sf\ctypes\sandbox\tools\codegen>h2xml winsock2.h -o winsock2.xml -q skipped #define SNDMSG ::SendMessage FunctionType c:\sf\ctypes\sandbox\tools\codegen>xml2py winsock2.xml -q -w -d -s WSAEnumNetworkEvents # generated by 'xml2py' # flags 'winsock2.xml -w -d -s WSAEnumNetworkEvents' from ctypes import * from ctypes import decorators class _WSANETWORKEVENTS(Structure): # C:/PROGRA~1/MICROS~3.NET/Vc7/PLATFO~1/Include/winsock2.h 1041 pass ws2_32 = CDLL('ws2_32') @ decorators.stdcall(c_int, ws2_32, [c_uint, c_void_p, POINTER(_WSANETWORKEVENTS)]) def WSAEnumNetworkEvents(p1, p2, p3): # C:/PROGRA~1/MICROS~3.NET/Vc7/PLATFO~1/Include/winsock2.h 2706 return WSAEnumNetworkEvents._api_(p1, p2, p3) _WSANETWORKEVENTS._fields_ = [ # C:/PROGRA~1/MICROS~3.NET/Vc7/PLATFO~1/Include/winsock2.h 1041 ('lNetworkEvents', c_long), ('iErrorCode', c_int * 10), ] assert sizeof(_WSANETWORKEVENTS) == 44, sizeof(_WSANETWORKEVENTS) assert alignment(_WSANETWORKEVENTS) == 4, alignment(_WSANETWORKEVENTS) c:\sf\ctypes\sandbox\tools\codegen> Thomas From abuse at solumslekt.org Thu Feb 17 04:19:27 2005 From: abuse at solumslekt.org (Leif B. Kristensen) Date: Thu, 17 Feb 2005 10:19:27 +0100 Subject: [newbie]How to install python under DOS and is there any Wxpython can be installed under dos? References: <1108557065.547230.254540@z14g2000cwz.googlegroups.com> <11172sa1sg2svc8@corp.supernews.com> Message-ID: john san skrev: > Actually the "windows" running very good under the xbox-NTOS via > xboxmediacenter. its just limited functions(not easy to programming > the "windows" prog.), if we can find WxPython-like can be ported (I > can import * > from it to my xboxPython) )it will be a great great ......... You > will have HD screen and web surfing on HDTV and computing on HDTV. > think about it! That is a real thing the python-like lang. should to > do otherwise just a garbage(toy). You can run Linux with MythTV on an XBox. Does all the things you want, and of course it will run WxPython. -- Leif Biberg Kristensen From kartic.krishnamurthy at gmail.com Fri Feb 4 11:35:55 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 4 Feb 2005 08:35:55 -0800 Subject: Thread in python In-Reply-To: <4rNMd.103073$Jk5.93452@lakeread01> References: <1107533540.641969.191940@z14g2000cwz.googlegroups.com> <1107534038.823409.89650@l41g2000cwc.googlegroups.com> <4rNMd.103073$Jk5.93452@lakeread01> Message-ID: <1107534954.988794.303330@o13g2000cwo.googlegroups.com> Ah! I forgot about this link.... the slideshow is very informative. From gandalf at geochemsource.com Tue Feb 8 08:23:03 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Tue, 08 Feb 2005 14:23:03 +0100 Subject: How to keep a module with the same name as a module it is importing from importing itself? In-Reply-To: <1107866562.822745.53480@o13g2000cwo.googlegroups.com> References: <1107866562.822745.53480@o13g2000cwo.googlegroups.com> Message-ID: <4208BD37.90001@geochemsource.com> >In my package, myapp, I have a module, logging.py. That module, >naturally, imports the library module logging with an 'import logging' >statement. However, when I use 'import myapp.logging' in my script, >the myapp.logging module tries to import itself rather than the library >logging module. > >How can I prevent this from happening other than using a name that >doesn't conflict? > > Did you try the built-in 'imp' module? http://docs.python.org/lib/module-imp.html I believe that 'load_module' is your very best friend. :-) Another idea: rename your modules so they do not conflict with standard modules. Best, Laci 2.0 -- _________________________________________________________________ Laszlo Nagy web: http://designasign.biz IT Consultant mail: gandalf at geochemsource.com Python forever! From cdieterich at geosci.uchicago.edu Thu Feb 3 12:43:07 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Thu, 3 Feb 2005 11:43:07 -0600 Subject: SysV IPC message queues In-Reply-To: <1107419374.385346.131940@f14g2000cwb.googlegroups.com> Message-ID: <10A2FF97-760B-11D9-8525-000A9582377C@geosci.uchicago.edu> On D?ardaoin, Feabh 3, 2005, at 02:29 America/Chicago, Aki Niimura wrote: > Hello everyone. > > I'm trying to control a program from a Python program using IPC. > Although using a socket is a common choice for such applications, I > would like > to use SysV message queues because I don't need to parse the stream. > > I thought Python had a support of SysV message queues (I have found > almost > anything I need in Python library modules so far). > But Python library seems not supporting SysV message queues yet. > > I'm thinking of calling a C function from Python but it seems not so > easy. Although this might not be the most elegant way to do what you want, it's relatively easy to make a C function work with Python. Have a look at http://www.swig.org/ Swig writes a C/Python wrapper for your C code which can be compiled into a shared object library. Then you can import that in Python. Swig is also (rudimentary) supported by distutils, so you don't even need to deal with the generation of the library. Christian Example: > cat src/SomeModule.i %module SomeModuleLib %{ #include "SomeModule.h" %} %include src/SomeModule.c > swig -python src/SomeModule.i > gcc -I/sw/include/python2.3 -c src/SomeModule.c -o SomeModule.o > gcc -I/sw/include/python2.3 -c src/SomeModule_wrap.c -o SomeModule_wrap.o > gcc -L/sw/lib -bundle -flat_namespace -undefined suppress SomeModule.o SomeModule_wrap.o -o _SomeModuleLib.so or automatic build from setup.py from distutils.core import setup, Extension import os, glob srcfiles = glob.glob(os.path.join('src', '*.[ci]')) setup(name="SomePackage", package_dir={"SomePackage": "lib"}, packages=["SomePackage"], ext_modules=[Extension("SomePackage._SomeModuleLib", srcfiles,),],) >>> import SomeModuleLib From cam.ac.uk at mh391.invalid Sun Feb 13 21:24:06 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 14 Feb 2005 02:24:06 +0000 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: Ilias Lazaridis wrote: > a) Why does the Python Foundation not provide additionally a binary > version, compiled with MinGW or another open-source compiler? I use a binary version of Python compiled with an open-source compiler on Windows that was provided by someone else. > b) Why does the Python Foundation not ensure, that the python > source-code is directly compilable with MinGW? Why should they? It already runs on Windows with a freely available compiler. > f) Are there any official (Python Foundation) statements / rationales > available, which explain why the MinGW compiler is unsupported, although > parts of the community obviously like to use it? Not to my knowledge. But I would guess because supporting it would obviously be a lot of work and the core developers have other things to do they consider more important. They are volunteers, you know. Why don't you solve this problem and produce a patched version of Python that does what you want. > [google is _not_ a fried here. I like to have a stable development > environment, which is supported by the official projects, thus it can > pass quality-assurance without beeing afraid about every next release.] Then you have several options: a) use a supported development environment b) do the work yourself to support MinGW c) pay someone else to do the work But don't act like the volunteers who develop Python owe you a version of Python that runs out of the box on MinGW. They don't, anymore than you owe *me* a version of Python that runs out of the box on MinGW. Now why haven't *you* produced a version of Python that is directly compileable with MinGW? Time's a-wasting. -- Michael Hoffman From jeremy+plusnews at jeremysanders.net Fri Feb 25 12:31:03 2005 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Fri, 25 Feb 2005 17:31:03 +0000 Subject: Splitting strings - by iterators? References: Message-ID: On Fri, 25 Feb 2005 10:57:59 -0600, Larry Bates wrote: > How did you get the string in memory in the first place? They're actually from a generated python script, acting as a saved file format, something like: interpret(""" lots of lines """) another_command() Obviously this isn't the most efficient format, but it's nice to encapsulate the data and the script into one file. Jeremy From max at alcyone.com Sun Feb 20 20:04:40 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 20 Feb 2005 17:04:40 -0800 Subject: exercise: partition a list by equivalence In-Reply-To: <1108931725.251996.56210@c13g2000cwb.googlegroups.com> References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> <1108814276.680736.264380@l41g2000cwc.googlegroups.com> <1108849063.857663.279920@c13g2000cwb.googlegroups.com> <1108931725.251996.56210@c13g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > Xah is asserting his right to be recognised as the author of his > artistic creations, line by line. Not very well, however, since his usage doesn't constitute a valid copyright notice :-). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Wyrd has swept all my kin / all the brave chiefs away! / Now I must follow them! -- Beowulf From caleb.hattingh at gmail.com Tue Feb 8 01:37:36 2005 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 7 Feb 2005 22:37:36 -0800 Subject: Multiple constructors In-Reply-To: References: <6SjNd.38337$K7.21639@fe2.news.blueyonder.co.uk> Message-ID: <1107844656.560243.211710@l41g2000cwc.googlegroups.com> Sure, Nick, I agree with you completely. I generally try to make sure that my classes are limited in what they do/provide, so it is not often a problem that a class may need to be instantiated in several very different ways. But your point is well taken. Thanks Caleb From nick at craig-wood.com Mon Feb 14 13:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 14 Feb 2005 18:30:01 GMT Subject: [PATCH] allow partial replace in string.Template References: Message-ID: Nick Coghlan wrote: > > a) Patches are more likely to be looked at if placed on the SF patch tracker. > > b) I don't quite see the point, given how easy these are to spell using the > basic safe_substitute. You're replacing one liners with one-liners. c) add a documentation patch d) add a test suite patch -- Nick Craig-Wood -- http://www.craig-wood.com/nick From claird at lairds.us Fri Feb 25 15:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Fri, 25 Feb 2005 20:08:03 GMT Subject: Flushing print() References: Message-ID: In article , Daniel Yoo wrote: >gf gf wrote: . . . >: If not, how can I flush it manually? sys.stdout.flush() didn't >: seem to work. > >Hmmmm, that's odd. sys.stdout.flush() should do it. How are you >testing that stdout isn't flushing as you expect? > > >Best of wishes to you! gf, remember to write sys.stdout.flush() rather than sys.stdout.flush That's a mistake that catches many. From eurleif at ecritters.biz Tue Feb 8 18:41:54 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 08 Feb 2005 18:41:54 -0500 Subject: What's wrong with `is not None`? In-Reply-To: References: Message-ID: <36t0v9F56r1sbU1@individual.net> Frans Englich wrote: > runner.py:587: Using is not None, may not always work It's a PyChecker bug relating to None being a constant in 2.4: . From joannis.courtis at gmx.de Wed Feb 23 19:08:21 2005 From: joannis.courtis at gmx.de (Courtis Joannis) Date: Thu, 24 Feb 2005 01:08:21 +0100 (MET) Subject: Question about logfiles in Python Message-ID: <12380.1109203701@www15.gmx.net> Hello readers, my name is Joannis Courtis and I study computer science in Frankfurt/Germany. I hope you can help me, because I try to find a script that helps me to filter logfiles which I received from the Microsoft Exchange Server. Can you help me, where I can find a script in Python. Regards Joannis Courtis -- Lassen Sie Ihren Gedanken freien Lauf... z.B. per FreeSMS GMX bietet bis zu 100 FreeSMS/Monat: http://www.gmx.net/de/go/mail From http Mon Feb 14 15:22:08 2005 From: http (Paul Rubin) Date: 14 Feb 2005 12:22:08 -0800 Subject: is there a safe marshaler? References: <420b6936$0$28982$e4fe514c@news.xs4all.nl> <1108051828.483222.62670@z14g2000cwz.googlegroups.com> Message-ID: <7xmzu6q4cv.fsf@ruckus.brouhaha.com> "guido at python.org" writes: > > Pickle and marshal are not safe. They can do harmful things if fed > > maliciously constructed data. That is a pity, because marshal is fast. > > I think marshal could be fixed; the only unsafety I'm aware of is that > it doesn't always act rationally when confronted with incorrect input > like bad type codes or truncated input. It only receives instances of > the built-in types and it never executes user code as a result of > unmarshalling. There's another issue with marshal that makes it unsuitable for Pyro, which is that its data format is (for legitimate reasons) not guaranteed to be the same across different Python releases. That means that if the two ends of the Pyro application aren't using the same Python version, they might not be able to interoperate. I don't remember if marshal strings contain a version number. If they do, then the non-interoperating versions can notice the incompatibility and raise an appropriate error. If they don't, then undefined behavior and possible security holes could result, unless Pyro takes special measures to notice the possibility. See SF bugs #467384 and #471893 for some further discussion. From jerf at jerf.org Fri Feb 11 21:22:08 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 11 Feb 2005 21:22:08 -0500 Subject: Big development in the GUI realm References: <1107795145.049239.73450@l41g2000cwc.googlegroups.com> <5ocf01hmspufk3iusvm35p6hj4mes5heke@4ax.com> <4207c8db$0$21623$a1866201@visi.com> <36sip2F56jjmaU1@individual.net> <374826F5851cbU1@individual.net> Message-ID: On Fri, 11 Feb 2005 14:45:09 -0800, Robert Kern wrote: > Until such matters are unequivocally determined in a court that has > jurisdiction over you, do you really want to open yourself to legal risk > and certain ill-will from the community? Huh? What are you talking about? I'm just pointing out the inability of the law to handle it. I have no intention of doing anything with it, except inasmuch as it makes it difficult to license my own works since I don't believe any license works. (But I use the LGPL anyways.) From dbeech at bigpond.net.au Thu Feb 10 04:15:40 2005 From: dbeech at bigpond.net.au (Dave Beech) Date: Thu, 10 Feb 2005 19:45:40 +1030 Subject: Python-list Digest, Vol 13, Issue 102 References: <20041006143440.CC5491E4005@bag.python.org> Message-ID: <040a01c50f51$1f8366c0$0100000a@vic.bigpond.net.au> ----- Original Message ----- From: To: Sent: Thursday, October 07, 2004 1:04 AM Subject: Python-list Digest, Vol 13, Issue 102 > 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: Python Macros (Carlos Ribeiro) > 2. Re: Python Macros (gabriele renzi) > 3. Re: Python Macros (gabriele renzi) > 4. Re: Python Macros (Alex Martelli) > 5. Re: Parallelization on muli-CPU hardware? (Nick Craig-Wood) > 6. Re: Job postings (Larry Bates) > 7. Re: Embedding python with debugging features (Wolfgang Langner) > 8. Re: re bug (Gustavo Niemeyer) > 9. How to improve extracting data speed (Yong Wang) > 10. Re: Parallelization on muli-CPU hardware? (?????? ???????????) > 11. Re: metaclass and customization with parameters (Gustavo Niemeyer) > ---------------------------------------------------------------------------- ---- > -- > http://mail.python.org/mailman/listinfo/python-list From kent37 at tds.net Sun Feb 13 14:26:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 13 Feb 2005 14:26:52 -0500 Subject: changing __call__ on demand In-Reply-To: References: Message-ID: <420fa70f$1_2@newspeer2.tds.net> Stefan Behnel wrote: > Hi! > > This somewhat puzzles me: > > Python 2.4 (#1, Feb 3 2005, 16:47:05) > [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > .>>> class test(object): > ... def __init__(self): > ... self.__call__ = self.__call1 > ... def __call1(self): > ... print 1 > ... def __call__(self): > ... print 2 > ... > .>>> t = test() > .>>> t() > 2 > It works the way you want if test is an old-style class: >>> class test: ... def __init__(self): ... self.__call__ = self.__call1 ... def __call1(self): ... print 1 ... def __call__(self): ... print 2 ... >>> t=test() >>> t() 1 Kent From ncoghlan at iinet.net.au Sat Feb 12 22:30:07 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 13 Feb 2005 13:30:07 +1000 Subject: namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP In-Reply-To: <420DB64E.9020000@iinet.net.au> References: <420DB64E.9020000@iinet.net.au> Message-ID: <420EC9BF.5020802@iinet.net.au> Yeah, talking to myself again. I had a couple of further thoughts on how to do things in an inheritance friendly way. . . Firstly, for Namespaces handling of special names, I think it would be good to make it easy for subclasses to change the sets of names that are handled using either Namespace lookup or standard Python lookup. The simplest way is to make the method that performs the check an instance method. class Namespace(object): # etc def _is_special_name(name): return name.startswith("__") and name.endswith("__") I also think subclasses should be able to affect update() just by defining __setattr__ (for example, my LockedView class forgot to deal with update()). So I'd replace the calls to self.__dict__.update(other) with calls to type(self)._update_dict(self, other): class Namespace(object): # etc def _update_dict(self, other): for k in other: setattr(self, k, other[k]) Finally, it might be nice if the get/set/del methods special-cased names with dots in them. Consider the following with a normal class: Py> class C(object): pass ... Py> c = C() Py> c.x = C() Py> setattr(c, "x.y", 1) Py> getattr(c, "x.y") 1 Py> vars(c.x) {} Py> vars(c) {'x.y': 1, 'x': <__main__.C object at 0x009E0A10>} Py> c.x.y Traceback (most recent call last): File "", line 1, in ? AttributeError: 'C' object has no attribute 'y' With a namespace, we can make the dotted access 'just work': Py> ns = namespaces.Namespace() Py> ns.x = C() Py> ns.y = namespaces.Namespace() Py> setattr(ns, "x.y", C()) Py> setattr(ns, "x.y.z", 1) Py> setattr(ns, "y.x", C()) Py> setattr(ns, "y.x.z", 2) Py> vars(ns) {'y': Namespace(x=<__main__.C object at 0x009EB8D0>), 'x': <__main__.C object at 0x009EB1F0>} Py> vars(ns.x) {'y': <__main__.C object at 0x009EB890>, 'y.z': 1} Py> vars(ns.y) {'x': <__main__.C object at 0x009EB8D0>} Py> vars(ns.y.x) {'z': 2} Combined with the update change, it means this code does the right thing: Py> settings = { ... "x" : 1, ... "y" : namespaces.Namespace(), ... "y.z" : 1, ... "y.x" : "Hi there!", ... } Py> ns = namespaces.Namespace(settings) Py> ns Namespace(x=1, y=Namespace(x='Hi there!', z=1)) Rather than sending it again, I've posted my current code at: http://members.iinet.net.au/~ncoghlan/public/namespaces.py Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From itsme at yahoo.com Fri Feb 25 00:09:27 2005 From: itsme at yahoo.com (It's me) Date: Fri, 25 Feb 2005 05:09:27 GMT Subject: Pythoncard - Mistake in walkthrough? References: Message-ID: No, those are old still. "Deltones" wrote in message news:e0f0f902.0502232113.2711a809 at posting.google.com... > > As stated in the on-line WalkThrough, the information there was written for > > an older version of the program. > > > > > Hi, > > I understand, but the walkthrough I'm doing comes from the doc folder > of the latest windows package. I thought that the walkthrough were > updated to fit the newest version. Thanks though. > > Denis From phd at mail2.phd.pp.ru Fri Feb 11 13:39:04 2005 From: phd at mail2.phd.pp.ru (Oleg Broytmann) Date: Fri, 11 Feb 2005 21:39:04 +0300 Subject: mxCGIPython binaries for Python 2.3.5 In-Reply-To: <20050211181320.GA23241@caltech.edu> References: <20050211154457.GA23787@phd.pp.ru> <20050211181320.GA23241@caltech.edu> Message-ID: <20050211183904.GA28714@phd.pp.ru> On Fri, Feb 11, 2005 at 10:13:21AM -0800, Titus Brown wrote: > what does mxCGIPython do? I can't find anything at that Web site that http://www.egenix.com/files/python/mxCGIPython.html > doesn't involve downloading & unpacking a file. It is unpackable, ready-to-run python binary. PS. I am neither author nor maintainer, I only provide binaries for some platforms... Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From walter_burleigh at yahoo.de Sat Feb 12 04:05:51 2005 From: walter_burleigh at yahoo.de (Walter Burleigh) Date: Sat, 12 Feb 2005 10:05:51 +0100 Subject: PHP session equivalent? References: <420d6010$1@nntp.zianet.com> Message-ID: Erik Johnson wrote: > There are a lot of things about PHP I was not too keen on and hence > why > my company is primarily doing Python these days, but one thing I was quite > impressed with was the ease with which it provided session > functionality... Like you I think it is a big plus of PHP as a beginner's web development tool that it provides session management out of the box. It would certainly make python more attractive for beginners if they could use session management out of the box, too. (I know that there are lots of web development frameworks, but they are to be too difficult to learn, if you are new to web development). There is no module for session management in the python standard library. But there are lots of python frameworks that would do this job well (my favorite: cherrypy). If you think that a whole framework would be overkill, you either could try to recylce the session part of an existing framework, or you could write a module for yourself. I have written a module which is quite similar to the php session management, except for that it does no url rewriting when cookies are not allowed. If you are interested, I will mail you a copy. From usenet_spam at janc.invalid Mon Feb 7 20:33:10 2005 From: usenet_spam at janc.invalid (JanC) Date: Tue, 08 Feb 2005 01:33:10 GMT Subject: Big development in the GUI realm References: <1107795145.049239.73450@l41g2000cwc.googlegroups.com> <5ocf01hmspufk3iusvm35p6hj4mes5heke@4ax.com> <1107815270.149109.80420@c13g2000cwb.googlegroups.com> Message-ID: Kartic schreef: > In any case, let's say I use Python to create an application that uses > some module that is GPL. So what are my options? For your own personal use: doesn't mather. If you want to distribute it, your application must be GPL'ed, so *all* source code must be made available for those you distribute it to. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From max at alcyone.com Sat Feb 12 19:37:27 2005 From: max at alcyone.com (Erik Max Francis) Date: Sat, 12 Feb 2005 16:37:27 -0800 Subject: help please In-Reply-To: <1108254434.871062.314510@g14g2000cwa.googlegroups.com> References: <1108254434.871062.314510@g14g2000cwa.googlegroups.com> Message-ID: gargonx at gmail.com wrote: > UnboundLocalError: local variable 't2' referenced before assignment ... > t2="" > > def Proc(text): # "text" is some random text or use OrigText > for word in text: > for letter in word: > if letter in std.keys(): > letter=std[letter] > t2=t2+letter # the problem is referene to this > elif letter in ext.keys(): > letter=ext[letter] > t2=t2+letter > elif letter in punc.keys(): > letter=punc[letter] > t2=t2+letter > > can anyone figure out why t2 is not being used properly? The problem is that you're not making it clear to Python that you want the t2 mentioned in Proc to reference the global t2, rather than a local. It's concluding the latter, whereas you mean the former. You can probably see that as a local, t2 is indeed referenced before it's assigned (t2 = t2 + letter). The fix is to declare t2 global at the top of Proc: def Proc(text): global t2 ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis I am become death, the destroyer of worlds. -- J. Robert Oppenheimer (quoting Hindu legend) From cpu.crazy at gmail.com Mon Feb 21 16:01:54 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Mon, 21 Feb 2005 15:01:54 -0600 Subject: A few q's on python files. Message-ID: <6.1.0.6.2.20050221145825.01e79150@pop.gmail.com> hiya, i'm new to python (by a week) but am learning fast (that's what I like about python--it's simplicity). I got disgusted with C and C++ (i was learning) probably because of a bad copy of Visual C++ 6.0 that gave me errors. I noticed that IDLE doesn't have an option to allow you to convert a .py or pyc. file into an executable. Why? Am i wrong? Where can I find one (if I'm right)? From elbertlev at hotmail.com Wed Feb 2 15:41:34 2005 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 2 Feb 2005 12:41:34 -0800 Subject: Where is WSAEnumNetworkEvents??? Message-ID: <1107376894.420724.260230@c13g2000cwb.googlegroups.com> I was trying to write an asyncronous TCP server for win32 using WSAEventSelect (which lives if win32file). Such events require WaitForMultipleObjects (which lives if win32event) and WSAEnumNetworkEvents WHICH IS NOT EXPOSED. This makes WSAEventSelect useless. Does somebody know how to add the WSAEnumNetworkEvents and WSANetwotkEvents structure win32file? Maybe I'm missing something? From ilias at lazaridis.com Tue Feb 15 16:19:54 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Tue, 15 Feb 2005 23:19:54 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: I'm 'closing' this thread now [means that I do possibly not respond anymore to messages]. Thank you for your time and effort. . -- http://lazaridis.com From as006d4848 at blueyonder.co.uk Thu Feb 17 00:27:50 2005 From: as006d4848 at blueyonder.co.uk (Philip Smith) Date: Thu, 17 Feb 2005 05:27:50 GMT Subject: Derived class and deepcopy Message-ID: Hi If I derive a class (eg Matrix) from list I presume this implies the classic OOP 'is a' relation between the derived and super class. I therefore presume I can use a derived class in any context that I can use the superclass. In the given example I want to apply deepcopy() to the Matrix instance (on initialisation) to ensure that the list part is not affected by subsequent changes to the initialising list or Matrix but this gives me a string of errors (some of which imply I'm trying to copy the class rather than the instance). Anyone got any thoughts on this???? Phil From ian at emit.demon.co.uk Mon Feb 21 08:28:23 2005 From: ian at emit.demon.co.uk (Ian McConnell) Date: Mon, 21 Feb 2005 13:28:23 +0000 Subject: Tiled Image viewer Message-ID: <87vf8m11qg.fsf@emit.demon.co.uk> Does anyone know of a widget or sample code for viewing huge (ie bigger than RAM) images in python? The usual way of doing this is to read part of the image into memory as a set of tiles and then zoom and pan the tiles. The sort of thing I'm trying to achive is at http://iipimage.sourceforge.net/IIPDemo.html but I'd like to be able to do something like this with python (wxpython). The other problems are that I don't really want a client/server (just a single executable) and I have a funny image format (100s MB of matrix data) so making the image pyramids would be a little tricky. I've found Matt Kimballs pan and zoom widget http://web.archive.org/web/20030810111006/http://matt.kimball.net/image_view.html but this still reads the whole image into memory. Is there something similar to image_view.py, but which also does tiling? Thanks, Ian From s.varun at gmail.com Thu Feb 24 15:59:39 2005 From: s.varun at gmail.com (Varun) Date: 24 Feb 2005 12:59:39 -0800 Subject: Python Online Programming Contest Message-ID: <1109278779.955986.193860@z14g2000cwz.googlegroups.com> Hi Friends, Department of Information Technology, Madras Institute of Technology, Anna University, India is conducting a technical symposium, Samhita. As a part of samhita, an Online Programming Contest is scheduled on Sunday, 27 Feb 2005. This is the first Online Programming Contest in India to support Python !!!!. Other languages supported are C and C++. For Registration and Rules of the contest, http://www.samhita.info/opc For details about samhita http://www.samhita.info/ Regards, -Online Programming Contest team From tjprojects_usenet at yahoo.com Tue Feb 15 22:24:09 2005 From: tjprojects_usenet at yahoo.com (tjprojects_usenet at yahoo.com) Date: 15 Feb 2005 19:24:09 -0800 Subject: Loading functions from a file during run-time References: <1108091598.055004.24890@g14g2000cwa.googlegroups.com> Message-ID: <1108524249.604500.15300@o13g2000cwo.googlegroups.com> I have to say, I was skeptical about your execution method at first -- simply joining all of the lines and then compiling them. My understanding of the compile method from the documentation led me to believe that you needed to process a line at a time. ''.join ing them all seems to work very well, however, and it's a lot easier! My comments about 'exec obj in globals()' still stand, however. Give it a try and let me know if it works the way you expect. T.J. From ugny-0502 at unigroup.org Tue Feb 15 23:36:38 2005 From: ugny-0502 at unigroup.org (Unigroup of New York) Date: Tue, 15 Feb 2005 23:36:38 -0500 Subject: LOCAL NYC - UNIGROUP 17-FEB-2005 (Thurs): ZOPE - Open Source Web Development Message-ID: <4212CDD6.ABAF0D29@unigroup.org> -------------- next part -------------- Subject: LOCAL NYC - UNIGROUP 17-FEB-2005 (Thurs): ZOPE - Open Source Web Development Unigroup's February 2005 meeting is THIS Thursday... ===================================================================== UNIGROUP OF NEW YORK - UNIX USERS GROUP - FEBRUARY 2005 ANNOUNCEMENTS ===================================================================== ----------------------------------------------------- 1. UNIGROUP'S FEBRUARY 2005 GENERAL MEETING ANNOUNCEMENT ----------------------------------------------------- When: THURSDAY, February 17th, 2005 (3rd Thursday) Where: Alliance for Downtown NY Conference Facility Downtown Center 104 Washington Street South West Corner of Wall Street Area Downtown, New York City ** Please RSVP (not mandatory) ** Time: 6:15 PM - 6:25 PM Registration 6:25 PM - 6:45 PM Ask the Wizard, Questions, Answers and Current Events 6:45 PM - 7:00 PM Unigroup Business and Announcements 7:00 PM - 9:30 PM Main Presentation ----------------------------------------------- Topic: ZOPE - An Open Source Web Development Framework ----------------------------------------------- Speakers: Rob Page, CEO and President, Zope Corporation INTRODUCTIONS: -------------- Please keep an eye out for a series of _MONTHLY_ meetings which we have confirmed for February, March and April 2005. The meeting schedule is posted below (all on the 3rd Thursday). We are finally holding our meeting on Web Development and Zope! This meeting was supposed to be a followup our meeting on Python (March 2003), but it wound up being delayed for various reasons and due to various events (including things like the Solaris 10 launch). During this time, our friends at Zope Corporation have been patient, and they have been waiting for the chance to present Zope to Unigroup. We do appreciate their support! I've called Zope a "Web Development Framework", but from what I've read, it may be much more than this (see below). Major corporations are using Zope to build web sites and bring content to market. One such example is Computer Associates... see their press release about CA and Zope Corp: http://www3.ca.com/Press/PressRelease.asp?CID=59297 Also note that we expect to have CA present to Unigroup, later in the year, and they were also invited to participate in this week's Zope meeting. ------------------------------------------------------------------- SPECIAL INSTRUCTIONS: --------------------- To REGISTER for this event, please RSVP by using the Unigroup Registration Page: http://www.unigroup.org/unigroup-rsvp.html This will allow us to automate the registration process. (Registration will also add you to our mailing list.) Please continue to check the Unigroup web site and meeting page, for any last minute updates concerning this meeting. If you registered for this meeting, please check your email for any last minute announcements as the meeting approaches. Please try to RSVP as soon as possible. Note: RSVP is not mandatory for this location, but it does help us to properly plan the meeting (food, drinks, handouts, seating, etc.). ------------------------------------------------------------------- OUTLINE OF THE MAIN PRESENTATION: --------------------------------- This month's meeting will be a presentation on ZOPE: - What is Zope? - Who uses the platform? - What is possible with the platform? - The Zope Community and Activities (e.g., Sprints) - Platform Futures The Zope Software System: ------------------------- (Extracted from http://www.zope.com/Corporate/CompanyProfile.html) Zope is a unique software system: a high-performance application server, a web server, and a content management system. It is a complete, self-contained solution, that includes a robust, scalable object database, web services architecture, and powerful programming capabilities. It is designed for customization and extensibility. Its components integrate tightly with a wide range of leading web server and database systems. Zope promotes rapid creation and deployment of complex applications, totally manageable through a web interface. All of this, and complete open source access, are provided without cost. There are no licensing or runtime fees for the software. What Is Zope? ------------- (Extracted from http://www.zope.org/WhatIsZope) Zope is an open source web application server primarily written in the Python programming language. It features a transactional object database which can store not only content and custom data, but also dynamic HTML templates, scripts, a search engine, and relational database (RDBMS) connections and code. It features a strong through-the-web development model, allowing you to update your web site from anywhere in the world. To allow for this, Zope also features a tightly integrated security model. Built around the concept of "safe delegation of control", Zope's security architecture also allows you to turn control over parts of a web site to other organizations or individuals. The transactional model applies not only to Zope's object database, but to many relational database connectors as well, allowing for strong data integrity. This transaction model happens automatically, ensuring that all data is successfully stored in connected data sources by the time a response is returned to a web browser or other client. There are numerous products (plug-in Zope components) available for download to extend the basic set of site building tools. These products include new content objects; relational database and other external data source connectors; advanced content management tools; and full applications for e-commerce, content and document management, or bug and issue tracking. Zope includes its own HTTP, FTP, WebDAV, and XML-RPC serving capabilities, but can also be used with the Apache or other web servers. ------------------------------------------------------------------- Web Resources: -------------- Zope Corporation http://www.zope.com Zope Open Source Community http://www.zope.com/Services/Community.html Zope Community http://www.zope.org Zope Developer Community http://dev.zope.org Zope Powered Sites http://www.zope.org/Resources/ZopePowered ------------------------------------------------------------------- Speaker Biography: ------------------ (Extracted from http://www.zope.com/Corporate/Management/Page.html) Rob Page, Chief Executive Officer & President, Zope Corporation: Rob Page provides leadership and vision, directing corporate operations, professional services, product development and sales. He is involved in all aspects of company strategy, client services and quality assurance. Prior to co-founding Zope Corporation in 1995, he co-founded Connecting Minds, a consultancy firm. He also served for nine years in the Marine Corps and Marine Corps Reserve as a data systems officer. Rob earned his B.S. in Aerospace Engineering from the University of Florida. Company Biography: ------------------ (Extracted from http://www.zope.com/Corporate/CompanyProfile.html) Zope Corporation uses Zope Software to create high-end custom solutions with unparalleled time to market. The company generates revenue by offering Zope-based products, content management solutions through consulting services, support and training. Building on the open source model, customers are freed of vendor dependence because they have the source code of their product / custom solution. ------------------------------------------------------------------- Giveaways: ---------- O'Reilly has been kind enough to provide us with some of their books, which we will continue to raffle off as giveaways at our meetings. Addison-Wesley Professional/Prentice Hall PTR has been kind enough to provide us with some of their books, which we will continue to raffle off as giveaways at our meetings. Unigroup would like to thank both companies for the support provided by their User Group programs. Note: The chances tend to be about 1 in 5, that any attendee of our meeting will walk away with a fairly valuable giveaway (ie. most books are valued between $30 and $60)! ------------------------------------------------------------------- Fee Schedule: Yearly Membership (includes all meetings): $ 50.00 Non-Member Single Meeting: $ 20.00 Student Yearly Membership: $ 20.00 Non-Member Student Single Meeting (with ID): $ 5.00 Payment Methods: Cash, Check, American Express. ------------------------------------------------------------------- Complimentary Food and Refreshments will be served. This includes sandwiches such as Turkey, Chicken, Tuna and Grilled Vegetables, as well as Assorted Salads (Cole Slaw, Potato, Tossed, Caesar, Pasta), Cookies/Brownies, Bottled Water and Assorted Beverages. ------------------------------------------------------------------- Directions: Alliance for Downtown NY Conference Facility Downtown Center 104 Washington Street Wall Street Area Downtown, New York City This building is located on the West side of the street, the second building north of Rector Street. Cross Streets: Between Rector (South) and Carlisle (North) Streets. Enter the lobby, and tell the guard at the desk that you are heading for Unigroup. You will be directed to the meeting room. Our meeting location is in the Lower West Corner of Downtown, North of the Battery Tunnel, South of the Downtown Hotel, East of West Street, and West of Greenwich Street. Walking West on Rector Street from Broadway, you pass Church, Greenwich then Washington Streets. There are multiple blocks of parking lots right there, between Washington and Greenwich Streets, starting at the Battery Tunnel and extending North for a number of blocks. Nearest mass transit stations, in order, are the '1/9' (Rector Street), 'R/W' (Rector Street) and the '4/5' (Wall Street). ----- Please mark this meeting on your calendar and join us! Please tell your friends about Unigroup! ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ----------------- 2. UPCOMING MEETINGS ----------------- We have a series of meetings in the works: - 17-FEB-2005 : Zope / Web Page Development Rob Page / Zope Corporation - 17-MAR-2005 : Solaris 10 Part 2 Field Trip to Sun Microsystems - 21-APR-2005 : AFS and OpenAFS Jeff Altman / Secure Endpoints - IPsec - Samba - Field Trip to HP - Invited - Field Trip to CA - Invited - Unix 35th Birthday Celebration - DNS - Unix Clusters and Clustered Databases - Linux Clustering Part 3: Beowulf version 2 - Building a Firewall using FreeBSD and Linux - High Performance Internet Servers / Web Acceleration - Unix Office Tools: Word Processors, Spreadsheets, Accounting Packages. - PKI - GNU Development Environments - iSCSI, Serial ATA, and other new peripheral technologies Please let us know about any other meeting topics that you may be interested in. Potential speakers on Unix related technology topics should contact the Unigroup board at ugny-0502 at unigroup.org. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ I hope to see you all at our next meeting! -Rob Weiner Unigroup Executive Director ugny-0502 at unigroup.org http://www.unigroup.org From steve at holdenweb.com Thu Feb 3 13:40:53 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Feb 2005 13:40:53 -0500 Subject: About standard library improvement In-Reply-To: References: Message-ID: <4kuMd.102708$Jk5.100022@lakeread01> Frank Abel Cancio Bello wrote: > Hi! > If I make some improvement to xmlrpclib module, where I should send this > improvement to form part of next standard library release? > > Thank > > > > Well done! The standard place to lodge patches (whether for bug fixes or improvements) is SourceForge. You'll need an account to submit patches or bugs, IIRC. Once you've created your account, log in and go to http://sourceforge.net/tracker/?group_id=5470&atid=305470 and click "Submit New". regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From cam.ac.uk at mh391.invalid Tue Feb 8 11:28:42 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 08 Feb 2005 16:28:42 +0000 Subject: Efficient checksum calculating on lagre files In-Reply-To: References: <5o2nd2-5hl.ln1@pluto.i.infosense.no> Message-ID: Michael Hoffman wrote: > Is there a reason you can't use the sha module? BTW, I'm using SHA-1 instead of MD5 because of the reported vulnerabilities in MD5, which may not be important for your application, but I consider it best to just avoid MD5 entirely in the future. -- Michael Hoffman From fredrik at pythonware.com Tue Feb 8 16:59:26 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Feb 2005 22:59:26 +0100 Subject: Loop in list. References: <1107874174.445345.41230@c13g2000cwb.googlegroups.com> <3e8ca5c805020813074e975a4d@mail.gmail.com> Message-ID: Stephen Thorne wrote: >> '>>> a = [i*2*b for i in range(3) for b in range(4)] >> '>>> a >> [0, 0, 0, 0, 0, 2, 4, 6, 0, 4, 8, 12] >> >> Might take you a while to correlate the answer with the loop, but you >> should be able to see after a while that this nesting is the same as >> >> '>>> a = [] >> '>>> for b in range(4): >> '>>> for i in range(3): >> '>>> a.append(i*2*b) > > There is a subtle error in this explanation. if you run the example, you'll notice that it's not so subtle. read on. > The equivilence actually looks like: > > '> a = [] > '> l1 = range(4) > '> l2 = range(3) > '> for b in l1: > '> for i in l2: > '> a.append(i*2*b) really? def myrange(x): print "RANGE", x return range(x) print [i*2*b for i in myrange(3) for b in myrange(4)] a = [] for b in myrange(4): for i in myrange(3): a.append(i*2*b) print a a = [] l1 = myrange(4) l2 = myrange(3) for b in l1: for i in l2: a.append(i*2*b) print a prints RANGE 3 RANGE 4 RANGE 4 RANGE 4 [0, 0, 0, 0, 0, 2, 4, 6, 0, 4, 8, 12] RANGE 4 RANGE 3 RANGE 3 RANGE 3 RANGE 3 [0, 0, 0, 0, 2, 4, 0, 4, 8, 0, 6, 12] RANGE 4 RANGE 3 [0, 0, 0, 0, 2, 4, 0, 4, 8, 0, 6, 12] (to translate a list comprehension to nested statements, remove the result expression, insert colons and newlines between the for/if statement parts, and put the append(result expression) part inside the innermost statement) From python-url at phaseit.net Wed Feb 9 05:22:55 2005 From: python-url at phaseit.net (Craig Ringer) Date: Wed, 09 Feb 2005 10:22:55 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Feb 9) Message-ID: QOTW: "Such infrastructure building is in fact fun and instructive -- as long as you don't fall into the trap of *using* such complications in production code, where Python's simplicity rules;-)." -- Alex Martelli http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/41a6c0e1e260cd72/ "C++ to Python is a steep 'unlearning' curve..." -- Philip Smith "URK -- _my_ feeling is that we have entirely *too many* options for stuff like web application frameworks, GUI toolkits, XML processing, ..." -- Alex Martelli http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a9bdc98acb5acae4/ "We should concentrate on *real* problems, ones that exist in real code, not ones that mostly exist in wild-eyed prose that consists of predictions of pain and death that conspicuously fail to occur, no matter how many times they are repeated or we are exhorted to heed them or face our doom." -- Jeremy Bowers http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a75da70b0845b6fe/ Special thanks this week to Dean Goodmanson for his help identifying several items. The Online Computer Library Center contest is open. It closes May 15. Among the usual C++ and Java languages, Python also is available for selection: http://www.oclc.org/research/researchworks/contest/default.htm#guidelines Baoqui Chi runs into a documented, but easily overlooked, trap in the handling of __del__ methods and receives good advice on better fixes: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/13ec343eb0a37247/ Steve Holden explains how to think about bytecode management: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/59c0466111b075b8/ in a conversation aimed at Pyro improvement. Michael Tobis sparks off a discussion on the underlying nature of generators and offers a caution on jumping to conclusions about the writings of non-native English speakers: http://mail.python.org/pipermail/python-list/2005-January/263448.html Derek finds out that the Python interpereter is smarter about finding resources than it lets on: http://mail.python.org/pipermail/python-list/2005-January/263473.html irc.freenode.net #python is overcrowded: the entrance now routes to #python-cleese or #python-gilliam: http://divmod.org/users/washort/python-split.htmlmklm Steve Holden provides an evocative illustration that the rules are there for a reason, even if breaking them doesn't hit you (*ahem*) immediately: http://mail.python.org/pipermail/python-list/2005-February/263851.html In response to a question about rewriting exceptions to include more information, Stefan Behnel gets a couple of rather useful answers: http://mail.python.org/pipermail/python-list/2005-February/263843.html Netcraft Reports 33K Zope servers in January, 55K in February! http://mail.zope.org/pipermail/zope-announce/2005-February/001651.html Joakim Stork discovers that thanks to classes being first class objects in Python, sometimes the best solution is so simple it's often possible to miss it entirely: http://mail.python.org/pipermail/python-list/2005-February/263891.html Someone posts an interesting attempt at a cross-platform way to discover the user's home directory: http://mail.python.org/pipermail/python-list/2005-February/263921.html Metaclasses are handy things. Steven Bethard demonstrates a nice simple use case: http://mail.python.org/pipermail/python-list/2005-February/264037.html As John Machin demonstrates, generating SQL in Python doesn't have to be ugly: http://mail.python.org/pipermail/python-list/2005-February/264248.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. 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 Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson 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/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. deli.cio.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/topics/pythonurl/ 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 Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From steven.bethard at gmail.com Sun Feb 6 14:44:01 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 06 Feb 2005 12:44:01 -0700 Subject: Multiple constructors In-Reply-To: <1grk3du.3zpb0h62fjd1N%aleaxit@yahoo.com> References: <6SjNd.38337$K7.21639@fe2.news.blueyonder.co.uk> <1grk3du.3zpb0h62fjd1N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > If you want to do this > all the time, you could even build appropriate infrastructure for this > task -- a little custom descriptor and metaclass, and/or decorators. > Such infrastructure building is in fact fun and instructive -- as long > as you don't fall into the trap of *using* such complications in > production code, where Python's simplicity rules;-). +1 QOTW. I think this is one of the "great truths" of Python. Descriptors, metaclasses, decorators, etc. are all there to let you do interesting, useful things. But if you're using such constructs for more than a few special cases, then you're missing out on a simple solution that Python, almost certainly, makes beautiful. Steve From ug at algonet.se Wed Feb 23 11:11:13 2005 From: ug at algonet.se (=?ISO-8859-1?Q?Ulf_G=F6ransson?=) Date: Wed, 23 Feb 2005 17:11:13 +0100 Subject: Fonts and PIL In-Reply-To: References: Message-ID: Greg Lindstrom wrote: > I'm running Python 2.3 on a windows box and would like to use PIL to > superimpose text over an existing pgn image. I have no problem getting > the text on the image but can not figure out how to manage fonts. How > to set the font style and size. From reading the archives I surmise > that I want to work with *.pil files. I've searched my box for the font > files but did not find them. I've googled for information on pil font > files and it appears to be involved with Zope. So, can any of you > honcho-level types help me out? How can I set font size and style in my > PIL application? Pick a nice .ttf file and load it with ImageFont.truetype(). /ug From tim.golden at viacom-outdoor.co.uk Mon Feb 14 03:21:22 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 14 Feb 2005 08:21:22 -0000 Subject: connecting to Sybase/MsSQL from python Message-ID: <9A28C052FF32734DACB0A288A3533991035AE0@vogbs009.gb.vo.local> [Ed Leafe] | Has anyone ever used this product: | http://www.object-craft.com.au/projects/mssql/ | | Any feedback, positive or negative? I have, pretty much constantly, for the last three years with no significant issues at all. I use it on Win32 boxes, although I have had it running under Linux -- don't remember how I got it to compile, unfortunately. Only slight issuettes are: it doesn't handle all the datatypes (eg IMAGE and some others I don't remember); as advertised, the callproc doesn't work on win32, but it's easy enough for most purposes to do a cursor.execute ("EXECUTE pr_...") although you won't get a return code that way. All in all, I'm a very happy customer. From time to time I've dabbled with other ways of accessing MSSQL - ADO, PyMSSQL, etc. but none has offered me anything I couldn't get from the Object Craft module. 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 exogen at gmail.com Thu Feb 17 11:24:23 2005 From: exogen at gmail.com (Brian Beck) Date: Thu, 17 Feb 2005 11:24:23 -0500 Subject: Getting milliseconds in Python In-Reply-To: <87d5uzyx39.fsf@gmail.com> References: <1108565135.167562.196830@z14g2000cwz.googlegroups.com> <37h5epF5ck38lU2@individual.net> <1108571009.698970.152020@z14g2000cwz.googlegroups.com> <87d5uzyx39.fsf@gmail.com> Message-ID: Martin Christensen wrote: > A math teacher! A math teacher! My kingdom for a math teacher! > > Martin Man, this is the hottest topic on c.l.py since that Lazaridis guy... -- Brian Beck Adventurer of the First Order From francis.girard at free.fr Tue Feb 1 15:47:07 2005 From: francis.girard at free.fr (Francis Girard) Date: Tue, 1 Feb 2005 21:47:07 +0100 Subject: Next step after pychecker [StarKiller?] In-Reply-To: References: <41ff0308$0$6503$636a15ce@news.free.fr> Message-ID: <200502012147.07153.francis.girard@free.fr> Hi, Do you have some more pointers to the StarKiller project ? According to the paper some implementation of this very interesting project exists. Thank you Francis Girard Le mardi 1 F?vrier 2005 11:21, Sylvain Thenault a ?crit?: > On Tue, 01 Feb 2005 05:18:12 +0100, Philippe Fremy wrote: > > Hi, > > Hi > > > I would like to develop a tool that goes one step further than pychecker > > to ensure python program validity. The idea would be to get close to what > > people get on ocaml: a static verification of all types of the program, > > without any kind of variable declaration. This would definitely brings a > > lot of power to python. > > > > The idea is to analyse the whole program, identify constraints on > > function arguments and check that these constraints are verified by other > > parts of the program. > > Did you take a look at the starkiller [1] and pypy projects [2] ? > > > What is in your opinion the best tool to achieve this ? I had an > > extensive look at pychecker, and it could certainly be extended to do > > the job. Things that still concern me are that it works on the bytecode, > > which prevents it from working with jython and the new .NET python. > > > > I am currently reading the documentation on AST and visitor, but I am > > not sure that this will be the best tool either. The AST seems quite > > deep and I am afraid that it will make the analysis quite slow and > > complicated. > > are you talking about the ast returned by the "parser" module, or the ast > from the "compiler" module ? The former is a higher abstraction, using > specific class instances in the tree, and most importantly with all the > parsing junk removed. See [3]. You may also be interested in pylint > [4] which is a pychecker like program built in top of the compiler ast, > and so doesn't require actual import of the analyzed code. However it's > not yet as advanced as pychecker regarding bug detection. > > And finally as another poster said you should probably keep an eye open > on the python 2.5 ast branch work... > > Hope that helps ! > > [1]http://www.python.org/pycon/dc2004/papers/1/paper.pdf) > [2]http://codespeak.net/pypy/index.cgi?home > [3]http://www.python.org/doc/current/lib/module-compiler.ast.html > [4]http://www.logilab.org/projects/pylint > > -- > Sylvain Th?nault LOGILAB, Paris (France). > > http://www.logilab.com http://www.logilab.fr http://www.logilab.org From eliediamonds at gmail.com Fri Feb 11 12:51:54 2005 From: eliediamonds at gmail.com (eliediamonds at gmail.com) Date: 11 Feb 2005 09:51:54 -0800 Subject: Partnership Opportunity Message-ID: <1108144314.761060.34690@g14g2000cwa.googlegroups.com> Partnership Opportunity Hello, I am with a manufacturer of fine jewelry and am currently looking for those interested in forming a partnership to sell jewelry on eBay or anywhere else. I work for Elie International, a manufacturer of fine jewelry located in the heart of the diamond district in New York City. We have been in the jewelry business for over 23 years and are registered with the Jewelers Board of Trade (JBT registration # 01222207) and Dunne & Bradstreet. For the first time in our company's history we are looking to build partnerships with individual sellers. We hold an extensive stock of over 24,000 items and need vendors to keep it moving. By selling our merchandise on eBay, or to family and friends, we become your partner not your competitor and offer you fine jewelry at wholesale prices which are a FRACTION of what YOUR CUSTOMERS pay in retail stores. We understand that many buyers are apprehensive about paying for merchandise up front, and we have devised our Direct Purchase Partnership program with these concerns in mind. Our Guaranteed Movers Policy states that if you cannot sell one of our items within 6 months we will exchange it. This insures that you are never stuck with merchandise you can't sell. We want to strongly emphasize that this is a partnership and we offer our partners the full support that they need, including pictures, prices and descriptions of all merchandise to get them started. Please contact us via e-mail at elieint at aol.com or at (212) 719-0090 if you are interested or have any questions and please include where you saw this message. Thank You From dbickett at gmail.com Thu Feb 3 22:52:22 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Thu, 3 Feb 2005 22:52:22 -0500 Subject: Possible additions to the standard library? (WAS: About standard library improvement) In-Reply-To: References: Message-ID: <1d6cdae3050203195251843db2@mail.gmail.com> I was reading the thread by Frank Bello[1] about his offered addition to the xmlrpclib module, and it reminded me of a few methods I had made in the past that I considered worthy of being a part of the standard library. Rather than reiterate his question of how one gets one's patch into the standard library -- as I can simply read the answers from his thread -- I am posting here asking the opinion of the Python community as to whether *you* consider these worthy of standard library implementation. The first one is a function I made for the _winreg module[2]. The commentary, I think, explains what it does and why it had to be written very clearly, so I'll just copy and paste it:[3] |def DeleteKeyAll( key , subKey ): | """ | Since DeleteKey() can't remove keys that contain subkeys, this serves | to iterate through a key and delete every single subkey, and then the | key itself. | | Note: This function assumes that _winreg has been imported using: | from _winreg import * | It can be easily converted by simply prepending all of the | applicable statements with `_winreg.' if you have imported | it otherwise. | """ | # try to open the specified key | try: | handle = OpenKey( key , subKey ) | except EnvironmentError: | return False | # now, iterate through the subkeys and remove | # each of them (recursively) | while True: | nextKey = QueryInfoKey( handle )[0] | if not nextKey: | # if there aren't any more subkeys, delete the key at hand | try: | DeleteKey( key , subKey ) | return True | except EnvironmentError: | break | else: | # otherwise, recursively delete the subkeys | DeleteKeyAll( key , subKey + "\\" + EnumKey( handle , 0 ) ) These next two are methods that I've applied to my own version of the string object from time to time: |class newstring( str ): | def setreplace( self , set ): | """ | Do multiple replaces at once, using dictionary `set' as a legend, | where each instance of each key is to be replaced with that key's | value. | """ | if type( set ) == dict: | result = self.__str__() | for key, value in set.iteritems(): | if type( key ) == str and type( key ) == str: | result = result.replace( key , value ) | else: | raise TypeError, "All items of parameter set must be strings" | return result | else: | raise TypeError, "Parameter set must be a dictionary" | | def reverse( self ): | """ | Return a reversed copy of string. | """ | string = [ x for x in self.__str__() ] | string.reverse() | return ''.join( string ) In action: >>> string = newstring("foo bar") >>> string.reverse() 'rab oof' >>> string.setreplace( { 'f' : 'b' , 'a' : 'o' } ) 'boo bor' I actually went on to write a method that reversed an integer (inspired by an SAT question -- I had time to kill) using the newstring's reverse() method, but it's hard enough justifying having a string reverse method (though not impossible,) let alone an integer reverse method, so I left that one on my hard drive :) One more thing worth noting is that I'm not educated in the ways of standard library etiquette, so I was more or less going out on the limb doing type-checking in setreplace(). For all I know that's some sort of paradox and you're supposed to let the user feel the pain, but I did what I felt was right at the time. This is basically all about commentary and criticism, and your opinion of whether or not these deserve to be added to the library (or rather, added as a patch, I presume). Thank you all for your time :) P.S.: I have included all of the methods in this post for the sake of accessibility, and i have preceded all of the code with `|' because I am unaware of the status of google's whitespace problem. If you want to more easily copy and paste this code, I have posted it on nopaste: DeleteKeyAll: http://rafb.net/paste/results/Yh6x0598.html newstring methods: http://rafb.net/paste/results/O51kja41.html NOTES: [1] http://tinyurl.com/4dkgw [2] I'm currently unaware if _winreg is a c extension module or pure python, but I'm assuming it's C, so I don't know how possible it is to add pure python to it... [3] I made a few quick edits after I pasted it in, so please bring to my attention any errors or inconsistencies you see -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From km at mrna.tn.nic.in Sun Feb 6 12:39:29 2005 From: km at mrna.tn.nic.in (km) Date: Sun, 6 Feb 2005 23:09:29 +0530 Subject: IPython colors in windows In-Reply-To: <1107530489.308497.103530@g14g2000cwa.googlegroups.com> References: <36hculF51ho2sU1@individual.net> <1107530489.308497.103530@g14g2000cwa.googlegroups.com> Message-ID: <20050206173929.GA3319@mrna.tn.nic.in> Hi all, Have u tried Colors0.1 module from python.org ? KM -------------------------------------------------------------------- On Fri, Feb 04, 2005 at 07:21:29AM -0800, Fuzzyman wrote: > Are you really using the readline module from newcenturycomputers ? > I've got a feeling that's broken and you need to use the Gary Bishop > one with IPython.... > > Sorry if this is spurious... (restricted internet access, so I can't > check for you... but the correct one is linked to from the IPython > site). > > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml > > Claudio Grondi wrote: > > Hi, > > > > I have watched this thread hoping to get an > > hint on my problem, but it seems I didn't. > > > > My problem is, that the background of part of > > the error messages is always black > > (e.g. after typing In [1]: sdfsdf) > > and my monitor failes to show the red, green > > texts on black background clearly enough > > to see it (I can read it after selection, which > > inverts the colors). > > I have tried to play with PyColorize.py, > > LightBGColors = ColorScheme( > > 'LightBG',{ > > token.NUMBER : Colors.Cyan, > > token.OP : Colors.Blue, > > token.STRING : Colors.Blue, > > tokenize.COMMENT : Colors.Red, > > token.NAME : Colors.White, # Colors.Black, > > token.ERRORTOKEN : Colors.Red, > > > > _KEYWORD : Colors.Green, > > _TEXT : Colors.Blue, > > > > 'normal' : Colors.White # Colors.Normal # color off > (usu. > > Colors.Normal) > > } > > but without success. > > How can I get rid of the black background > > > "--------------------------------------------------------------------------- > > " > > "exceptions.NameError" Traceback > (most > > recent call last) > > in with quotation marks marked areas? > > Where is the color of the background of this > > areas defined? > > The color scheme seems to handle only the > > text colors, not the background. > > > > Claudio > > > > "Ashot" schrieb im Newsbeitrag > > news:opsln54fpwej1m1c at ashot... > > > yea, I've done that. It must be something subtle, as the colors and > tab > > > completion works. > > > On Thu, 03 Feb 2005 20:31:37 -0800, DogWalker > > > wrote: > > > > > > > "Ashot" said: > > > > > > > >> On 3 Feb 2005 19:18:33 -0800, James wrote: > > > >> > > > >>> > > > >>> Ashot wrote: > > > >>>> I am using IPython in windows and the LightBG setting doesn't > > > >>> correctly > > > >>>> because the background of the text is black even if the > console > > > >>> background > > > >>>> is white. Anyone know whats going on? Thanks. > > > >>>> > > > >>>> -- > > > >>>> ============================== > > > >>>> Ashot Petrosian > > > >>>> University of Texas at Austin, Computer Sciences > > > >>>> (views expressed are solely my own) > > > >>>> ============================== > > > >>> > > > >>> Did you try installing readline for windows? > > > >>> http://newcenturycomputers.net/projects/readline.html > > > >>> > > > >> > > > >> yea I've installed that and ctypes. The color and tab > completion work, > > > >> its just that colored get displayed with black background, it > almost > > > >> works > > > >> so its very frustrating.. > > > >> > > > > > > > > Did you try the following (from the manual)?: > > > > > > > > Input/Output prompts and exception tracebacks > > > > > > > > > > > > You can test whether the colored prompts and tracebacks work on > your > > > > system interactively by typing '%colors Linux' at the prompt (use > > > > '%colors LightBG' if your terminal has a light background). If > the input > > > > prompt shows garbage like: > > > > [0;32mIn [[1;32m1[0;32m]: [0;00m > > > > instead of (in color) something like: > > > > In [1]: > > > > this means that your terminal doesn't properly handle color > escape > > > > sequences. You can go to a 'no color' mode by typing '%colors > NoColor'. > > > > > > > > > > > > You can try using a different terminal emulator program. To > > > > permanently set your color preferences, edit the file > > > > $HOME/.ipython/ipythonrc and set the colors option to the desired > value. > > > > > > > > > > > > -- > > > ============================== > > > Ashot Petrosian > > > University of Texas at Austin, Computer Sciences > > > (views expressed are solely my own) > > > ============================== > > -- > http://mail.python.org/mailman/listinfo/python-list -- From trial at ugyvitelszolgaltato.hu Fri Feb 25 08:33:55 2005 From: trial at ugyvitelszolgaltato.hu (Attila Szabo) Date: Fri, 25 Feb 2005 14:33:55 +0100 Subject: strange SyntaxError Message-ID: <20050225133355.GI20239@csola.ugyvitelszolgaltato.hu> Hi, I wrote this sample piece of code: def main(): lambda x: 'ABC%s' % str(x) for k in range(2): exec('print %s' % k) main() With the lambda line, I get this: SyntaxError: unqualified exec is not allowed in function 'main' it contains a nested function with free variables Without the lambda, it's ok... What's this ? thanks -- A t t i l a :: trial at ugyvitelszolgaltato.hu :: S z a b o From steve at holdenweb.com Thu Feb 3 17:17:51 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Feb 2005 17:17:51 -0500 Subject: List mapping question In-Reply-To: References: Message-ID: Marc Huffnagle wrote: > I have a number of variables that I want to modify (a bunch of strings > that I need to convert into ints). Is there an easy way to do that > other than saying: > > > a = int(a) > > b = int(b) > > c = int(c) > > I tried > > > [i = int(i) for i in [a, b, c]] > > but that didn't work because it was creating a list with the values of > a, b and c instead of the actual variables themselves, then trying to > set a string equal to an integer, which it really didn't like. > > Marc >>> a,b,c = 1.1, 2.2, 3.3 >>> a,b,c = map(int, (a,b,c)) >>> a,b,c (1, 2, 3) >>> a,b,c = [int(x) for x in (a,b,c)] >>> a,b,c (1, 2, 3) regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From erikbethke at gmail.com Wed Feb 9 09:21:54 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 9 Feb 2005 06:21:54 -0800 Subject: Trouble with the encoding of os.getcwd() in Korean Windows In-Reply-To: <1107956992.350460.12720@f14g2000cwb.googlegroups.com> References: <1107953764.478501.176650@c13g2000cwb.googlegroups.com> <1107956992.350460.12720@f14g2000cwb.googlegroups.com> Message-ID: <1107958914.583017.79190@l41g2000cwc.googlegroups.com> Hello All, sorry for all the posts... I am *almost* there now... okay I have this code: import sys, os encoding = locale.getpreferredencoding() htmlpath = os.getcwd() htmlpath = htmlpath.decode( encoding ) ..... write to the file ..... ..... file is written fine, and can be opened by both FireFox and IE and displays fine ... webbrowser.open( htmlpath.encode ( encoding ), True, True ) the line above now works fine (fixed the ascii error) but *NOW* my problem is that FirefOX pops up a message box complaining that the file does not exist, but it certainly does, it just doesn't like what it is called... Any ideas now? Thanks, -Erik From littlejohn.75 at news.free.fr Tue Feb 1 07:08:15 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 01 Feb 2005 12:08:15 GMT Subject: Python's idiom for function overloads References: <41ff066c$0$6473$636a15ce@news.free.fr> <41ff63bb$0$21348$636a15ce@news.free.fr> Message-ID: <41ff712f$0$19558$636a15ce@news.free.fr> Le Tue, 01 Feb 2005 12:10:47 +0100, Philippe Fremy a ?crit : > >> Frequently, in Python, code which checks for types, rather than >> checking for features, ends up being excessively restrictive and >> insufficiently general. > snip > > Enforcing types also brings the benefit that the program is more > deterministic. In my experience, there is a lot more benefits to have an > object whose type is clearly identified than to have function that > accepts generic objects. If you insist to always have only clearly identified types of variables you will use the Hungarian notation : bool bIsDir = blah const char *lpszMessage = "It's a directory"; > > I would go as far as saying that variables should have immutable types. > It is more restricting that what python provides currently, but leads to > clearer programming practice: the intent of the developer shows up in > the type he uses. clearer programming practice which goes with unreadable code ? > > > While Python's dynamic typing liberty is enjoyable, I think it harms > when you start to work on big projects. It prevents you to put many > safety assumptions which might bite you back. Python is strongly typed (at run-time). You can get a traceback sure but it is rather difficult to get unreliable results. > > regards, > > Philippe From me at privacy.net Mon Feb 28 22:18:43 2005 From: me at privacy.net (Dan Sommers) Date: 28 Feb 2005 22:18:43 -0500 Subject: accessor/mutator functions References: Message-ID: On Tue, 01 Mar 2005 02:27:03 GMT, Andrew Dalke wrote: > Me: >>> What's wrong with the use of attributes in this case and how >>> would you write your interface? > Dan Sommers: >> I think I'd add a change_temperature_to method that accepts the target >> temperature and some sort of timing information, depending on how the >> rest of the program and/or thread is structured. > Hmmm. I wonder if this is mostly a question of how the process > decomposition occurs. I think in objects ("thingys with state") > whereas you think in tasks ("thingys that do stuff")? I say that > somewhat surprisingly in that I'm not a deep OO person - functions are > fine with me and I don't like the Java/Ruby "everything is in a class" > world view. I'm not an OO guy, either. Somewhere back in the mid 90's, I was dragged, kicking and screaming, into OO from the world of Structured Programming. You're right about my notion of an object: I think that if all you have is state information, then you just have a C struct and there's no point in doing OO. I still write plenty of (smallish) programs like that. >> It might turn into two or three methods, depending on whether I can >> afford to block while waiting, or what kind of intermediate feedback >> and/or error handling I want (or one method with some carefully >> chosen default arguments). > In the case I'm hypothesizing (haven't worked with a temperature > controller in about 15 years) it's hard to put a layer above > everything because there could be so many different protocols > (chemical protocols, not I/O ones) with different rates. Eg, it could > be an exponential decay, or step-wise approximation thereof. Yes, it would be difficult (and silly and a maintentance nightmare, too!) to put every protocol into the temerature controller. I think at that point, I'd put the protocols in a separate "layer," and I'd have to think carefully about that layer's interface to the temperature controller. My application would be that much farther from even having to know the current temperature, let alone access it directly from the TemperatureController object (although at some point, the application would probably end up displaying that current temperature, so it's not like everything is completely isolated from everything else). >> I don't know how that device driver works, but it might look something >> like this: >> >> def change_temperature_to( self, target, seconds_between_checks ): >> print 'target temperature:', target >> tell_the_device_to_change( ) >> while 1: >> current = read_the_temperature_from_the_device( ) >> print 'current temperature:', current >> if abs( current - target ) < 0.1: >> break >> time.sleep( seconds_between_checks ) > Your "tell_the_device_to_change" is my "self.target" and your > "read_the_temperature_from_the_device" is "self.current_temperature". > In some sense it comes down to style. My point was mostly that change_temerature_to would be a method of a TemperatureController object. "tell_the_device_to_change" is whatever method/function you have behind setting self.target. As you noted, I think of the temperature controller as being able to manage its own temperature rather than be a (thin) wrapper around a device driver. > BTW, had I done this for real I would have two layers, one which is > communications oriented ("send 'get current temperature' message to > device") and my object model which uses the messaging interface > underneath. That sounds about right. > I liked being able to say: > print atom.symbol, "with charge", atom.charge, "has", \ > len(atom.bonds), "bonds" > for i, bond in enumerate(bonds): > print "bond", i, "has type", bond.bondtype > To me this is a very natural way of querying the data and > traversing the data structure. > Now underneath the covers it looks like this: > atom.charge fails so use __getattr__(atom, "charge") > __getattr__ uses a dispatch table to get the underlying C function > which is "dt_getcharge" > return dt_getcharge(self.handle) > where "handle" is the handle used by the C library. > I figured though that this example might be more esoteric > than my PID controller example, though in retrospect it > looks like it might be a better justification. I like that kind of abstraction: the atom object hides the fact that the charge comes out of another layer/library/object entirely. Regards, Dan -- Dan Sommers ?? ? ?? ? c? = 1 From enrio at online.no Mon Feb 28 19:53:16 2005 From: enrio at online.no (enrio at online.no) Date: 28 Feb 2005 16:53:16 -0800 Subject: zlib.decompress cannot, gunzip can Message-ID: <1109638396.839493.50070@l41g2000cwc.googlegroups.com> I have a string which I try to decompress: body = zlib.decompress(body) but I get zlib.error: Error -3 while decompressing data: incorrect header check However, I can write the string to a file and run gunzip with the expected results: f = open('/tmp/bd.gz', 'w') f.write(body) f.close ... $ gunzip bd.gz $ less bd What should I do to decompress it in Python? Regards, Enrique From nhodgson at bigpond.net.au Tue Feb 15 05:20:32 2005 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 15 Feb 2005 10:20:32 GMT Subject: os.rename() doesn't work w/unicode?? References: Message-ID: fanbanlo: > The filename is supposed to be in Chinese, on NTFS (WinXP). However, > when i print it, they are all '???', and that caused os.rename() to break. > > How to force os.walk to return a list of unicode filename? The convention in the unicode file name support is that calls with unicode arguments return unicode results: >>> h = "e:\\unicode" >>> import os >>> for p,d,f in os.walk(h): ... print p, "!", d, "!", f ... e:\unicode ! [] ! ['ko.py', 'abc', 'ascii', 'Gr\xfc\xdf-Gott', 'uni.py', 'Ge??-sa?', '????????????', '??????', '???', '????G\xdf', '???', 'unilin.py'] >>> for p,d,f in os.walk(unicode(h, "latin1")): ... print p, "!", d, "!", f ... e:\unicode ! [] ! [u'ko.py', u'abc', u'ascii', u'Gr\xfc\xdf-Gott', u'uni.py', u'\u0393\u03b5\u03b9\u03ac-\u03c3\u03b1\u03c2', u'\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439\u0442\u0435', u'\u05d4\u05e9\u05e7\u05e6\u05e5\u05e1', u'\u306b\u307d\u3093', u'\u66e8\u05e9\u3093\u0434\u0393\xdf', u'\u66e8\u66e9\u66eb', u'unilin.py'] Neil From steven.bethard at gmail.com Thu Feb 3 16:10:08 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 03 Feb 2005 14:10:08 -0700 Subject: Basic file operation questions In-Reply-To: References: <1107379669.870799.256030@g14g2000cwa.googlegroups.com> Message-ID: Caleb Hattingh wrote: > Peter > >> Yes, you can even write >> >> f = open("data.txt") >> for line in f: >> # do stuff with line >> f.close() >> >> This has the additional benefit of not slurping in the entire file at >> once. > > Is there disk access on every iteration? I'm guessing yes? It > shouldn't be an issue in the vast majority of cases, but I'm naturally > curious :) Short answer: No, it's buffered. Long answer: This buffer is actually what causes the problems in interactions between uses of the next method and readline, seek, etc: py> f = file('temp.txt') py> for line in f: ... print line, ... break ... line 1 py> f.read() '' py> for line in f: ... print line, ... line 2 line 3 Using the iteration protocol (specificaly, when file.next is called) causes the file object to read part of the file into a buffer for the iterator. The read method doesn't access the same buffer, and sees that (because the file is so small) we've already seeked to the end of the file, so it returns '' to signal that the entire file has been read, even though we have not finished iterating. The iterator however, which has access to the buffer, can still complete its iteration. The moral of the story is that, in general, you should only use the file as an iterator after you are done calling read, readline, etc. unless you want to keep track of the file position and do an appropriate file.seek() call after each use of the iterator. Steve From ilias at lazaridis.com Sat Feb 19 13:59:31 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sat, 19 Feb 2005 20:59:31 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <42172136$0$27576$9b622d9e@news.freenet.de> Message-ID: Diez B. Roggisch wrote: >>Thank you for the links. >> >>They are irrelevant for me. > > As usual. sorry. >>>Just out of curiousity: How many python extensions are you planning to >>>write? >> >>I estimate 10 to 100, depending on abstractional capabilities of the >>extension system. >> >>>And how many lines of pure python code have you written in your life? >> >>0 (zero). > > Awesome. Without any lines of code written, you have already identified the > areas where python lacks features that have to be overcome with C-written > extensions. writing code is not the only way. > As usual, I stand with my mouth agape over your near-psychic > abilities to analyze even the complexest matters without any actual > fiddling with the nitty gritty details. Nothing special. Abstraction, Generalization, Inhibition. > The day where you team up with Uri Geller - who will make even the worst > code running by just putting a printout of it on top of an image of the > master himself - is to be feared by all of us humble developers who > actually _deal_ with problems. Don't worry. Mr. Geller will be shortly hired by Sun Microsystems. . -- http://lazaridis.com From fuzzyman at gmail.com Thu Feb 10 06:04:14 2005 From: fuzzyman at gmail.com (fuzzyman at gmail.com) Date: 10 Feb 2005 03:04:14 -0800 Subject: [ANN] Movable Python 0.4.6 Message-ID: A new release of Movable Python is available - 0.4.6 This fixes a few issues including a bug in the Python 2.2 support, and a fix for a psyco/IPython incompatibility issue. We have a new icon and logo thanks to Aidan Ashby - http://aidan.voidspace.org.uk Due to bugfixes (in movpy) we can now offer a prebuilt environment for Python 2.2 that includes wxPython and SPE. The prebuilt environments feature updated versions of several components (SPE, IPython, readline) Downloads - http://sourceforge.net/projects/movpy Documentation - http://www.voidspace.org.uk/python/movpy What is Movable Python ? ------------------------- Movable Python is a way of building portable, standalone, Python environments. The result is a version of Python that can be used without having to install python on the target machine. (Currently windows only - but could be ported to Mac using py2app and Lunix using cx_freeze). This means you can carry around a prebuilt python environment on a USB memory stick - Python on a stick. Come and get your gannet ripple, python on a stick..... [1] This is useful for : * Machines where you don't have admin rights (can't install programs) * Where you need a portable 'Build, Test, and Run' Python environment (will nicely fit on a usb memory stick) * Having several versions of python on the same machine for forward/backward compatibility testing * Easily deploying python scripts without having to install python * Try before you buy - test python without having to install it, including new versions * 'Python Runtime Environment'. '.py' files can be associated with movpy With the addition of wxPython, SPE [2], and IPython [3] it becomes a full 'Build, Test, and Run' environment. What's Available ? ------------------- >From sourceforge ( http://sourceforge.net/projects/movpy ) : The source distribution that allows you to customize and build your own environments. This requires py2exe. Prebuilt environments for Python 2.2, 2.3, and 2.4. Environments are available either as 'basic' build, or 'standard' build. Basic comes with the standard library, psyco, and IPython. Standard has wxPython and SPE included. What Has Changed ? ------------------- 2005/02/07 Version 0.4.6a Movpy Icon and image added by Aidan Ashby - http://aidan.voidspace.org.uk Changes by Michael We use exec rather than eval (which shouldn't be used with `multiple statement code objects`) IPython isn't called if -p is on (psyco and IPython don't play well together yet) IPython won't be called if psyco.full() has been called in your script locals() and globals() are now passed explicitly to interactive() (optional if you use interactive yourself) (This was an attempt to make IPython work with psyco - which it doesn't yet !) Fixed a bug in Python 2.2 support - 'exclude_modules' now works ! Forced package import for encodings. SPE now works with python 2.2 - but still 'experimental'. Icon is now used in python 2.2 Plus the pre-built environments use newer versions of readline, IPython, and SPE Regards, Michael Foord http://www.voidspace.org.uk/python/index.shtml [1] For the 'Pythonically Challenged' this alludes to the python's sketch where John Cleese is dressed as an usherette selling ice-creams during the interval in a british film-house. He shouts: "Albatross! Albatross! Stormy-petrel on a stick! Gannet ripple!". Silly Monty Python reference supplied by John Davenport. [2] Stanis Python Editor IDE - see http://spe.pycs.net [3] IPython - enormously flexible interactive shell for Python. See http://ipython.scipy.org From AS at nospam.org Sun Feb 20 05:31:48 2005 From: AS at nospam.org (Alberto Santini) Date: Sun, 20 Feb 2005 11:31:48 +0100 Subject: Real-Time Fluid Dynamics for Games... Message-ID: I ported a Jos Stam's demo about Fluid mech to check the difference of speed between C implementation and Python. I think I achieved good results with Python and there is space to improve, without to extend the program with C routine, I mean. -- Good hack, Alberto Santini (http://www.albertosantini.it/) --------------------------- demo.py --------------------------- """ Real-Time Fluid Dynamics for Games by Jos Stam (2003). Parts of author's work are also protected under U. S. patent #6,266,071 B1 [Patent]. Original paper by Jos Stam, "Real-Time Fluid Dynamics for Games". Proceedings of the Game Developer Conference, March 2003 http://www.dgp.toronto.edu/people/stam/reality/Research/pub.html Tested on python 2.4 numarray 1.1.1 PyOpenGL-2.0.2.01.py2.4-numpy23 glut-3.7.6 How to use this demo: Add densities with the right mouse button Add velocities with the left mouse button and dragging the mouse Toggle density/velocity display with the 'v' key Clear the simulation by pressing the 'c' key """ import psyco psyco.full() import sys from numarray import Float64, zeros from solver import vel_step, dens_step try: from OpenGL.GLUT import * from OpenGL.GL import * from OpenGL.GLU import * except: print ''' ERROR: PyOpenGL not installed properly. ''' sys.exit() N = 32 size = N+2 dt = 0.1 diff = 0.0 visc = 0.0 force = 5.0 source = 100.0 dvel = False win_x = 512 win_y = 512 omx = 0.0 omy = 0.0 mx = 0.0 my = 0.0 mouse_down = [False,False,False] """ Start with two grids: one that contains the density values from the previous time step and one that will contain the new values. For each grid cell of the latter we trace the cell's center position backwards through the velocity field. We then linearly interpolate from the grid of previous density values and assign this value to the current grid cell. """ u = zeros((size,size), Float64) # velocity u_prev = zeros((size,size), Float64) v = zeros((size,size), Float64) # velocity v_prev = zeros((size,size), Float64) dens = zeros((size,size), Float64) # density dens_prev = zeros((size,size), Float64) def clear_data(): global u, v, u_prev, v_prev, dens, dens_prev, size u[0:size,0:size] = 0.0 v[0:size,0:size] = 0.0 u_prev[0:size,0:size] = 0.0 v_prev[0:size,0:size] = 0.0 dens[0:size,0:size] = 0.0 dens_prev[0:size,0:size] = 0.0 def pre_display(): glViewport(0, 0, win_x, win_y ) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0.0, 1.0, 0.0, 1.0) glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT) def post_display(): glutSwapBuffers () def draw_velocity(): h = 1.0/N glColor3f(1.0, 1.0, 1.0) glLineWidth(1.0) glBegin(GL_LINES) for i in range(1, N+1): x = (i-0.5)*h; for j in range(1, N+1): y = (j-0.5)*h glColor3f(1, 0, 0) glVertex2f(x, y) glVertex2f(x+u[i,j], y+v[i,j]) glEnd() def draw_density(): h = 1.0/N glBegin(GL_QUADS) for i in range(0, N+1): x = (i-0.5)*h for j in range(0, N+1): y = (j-0.5)*h d00 = dens[i,j] d01 = dens[i,j+1] d10 = dens[i+1,j] d11 = dens[i+1,j+1] glColor3f(d00, d00, d00); glVertex2f(x, y) glColor3f(d10, d10, d10); glVertex2f(x+h, y) glColor3f(d11, d11, d11); glVertex2f(x+h, y+h) glColor3f(d01, d01, d01); glVertex2f(x, y+h) glEnd () def get_from_UI(d, u, v): global omx, omy d[0:size,0:size] = 0.0 u[0:size,0:size] = 0.0 v[0:size,0:size] = 0.0 if not mouse_down[GLUT_LEFT_BUTTON] and not mouse_down[GLUT_RIGHT_BUTTON]: return i = int((mx/float(win_x))*N+1) j = int(((win_y-float(my))/float(win_y))*float(N)+1.0) if i<1 or i>N or j<1 or j>N: return if mouse_down[GLUT_LEFT_BUTTON]: u[i,j] = force * (mx-omx) v[i,j] = force * (omy-my) if mouse_down[GLUT_RIGHT_BUTTON]: d[i,j] = source omx = mx omy = my def key_func(key, x, y): global dvel if key == 'c' or key == 'C': clear_data() if key == 'v' or key == 'V': dvel = not dvel def mouse_func(button, state, x, y): global omx, omy, mx, my, mouse_down omx = mx = x; omy = my = y; mouse_down[button] = (state == GLUT_DOWN) def motion_func(x, y): global mx, my mx = x; my = y def reshape_func(width, height): global win_x, win_y glutReshapeWindow(width, height) win_x = width win_y = height def idle_func(): global dens, dens_prev, u, u_prev, v, v_prev, N, visc, dt, diff get_from_UI(dens_prev, u_prev, v_prev) vel_step(N, u, v, u_prev, v_prev, visc, dt) dens_step(N, dens, dens_prev, u, v, diff, dt) glutPostRedisplay() def display_func(): pre_display() if dvel: draw_velocity() else: draw_density() post_display() def open_glut_window(): glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE) glutInitWindowPosition(0, 0) glutInitWindowSize(win_x, win_y) glutCreateWindow("Alias | wavefront (porting by Alberto Santini)") glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT) glutSwapBuffers() glClear(GL_COLOR_BUFFER_BIT) glutSwapBuffers() pre_display () glutKeyboardFunc(key_func) glutMouseFunc(mouse_func) glutMotionFunc(motion_func) glutReshapeFunc(reshape_func) glutIdleFunc(idle_func) glutDisplayFunc(display_func) if __name__ == '__main__': glutInit(sys.argv) clear_data() open_glut_window() glutMainLoop() --------------------------------------------------------------- --------------------------- solver.py --------------------------- """ Real-Time Fluid Dynamics for Games by Jos Stam (2003). Parts of author's work are also protected under U. S. patent #6,266,071 B1 [Patent]. """ def set_bnd(N, b, x): """We assume that the fluid is contained in a box with solid walls: no flow should exit the walls. This simply means that the horizontal component of the velocity should be zero on the vertical walls, while the vertical component of the velocity should be zero on the horizontal walls. For the density and other fields considered in the code we simply assume continuity. The following code implements these conditions. """ for i in range(1, N+1): if b == 1: x[0,i] = -x[1,i] else: x[0,i] = x[1,i] if b == 1: x[N+1,i] = -x[N,i] else: x[N+1,i] = x[N,i] if b == 2: x[i,0] = -x[i,1] else: x[i,0] = x[i,1] if b == 2: x[i,N+1] = -x[i,N] else: x[i,N+1] = x[i,N] x[0,0] = 0.5*(x[1,0]+x[0,1]) x[0,N+1] = 0.5*(x[1,N+1]+x[0,N]) x[N+1,0] = 0.5*(x[N,0]+x[N+1,1]) x[N+1,N+1] = 0.5*(x[N,N+1]+x[N+1,N]) def lin_solve(N, b, x, x0, a, c): for k in range(0, 20): x[1:N+1,1:N+1] = (x0[1:N+1,1:N+1] + a*(x[0:N,1:N+1]+x[2:N+2,1:N+1]+x[1:N+1,0:N]+x[1:N+1,2:N+2]))/c set_bnd(N, b, x) # Addition of forces: the density increases due to sources def add_source(N, x, s, dt): size = (N+2) x[0:size,0:size] += dt*s[0:size,0:size] # Diffusion: the density diffuses at a certain rate def diffuse (N, b, x, x0, diff, dt): """ The basic idea behind our method is to find the densities which when diffused backward in time yield the densities we started with. The simplest iterative solver which works well in practice is Gauss-Seidel relaxation. """ a = dt*diff*N*N lin_solve(N, b, x, x0, a, 1+4*a) # Advection: the density follows the velocity field def advect (N, b, d, d0, u, v, dt): """ The basic idea behind the advection step. Instead of moving the cell centers forward in time through the velocity field, we look for the particles which end up exactly at the cell centers by tracing backwards in time from the cell centers. """ dt0 = dt*N; for i in range(1, N+1): for j in range(1, N+1): x = i-dt0*u[i,j]; y = j-dt0*v[i,j] if x<0.5: x=0.5 if x>N+0.5: x=N+0.5 i0 = int(x); i1 = i0+1 if y<0.5: y=0.5 if y>N+0.5: y=N+0.5 j0 = int(y); j1 = j0+1 s1 = x-i0; s0 = 1-s1; t1 = y-j0; t0 = 1-t1 d[i,j] = s0*(t0*d0[i0,j0]+t1*d0[i0,j1])+s1*(t0*d0[i1,j0]+t1*d0[i1,j1]) set_bnd (N, b, d) def project(N, u, v, p, div): h = 1.0/N div[1:N+1,1:N+1] = -0.5*h*(u[2:N+2,1:N+1]-u[0:N,1:N+1]+v[1:N+1,2:N+2]-v[1:N+1,0:N]) p[1:N+1,1:N+1] = 0 set_bnd (N, 0, div) set_bnd (N, 0, p) lin_solve (N, 0, p, div, 1, 4) u[1:N+1,1:N+1] -= 0.5*(p[2:N+2,1:N+1]-p[0:N,1:N+1])/h # ??? not in the paper /h v[1:N+1,1:N+1] -= 0.5*(p[1:N+1,2:N+2]-p[1:N+1,0:N])/h # ??? not in the paper /h set_bnd (N, 1, u) set_bnd (N, 2, v) # Evolving density: advection, diffusion, addition of sources def dens_step (N, x, x0, u, v, diff, dt): add_source(N, x, x0, dt) x0, x = x, x0 # swap diffuse(N, 0, x, x0, diff, dt) x0, x = x, x0 # swap advect(N, 0, x, x0, u, v, dt) # Evolving velocity: self-advection, viscous diffusion, addition of forces def vel_step (N, u, v, u0, v0, visc, dt): add_source(N, u, u0, dt) add_source(N, v, v0, dt); u0, u = u, u0 # swap diffuse(N, 1, u, u0, visc, dt) v0, v = v, v0 # swap diffuse(N, 2, v, v0, visc, dt) project(N, u, v, u0, v0) u0, u = u, u0 # swap v0, v = v, v0 # swap advect(N, 1, u, u0, u0, v0, dt) advect(N, 2, v, v0, u0, v0, dt) project(N, u, v, u0, v0) ----------------------------------------------------------------- From jeremy+plusnews at jeremysanders.net Wed Feb 2 09:36:34 2005 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Wed, 02 Feb 2005 14:36:34 +0000 Subject: webbrowser.py Message-ID: It occurs to me that webbrowser could be more intelligent on Linux/Unix systems. Both Gnome and KDE have default web browsers, so one could use their settings to choose the appropriate browser. I haven't been able to find a freedesktop common standard for web browser, however. Firefox now sets itself as a "default browser" on startup, so python could also look for a similar setting. webbrowser could identify whether it was running under KDE/Gnome (maybe scan the processes?), identify the correct desktop's browser (or just use Gnome, maybe), and start that web browser. Comments? Jeremy From a.schmolck at gmx.net Sun Feb 27 14:07:43 2005 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Sun, 27 Feb 2005 19:07:43 +0000 Subject: [ANN] mlabwrap v0.9 released Message-ID: This release just adds OS X support to setup.py (thanks to Josh Marshall). I've also made some recent improvements to the website, based on user feedback. In the absence of any bug reports so far I'd tentatively consider mlabwrap as stable. Dowload from: What is mlabwrap? ----------------- A high-level python to matlab(tm) bridge (low-level access is also possible). It should work with recent python >=2.3 and matlab(tm) >=6.0 versions and under practically any supported by both matlab and python (I'm using linux myself, but thanks to user feeback windows and OS X should also work fine). Here is a short demo snippet: >>> from mlabwrap import mlab >>> import Numeric >>> mlab.lookfor('singular value') GSVD Generalized Singular Value Decompostion. SVD Singular value decomposition. [...] >>> help(mlab.svd) mlab_command(*args, **kwargs) SVD Singular value decomposition. [U,S,V] = SVD(X) produces a diagonal matrix S, of the same dimension as X and with nonnegative diagonal elements in [...] >>> mlab.svd(array([[1,2], [1,3]])) array([[ 3.86432845], [ 0.25877718]]) 'as From __peter__ at web.de Thu Feb 3 16:48:02 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Feb 2005 22:48:02 +0100 Subject: Basic file operation questions References: <1107379669.870799.256030@g14g2000cwa.googlegroups.com> Message-ID: Caleb Hattingh wrote: >> Yes, you can even write >> >> f = open("data.txt") >> for line in f: >> # do stuff with line >> f.close() >> >> This has the additional benefit of not slurping in the entire file at >> once. > > Is there disk access on every iteration? I'm guessing yes? It shouldn't > be an issue in the vast majority of cases, but I'm naturally curious :) Well, you will hardly find an OS that does no buffering of disk access -- but file.next() does some extra optimization as Steven already explained. Here are some timings performed on the file that has the first-hand information about Python's file buffering strategy :-) $ python2.4 -m timeit 'for line in file("fileobject.c"): pass' 1000 loops, best of 3: 528 usec per loop $ python2.4 -m timeit 'for line in file("fileobject.c").readlines(): pass' 1000 loops, best of 3: 635 usec per loop $ python2.4 -m timeit 'for line in iter(file("fileobject.c").readline, ""): pass' 1000 loops, best of 3: 1.59 msec per loop $ python2.4 -m timeit 'f = file("fileobject.c")' 'while 1:' ' if not f.readline(): break' 100 loops, best of 3: 2.08 msec per loop So not only is for line in file(...): # do stuff the most elegant, it is also the fastest. file.readlines() comes close, but is only viable for "small" files. Peter From a.schmolck at gmx.net Fri Feb 18 15:27:10 2005 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Fri, 18 Feb 2005 20:27:10 +0000 Subject: Python, Matlab and AI question References: Message-ID: Robert Kern writes: > dataangel wrote: >> I'm a student who's considering doing a project for a Machine Learning class >> on pathing (bots learning to run through a maze). The language primarily >> used by the class has been Matlab. I would prefer to do the bulk of the >> project in python because I'm familiar with pygame (for the visuals) but I >> already have a lot of AI code written in Matlab. >> I'd like to be able to call Matlab code from within python. I'm not sure >> this is possible. My code runs in Octave just fine. > > There have been some bridges between Matlab and Python, but most of them are > old, I believe. > > http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html Actually, I've written a highlevel matlab-python bridge (based on bugfixed and slightly extended version of the original pymat) which is quite up-to-date; by and large it makes using matlab from python as easy as if matlab were just some python library: >>> from mlabwrap import mlab; mlab.plot([1,2,3],'-o') >>> mlab.sin([4,5,6]) array([[-0.7568025 ], [-0.95892427], [-0.2794155 ]]) As you can see from the last example there a certain minor idiosyncrasies stemming from unbridgable semantic differences between matlab and python (matlab doesn't have "real" vectors, which means that Numeric vectors are translated to Nx1 matrices), also the call to matlab of course incurs a significant overhead compared to Numeric.sin. All in all I it works quite well for me, though (I've been using it productively for years now and a couple of other people have also used it) -- so I guess I should finally announce it (there were a few minor things I wanted to add first, but since people periodically ask for something like it on c.l.py so now would seem like a good time). You can find it on sourceforge: I'd appreciate feedback. 'as p.s. never mind the project activity meter at 0% -- as you can see the latest version was uploaded mid january this year. From pf_moore at yahoo.co.uk Mon Feb 21 12:03:20 2005 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Mon, 21 Feb 2005 17:03:20 +0000 Subject: Unittest - testing properties (read-only attributes) Message-ID: I have a class with a read-only attribute, and I want to add a unit test to ensure that it really *is* read-only. I can do this as def test_readonly(self): """Value and multiplier must be readonly""" try: self.combat.value = 1 self.fail("Value is not read only") except AttributeError: pass That works, but it seems a bit clumsy. Is there a better way? Thanks, Paul. -- XML with elementtree is what makes me never have think about XML again. -- Istvan Albert From davidf at sjsoft.com Mon Feb 14 05:08:48 2005 From: davidf at sjsoft.com (David Fraser) Date: Mon, 14 Feb 2005 12:08:48 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: Ilias Lazaridis wrote: > I'm a newcomer to python: > > [EVALUATION] - E01: The Java Failure - May Python Helps? > http://groups-beta.google.com/group/comp.lang.python/msg/75f0c5c35374f553 > > - > > I've download (as suggested) the python 2.4 installer for windows. > > Now I have problems to compile python extension that some packages > depend on. > > I use the MinGW open-source compiler. > > - > > My questions: > > a) Why does the Python Foundation not provide additionally a binary > version, compiled with MinGW or another open-source compiler? > > b) Why does the Python Foundation not ensure, that the python > source-code is directly compilable with MinGW? > > c) Why are the following efforts not _directly_ included in the python > source code base? > > http://jove.prohosting.com/iwave/ipython/pyMinGW.html > > above link found in this thread: > > http://groups-beta.google.com/group/comp.lang.python/msg/c9f0444c467de525 > > d) Is it really neccessary that I dive into such adventures, to be able > to do the most natural thing like: "developing python extensions with > MinGW"? > > http://starship.python.net/crew/kernr/mingw32/Notes.html > > e) Is there any official statement available regarding the msvcr71.dll > and other MS licensing issues? > > [see several threads "[Python-Dev] Is msvcr71.dll re-redistributable?"] > > http://mail.python.org/pipermail/python-dev/2005-February/thread.html > > f) Are there any official (Python Foundation) statements / rationales > available, which explain why the MinGW compiler is unsupported, although > parts of the community obviously like to use it? > > http://groups-beta.google.com/group/comp.lang.python/msg/dc3474e6c8053336 > > - > > I just want to understand. > > Thankfull for any pointer to official documents / statements. > > [google is _not_ a fried here. I like to have a stable development > environment, which is supported by the official projects, thus it can > pass quality-assurance without beeing afraid about every next release.] Just to add to all the other answers: Don't just complain, submit patches and work at keeping them maintained. If this is done for a while it may be more of an argument for having them included David From kartic.krishnamurthy at gmail.com Tue Feb 1 14:06:57 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 1 Feb 2005 11:06:57 -0800 Subject: How do you do arrays In-Reply-To: References: Message-ID: <1107284817.848551.79000@c13g2000cwb.googlegroups.com> Tom, Before you use iMatrix[index], you have to tell python to use iMatrix as an array. You will do that using iMatrix = [] *outside* the loop. iMatrix = [] while index < majorlop1: # rest of the loop statements Since you are new, please take a look at the Python tutorial to get you started. http://docs.python.org/tut/tut.html Thanks, -Kartic From alanmk at hotmail.com Sat Feb 12 13:12:34 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Sat, 12 Feb 2005 18:12:34 +0000 Subject: is there a safe marshaler? In-Reply-To: <420d2441$0$28991$e4fe514c@news.xs4all.nl> References: <420b6936$0$28982$e4fe514c@news.xs4all.nl> <9RMOd.47295$Z14.32810@news.indigo.ie> <420bd184$0$28994$e4fe514c@news.xs4all.nl> <420bedb4$0$28975$e4fe514c@news.xs4all.nl> <420d2441$0$28991$e4fe514c@news.xs4all.nl> Message-ID: [Irmen de Jong] > Interestingly enough, I just ran across "Flatten": > http://sourceforge.net/project/showfiles.php?group_id=82591&package_id=91311 > > "...which aids in serializing/unserializing networked data securely, > without having to fear execution of code or the like." > > Sounds promising! Well, I'm always dubious of OSS projects that don't even have any bugs reported, let alone fixed: no patches submitted, etc, etc. http://sourceforge.net/tracker/?group_id=82591 Though maybe I'm missing something obvious? -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From raghulj at gmail.com Tue Feb 22 23:09:50 2005 From: raghulj at gmail.com (Raghul) Date: 22 Feb 2005 20:09:50 -0800 Subject: user interface for python Message-ID: <1109131790.140672.209730@l41g2000cwc.googlegroups.com> Hi, Which of the UI I can used for my program that I can use both in windows and in Linux. Is it possible for me to use Wxpython for my program so that it can run on both the windows and linux machine? Will it be platform independent? From fumanchu at amor.org Tue Feb 15 13:00:06 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 15 Feb 2005 10:00:06 -0800 Subject: replacing ASP/VBScript with Python Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398431@exchange.hqamor.amorhq.net> Peter Maas wrote: > I have inherited an extremely messy ASP/VBScript application which > is a pain for me to support. Now the customer is thinking about a > redesign. I'd like to rewrite the whole thing in Python but the app > has to meet some conditions like > > - IIS frontend > - MSSQL db server > - Win32 authentication > - No 'ugly' URLs like http://server/cgi-bin/frontend.cgi?main.py > - Performance: intranet with ~ 1000 users None of those sound like a problem. > My personal preferences: > > - I'd rather do this in plain Python than using e.g. Zope because I > fear the additional complexity of handling Zope and make it seam- > lessly work with IIS. I had the same fear. :) > - I'd like to do session handling in Python because ASP's session > object is quite limited and some of the ASP app's mess is caused > by trying to use it for compound data type storage. OTOH I could > pickle Python objects to a string and store that in an ASP session. > In the meantime I have searched the internet and found plenty of options: > > - plain cgi with fastcgi and mod_rewrite for IIS to transform the URL > - quixote cgi with fastcgi and mod_rewrite > - Webware + wkcgi > - Python ASP (registering Python with Pywin32 as ASP language) > - mxODBC + SQL ODBC driver > - pyADO + SQL MDAC driver > > I'm now confident that it is doable and keen on finding out. The usual > question: what is the one and best way to do it? ;) Python ASP (pywin32), but put as little code as possible into the ASP--make it just a stub to call the real Python app. That app will be running persistently in the background, which should obviate most of the need for session support. That's been my experience, anyway. Here's an example (from http://www.aminus.org/rbre/cation/html/admin/ASP.html): <%@Language=Python%> <% from cation.html.uiasp import UserInterfaceASP from cation import catapp ui = UserInterfaceASP(catapp) ui.request(Request, Response) %> The only downside is that ASP expects a physical file for every URL, so you'll either have lots of dumb copies of the stub, or a single dispatcher (and the ugly URL's you wanted to avoid). With a little planning, you can have the stubs auto-generated. Database side: try them all and see which is best with your dataset. ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org From jfj at freemail.gr Tue Feb 8 03:39:30 2005 From: jfj at freemail.gr (jfj) Date: Tue, 08 Feb 2005 00:39:30 -0800 Subject: Confused with methods In-Reply-To: References: <1grknb0.ygwohl17y6j5yN%aleaxit@yahoo.com> <1grmd4z.1tlm4e61650vedN%aleaxit@yahoo.com> <1grmg8s.17t7tj4180jdj6N%aleaxit@yahoo.com> Message-ID: <42087AC2.5070708@freemail.gr> Steven Bethard wrote: > > For your benefit, and the benefit of others who make this same mistake, > I'll rewrite your original post in a manner that won't seem so > self-important and confrontational[1]. > ``People who code too much tend to get authoritative'', in general. I am an arrogant noob -- just like arrogant experts... Inconsistenly y'rs jfj From danperl at rogers.com Mon Feb 7 08:42:46 2005 From: danperl at rogers.com (Dan Perl) Date: Mon, 7 Feb 2005 08:42:46 -0500 Subject: CGI POST problem was: How to read POSTed data References: <1107659974.048175.221770@z14g2000cwz.googlegroups.com> <1107756968.920802.99540@c13g2000cwb.googlegroups.com> Message-ID: "M.E.Farmer" wrote in message news:1107756968.920802.99540 at c13g2000cwb.googlegroups.com... > Sweet! > Glad you fixed it, and documented it all! > Thanks for the followups. > Now the next poor soul to stumble in can get the right fix. > Never know when it could be me ;) Thanks for the comments. I did indeed post the info on the bug to let other people know about it. Anyway, this was more of a learning experience than I intended it to be. And now it's time for me to move on and to get into CherryPy. From belred at gmail.com Thu Feb 24 20:48:47 2005 From: belred at gmail.com (Bryan) Date: Thu, 24 Feb 2005 17:48:47 -0800 Subject: [perl-python] generic equivalence partition In-Reply-To: <1109245733.261643.219420@f14g2000cwb.googlegroups.com> References: <1109245733.261643.219420@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > another functional exercise with lists. > > Here's the perl documentation. I'll post a perl and the translated > python version in 48 hours. > > =pod > > parti(aList, equalFunc) > > given a list aList of n elements, we want to return a list that is a > range of numbers from 1 to n, partition by the predicate function of > equivalence equalFunc. (a predicate function is a function that > takes two arguments, and returns either True or False.) > > Note: a mathematical aspect: there are certain mathematical constraints > on the a function that checks equivalence. That is to say, if a==b, > then b==a. If a==b and b==c, then a==c. And, a==a. If a equivalence > function does not satisfy these, it is inconsistent and basically give > meaningless result. > > example: > parti([['x','x','x','1'], > ['x','x','x','2'], > ['x','x','x','2'], > ['x','x','x','2'], > ['x','x','x','3'], > ['x','x','x','4'], > ['x','x','x','5'], > ['x','x','x','5']], sub {$_[0]->[3] == $_[1]->[3]} ) > > returns > [[1],['2','3','4'],['5'],['6'],['7','8']]; > > =cut > > In the example given, the input list's elements are lists of 4 > elements, and the equivalence function is one that returns True if the > last item are the same. > > Note that this is a generic function. The input can be a list whose > elements are of any type. What "parti" does is to return a partitioned > range of numbers, that tells us which input element are equivalent to > which, according to the predicate given. For example, in the given > example, it tells us that the 2nd, 3rd, 4th elements are equivalent. > And they are equivalent measured by the predicate function given, which > basically tests if their last item are the same integer. (note that if > we want to view the result as indexes, then it is 1-based index. i.e. > counting starts at 1.) > > PS if you didn't realize yet, nested lists/dictionaries in perl is a > complete pain in the ass. > > PS note that the code "sub {$_[0]->[3] == $_[1]->[3]}" is what's called > the lambda form, in Perl. > > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html > this is the first thing that came to my mind. i'm sure there are more clever ways to do this. elements = [['x', 'x', 'x', '1'], ['x', 'x', 'x', '2'], ['x', 'x', 'x', '2'], ['x', 'x', 'x', '2'], ['x', 'x', 'x', '3'], ['x', 'x', 'x', '4'], ['x', 'x', 'x', '5'], ['x', 'x', 'x', '5']] pos = {} for i, element in enumerate(elements): pos.setdefault(element[-1], []).append(i+1) p = pos.values() p.sort() [[1], [2, 3, 4], [5], [6], [7, 8]] bryan From dontwant at spam.com Fri Feb 11 11:20:29 2005 From: dontwant at spam.com (Courageous) Date: Fri, 11 Feb 2005 08:20:29 -0800 Subject: THREAD_STACK_SIZE and python performance? References: Message-ID: >The FreeBSD patch, setting the value to 0x100000 >seems to be enough for most of our zope servers,... Is that value in /bytes/? In modern solaris implementations of posix threads, the default stack size is 2 megabytes fo 64 bit machines. I can't fathom what your performance consideration would be; I'd think there'd not be one, with any reasonable amount of memory on your server. C// From Scott.Daniels at Acm.Org Mon Feb 28 12:03:56 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 28 Feb 2005 09:03:56 -0800 Subject: Newbie question -- fiddling with pictures. In-Reply-To: References: Message-ID: <42234ab9$1@nntp0.pdx.net> Ryan White wrote: > Subject: Newbie question Not a very good subject -- many people will not even look at it unless you describe what your question is about. > I'm wanting to use python to display some jpeg images, maybe present them at > a percentage of their actual size etc. > How do I display an image in Python? - I've run over Tkinter, but obviously > in all the wrong places. You probably want Fredrik Lundh's PIL (Python Imaging Library) package to read and manipulate the images, and then use TKinter to display the images. --Scott David Daniels Scott.Daniels at Acm.Org From steven.bethard at gmail.com Sun Feb 6 15:03:27 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 06 Feb 2005 13:03:27 -0700 Subject: loops -> list/generator comprehensions In-Reply-To: <1107718117.221204.80410@l41g2000cwc.googlegroups.com> References: <1107718117.221204.80410@l41g2000cwc.googlegroups.com> Message-ID: jamesthiele.usenet at gmail.com wrote: > I wrote this little piece of code to get a list of relative paths of > all files in or below the current directory (*NIX): > > walkList = [(x[0], x[2]) for x in os.walk(".")] > filenames = [] > for dir, files in walkList: > filenames.extend(["/".join([dir, f]) for f in files]) > > It works fine, I don't need to change it, but I know there is a one > liner list/generator comprehension to do this - I'm just not well > enough versed in comprehensions to figure it out. Can someone please > show me what it is? I've used os.path.join instead of "/".join since it's more general, but other than that, this should be eqivalent: filenames = [os.path.join(dirpath, filename) for dirpath, _, filenames in os.walk('.') for filename in filenames] > Even better, is there a generalized way to transform simple loops into > comprehensions that someone can point me to? Well, generally, you need to write your loops to use an append, and then the translation to LC is simpler. filenames = [] for dirpath, _, filenames in os.walk('.'): for filename in filenames: filenames.append(os.path.join(dirpath, filename)) Now that you know what it looks like with an append, you simply move the expression in the append to the top, and leave the fors in the same order: filenames = [os.path.join(dirpath, filename) for dirpath, _, filenames in os.walk('.') for filename in filenames] HTH, STeVe From harlinseritt at yahoo.com Wed Feb 23 21:36:06 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 23 Feb 2005 18:36:06 -0800 Subject: Question about logfiles in Python In-Reply-To: References: Message-ID: <1109212566.723878.83400@g14g2000cwa.googlegroups.com> I'm not familiar with Exchange log files but this can be done rather easily assuming the log file is a flat text file (which usually these are not-- like NT event logs). search_str = "words and phrases" data = open(LogFile, 'r').read() if search_str in data: flag = 1 If they are binary files, you may have to use a special module (or write one yourself if it doesn't exist). A good place to look is in Mark Hammond's Win32 modules. You'll find some stuff here: http://starship.python.net/crew/mhammond/ Hope this sends you in the right direction. From petr at tpc.cz Mon Feb 14 16:43:44 2005 From: petr at tpc.cz (McBooCzech) Date: 14 Feb 2005 13:43:44 -0800 Subject: Considering python - have a few questions. References: Message-ID: <1108417424.289500.85300@g14g2000cwa.googlegroups.com> Sorry, I have forgotten to mention binding for Firebird to Python: kinterbasdb http://kinterbasdb.sourceforge.net/ Petr Jakes From jackdied at jackdied.com Fri Feb 4 17:46:44 2005 From: jackdied at jackdied.com (Jack Diederich) Date: Fri, 4 Feb 2005 17:46:44 -0500 Subject: Persistence design [was: RE: OT: why are LAMP sites slow?] In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3398367@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3398367@exchange.hqamor.amorhq.net> Message-ID: <20050204224644.GG1607@performancedrivers.com> On Fri, Feb 04, 2005 at 10:31:19AM -0800, Robert Brewer wrote: > Jack Diederich wrote: > > *ding*ding*ding* The biggest mistake I've made most > > frequently is using > > a database in applications. YAGNI. Using a database at all has it's > > own overhead. Using a database badly is deadly. Most sites would > > benefit from ripping out the database and doing something simpler. > > Refactoring a database on a live system is a giant pain in the ass, > > simpler file-based approaches make incremental updates easier. > > > > The Wikipedia example has been thrown around, I haven't looked at the > > code either; except for search why would they need a database to > > look up an individual WikiWord? Going to the database > > requires reading > > an index when pickle.load(open('words/W/WikiWord')) would > > seem sufficient. > > > ... > > > > If there is interest I'll follow up with some details on my own LAMP > > software which does live reports on gigs of data and - you > > guessed it - > > I regret it is database backed. That story also involves why > > I started > > using Python (the prototype was in PHP). > > I'd be interested, if only selfishly to hear more potential use cases > for *my* projects. ;) It would be long so I'll spin it into a blog piece. They seem to be all the rage these days *0.5 wink* > One of my goals for Dejavu* (my ORM) is to abstract persistence to the > point that you can easily test your actual, live dataset against many > potential storage mechanisms (i.e. multiple DB's, but also shelve, > etc.). I need to finish the migration tools, but it's well on the way. I just looked at the docs, looks like a nicer version of the homespun one I use. If someone lends you the time machine set the year to 2001 and I'll use Dejavu instead. Reading the docs also makes me long for class decorators (again). I use metaclasses to register tables to databases, I see you inspect globals. ex in a better world: mydb = Database('foo') @mydb.add_table class Foo(Table): col1 = int col2 = str @mydb.add_table class Bar(Table): foo_id = str colb = unicode *sigh* maybe in 2.5? -Jack From jkjone2002 at att.net Thu Feb 17 10:15:48 2005 From: jkjone2002 at att.net (john san) Date: Thu, 17 Feb 2005 10:15:48 -0500 Subject: [newbie]How to install python under DOS and is there any Wxpython can be installed under dos? References: <1108557065.547230.254540@z14g2000cwz.googlegroups.com> <11172sa1sg2svc8@corp.supernews.com> Message-ID: <4K6dneoBWMc4KInfRVn-rA@rogers.com> yes. u need mod-xbox. since its be easy done and we already have OS, "Python" support what we need now is only that "Python" can easy to coding and show "window" program just like wt we can do under Windows. "Lucas Raab" ???? news:WC0Rd.5165$VI5.2979 at newsread3.news.atl.earthlink.net... > Leif B. Kristensen wrote: > > john san skrev: > > > > > >>Actually the "windows" running very good under the xbox-NTOS via > >>xboxmediacenter. its just limited functions(not easy to programming > >>the "windows" prog.), if we can find WxPython-like can be ported (I > >>can import * > >>from it to my xboxPython) )it will be a great great ......... You > >>will have HD screen and web surfing on HDTV and computing on HDTV. > >>think about it! That is a real thing the python-like lang. should to > >>do otherwise just a garbage(toy). > > > > > > You can run Linux with MythTV on an XBox. Does all the things you want, > > and of course it will run WxPython. > > But does that involve modding the Xbox?? As in messing with the hardware?? From fredrik at pythonware.com Mon Feb 14 17:09:43 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Feb 2005 23:09:43 +0100 Subject: [NooB] a Variable in multiple quotes... References: <614c778e.0502130204.5824cddf@posting.google.com><378onnF5aoj75U1@individual.net> <614c778e.0502141354.53d6675b@posting.google.com> Message-ID: "administrata" wrote: >> Oh: from the subject line, I'm guessing that you want it to say "John >> used to love pizza" instead? In that case, try doing this: >> >> I = "John" >> print "%s used to love pizza" % I > > How can I do it with several variables? > > About 10 or more... two: print I, "used to love", J or print "%s used to love %s" % (I, J) three: print I, "used to", J, K print "%s used to %s %s" % (I, J, K) five: print I, J, "to", K, L, M print "%s %s to %s %s %s" % (I, J, K, L, M) (you get the idea) for more on this, and some variations, read the "fancier output formatting" chapter in the tutorial again: http://docs.python.org/tut/node9.html (you've read the tutorial before, right?) From jerf at jerf.org Fri Feb 4 12:42:01 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 04 Feb 2005 12:42:01 -0500 Subject: returning True, False or None References: Message-ID: On Fri, 04 Feb 2005 16:44:48 -0500, Daniel Bickett wrote: > [ False , False , True , None ] > > False would be returned upon inspection of the first index, even > though True was in fact in the list. The same is true of the code of > Jeremy Bowers, Steve Juranich, and Jeff Shannon. As for Raymond > Hettinger, I can't even be sure ;) Nope. To recall, my code was: seenFalse = False for item in list: if item: return True if item is False: seenFalse = True if seenFalse: return False return None So, turning that into a real function and not a sketch: Python 2.3.4 (#1, Jan 25 2005, 21:29:33) [GCC 3.4.3 (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def thingy(l): ... seenFalse = False ... for item in l: ... if item: return True ... if item is False: seenFalse = True ... if seenFalse: ... return False ... return None ... >>> thingy([ False , False , True , None ]) True >>> The defense rests, your honor. :-) (I like the later use of "returnValue" and the reduce solution was cute and quite educational (very appropriate here). I deliberately eschewed fanciness, though.) From harlinseritt at yahoo.com Wed Feb 16 07:28:25 2005 From: harlinseritt at yahoo.com (Harlin) Date: 16 Feb 2005 04:28:25 -0800 Subject: MYSQL - how to install ? References: <1108547199.260223.211450@f14g2000cwb.googlegroups.com> Message-ID: <1108556905.444394.210020@l41g2000cwc.googlegroups.com> For MySQL on windows go here: http://dev.mysql.com/get/Downloads/MySQL-4.1/mysql-4.1.10-win32.zip/from/pick#mirrors For Python 2.3.5 binary installer for win32: http://www.python.org/ftp/python/2.3.5/Python-2.3.5.exe From steve at holdenweb.com Sat Feb 5 09:03:44 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 05 Feb 2005 09:03:44 -0500 Subject: Trouble converting hex to decimal? In-Reply-To: References: Message-ID: Earl Eiland wrote: > I'm trying to process the IP packet length field, as recorded by pcap > (Ethereal) and recovered using pcapy. When I slice out those bytes, I > get a value that shows in '\x00' format, rather than '0x00'. Neither > int() nor eval() are working. How do I handle this? > > Earl Eiland > You could either reconstruct the value yourself from the ord() values of the individual bytes, or look at the struct module which can help you with this kind of decoding task. regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From ncoghlan at iinet.net.au Wed Feb 23 05:43:08 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 23 Feb 2005 20:43:08 +1000 Subject: Style guide for subclassing built-in types? In-Reply-To: <1109151417.903188.73790@f14g2000cwb.googlegroups.com> References: <1109127834.660822.247120@g14g2000cwa.googlegroups.com> <1109150091.356411.150460@l41g2000cwc.googlegroups.com> <1109151417.903188.73790@f14g2000cwb.googlegroups.com> Message-ID: <421C5E3C.2080404@iinet.net.au> janeaustine50 at hotmail.com wrote: > p.s. the reason I'm not sticking to reversed or even reverse : suppose > the size of the list is huge. Reversed is an iterator - it does NOT copy the list. In other words, reversed already does pretty much what you want. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From adam at cognitcorp.com Tue Feb 8 17:40:31 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Tue, 08 Feb 2005 17:40:31 -0500 Subject: Python versus Perl ? In-Reply-To: References: <1107695949.247611.272800@g14g2000cwa.googlegroups.com> Message-ID: <1107902431.3672.25.camel@localhost.localdomain> On Tue, 2005-02-08 at 22:44, Caleb Hattingh wrote: > Hi m > > Speed is a contentious issue here. Point is, if you really need raw > speed, why stop only at Perl and Python? There are plenty of statically > compiled languages that will produce native binaries. > > The relative difference in speed between Perl and Python, whatever it is, > is completely washed out by the enormous jump using, say, C for example > [please, everyone else, I am aware of all the mitigating circumstances > regarding, e.g. parts of the standard library written in C, etc. That is > not my point.] I think the expression you seek is "comparing virtue among whores." Now we can all acknowledge that there is a spectrum in the programmer time vs machine time trade-off. (Voice reader users: Please forgive my ASCII art ... imagine a data set that loosely fits a linear relationship with a negative slope.) ASCII art start + M|* A| * * C| * H| * "STUPID" I| * * N| * E| * | * C| * * O| "Holy * S| Grail" * T| * 0------------------------- + PROGRAMMER COST ASCII art stop This metric is actually in two dimensions, but we usually consider it in one dimension with High Machine cost and low programmer cost at one extreme and low machine cost and high programmer cost at the other extreme. ASCII art start High Machine <---------------> High Programmer Cost ASCII art stop because there is a high inverse correlation between programmer and machine costs. Only a fool would use a programing language in the "stupid" area of the above chart (both costs high). Likewise, nobody gets to use the language that does not exist in the "Holy Grail" area of the chart (both costs low.) Both Python and Perl are way up in the upper left ( machine cost high, programmer cost low) of my little chart. Perl has much magic that drives up its programmer cost. Not by much in the know, but by enough that I would consider it to have a slightly higher programmer cost than Python. If Perl code executes a bit faster, then fine, all I can say is "that's nice." If machine costs were an issue I'd recode in vhdl and compile to silicone. Of the topic I want to address, you can entirely circumvent those issues by coding in C and using the Python C-API instead of strcmp and friends. > > A Good Reason for thinking along these lines (Perl/Python) is more > something like speed and reliability of development. Another one is > maintaintability. I must confess that I know pretty much nothing about > Perl, so I can't comment about that. My opinion about Python is that it > is very, very good for these things. > > The problem domains in which I do most of my work (chemical process > modelling and simulation) really do require speed. That's why I mostly > use Delphi (i.e. reasonably fast code) at work. I believe I know when > speed is and is not an issue, and (by far) most of the time, my experience > is that it is *not*. So I use Delphi for numerical code and python for > everything else. Why don't you use C for the numerical work? Then you can do your number crunching within a c-based python module. Have your cake and ... > > You really will have to convince people here that execution speed is a > real issue for your programming task (in order to continue this > discussion). Otherwise the debate will go south real quick. Not only most speed be an issue, but the economics must be such that any alternative is better than throwing more hardware at the problem. Adam DePrince From quentel.pierre at wanadoo.fr Sun Feb 6 15:11:55 2005 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Sun, 06 Feb 2005 21:11:55 +0100 Subject: How to read POSTed data In-Reply-To: References: <4205d419$0$6610$8fcfb975@news.wanadoo.fr> Message-ID: <42067a0d$0$10490$8fcfb975@news.wanadoo.fr> > Pierre, I am repeating some questions I already stated in another thread, > 'CGI POST problem', but do you have any opinions on how CGIHTTPServer's > do_POST handles requests? It looks to me like it always expects form data > to be part of the POST command header, in the path of the URL, just like a > GET request. Am I understanding the code incorrectly? The code in CGIHTTPServer is not very easy to understand, but it does read the request body, as many bytes as indicated in the Content-Length header. See line 262 (in the Python 2.4 distribution) or 250 in Python 2.3 (this is the Windows version) : data = self.rfile.read(nbytes) Then this data is sent to the standard input of the CGI script. If this script is a Python program using the cgi module, it usually creates a cgi.FieldStorage() instance : upon creation, the standard input is read (in self.read_urlencoded() for instance) and the string collected is processed to produce a dictionary-like object, with keys matching the form field names This is compliant with the CGI specification (HTTP doesn't say anything about the management of data sent by POST requests). The code I sent is an alternative to CGI, leaving the management of this data (available in self.body) to a method of the RequestHandler instance Regards, Pierre From benn at cenix-bioscience.com Wed Feb 9 05:25:57 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Wed, 09 Feb 2005 11:25:57 +0100 Subject: Reportlab and Barcodes In-Reply-To: <1107894763.331701.26470@c13g2000cwb.googlegroups.com> References: <1107894763.331701.26470@c13g2000cwb.googlegroups.com> Message-ID: <4209E535.1010501@cenix-bioscience.com> Josh wrote: >Hi All, > >I need someone to explain to me how to output a Code39 barcode to a >Reportlab PDF. As far as I can tell, there is no means to do this with >the Canvas object, and the demo that is included with the libraries is >using the platypus Frame to place the barcode on the form. I do not >wish to use this method. I'm guessing that it needs to be placed on the >form as some type of graphic. It's obviously not going to work with the >drawText method. Any ideas? > >Thanks > >Josh > > > Hello, Code39 isn't that complicated a barcode symbology to work with. What you can do is to write some code which can encode a Code39 barcode from a string into a simple graphic. I used to have the official spec for the barcode but that was in an old job. You can get the official spec from AIM - you'll have to pay for it but it's not much. Although beware about the Narrow:Width ratio if you're gonna try and scan the barcode after printing it out - try and get hold of a crappy scanner (I got stung by using a good scanner before in the past). Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From steve at holdenweb.com Tue Feb 1 08:24:32 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 01 Feb 2005 08:24:32 -0500 Subject: Advice on OSX cocoa app with Python backend In-Reply-To: <1107242909.3662.10.camel@temp.ant> References: <1107242909.3662.10.camel@temp.ant> Message-ID: <41FF8310.7050801@holdenweb.com> Socheat Sou wrote: > After a brief, but informative, discussion on Freenode's #zope > chatroom, I was advised to consult the gurus on c.l.p. > > I'm working for a small company who is in desperate need to rewrite it's > 15+ year old, flat-file, client-tracking database. The staff uses OSX, > while I administer the couple linux servers we have to run our website > and some internal sites. In our initial brainstorming session, we > decided to go with a Python backend server, handling the database and > business logic, and a native Cocoa application on the client side, with > enough glue to make the two stick. > Sounds like a plan, for a Mac house. > Also, after a bit of research, I discovered Twisted and PB. I figured > I'd have to write a customized backend to meet our needs. However, > seeing as how 1) I've never written a netwo > rk application before, let alone a multi-threaded application and 2) I'm > the sole developer > on this project, I was looking for as many API's, modules, frameworks, > and/or prebuilt solutions as possible to help me out. > First of all, note that Twisted applications needn't be multi-threaded, as Twisted makes use of asynchronous interfaces. You *can* write multi-threaded code under Twisted, but you don't have to most of the time. > I initially thought of Zope because I had often heard it referred to as > an application serv > er, so I thought it might be something I could use as a basis, write the > business logic, and have the Cocoa application, with some PyObjC, > communicate with the Zope server. We're definately not looking for a > web-based application, so I wasn't quite sure Zope was what I wa > nted. > It isn't. Much too heavyweight, with much too steep a learning curve for what appears to be essentially a simple project. > For those that are interested, we're looking at using MySQL as the DBMS. > From what little I know of OODBMS it doesn't seem like the right choice > because aside from data entry and client record lookups, the biggest use > of the database would be to generate reports and tabulated data on an > arbitrary set of fields. I've read that this isn't exactly the strength > of OODBMS? > Who told you that MySQL was OO? It's a bog-standard relational back-end with transactional capabilities. > We are also looking at a server-client architecture, rather than > individual clients connecting to the database over the network, because > there are some features the staff would like (such as something similar > to message passing between each other, and also being able to administer > connected users). > So you need a(t least one) layer between the database and the client, which you plan to write in Python. This makes perfect sense. Almost everything you find about writing servers in Python is going to work for you, so Google away! > Does anyone here have any experience building an OSX application with > Python running the show behind the scenes? I hope I didn't come off as > asking "tell me what to do", but rather I would appreciate any advice or > links to resources that might be helpful in this project. > Mostly, remember that OSX is effectively just another U**x environment, so server structures that work under BSD and Linux will tend to work under OSX. The unique parts of OSX appear (from the outside) to be Carbon/Cocoa and the funky GUI stuff. So have at it and come back for advice when you need it. Good luck with your project. [OBPyCon: of course, if you come to PyCon DC 2005 you can discuss this stuff with experts: http://www.python.org/pycon/2005/register.html The numbers tell us this could be the biggest PyCon ever!] regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From steven.bethard at gmail.com Mon Feb 21 13:39:14 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 21 Feb 2005 11:39:14 -0700 Subject: Test for structure In-Reply-To: <1108974803.420441.18850@z14g2000cwz.googlegroups.com> References: <1108566497.848623.45360@c13g2000cwb.googlegroups.com> <1108937287.079367.276910@g14g2000cwa.googlegroups.com> <1108974803.420441.18850@z14g2000cwz.googlegroups.com> Message-ID: > Steven Bethard wrote: >> >>Right. str and unicode objects support iteration through the old >>__getitem__ protocol, not the __iter__ protocol. If you want to use >>something as an iterable, just use it and catch the exception: >> >>try: >> itr = iter(a) >>except TypeError: >> # 'a' is not iterable >>else: >> # 'a' is iterable Martin Miller broke the order of reading by top-posting: > In either case, you can't tell a string and list apart, which is what > the OP wanted to know, namely how to differentiate the two. Yes, sorry, I should have marked my post OT. It was an answer to Terry Hancock's post suggesting hasattr(x, '__iter__'), not the OP. > Perhaps the test for an __iter__ attribute *is* the way to go because > you can tell the difference between the two type. I've seen this done before, e.g.: try: itr = iter(x) except TypeError: # is not iterable else: if hasattr(x, '__iter__'): # is other iterable else: # is str or unicode I don't like this idea much because it depends on str and unicode _not_ having a particular function. I haven't seen any guarantee anywhere that str or unicode won't ever grow an __iter__ method. So this code seems dangerous as far as future compatibility goes. > I think the technique suggested by Robin Munn nearly a year ago (and > referenced by the link in Simon Brunning's post): > http://groups-beta.google.com/group/comp.lang.python/msg/c8befd4bed517bbc > namely: > > try: > a + '' > except TypeError: > pass > else: > a= [a] > > would be a good usable solution, although it's not totally infallible. Yup, if I had to do this kind of type-checking (which I don't think I ever do), I'd probably go with something along these lines. STeVe From steve at holdenweb.com Tue Feb 1 08:34:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 01 Feb 2005 08:34:05 -0500 Subject: PyCon signature advertising Message-ID: You will note that I have changed my signature for newsgroups to include a plug for PyCon. I would very much appreciate any similar changes that c.l.py readers felt able to make to help get the word out that PyCon is *the* place to be for Python users and developers. I appreciate that not everyone has control over their .sig, and that some people find advertising of this crassly commercial nature a little distasteful. If either of these is the case, please simply ignore this message (though you should, of course, still come to PyCon :-) Every little helps, however, and I'd like my third (and final) year as chairman to see the biggest and (much more importantly) best PyCon ever. I hope to meet as many of you as possible in DC, March 23-25 (and during the four-day sprint preceding the main event). regards Steve -- Meet the Python developers and your c.l.py favorites Come to PyCon!!!! http://www.python.org/pycon/2005/ Steve Holden http://www.holdenweb.com/ From creditwrench at gmail.com Sat Feb 19 18:31:00 2005 From: creditwrench at gmail.com (Creditwrench) Date: Sat, 19 Feb 2005 23:31:00 GMT Subject: Creditwrench Message-ID: <1108855575.9247da9b927a6b72c38d7d33ddd1a139@teranews> And the truth shall set ye free http://www.creditwrench-thetruth.blogspot.com/ Uncle Normie From enleverlesO.OmcO at OmclaveauO.com Mon Feb 14 16:01:23 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Mon, 14 Feb 2005 22:01:23 +0100 Subject: DHTML control from Python? References: <140220051355142173%kenneth.m.mcdonald@sbcglobal.net> Message-ID: <421111c4$0$6595$8fcfb975@news.wanadoo.fr> See Pamie : http://pamie.sourceforge.net @-salutations -- Michel Claveau From FBatista at uniFON.com.ar Wed Feb 16 12:51:15 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 16 Feb 2005 14:51:15 -0300 Subject: Getting milliseconds in Python Message-ID: [Brian Beck] #- seconds * 100 = milliseconds Whaaaat? It really is seconds = 1000 * milliseconds . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Sun Feb 13 03:34:03 2005 From: timr at probo.com (Tim Roberts) Date: Sun, 13 Feb 2005 00:34:03 -0800 Subject: Considering python - have a few questions. References: Message-ID: "Heather Stovold" wrote: > >I need to make a GUI interface. Some of the screens need to be dynamically >created, with the screen information in a database. Included in the database >will be pictures (.gif or .jpg) that need to be displayed. A second >database would hold the user's data. I would also need to be able to print >reports made in a similar fashion. > >I would want the program to run in Windows for sure. If it could work on a >Mac and other systems, that would be a plus. I would really love it to be >able to also be able to be run on the internet (allowing more than one >person access to the data), but I've never done anything other than basic >web pages with a web page editor (dreamweaver.) > >btw - I have the database designed (and the program info database filled) in >Access.... > >I don't mind working hard to learn how to do it.... I just want to know if >Python is a good choice or not! Python is a great choice. Personally, given your requirements, I would make this a web application. In my opinion, HTML is the easiest way to generate a user interface on-the-fly. With a package like CherryPy, you get a web server built-in. You fire up the server in the background, and bring up Internet Explorer as "your" user interface. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jerf at jerf.org Wed Feb 2 16:33:05 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 02 Feb 2005 16:33:05 -0500 Subject: Generating modul classes with eval References: Message-ID: On Wed, 02 Feb 2005 16:20:41 -0500, Jeremy Bowers wrote: > That said, "__main__" indicates you ran it in the interactive shell. Or ran it directly on the command line. Duh. I thought that clause really loudly, but I guess I never actually typed it. From luke at tatooine.planet Mon Feb 7 10:42:12 2005 From: luke at tatooine.planet (Luke Skywalker) Date: Mon, 07 Feb 2005 16:42:12 +0100 Subject: WYSIWYG wxPython "IDE"....? References: <1107560658.584623.303310@o13g2000cwo.googlegroups.com> <4205fcd9@news.highway1.com.au> <1107751731.066796.295170@g14g2000cwa.googlegroups.com> <47pe019efj34ua4o5pjjarlv3i85pa9048@4ax.com> <42077A42.6D22@zeusedit.com> Message-ID: <613f0158aqibks8kvnptbmq3hum6hgs6f1@4ax.com> On Tue, 08 Feb 2005 01:25:06 +1100, Jussi Jumppanen wrote: >> To me, the very fact that the only solution if you don't want >> to carry a multi-megabyte widget set with you (either wxWidgets >> or QT is to go the MFC way (which a lot of C developers seem >> to hate) through > >Have you ever tried to use MFC in anything other than a >simple application? ... which is why I said that the alternative of using PyWin32 didn't sound like a lot of fun :-) Luke. From t-meyer at ihug.co.nz Thu Feb 3 17:26:41 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 4 Feb 2005 11:26:41 +1300 Subject: Where are list methods documented? In-Reply-To: Message-ID: > You're not the only one with a hard time finding the list > documentation. It's even crazier for string docs. > > If you want to see how to strip strings in Python you have to go to > the library docs, then click "sequence types" (betcha don't think of > strings as sequences), then scroll to the bottom, then click "String > Methods", then scroll to find "strip()". Does nobody use an index anymore? If you type "strip" into the index of the Windows HTML help, the first entry is "strip (string method)", which is probably what you want. Or you can use the pyhelp.cgi script linked from and search for "strip" and "strip (string method)" is the second entry (the first, which is strip in the string module, would tell you more-or-less the same, anyway). Or you can go to the general index in the regular version of the HTML help. As you might expect, "strip" can be found under "s". I presume that there's some sort of index in the PDF and all the other versions of the help, too. =Tony.Meyer From fredrik at pythonware.com Mon Feb 14 17:35:54 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Feb 2005 23:35:54 +0100 Subject: tk resource file for geometry? References: <5175a81c05021213322597c0d9@mail.gmail.com> Message-ID: Gabriel B. wrote: > i'm using almost every widget property from my pyTk programs in the > form of resources, like: > self.tk.option_add ( "*InputClass*background", "White" ) > > In the widget creation i have only the Class and the Command > attribute, but i'm having to add some tk options to the geometry > method, in the case, pack. Is there a way to overcome this? > > For example, every single Frame i pack i use > self.pack(fill='both', expand=1) > I'd love to have something like: > self.tk.option_add ( "*Frame*fill", 'both' ) > self.tk.option_add ( "*Frame*expand", 'yes' ) > > Is there anything like it? not that I'm aware of, but I might be missing something. you might wish to repost your question to the tkinter discuss mailing list: http://mail.python.org/mailman/listinfo/tkinter-discuss http://dir.gmane.org/gmane.comp.python.tkinter From invalidemail at aerojockey.com Mon Feb 14 05:17:32 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 14 Feb 2005 02:17:32 -0800 Subject: custom classes in sets References: Message-ID: <1108376252.565131.237330@o13g2000cwo.googlegroups.com> vegetax wrote: > Steven Bethard wrote: > > > vegetax wrote: > >> How can i make my custom class an element of a set? > >> > >> class Cfile: > >> def __init__(s,path): s.path = path > >> > >> def __eq__(s,other): > >> print 'inside equals' > >> return not os.popen('cmp %s %s' % (s.path,other.path)).read() > >> > >> def __hashcode__(s): return s.path.__hashcode__() > >> > >> the idea is that it accepts file paths and construct a set of unique > >> files (the command "cmp" compares files byte by byte.),the files can > >> have different paths but the same content > >> > >> but the method __eq__ is never called [snip] > I just tried and it wont be called =(, so how can i generate a hash code for > the CFile class? note that the comparitions(__eq__) are done based on the > contents of a file using the command 'cmp', i guess thats not posible but > thanks. Let me suggest that, if your idea is to get a set of files all with unique file contents, comparing a file byte-by-byte with each file already in the set is going to be absurdly inefficient. Instead, I recommend comparing md5 (or sha) digest. The idea is, you read in each file once, calculate an md5 digest, and compare the digests instead of the file contents. . import md5 . . class Cfile: . def __init__(self,path): . self.path = path . self.md5 = md5.new().update(open(path).read()).digest() . def __eq__(self,other): . return self.md5 == other.md5 . def __hash__(self): . return hash(self.md5) This is kind of hackish (not to mention untested). You would probably do better to mmap the file (see the mmap module) rather than read it. And, in case you're wondering: yes it is theoretically possible for different files to have the same md5. However, the chances are microscopic. (Incidentally, the SCons build system uses MD5 to decide if a file has been modified.) -- CARL BANKS From steve at holdenweb.com Wed Feb 2 07:36:29 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 02 Feb 2005 07:36:29 -0500 Subject: Next step after pychecker In-Reply-To: References: <41ff0308$0$6503$636a15ce@news.free.fr> <369mivF4ubv6mU1@individual.net> <200502012113.26393.francis.girard@free.fr> Message-ID: Skip Montanaro wrote: > Francis> "Every well-formed expression of the language can be assigned a > Francis> type that can be deduced from the constituents of the > Francis> expression alone." Bird and Wadler, Introduction to Functional > Francis> Programming, 1988 > > Francis> This is certainly not the case for Python since one and the > Francis> same variable can have different types depending upon the > Francis> execution context. Example : > > Francis> 1- if a is None: > Francis> 2- b = 1 > Francis> 3- else: > Francis> 4- b = "Phew" > Francis> 5- b = b + 1 > > Francis> One cannot statically determine the type of b by examining the > Francis> line 5- alone. > > Do you have an example using a correct code fragment? It makes no sense to > infer types in code that would clearly raise runtime errors: > > >>> "Phew" + 1 > Traceback (most recent call last): > File "", line 1, in ? > TypeError: cannot concatenate 'str' and 'int' objects > > Also, note that the type assigned to an expression may be nothing more than > "object". Clearly that wouldn't be very helpful when trying to write an > optimizing compiler, but it is a valid type. > > Skip So reaplce the plus sign with an asterisk ... regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.python.org/pycon/2005/ Steve Holden http://www.holdenweb.com/ From idadesub at gmail.com Thu Feb 3 16:03:07 2005 From: idadesub at gmail.com (Erick) Date: 3 Feb 2005 13:03:07 -0800 Subject: streaming a file object through re.finditer In-Reply-To: References: <1107396145.400036.271010@g14g2000cwa.googlegroups.com> Message-ID: <1107464587.484924.143160@l41g2000cwc.googlegroups.com> I did try to see if I could get that to work, but I couldn't figure it out. I'll see if I can play around more with that api. So say I did investigate a little more to see how much work it would take to adapt the re module to accept an iterator (while leaving the current string api as another code path). Depending on how complicated a change this would be, how much interest would there be in other people using this feature? From what I understand about regular expressions, they're essentially stream processing and don't need backtracking, so reading from an interator should work too (right?). Thanks, -e From bedouglas at earthlink.net Fri Feb 25 19:10:45 2005 From: bedouglas at earthlink.net (bruce) Date: Fri, 25 Feb 2005 16:10:45 -0800 Subject: possible python/linux/gnome issue!! Message-ID: <014f01c51b97$9eff4bb0$0301a8c0@Mesa.com> hi... i'm running rh8.0 with gnome.. i'm not sure of the version (it's whatever rh shipped). i've recently updated (or tried to update) python to the latest version. when i try to run the 'Server Settings/Services' Icon within gnome, nothing happens... i tried to run the 'start services' command from a command line, and got the following... it appears to be a conflict somewhere... -------------------------------------------------------- [root at lserver2 bin]# redhat-config-services /usr/share/redhat-config-services/serviceconf.py:331: SyntaxWarning: argument named None def on_mnuRescan_activate(self,None): /usr/share/redhat-config-services/serviceconf.py:342: SyntaxWarning: argument named None def on_optRL3_activate(self, None): /usr/share/redhat-config-services/serviceconf.py:351: SyntaxWarning: argument named None def on_optRL4_activate(self, None): /usr/share/redhat-config-services/serviceconf.py:375: SyntaxWarning: argument named None def on_optRL5_activate(self, None): /usr/share/redhat-config-services/serviceconf.py:409: SyntaxWarning: argument named None def on_selectCursor(self,None): /usr/share/redhat-config-services/serviceconf.py:419: SyntaxWarning: argument named None def on_btnSave_clicked(self, None): /usr/share/redhat-config-services/serviceconf.py:435: SyntaxWarning: argument named None def on_btnRevert_clicked(self, None): /usr/share/redhat-config-services/serviceconf.py:456: SyntaxWarning: argument named None def on_btnStart_clicked(self,None): /usr/share/redhat-config-services/serviceconf.py:462: SyntaxWarning: argument named None def on_btnStop_clicked(self,None): /usr/share/redhat-config-services/serviceconf.py:468: SyntaxWarning: argument named None def on_btnRestart_clicked(self,None): Traceback (most recent call last): File "/usr/share/redhat-config-services/serviceconf.py", line 24, in ? import gtk ImportError: No module named gtk [root at lserver2 bin]# --------------------------------------------------------- can someone perhaps suggest a solution, or point me to where i might find a solution to this issue. could the python changes be causing a problem? would upgrading gnome potentially fix the issue? can you upgrade gnome without upgrading the rh kernel? i'm posting here, because it might be a python related issue, in that i might have to upgrade other apps to match the new version of python. any ideas/thoughts/etc.. would be appreciated... this is rather frustrating... thanks -bruce bedouglas at earthlink.net From tom at dtsam.com Tue Feb 1 12:50:30 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Tue, 1 Feb 2005 11:50:30 -0600 Subject: variable declaration References: <1107205410.367521.50490@f14g2000cwb.googlegroups.com> <44SdnUZGopnrAWLcRVn-pg@telcove.net> <41FFAE20.7030802@holdenweb.com> Message-ID: "Steve Holden" wrote in message news:41FFAE20.7030802 at holdenweb.com... > Thomas Bartkus wrote: > > > "Carl Banks" wrote in message > > news:1107205410.367521.50490 at f14g2000cwb.googlegroups.com... > > > > > >>How common is it for a local variable to be bound in > >>more than one place within a function? > > > > > > How common? It shouldn't happen at all and that was the point. > > This seems a little excessive to me. Sample use case: > > for something in lst: > if type(something) != type(()): > something = tuple(something) Hhhmmh! I presume you are going through the list and want to gaurantee that every item you encounter is a tuple! So if it ain't - you just re-declare "something" to be a tuple. What was formerly a single string, integer, whathaveyou is now a tuple *containing* a single string, integer, whathaveyou. Do you do it that way because you can? Or because you must? And If the former - is it a good idea? OR did I just miss your codes intent completely? My first inclination would be to create a new variable (type = tuple) and accept (or typecast) each "something" into it as required. The notion that you just morph "something" still seems rather abhorrent. It hadn't occurred to me that iterating through a list like that means the iterater "something" might need to constantly morph into a different type according to a lists possibly eclectic contents. It might explain why the interpreter is incapable of enforcing a type. It would forbid iterating through lists containing a mix of different types. EXCEPT- I must note, that other languages manage to pull off exactly such a trick with a variant type. When you need to pull off a feat such as this, you declare a variant type where the rules are relaxed *for that situation only* and there is no need to toss the baby out with the bathwater. Thomas Bartkus From amichail at gmail.com Tue Feb 22 04:46:52 2005 From: amichail at gmail.com (Amir Michail) Date: 22 Feb 2005 01:46:52 -0800 Subject: Open Course on Software System Design and Implementation Message-ID: <1109065612.062177.52610@f14g2000cwb.googlegroups.com> Hi, I will be teaching a course on software system design and implementation. Like last year, the course will be open meaning that anyone can participate in online discussions -- not only UNSW students. You can find a mind map of topics covered last year here: http://cs3141.web.cse.unsw.edu.au/mindmap.html (Java required) There is a significant python component. Feel free to register and participate in the online discussions. http://cs3141.web.cse.unsw.edu.au Amir From eric_brunel at despammed.com Mon Feb 28 06:27:28 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 28 Feb 2005 12:27:28 +0100 Subject: Polling selections from a listbox (Tkinter) References: <1109418496.454931.302810@z14g2000cwz.googlegroups.com> Message-ID: On 26 Feb 2005 03:48:16 -0800, Harlin Seritt wrote: [snip] > Obviously when this starts up this is going to show selection #0 inside > the label box. How do I make sure that whatever is arbitrarily selected > ends up in the label box as this gui runs? I tried doing a bind: > > self.listbox.bind("", self.changelabel) > > This did not work as intended as the changelabel's text option only > showed what the selection index was BEFORE the event took place. Bind on ; is a synonym for , and when the button is pressed, the selection is not done yet. HTH -- python -c 'print "".join([chr(154 - ord(c)) for c in "U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])' From deetsNOSPAM at web.de Sun Feb 13 14:01:54 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 13 Feb 2005 20:01:54 +0100 Subject: Second posting - Howto connect to MsSQL References: Message-ID: John Fabiani wrote: > Hi, > Since this is (sort of) my second request it must not be an easy solution. > Are there others using Python to connect MsSQL? At the moment I'd accept > even a windows solution - although, I'm looking for a Linux solution. Use unix-odbc and a mssql driver for unxi-odbc. Its called ftl or tls or something. As always: Google is your friend... -- Regards, Diez B. Roggisch From gmane-schpam at joefrancia.com Wed Feb 16 15:40:31 2005 From: gmane-schpam at joefrancia.com (Joe Francia) Date: Wed, 16 Feb 2005 15:40:31 -0500 Subject: How can I Fill in web form and post back References: <3QMQd.2109818$B07.322065@news.easynews.com> Message-ID: On Wed, 16 Feb 2005 19:05:35 GMT, Rigga wrote: > Joe Francia wrote: > >> Rigga wrote: >>> Hi, >>> >>> I am looking for the best way to use Python to get a web page, look for >>> some particular fields on a form, fill in the fields and submit the >>> form >>> but I have no idea where to start - any pointers appreciated >>> >>> many thanks >>> >>> Rigga >> >> Here's a pretty good resource: >> http://www.google.com/search?q=python+fill+web+forms >> > Thanks but I already checked there and didnt come up with much Really? The second link is for ClientForm, the description of which reads: "ClientForm is a Python module for handling HTML forms on the client side, useful for parsing HTML forms, filling them in and returning the completed forms to the server." That seems to exactly fulfil your requirements. Are you sure you really looked? -- Soraia: http://www.soraia.com/ From ilias at lazaridis.com Mon Feb 14 05:33:16 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Mon, 14 Feb 2005 12:33:16 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: David Fraser wrote: > Ilias Lazaridis wrote: [...] > Just to add to all the other answers: > > Don't just complain, submit patches and work at keeping them maintained. > If this is done for a while it may be more of an argument for having > them included I do not "just complain". I've spend already hours with writing down the questionaire [which you have successfully ignored]. . -- http://lazaridis.com From jzgoda at gazeta.usun.pl Fri Feb 18 15:13:11 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 18 Feb 2005 21:13:11 +0100 Subject: unicode encoding usablilty problem In-Reply-To: References: Message-ID: Fredrik Lundh napisa?(a): >>This brings up another issue. Most references and books focus exclusive on entering unicode >>literal and using the encode/decode methods. The fallacy is that string is such a basic data type >>use throughout the program, you really don't want to make a individual decision everytime when >>you use string (and take a penalty for any negligence). The Java has a much more usable model >>with unicode used internally and encoding/decoding decision only need twice when dealing with >>input and output. > > that's how you should do things in Python too, of course. a unicode string > uses unicode internally. decode on the way in, encode on the way out, and > things just work. There are implementations of Python where it isn't so easy, Python for iSeries (http://www.iseriespython.com/) is one of them. The code written for "normal" platform doesn't work on AS/400, even if all strings used internally are unicode objects, also unicode literals don't work as expected. Of course, this is implementation fault but this makes a headache if you need to write portable code. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From bjourne at gmail.com Sat Feb 5 13:49:48 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 5 Feb 2005 19:49:48 +0100 Subject: Alternative to standard C "for" In-Reply-To: <1107628331.816935.16760@o13g2000cwo.googlegroups.com> References: <1107628331.816935.16760@o13g2000cwo.googlegroups.com> Message-ID: <740c3aec050205104924a82d23@mail.gmail.com> > I am quite new to Python, and have a straight & simple question. > In C, there is for (init; cond; advance). We all know that. > In Python there are two ways to loop over i=A..B (numerical.): > 1) i = A > while i ...do something... > i+=STEP This is indeed quite ugly. You rarely need such loops in Python and with some thinking you can often translate the C-equivalent to something more pythonic. As you guessed, your second problem is best solved with a generator function - xrange(). It is completely equal to range() except that it returns a generator instead of a list. -- mvh Bj?rn From simoninusa2001 at yahoo.co.uk Fri Feb 11 15:04:33 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 11 Feb 2005 12:04:33 -0800 Subject: Multi-Platform installer generator In-Reply-To: References: Message-ID: <1108152273.114309.92060@o13g2000cwo.googlegroups.com> if you're referring to the installshield x/mp products, forget it, they are really bad. the last company i worked for who used x/mp actually went back to shell scripts for unix and installshield pro for windows, as the java thing was abismall, and even the ide was written in java, so horribly slow. personally i'd stick with shell scripts for unix, and innosetup for windows. From kdahlhaus at yahoo.com Fri Feb 18 10:15:05 2005 From: kdahlhaus at yahoo.com (kdahlhaus at yahoo.com) Date: 18 Feb 2005 07:15:05 -0800 Subject: Chart Director? Message-ID: <1108739705.870161.36050@z14g2000cwz.googlegroups.com> Does anyone here have experience with Chart Director (http://www.advsofteng.com/index.html)? I'm thinking about purchasing it and looking for any feedback from the Python community. Thanks From jdhunter at ace.bsd.uchicago.edu Thu Feb 3 21:59:14 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 03 Feb 2005 20:59:14 -0600 Subject: [Fwd: [gnu.org #220719] Re: python and gpl] In-Reply-To: <7x3bwdkpbe.fsf@ruckus.brouhaha.com> (Paul Rubin's message of "03 Feb 2005 18:54:13 -0800") References: <7x3bwdkpbe.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "Paul" == Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes: Paul> Various possible candidates for such dragging have Paul> apparently decided that their chances weren't too good. Or simply that it wasn't worth the cost to go to court, even if they presumed they would eventually win. JDH From aisomurs at paju.oulu.fi Sat Feb 12 12:15:26 2005 From: aisomurs at paju.oulu.fi (Antti Isomursu) Date: 12 Feb 2005 09:15:26 -0800 Subject: Newbie needs help with canvas.create_image ! Message-ID: Ok, this is my problem: With code below I get a red box with given width and height. When I use that create_image, nothing happens. I only see that same red box. Why is that? The loop.bmp is working fine when I use show() method. win = Toplevel() canvas = Canvas(win, width=100, height=100, background='red') canvas.pack() im = Image.open("loop.bmp") photo = ImageTk.PhotoImage(im) canvas.create_image(8, 8, anchor="nw", image=photo) (Interestingly loop.bmp appears to the red box if I try to pack that canvas.create_image ( canvas.create_image.pack()) and ofcourse I also get an error message that It can't be done. But anyway the picture appears ...weird) From steven.bethard at gmail.com Mon Feb 21 23:37:07 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 21 Feb 2005 21:37:07 -0700 Subject: NOOB coding help.... In-Reply-To: <69012ed09e48920e1e80e311bca1659c@localhost.talkaboutprogramming.com> References: <69012ed09e48920e1e80e311bca1659c@localhost.talkaboutprogramming.com> Message-ID: Igorati wrote: > list = [ ] > a = 1 > print 'Enter numbers to add to the list. (Enter 0 to quit.)' > while a != 0 : > a = input('Number? ') > list.append(a) > zero = list.index(0) > del list[zero] > list.sort() A simpler approach is to use the second form of the builtin iter function which takes a callable and a sentinel: py> def getint(): ... return int(raw_input('Number? ')) ... py> numbers = sorted(iter(getint, 0)) Number? 3 Number? 7 Number? 5 Number? 2 Number? 0 py> numbers [2, 3, 5, 7] Note that I've renamed 'list' to 'numbers' so as not to hide the builtin type 'list'. > variableMean = lambda x:sum(x)/len(x) > variableMedian = lambda x: x.sort() or x[len(x)//2] > variableMode = lambda x: max([(x.count(y),y) for y in x])[1] > s = variableMean(list) > y = variableMedian(list) > t = variableMode (list) See "Inappropriate use of Lambda" in http://www.python.org/moin/DubiousPython. Lambdas aside, some alternate possibilities for these are: def variable_median(x): # don't modify original list return sorted(x)[len(x)//2] def variable_mode(x): # only iterate through x once (instead of len(x) times) counts = {} for item in x: counts[x] = counts.get(x, 0) + 1 # in Python 2.5 you'll be able to do # return max(counts, key=counts.__getitem__) return sorted(counts, key=counts.__getitem__, reverse=True)[0] Note also that you probably want 'from __future__ import divsion' at the top of your file or variableMean will sometimes give you an int, not a float. > x = (s,y,t) > inp = open ("Wade_StoddardSLP3-2.py", "r") > outp = open ("avg.py", "w") > f = ("avg.py") > for x in inp: > outp.write(x) > import pickle > pickle.dump(x, f) If you want to save s, y and t to a file, you probably want to do something like: pickle.dump((s, y, t), file('avg.pickle', 'w')) I don't know why you've opened Wade_StoddardSLP3-2.py, or why you write that to avg.py, but pickle.dump takes a file object as the second parameter, and you're passing it a string object, "avg.py". > f = open("avg.py","r") > avg.py = f.read() > print 'The Mean average is:', mean > print 'The Median is:', meadian > print 'The Mode is:', mode mean, median, mode = pickle.load(file('avg.pickle')) print 'The Mean average is:', mean print 'The Median is:', meadian print 'The Mode is:', mode HTH, STeVe From deetsNOSPAM at web.de Tue Feb 15 06:43:29 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 15 Feb 2005 12:43:29 +0100 Subject: Accessing Objects Based On Their ID References: Message-ID: <37e5ioF5brmq1U1@individual.net> > Given the ID of an object, is there a way to access it? For example, > if we have the ID of a class instance, is there a way to invoke its > methods and attributes knowning only that ID? Similarly, if we have the > ID of a function, is there a way to call it? No. > This comes up because of an implementation I had in mind wherein I > would store the IDs of a notionally linked-list of objects - but without > the link - I just want to store their IDs in the desired order. But > later, when I want to actually use the objects I need a way to get from ID > back to something accessible in the namespace... Why only the id? A list only stores a reference to the object anyway - no copy of it. So you don't gain anything by using the id. -- Regards, Diez B. Roggisch From pinard at iro.umontreal.ca Sun Feb 20 09:22:46 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Sun, 20 Feb 2005 09:22:46 -0500 Subject: [ANN] Python 2.4 Quick Reference available In-Reply-To: <421898CD.6040408@iinet.net.au> References: <1108831318.290846.5930@z14g2000cwz.googlegroups.com> <37qaleF5gd7bcU1@individual.net> <421898CD.6040408@iinet.net.au> Message-ID: <20050220142246.GA17000@phenix.progiciels-bpi.ca> [Nick Coghlan] > George Sakkis wrote: > > >Still the word "open" sounds too general if the meaning is "open > >a file-like object"; OTOH this could be a good thing if in some > >future version "open('http://www.python.org')" was e.g. an alias to > >urllib2.urlopen. > Exactly the reason the BDFL gave for preferring 'open' - it may be extended > to opening other types of objects than files. So, when we *know* we are opening a file, `file' cannot be a bad choice! :-) Moreover, practically, most of the times, we know we are opening a file. `open' is opened (sic!) for some future magic. I prefer to protect my programs against future magic, until this magic is precisely specified. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From peter at somewhere.com Fri Feb 18 02:29:45 2005 From: peter at somewhere.com (Peter Maas) Date: Fri, 18 Feb 2005 08:29:45 +0100 Subject: [EVALUATION] - E02 - ULTIMATE RECIPE TO RESOLVE ALL ISSUES In-Reply-To: References: Message-ID: Terry Reedy schrieb: > "Peter Maas" wrote in message > news:cuv1st$6um$1 at swifty.westend.com... > >>http://nobelprize.org/medicine/educational/pavlov/ >> >>and then do something useful :) > > > Thanks. I showed this to my daughter, who enjoyed the game, and explained > your point re Pavlov posting, and about Pavlov advertising, etc. Fine that at least one person benefitted from my post :) I came across this when I browsed through the Lazaridis thread which was - if for nothing else - good for some laughs. But at the same time I felt uncomfortable to see how many bright Pythoneers cared to give well thought, helpful and friendly answers to somebody who was acting unpolite and kind of stupid, even mechanical. This newsgroup is used to be helpful to newbies and Lazaridis was ringing the newbie bell. Perhaps we will soon see a triumphant publication with the title "Ilias Lazaridis - the ELIZA of the 21st century. A milestone towards the perfect Turing test" ;) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From dontwant at spam.com Sat Feb 12 21:53:32 2005 From: dontwant at spam.com (Courageous) Date: Sat, 12 Feb 2005 18:53:32 -0800 Subject: Kill GIL (was Re: multi threading in multi processor (computer)) References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <1107964587.818199.223980@g14g2000cwa.googlegroups.com> <7xr7jlwieq.fsf@ruckus.brouhaha.com> Message-ID: >Killing the GIL is proposing a silver bullet where there is no werewolf-ly, About the only reason for killing the GIL is /us/. We, purists, pythonistas, language nuts, or what not, who for some reason or other simply hate the idea of the GIL. I'd view it as an artistic desire, unurgent, something to plan for the future canvas upon which our painting is painted... C// From Serge.Orlov at gmail.com Tue Feb 15 00:59:01 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: Tue, 15 Feb 2005 05:59:01 +0000 (UTC) Subject: os.rename() doesn't work w/unicode?? References: Message-ID: fanbanlo wrote: > C:\MP3\001.txt -> 0.txt > C:\MP3\01. ??? - ????(???).mp3 -> 1.mp3 > > 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 "C:\MP3\!RenameNum.py", line 40, in ? > renameFiles(os.path.dirname(sys.argv[0])) > File "C:\MP3\!RenameNum.py", line 26, in renameFiles > os.rename(os.path.join(path, filenames), new_filename) > OSError: [Errno 22] Invalid argument os.rename works with unicode, you're getting this error because question marks are not allowed in file names on Windows. Serge. From ilias at lazaridis.com Mon Feb 14 07:23:08 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Mon, 14 Feb 2005 14:23:08 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: Brian Beck wrote: > Ilias Lazaridis wrote: >> this answer do not fit in most questions. >> >> please review them again. > > Actually, it does. Please review them again. > >> My questions: >> >> a) Why does the Python Foundation not provide additionally a binary >> version, compiled with MinGW or another open-source compiler? > > Because no one has yet volunteered their time and effort to get the > job done. [...] thank you for placing the answers in context. >> I ask some questions and suggest some things. >> >> Voluntarlily and without beeing paid. > > What a martyr you are. like all the open-source folks? >> There are many commercial systems around python. >> >> So please stop this volunteerism-stuff. > > If the support you're looking for is beneficial to your commercial > application a.k.a. business, then why aren't you making it happen? I am in the process of doing so. First I have to analyze the status-quo. Which is not very simple with such a community. > Obviously the existing commercial development teams are doing fine > without it, otherwise it would exist. Even then, a commercial > developer providing their development work to enhance the standard > Python distribution IS volunteering. One of the most funny things within open-source is that switching: first: "we have powerfull solutions which beat this and that" then: "hey, this is just volunteer work" - I was impressed by zope and plone. But if those answers above were of official nature, I must seriously rethink if I can rely on _any_ system which is based on python, as the foundation and the community do not care about essential needs and requirements. . -- http://lazaridis.com From me at privacy.net Tue Feb 22 06:40:31 2005 From: me at privacy.net (Dan Sommers) Date: 22 Feb 2005 06:40:31 -0500 Subject: python2.4 generator expression > python2.3 list expression References: Message-ID: On 22 Feb 2005 09:14:50 GMT, Duncan Booth wrote: > Here's yet another way to achieve the same results. This version doesn't > iterate over any bits at all: >>>> import operator >>>> parity = [ False ] >>>> for i in range(7): > parity += map(operator.not_, parity) Very clever! :-) Picking a nit, that version iterates over *two* sets of bits. The "for" loop over each possible bit in the input values. The "map" function over the parity bits accumulated up to that point. And the "+=" operator over those same bits again. Make that *three* sets of bits. I stand humbled. Regards, Dan -- Dan Sommers ?? ? ?? ? c? = 1 From whereU at now.com Sat Feb 19 17:09:59 2005 From: whereU at now.com (Eric Pederson) Date: Sat, 19 Feb 2005 14:09:59 -0800 Subject: exercise: partition a list by equivalence In-Reply-To: <1108849063.857663.279920@c13g2000cwb.googlegroups.com> References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> <1108814276.680736.264380@l41g2000cwc.googlegroups.com> <1108849063.857663.279920@c13g2000cwb.googlegroups.com> Message-ID: <20050219140959.10815564.whereU@now.com> > From: "Xah Lee" > > The GOTO statement from Perl has been messed up. hey, I didn't do it! > > This block: > ? for group in interm: what do the funny little "?"s stand for? Eric Pederson http://www.songzilla.blogspot.com ::::::::::::::::::::::::::::::::::: domainNot="@something.com" domainIs=domainNot.replace("s","z") ePrefix="".join([chr(ord(x)+1) for x in "do"]) mailMeAt=ePrefix+domainIs ::::::::::::::::::::::::::::::::::: From jorgencederberg at hotmail.com Fri Feb 25 02:44:28 2005 From: jorgencederberg at hotmail.com (=?ISO-8859-1?Q?J=F8rgen_Cederberg?=) Date: Fri, 25 Feb 2005 08:44:28 +0100 Subject: Default value for Listbox (Tkinter) In-Reply-To: <1109299588.575892.244990@g14g2000cwa.googlegroups.com> References: <1109299588.575892.244990@g14g2000cwa.googlegroups.com> Message-ID: Harlin Seritt wrote: > Whenever I set up something similar: > > vals = ['1', '2','3'] > for v in vals: > listbox.inset(END, v) > > I notice that when this listbox is displayed, there is never a default > value. How can I make sure that one of the indices is selected by > default? > Hi Harlin, you must use the select_set method of the listbox. --- from Tkinter import * root = Tk() listbox = Listbox(root) listbox.pack() vals = ['1', '2','3'] for v in vals: listbox.insert(END, v) listbox.select_set(0) # sets the first element root.mainloop() --- Some good resources for Tkinter: http://www.pythonware.com/library/tkinter/introduction/index.htm http://infohost.nmt.edu/tcc/help/pubs/tkinter/ HTH J?rgen Cederberg From jeffrey at fro.man Fri Feb 4 10:55:37 2005 From: jeffrey at fro.man (Jeffrey Froman) Date: Fri, 04 Feb 2005 07:55:37 -0800 Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xy8e5jagh.fsf@ruckus.brouhaha.com> <1107490052.542546.285950@c13g2000cwb.googlegroups.com> Message-ID: <11076nqn1ats421@corp.supernews.com> M.E.Farmer wrote: > Div is a block level tag and span isn't. > You can also group them??together?and?nest?them. One caveat here -- I don't believe you can (should) nest a
inside a , or for that matter, nest any block-level element inside an inline element. Jeffrey From janeaustine50 at hotmail.com Wed Feb 23 04:36:57 2005 From: janeaustine50 at hotmail.com (janeaustine50 at hotmail.com) Date: 23 Feb 2005 01:36:57 -0800 Subject: Style guide for subclassing built-in types? In-Reply-To: <1109150091.356411.150460@l41g2000cwc.googlegroups.com> References: <1109127834.660822.247120@g14g2000cwa.googlegroups.com> <1109150091.356411.150460@l41g2000cwc.googlegroups.com> Message-ID: <1109151417.903188.73790@f14g2000cwb.googlegroups.com> Fuzzyman wrote: > I guess print is using the __repr__ (or __str__ ?) methods of lsit - > which you will need to override as well. > > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml Thank you but the problem is that I have to express my intention in duplicate places -- __iter__(along with "next"), __str__, __eq__ and so on. p.s. the reason I'm not sticking to reversed or even reverse : suppose the size of the list is huge. From anomousty at webwonders.org Fri Feb 18 12:31:46 2005 From: anomousty at webwonders.org (m) Date: Fri, 18 Feb 2005 11:31:46 -0600 Subject: Newbie CGI problem In-Reply-To: References: Message-ID: Rory Campbell-Lange wrote: > #!/usr/bin/python > import cgi > print "Content-type: text/html\n\n" > print "hi" > > Gives me the following in my browser: > > ''' > hi > Content-type: text/html > > > hi > ''' > > Why are there two 'hi's? > > Thanks, > Rory gives just one hi for me. From AnOvercomer02 at webtv.zzn.com Tue Feb 8 05:06:17 2005 From: AnOvercomer02 at webtv.zzn.com (AnOvercomer02@webtv.net (Cody Houston)) Date: 8 Feb 2005 02:06:17 -0800 Subject: Learning Python - resources and ideas Message-ID: <1107855763.533466.254380@c13g2000cwb.googlegroups.com> Hi. What is the best way to learn Python? None of the local schools near me teach any courses on the topic. Thanks. -- Cody Houston AnOvercomer02 at webtv.net From michels at linmpi.mpg.de Wed Feb 16 08:43:08 2005 From: michels at linmpi.mpg.de (Helmut Michels) Date: Wed, 16 Feb 2005 14:43:08 +0100 Subject: [ANN] Data Plotting Library DISLIN 8.3 Message-ID: I am pleased to announce version 8.3 of the data plotting software DISLIN. DISLIN is a high-level and easy to use plotting library for displaying data as curves, bar graphs, pie charts, 3D-colour plots, surfaces, contours and maps. Several output formats are supported such as X11, VGA, PostScript, PDF, CGM, WMF, HPGL, TIFF, GIF, PNG, BMP and SVG. The software is available for several C, Fortran 77 and Fortran 90 compilers. Plotting extensions for the interpreting languages Perl, Python and Java are also supported for the most operating systems. DISLIN distributions and manuals in PDF, PostScript and HTML format are available from the DISLIN home page http://www.dislin.de and via FTP from the server ftp://ftp.gwdg.de/pub/grafik/dislin ------------------- Helmut Michels Max Planck Institute for Solar System Research Phone: +49 5556 979-334 Max-Planck-Str. 2 Fax : +49 5556 979-240 D-37191 Katlenburg-Lindau Mail : michels at linmpi.mpg.de From mahs at telcopartners.com Fri Feb 4 22:55:03 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 04 Feb 2005 19:55:03 -0800 Subject: changing local namespace of a function In-Reply-To: <4204400C.5060608@iinet.net.au> References: <4204400C.5060608@iinet.net.au> Message-ID: Nick Coghlan wrote: > Michael Spencer wrote: > >>> def fun(dict): >>> # set dict as local namespace >>> # locals() = dict? >>> z = x + y >> >> >> As you no doubt have discovered from the docs and this group, that >> isn't doable with CPython. > > > Not entirely impossible: > > Py> def f(d): > ... exec "locals().update(d)" > ... return x + y > ... > Py> f(dict(x=1, y=2)) > 3 > > Due to the way 'exec' is implemented, modifications to locals() inside > an exec statement actually take effect (basically, they're freeloading > on the code which allows 'exec "x = 1"' to work properly). > > This is an evil, evil hack and almost certainly not what anyone should > be doing. Also, variables created this way will be slower than normal > variables due to the way the associated code works. > > Cheers, > Nick. > Oooh - evil indeed, but thanks for the pointer. I debated including a link to one of the 'writable locals' threads, when I settled on not 'doable', but gambled on being probably useful rather than certainly accurate. Just goes to show you can't get away with anything in this NG ;-) Cheers Michael From raghulj at gmail.com Mon Feb 21 23:29:38 2005 From: raghulj at gmail.com (Raghul) Date: 21 Feb 2005 20:29:38 -0800 Subject: copying or moving the mail message using imaplib In-Reply-To: References: <1109044151.869953.187270@c13g2000cwb.googlegroups.com> Message-ID: <1109046578.692118.24350@l41g2000cwc.googlegroups.com> Thanks for ur message .How it is possible to copy the messages betwwen folder ?I can't understand the copy function in python documentation. Please Can u give me a sample example for this. And I also to copy using uid but in vain. here is my program. #!/usr/bin/env python #Normal Library import socket import os import re import time import sys import getopt import types import traceback import email import mhlib,popen2 import string, random import StringIO, rfc822 import email.Parser from getpass import getpass from email.Header import Header from email.Utils import parsedate from imaplib import IMAP4 as BaseIMAP from email.Message import Message from email.Header import Header # Antispam database lib class IMAPSession(BaseIMAP): def __init__(self, server, port, debug=0, do_expunge=False): BaseIMAP.__init__(self, server, port) def getsizes(imap, msgs): uidfetchbatchsize =25 res2=[] # Python really needs do - while while 1: if len(msgs)==0: break if len(msgs)>uidfetchbatchsize: msgmore=msgs[uidfetchbatchsize:] msgs=msgs[:uidfetchbatchsize] else: msgmore=[] msgs=string.join(msgs, ',') res=imap.uid("FETCH", msgs, "(UID RFC822.SIZE)") assertok(res, "uid fetch", msgs, "(UID RFC822.SIZE)") for i in res[1]: mo=gsre.match(i) if mo is None: if verbose: print "getsize Eh?", i else: res2.append((mo.group(2), mo.group(1))) msgs=msgmore return res2 def run(): import getpass #name = raw_input("Enter User name : ") passwd = getpass.getpass ("Enter the password : ") server ="mail.myhost.com" port = 143 ss = IMAPSession(server,port) sd = ss.login ("raghul",passwd) uidfetchbatchsize =25 print ss.list() print ss.select('Junk E-mail') typ, data = ss.search(None,"ALL" ) for num in data[0].split(): typ, data = ss.fetch(num, '(RFC822)') print 'Message %s\n%s\n' % (num, data[0][1]) print "_____" dat = ss.uid('copy',num,'INBOX') print "copied" print dat print num print "_____" ss.logout() if __name__ == '__main__': run() From evrim at ankabt.com Sat Feb 5 02:43:44 2005 From: evrim at ankabt.com (Evrim Ozcelik) Date: Sat, 05 Feb 2005 09:43:44 +0200 Subject: Medical GUI Application With Python Message-ID: <42047930.1030604@ankabt.com> We are developing a medical software about PSG (PolySomnoGraphy) analysis. The application takes signal data from an electronic device and we will show this continious signal function on the interfaces. There are about 20-30 signal channels and the user selected channels are shown. We want to run this application over different platforms. My question is: 1. What must be our IDE 2. What class library for GUI must be use (wxWindows, Qt, GTK, etc.) 3. Is there any GUI package for visulazing signal functions (like sinozodial functions) in real time; this module will behave as an oscilloscope Thanks, -- Evrim ?z?elik Anka Information Technologies R&D Co. Manager of Internet Technologies Web : http://www.ankabt.com/ Gsm : +90 555 474 84 52 Phone : +90 212 276 19 69 # 134 -------------- next part -------------- An HTML attachment was scrubbed... URL: From robin at reportlab.com Tue Feb 15 13:43:54 2005 From: robin at reportlab.com (Robin Becker) Date: Tue, 15 Feb 2005 18:43:54 +0000 Subject: customizing metaclass constructed classes In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3398430@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3398430@exchange.hqamor.amorhq.net> Message-ID: <421242EA.2070701@chamonix.reportlab.co.uk> Robert Brewer wrote: ....... .......... > > You *are* using a language with callable functions, right? ;) > > #base.py > > def create_special_property(cls, f): > # create special property based on f > > class M(type): > def __init__(cls, name, bases, dict): > super(M, cls).__init__(name, bases, dict) > for f in dict['_fieldDefs']: > create_special_property(cls, f) > > #database.py > class C(A): > _fieldDefs =[ > IntColumn('id',primaryKey=1,allowNull=0), > TextColumn('name',allowNull=0,size=50), > TextColumn('description',allowNull=1,size=50), > ] > > base.create_special_property(C, DateColumn('start_date')) You're absolutely right :) I can modify the class in place if I have access to the required modifications. This seems more easily assimilable and definitely works in my cases. Would it make sense to put the def create_special_property inside the metaclass as it then becomes available as a class method of A as well as being visible as cls.create_special_property(f) in the metaclass __init__? > Slightly off-topic: if you really want to make it pretty, add a custom > descriptor so you can write: > > class C(A): > id = IntColumn(primaryKey=1,allowNull=0) > name = TextColumn(allowNull=0,size=50) > description = TextColumn(allowNull=1,size=50) > I'll certainly take a look at this > See UnitProperty (the descriptor), MetaUnit (the metaclass), and Unit > (the domain object) in http://www.aminus.org/rbre/dejavu/__init__.py for > an implementation of mine which you can steal in toto (because it's > public domain). > -- Robin Becker From steven.bethard at gmail.com Fri Feb 25 01:06:01 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 24 Feb 2005 23:06:01 -0700 Subject: Interesting decorator use. In-Reply-To: References: <421e2398@nntp0.pdx.net> Message-ID: <67-dndQDN9PaXYPfRVn-3A@comcast.com> Tom Willis wrote: > Getting back to your recipe. Through the explanation of how to get > parameters in there, I see how it is possible to get a logger in > there. Cool. But credit where it's due, the recipe's Scott David Daniels's. =) STeVe From deetsNOSPAM at web.de Mon Feb 14 07:12:04 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 14 Feb 2005 13:12:04 +0100 Subject: Problem with nested lists as arrays References: <1108382521.266024.281620@g14g2000cwa.googlegroups.com> Message-ID: <37bisjF58tsaeU1@individual.net> Some general remarks: > def getEmptySlot(self): > i = 0 > j = 0 > while i <= self.dim-1: > while j <= self.dim-1: > if self.elements[j][i] == -1: > return [j, i] > j = j+1 > j = 0 > i = i + 1 make this: def getEmptySlot(self): for i in xrange(self.dim): for j in xrange(self.dim): if self.elements[i][j] == -1: return (i,j) > def getPossibleMoves(self): > emptySlot = self.getEmptySlot() > y = emptySlot[1] > x = emptySlot[0] make this: x,y = self.getEmptySlot() -- Regards, Diez B. Roggisch From gandalf at geochemsource.com Tue Feb 8 07:59:48 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Tue, 08 Feb 2005 13:59:48 +0100 Subject: python connect to server using SSH protocol In-Reply-To: <1107850655.289129.94880@o13g2000cwo.googlegroups.com> References: <1107850655.289129.94880@o13g2000cwo.googlegroups.com> Message-ID: <4208B7C4.5090000@geochemsource.com> ajikoe at gmail.com wrote: >How can python connect to server which use SSH protocol? >Is it easy since my python has to run third party vendor, write data, >read data inside the server (supercomputer). > > In advance, I'm not sure if I understood your problem. SSH is clearly a remote shell. You will be able to execute other programs on the remote computer. Is is suitable to use this: child_stdin,child_stdout,child_stderr = os.popen2('ssh -l my_username my_host') On the other side, you can write an application that also uses stdin/stdout for communication. Best, Laci 2.0 -- _________________________________________________________________ Laszlo Nagy web: http://designasign.biz IT Consultant mail: gandalf at geochemsource.com Python forever! From mefjr75 at hotmail.com Sun Feb 6 22:58:25 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 6 Feb 2005 19:58:25 -0800 Subject: pygame.mixer.music not playing References: <36mb0iF54udklU1@individual.net> <1107700800.258876.298010@z14g2000cwz.googlegroups.com> <36mvjkF54gvnrU1@individual.net> Message-ID: <1107748705.808825.319270@f14g2000cwb.googlegroups.com> Hello again, Sorry you have had no success. I would suspect it is your system setup. Seems the code is working. I didn't think you had the typo problem, just mentioned it because it says somewhere in the docs that if the mixer has problems with file loading it would result in a proxy object that supported the play and stop commands. Please post your os name and version, Python version, Pygame version, etc. Some genius out there might know how to fix it. Also you can try and look for another sound package, like maybe pyFMOD ;) Home of FMOD http://www.fmod.org/ and the Python bindings http://sourceforge.net/projects/uncassist the people who wrote pyFMOD (lots of stuff there) http://www.cs.unc.edu/~parente/tech/tr01.shtml Hth, M.E.Farmer From tzot at sil-tec.gr Thu Feb 3 08:43:26 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 03 Feb 2005 15:43:26 +0200 Subject: streaming a file object through re.finditer References: <1107396145.400036.271010@g14g2000cwa.googlegroups.com> <1107397107.667600.326820@o13g2000cwo.googlegroups.com> Message-ID: On Wed, 2 Feb 2005 22:22:27 -0500, rumours say that Daniel Bickett might have written: >Erick wrote: >> True, but it doesn't work with multiline regular expressions :( >If your intent is for the expression to traverse multiple lines (and >possibly match *across* multiple lines,) then, as far as I know, you >have no choice but to load the whole file into memory. *If* the OP knows that their multiline re won't match more than, say, 4 lines at a time, the code attached at the end of this post could be useful. Usage: for group_of_lines in line_groups(, line_count=4): # bla bla The OP should take care to ignore multiple matches as the n-line window scans through the input file; eg. if your re searches for '3\n4', it will match 3 times in the first example of my code. |import collections | |def line_groups(fileobj, line_count=2): | iterator = iter(fileobj) | group = collections.deque() | joiner = ''.join | | try: | while len(group) < line_count: | group.append(iterator.next()) | except StopIteration: | yield joiner(group) | return | | for line in iterator: | group.append(line) | del group[0] | yield joiner(group) | |if __name__=="__main__": | import os, tempfile | | # create two temp file for 4-line groups | | # write n+3 lines in first file | testname1= tempfile.mktemp() # depracated & insecure but ok for this test | testfile= open(testname1, "w") | testfile.write('\n'.join(map(str, range(7)))) | testfile.close() | | # write n-2 lines in second file | testname2= tempfile.mktemp() | testfile= open(testname2, "w") | testfile.write('\n'.join(map(str, range(2)))) | testfile.close() | | # now iterate over four line groups | | for bunch_o_lines in line_groups( open(testname1), line_count=4): | print repr(bunch_o_lines), | print | | for bunch_o_lines in line_groups( open(testname2), line_count=4): | print repr(bunch_o_lines), | print | | os.remove(testname1); os.remove(testname2) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From fredrik at pythonware.com Mon Feb 7 18:11:14 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Feb 2005 00:11:14 +0100 Subject: Big development in the GUI realm References: <1107795145.049239.73450@l41g2000cwc.googlegroups.com><5ocf01hmspufk3iusvm35p6hj4mes5heke@4ax.com> <4207D64F.2000709@optushome.com.au> Message-ID: Tim Churches wrote: > Thus, it seems to me, and to the expert legal advice which we sought (note the scope of the advice > was Australian law only) that provided no GLPed source or object code is mixed, included or > combined with non-GPLed code and how exactly are you going to load a DLL from an EXE file with- out "mixing, including, or combining" the two? I don't see how the legal advice you got is incompatible with the FAQ; they both say that as long as you keep things separate, you're in the clear. but as soon as you mix things, the GPL applies. From polytechnique at gmail.com Mon Feb 28 11:31:09 2005 From: polytechnique at gmail.com (DENG) Date: 28 Feb 2005 08:31:09 -0800 Subject: Share your SciTEGlobal.properties pls~~~~ Message-ID: <1109608269.649625.208200@o13g2000cwo.googlegroups.com> hi, im new to Python, i chose SciTE as my Python editor. but the problem is SciTE needs to be config carefully, are there anyone use SciTE too? can you share your SciTEGlobal.properties file? black background solution is prefered:) thanks in advance best regards From stephen.thorne at gmail.com Fri Feb 11 02:10:25 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Fri, 11 Feb 2005 17:10:25 +1000 Subject: convert list of tuples into several lists In-Reply-To: <420c5241$0$6619$8fcfb975@news.wanadoo.fr> References: <36uihlF58p63iU1@individual.net> <1107998078.610891.111510@z14g2000cwz.googlegroups.com> <420c5241$0$6619$8fcfb975@news.wanadoo.fr> Message-ID: <3e8ca5c80502102310d434672@mail.gmail.com> On Fri, 11 Feb 2005 07:35:43 +0100, Pierre Quentel wrote: > Steven Bethard a ?crit : > > Cappy2112 wrote: > > > >> What does the leading * do? > > > > > > Tells Python to use the following iterable as the (remainder of the) > > argument list: > > > > Could someone explain why this doesn't work : > > Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> def f(*args,**kw): > ... print args, kw > ... > >>> f(*[1,2]) > (1, 2) {} > >>> f(*[1,2],x=1) > File "", line 1 > f(*[1,2],x=1) > ^ > SyntaxError: invalid syntax the * and ** must occur at the end. f(x=1, *[1,2]) is valid. Stephen. From tjreedy at udel.edu Mon Feb 14 12:38:02 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Feb 2005 12:38:02 -0500 Subject: nested lists as arrays References: <1108384089.804375.179130@f14g2000cwb.googlegroups.com> <37bklfF5a7s7vU2@individual.net> Message-ID: "Diez B. Roggisch" wrote in message > >And use xrange instead of range. For small dimensions like 3,4,5, xrange is way overkill and perhaps takes both more space and time. Since dim is a constant for a given puzzle, I would set self._range = range(dim) in __init__() and use that to iterate. And, as I said in another response, I would not iterate to make a move. Terry J. Reedy From jack at performancedrivers.com Fri Feb 4 13:02:36 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 4 Feb 2005 13:02:36 -0500 Subject: "Collapsing" a list into a list of changes In-Reply-To: References: Message-ID: <20050204180236.GD1607@performancedrivers.com> On Fri, Feb 04, 2005 at 12:43:37PM -0500, Alan McIntyre wrote: > Hi all, > > I have a list of items that has contiguous repetitions of values, but > the number and location of the repetitions is not important, so I just > need to strip them out. For example, if my original list is > [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5], I want to end up with [0,1,2,3,2,4,5]. > > Here is the way I'm doing this now: > > def straightforward_collapse(myList): > collapsed = [myList[0]] > for n in myList[1:]: > if n != collapsed[-1]: > collapsed.append(n) > > return collapsed > > Is there an elegant way to do this, or should I just stick with the code > above? > If you are using python2.4, >>> import itertools as it >>> [x[0] for (x) in it.groupby([0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5])] [0, 1, 2, 3, 2, 4, 5] >>> Since this is 2.4 you could also return a generator expression. >>> def iter_collapse(myList): ... return (x[0] for (x) in it.groupby([0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5])) ... >>> i = iter_collapse([0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5]) >>> i >>> list(i) [0, 1, 2, 3, 2, 4, 5] >>> -Jack From ilias at lazaridis.com Sun Feb 6 04:46:57 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sun, 06 Feb 2005 11:46:57 +0200 Subject: [EVALUATION] - E01: The Java Failure - May Python Helps? In-Reply-To: References: Message-ID: Terry Reedy wrote: > "Ilias Lazaridis" wrote in message > >>>Then 'print html_doc_instance' can print the html doc corresponding to >>>the object model. >> >>I understand this procedure. >> >>I would like to use a standard way, which uses the standard metadata >>[implicit/explicit defined]. >> >>Does such standard exist? > > I am not sure of what *you* mean by 'standard way'. a formal standard (like e.g. ODMG for OODBMS). a quasi standard (e.g. an widely accepted definition/inpementation etc.) > That is probably > because Python and the community is not big on 'standard ways' other than > what is specified in the two reference manuals. I would say this is a "standard". Can one please point me to a downloadable version of the 2 reference manuals (did not found them)? > And even then, Python is > intentionally flexible in various ways (though not all). Flexibility is of course always very positive. > So the answer to your question is probably 'no'. > > Terry J. Reedy . -- http://lazaridis.com From steven.bethard at gmail.com Sun Feb 6 16:00:49 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 06 Feb 2005 14:00:49 -0700 Subject: loops -> list/generator comprehensions In-Reply-To: References: <1107718117.221204.80410@l41g2000cwc.googlegroups.com> Message-ID: <4qCdnXI11-vhGJvfRVn-vQ@comcast.com> On 6 Feb 2005 11:28:37 -0800, wrote: > > walkList = [(x[0], x[2]) for x in os.walk(".")] > filenames = [] > for dir, files in walkList: > filenames.extend(["/".join([dir, f]) for f in files]) Caleb Hattingh top-posted: > I would be interested to see an example of code that is more concise > but yet as *clear* as the one you already have. Out of curiosity, do you find: filenames = [os.path.join(dirpath, filename) for dirpath, _, filenames in os.walk('.') for filename in filenames] harder to read? Steve From erikbethke at gmail.com Tue Feb 8 13:35:28 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 8 Feb 2005 10:35:28 -0800 Subject: Effbot's SimpleXMLWriter fails when py2exe'd In-Reply-To: References: <1107880337.524216.180440@g14g2000cwa.googlegroups.com> Message-ID: <1107887728.421109.221640@f14g2000cwb.googlegroups.com> Awesome! Great thank you both, fixed! -Erik From eee at nmt.edu Sat Feb 5 08:51:32 2005 From: eee at nmt.edu (Earl Eiland) Date: Sat, 05 Feb 2005 06:51:32 -0700 Subject: Trouble converting hex to decimal? Message-ID: <1107611491.18588.26.camel@dulcevida> I'm trying to process the IP packet length field, as recorded by pcap (Ethereal) and recovered using pcapy. When I slice out those bytes, I get a value that shows in '\x00' format, rather than '0x00'. Neither int() nor eval() are working. How do I handle this? Earl Eiland From bvande at po-box.mcgill.ca Sat Feb 5 17:30:31 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 05 Feb 2005 17:30:31 -0500 Subject: empty classes as c structs? In-Reply-To: <864d37090502051335f71127c@mail.gmail.com> References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <42053394.6020203@po-box.mcgill.ca> <864d37090502051335f71127c@mail.gmail.com> Message-ID: <42054907.5000802@po-box.mcgill.ca> Carlos Ribeiro said unto the world upon 2005-02-05 16:35: > On Sat, 05 Feb 2005 15:59:00 -0500, Brian van den Broek > wrote: > >>(I'm just a hobbyist, so if this suggestion clashes with some well >>established use of 'Bag' in CS terminology, well, never mind.) > > > There's already a well know know use for the 'bag' name, including a > recipe in Python. A bag is an arbitrary collection of objects. It's > similar to a set. The cookbook code is at: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259174 OK then, never mind ;-) Thanks for the link. Best, Brian vdB From tjreedy at udel.edu Thu Feb 10 02:14:56 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Feb 2005 02:14:56 -0500 Subject: Testing conditions. References: Message-ID: "Ray Gibbon" wrote in message news:cues7q$mg7$1 at news7.svr.pol.co.uk... > e.g. 1 > | while new_data = get_more_data(source): > | process_data(new_data) > > is obviously the sort of thing I'm missing, but it is not a general > solution > because :- > > e.g. 2 > | while new_data, environment = get_more_data(source): > | process_data(new_data, environment) > > is something I'm equally likely to want to do, but I can't express it's > meaning. The other problem with while loops, even if assignment were allowed, is that the loop stops on any null (False) value. So you soon would need to have the assignment buried within a comparison expression, as in C. > Before I resign myself to the inevitable, 'that's the way it is - get > used > to it', I'd just like to scratch it once. But, before I try walking on > very > thin ice, I want to ask whether there are expectations of some future > changes which address these issues? As Jeremy already implicitly pointed out, for loops already address these issues by combining assignment and a stop test, with the stop test being for a StopIteration exception rather than a null value. Separating data generation and validation from data processing is much cleaner. Terry J. Reedy From steven.bethard at gmail.com Tue Feb 15 11:03:06 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 15 Feb 2005 09:03:06 -0700 Subject: newbie question convert C to python In-Reply-To: <7xr7jixxdm.fsf@ruckus.brouhaha.com> References: <1108440952.526232.234130@c13g2000cwb.googlegroups.com> <7xr7jixxdm.fsf@ruckus.brouhaha.com> Message-ID: <3P6dnYqXu9GngI_fRVn-2g@comcast.com> Paul Rubin wrote: > doodle4 at gmail.com writes: > >>How do i handle this piece of code in python: >> >># define vZero 15 >># define vOne 20 >> >>unsigned int vTable[Zero][One] >> >>if(vGroup[vZero][vOne] == 0) >> { >> vGroup[vZero][vOne]-- >> ..... >> ..... >> } > > Simplest might be with a dictionary: > > vGroup = {} # I assume you meant vGroup not vTable > if vGroup[(vZero, vOne)] == 0: > vGroup[(vZero, vOne)] -= 1 > ..... > ..... Or, if you like, the parentheses are unnecessary: vGroup = {} if vGroup[vZero, vOne] == 0: vGroup[vZero, vOne] -= 1 ..... This (or the semantically identical version with parentheses) is definitely the best approach if you expect to have a lot of empty spots in your table. STeVe From john at grulic.org.ar Fri Feb 18 09:43:03 2005 From: john at grulic.org.ar (John Lenton) Date: Fri, 18 Feb 2005 11:43:03 -0300 Subject: low-end persistence strategies? In-Reply-To: <1108707658.105102.298300@z14g2000cwz.googlegroups.com> References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <1108622622.119311.43200@f14g2000cwb.googlegroups.com> <1108629775.800508.3400@f14g2000cwb.googlegroups.com> <1108702957.327528.22010@z14g2000cwz.googlegroups.com> <1108707658.105102.298300@z14g2000cwz.googlegroups.com> Message-ID: <20050218144303.GB17991@grulic.org.ar> On Thu, Feb 17, 2005 at 10:20:58PM -0800, Michele Simionato wrote: > Ok, I have yet another question: what is the difference > between fcntl.lockf and fcntl.flock? The man page of > my Linux system says that flock is implemented independently > of fcntl, however it does not say if I should use it in preference > over fcntl or not. it depends on what you want to do: as the manpages say, flock is present on most Unices, but lockf is POSIX; flock is BSD, lockf is SYSV (although its in XPG4.2, so you have it on newer Unices of any flavor); on Linux, lockf works over NFS (if the server supports it), and gives you access to mandatory locking if you want it. You can't mix lockf and flock (by this I mean: you can get a LOCK_EX via flock and via lockf on the same file at the same time). So: use whichever you feel more comfortable with, although if you are pretty confident your program will run mostly on Linux there is a bias towards lockf given its extra capabilities there. -- John Lenton (john at grulic.org.ar) -- Random fortune: ?? QQuuiittaa eell LLooccaall EEcchhoo,, MMaannoolloo !! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From jerf at jerf.org Thu Feb 3 14:14:06 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 03 Feb 2005 14:14:06 -0500 Subject: Integrated Testing - Peppable? References: <1107373949.960435.212020@z14g2000cwz.googlegroups.com> <1107452455.739263.145440@f14g2000cwb.googlegroups.com> Message-ID: On Thu, 03 Feb 2005 09:40:55 -0800, carl.manaster at gmail.com wrote: > Thanks, Jeremy, > >> No prose can compare to a live, functional demonstration. > > I agree; that's what my prototype amounts to: > > > > (sorry, it's Windows-only) > > But I take your larger message, and John's, to heart - this isn't > worthy of making it into Python. OK; thanks anyway for taking the time > to think about it and reply. But I do encourage you, if you believe in this, to continue working on it as a module. Unfortunately, I don't run Windows so if it's Windows only I can't really look at that. I would certainly be interested in at least trying it if you ever got a more generally cross-platform release. Be sure to ANN: ounce it here, if you do. As I just wrote in another message (although stated another way), "useful" and "in the standard library" aren't necessarily related! From klachemin at comcast.net Mon Feb 14 09:06:49 2005 From: klachemin at comcast.net (Kamilche) Date: 14 Feb 2005 06:06:49 -0800 Subject: Help with embedding fully qualified script name In-Reply-To: References: Message-ID: <1108390009.262197.121560@g14g2000cwa.googlegroups.com> To avoid pathname headaches, I've taken to including the following 3 lines at the top of every script that will be double-clicked: import os, sys pathname, scriptname = os.path.split(sys.argv[0]) pathname = os.path.abspath(pathname) os.chdir(pathname) From almad at include.cz Mon Feb 7 18:15:47 2005 From: almad at include.cz (Almad) Date: Tue, 08 Feb 2005 00:15:47 +0100 Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xy8e5jagh.fsf@ruckus.brouhaha.com> <1107490052.542546.285950@c13g2000cwb.googlegroups.com> Message-ID: M.E.Farmer wrote: > Paul Rubin wrote: > To emulate a table you use the div and span tag. Sorry, but I don't think that this is the way you have to create web pages. I think the most important think is to have web pages "semantic valid". That means, do not use table for formatting whole page, but when you have table data, you have to use tables. Don't you? -- Lukas "Almad" Linhart [:: http://www.almad.net/ ::] [:: Humans are too complicated to be described with words. ::] [:: PGP/GNUPg key: http://www.almad.net/download/pubkey.asc ::] From sjmachin at lexicon.net Wed Feb 16 17:56:49 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 17 Feb 2005 09:56:49 +1100 Subject: Why doesn't join() call str() on its arguments? References: <37hippF4gcimiU1@individual.net> Message-ID: On Wed, 16 Feb 2005 14:24:02 -0600, Skip Montanaro wrote: > > John> 4. For consistency, would you like "1" + 2 to produce "12"? > >No, the correct answer is obviously 3. ;-) > Obviously, in awk. Bletch! I once had to help out some users of a system where software development had been outsourced and upstuffed and they needed some data file fixups done but their system was so locked down even the manufacturer-supplied free pre-ANSI C compiler had been deleted and one couldn't download stuff off the net but the thought police had overlooked awk ... I even had to implement proper CSV-reading routines in awk. No thanks for reminding me :-( From onurb at xiludom.gro Mon Feb 14 08:14:28 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 14 Feb 2005 14:14:28 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: <4210a434$0$23451$626a14ce@news.free.fr> Ilias Lazaridis wrote: > I'm a newcomer to python: > > [EVALUATION] - E01: The Java Failure - May Python Helps? > http://groups-beta.google.com/group/comp.lang.python/msg/75f0c5c35374f553 > My trollometer's beeping... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From kent3737 at yahoo.com Sat Feb 5 11:16:29 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Sat, 05 Feb 2005 11:16:29 -0500 Subject: changing local namespace of a function In-Reply-To: References: Message-ID: <4204ee9b_2@newspeer2.tds.net> Bo Peng wrote: > Yes. I thought of using exec or eval. If there are a dozen statements, > > def fun(d): > exec 'z = x + y' in globals(), d > > seems to be more readable than > > def fun(d): > d['z'] = d['x'] + d['y'] > > But how severe will the performance penalty be? You can precompile the string using compile(), you only have to do this once. >>> def makeFunction(funcStr, name): ... code = compile(funcStr, name, 'exec') ... def f(d): ... exec code in d ... del d['__builtins__'] # clean up extra entry in d ... return f ... >>> f = makeFunction('z = x + y', 'f') >>> a = {'x':1, 'y':2} >>> b = {'x':3, 'y':3} >>> f(a) >>> a {'y': 2, 'x': 1, 'z': 3} >>> f(b) >>> b {'y': 3, 'x': 3, 'z': 6} From ncoghlan at iinet.net.au Tue Feb 22 04:33:30 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 22 Feb 2005 19:33:30 +1000 Subject: subclassing Decimal In-Reply-To: <1109038642.719116.221250@o13g2000cwo.googlegroups.com> References: <1109022264.823730.224910@o13g2000cwo.googlegroups.com> <8sadneLa1dUmxoffRVn-uw@comcast.com> <1109038642.719116.221250@o13g2000cwo.googlegroups.com> Message-ID: <421AFC6A.7050201@iinet.net.au> jbauer at rubic.com wrote: > yea-though-I-walk-thru-the-valley-of-__new__-I-will-fear-no-super-ly That's beautiful }:> Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From neutrinman at myrealbox.com Thu Feb 24 11:36:17 2005 From: neutrinman at myrealbox.com (neutrinman at myrealbox.com) Date: 24 Feb 2005 08:36:17 -0800 Subject: what is wrong? Message-ID: <1109262977.742242.179610@l41g2000cwc.googlegroups.com> I cannot find out why the following code generates the error: Traceback (most recent call last): File "D:/a/Utilities/python/ptyhon22/test.py", line 97, in ? main() File "D:/a/Utilities/python/ptyhon22/test.py", line 60, in main crit = Critter(crit_name) File "D:/a/Utilities/python/ptyhon22/test.py", line 8, in __init__ self.feed = feed # I wrote this AttributeError: can't set attribute I add some codes to a program on a book. The lines that have "I wrote this" comment is the added codes. Could anyone tell me what is worng here? -------------- ## class Critter(object): """A virtual pet""" def __init__(self, name, hunger = 0, boredom = 0, feed = 0): self.name = name self.hunger = hunger self.boredom = boredom self.feed = feed # I wrote this def __pass_time(self): self.hunger += 1 self.boredom += 1 def __feed_time(self): # I worte this self.feed += 1 # I wote this def __get_feed(self): # I wrote this return self.feed # I worte this feed = property(__get_feed) # I wrote this def __get_mood(self): unhappiness = self.hunger + self.boredom if unhappiness < 5: mood = "happy" elif 5 <= unhappiness <= 10: mood = "okay" elif 11 <= unhappiness <= 15: mood = "frustrated" else: mood = "mad" return mood mood = property(__get_mood) def talk(self): print "I'm", self.name, "and I feel", self.mood, "now.\n" self.__pass_time() def eat(self, food = 4): print "Brruppp. Thank you." self.hunger -= food self.__feed_time() # I wrote this print self.feed # I wrote this if self.hunger < 0: self.hunger = 0 self.__pass_time() def play(self, fun = 4): print "Wheee!" self.boredom -= fun if self.boredom < 0: self.boredom = 0 self.__pass_time() ## def main(): crit_name = raw_input("What do you want to name your critter?: ") crit = Critter(crit_name) choice = None while choice != "0": print \ """ Critter Caretaker 0 - Quit 1 - Listen to your critter 2 - Feed your critter 3 - Play with your critter """ choice = raw_input("Choice: ") print # exit if choice == "0": print "Good-bye." # listen to your critter elif choice == "1": crit.talk() # feed your critter elif choice == "2": crit.eat() # play with your critter elif choice == "3": crit.play() # some unknown choice else: print "\nSorry, but", choice, "isn't a valid choice." main() ("\n\nPress the enter key to exit.") From fredrik at pythonware.com Mon Feb 7 11:31:41 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 7 Feb 2005 17:31:41 +0100 Subject: xmlentities References: <66dkd2-6f2.ln1@pluto.i.infosense.no> Message-ID: Ola Natvig wrote: > Does anyone know a good library for transfering non standard characters to enity characters in > html. I want characters like < and > to be transformed to < and >. And the norwegian ? to > ø the third example on http://effbot.org/librarybook/htmlentitydefs.htm includes a function that translates an ISO-8859-1 encoded string to HTML- encoded text. From alan.mcintyre at esrgtech.com Sun Feb 13 12:01:20 2005 From: alan.mcintyre at esrgtech.com (Alan McIntyre) Date: Sun, 13 Feb 2005 12:01:20 -0500 Subject: changing __call__ on demand In-Reply-To: References: Message-ID: I tried this: >>>class test(object): ... def __call1(self): ... print 1 ... __call__ = __call1 ... >>>t = test() >>>t() 1 >>> Is that what you were looking for? -- Alan McIntyre ESRG LLC http://www.esrgtech.com Stefan Behnel wrote: > Hi! > > This somewhat puzzles me: > > Python 2.4 (#1, Feb 3 2005, 16:47:05) > [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > .>>> class test(object): > ... def __init__(self): > ... self.__call__ = self.__call1 > ... def __call1(self): > ... print 1 > ... def __call__(self): > ... print 2 > ... > .>>> t = test() > .>>> t() > 2 > > If I take out the __call__ method completely and only set it in > __init__, I get a TypeError saying that test is not callable. > > I want to use this in order to provide different implementations based > on the object configuration. Calculating the right function to call is > non-trivial and calls are frequent, so I want to change __call__ in > order to run the right function directly. > > I know, I could use another level of indirection: > > def __call__(self): > self.the_right_method() > > and then set the_right_method accordingly, but I find that somewhat > sub-optimal. Is there a way to change __call__ after class creation? > > Stefan From deetsNOSPAM at web.de Tue Feb 22 07:55:18 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 22 Feb 2005 13:55:18 +0100 Subject: Sequence of empty lists References: Message-ID: <380obbF5g1lfrU1@individual.net> seq = [[] for i in xrange(10)] -- Regards, Diez B. Roggisch From jerf at jerf.org Thu Feb 17 11:33:16 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 17 Feb 2005 11:33:16 -0500 Subject: Why doesn't join() call str() on its arguments? References: <37hippF4gcimiU1@individual.net> <37hqlrF59l2b2U1@individual.net> <873bvw9nqh.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <421450CC.9080504@swiftdsl.com.au> <87psyz8h9o.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <4214A800.4010509@swiftdsl.com.au> Message-ID: On Thu, 17 Feb 2005 14:00:59 -0700, Dave Benjamin wrote: > Jeremy Bowers wrote: >> I'd point out that the Zen that can be comprehended by checking off items >> in a list is not the true Zen. > > The Zen that can be imported is not the eternal Zen. =) Yes, there is that too. :-) From lbates at syscononline.com Fri Feb 11 16:34:01 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 11 Feb 2005 15:34:01 -0600 Subject: Commerical graphing packages? In-Reply-To: <420d1595$1@nntp.zianet.com> References: <420d1595$1@nntp.zianet.com> Message-ID: ReportLab has pretty good Graphics Module. About the only thing it needs is Python Imaging Library (which you would probably want anyway). Larry Bates Erik Johnson wrote: > I am wanting to generate dynamic graphs for our website and would rather > not invest the time in developing the code to draw these starting from > graphics primitives. I am looking for something that is... "fairly robust" > but our needs are relatively modest: X-Y scatter plots w/ data point > symbols, multiple data set X-Y line plots, bar charts, etc. > > Preferably this would come from a company that can provide support & > decent documentation, and a package that can be installed without a bunch of > extra hassle (e.g., needs Numeric Python, needs to have the GD library > installed, needs separate JPEG encoders, font libraries, etc.) > > I am aware of ChartDirector (http://www.advsofteng.com/ ) which > explicitly supports python and seems to be about the right level of > sophistication. I don't really know of any other packages in this space, do > you? I am seeking feedback and reccomendations from people who have used > this package or similar ones. I am particularly interested to hear about any > limitations or problems you ran into with whatever package you are using. > > Thanks for taking the time to read my post! :) > > -ej > > From caleb1 at telkomsa.net Tue Feb 15 20:45:01 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 15 Feb 2005 20:45:01 -0500 Subject: some qustions on python References: Message-ID: http://www.python.org On Tue, 15 Feb 2005 13:16:53 -0500, samar bazied wrote: > Hi.. > plz > can u help me?? > I am very new in python and I have some qustions about it. > can u give me design process of python and their related langauges? > and I will be very habby if u give me small evaluation of python>> > plz.. > plz... > plz.... > help me.. > ------------ From marian at mba-software.de Sun Feb 6 23:33:58 2005 From: marian at mba-software.de (=?ISO-8859-1?Q?Marian_Aldenh=F6vel?=) Date: Mon, 07 Feb 2005 05:33:58 +0100 Subject: pygame.mixer.music not playing In-Reply-To: <1107748705.808825.319270@f14g2000cwb.googlegroups.com> References: <36mb0iF54udklU1@individual.net> <1107700800.258876.298010@z14g2000cwz.googlegroups.com> <36mvjkF54gvnrU1@individual.net> <1107748705.808825.319270@f14g2000cwb.googlegroups.com> Message-ID: <36o9dvF53a94mU1@individual.net> Hi, > Please post your os name and version, Python version, Pygame version, German Windows XP Home, 2.3.4, 1.6 > Also you can try and look for another sound package I will. Until I find something suitable I will just build a dummy class that has the commands I need, I can later interface that to whatever I really use. Should I ever get to that point - as I said, this is a toy project and they tend to die suddenly :-). Ciao, MM -- Marian Aldenh?vel, Rosenhain 23, 53123 Bonn. +49 228 624013. http://www.marian-aldenhoevel.de "Wir brauchen keine Opposition, wir sind bereits Demokraten." From mchermside at ingdirect.com Fri Feb 4 13:24:39 2005 From: mchermside at ingdirect.com (Chermside, Michael) Date: Fri, 4 Feb 2005 13:24:39 -0500 Subject: Converting strings to dates Message-ID: <0CFFADBB825C6249A26FDF11C1772AE1021C1B7F@ingdexj1.ingdirect.com> I'm trying to convert a string back into a datetime.date. First I'll create the string: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import time, datetime >>> a_date = datetime.date.today() >>> s = str(a_date) >>> print s 2005-02-04 Now I convert it back: >>> new_date = datetime.date.fromtimestamp( ... time.mktime(time.strptime(s, '%Y-%m-%d'))) >>> new_date datetime.date(2005, 2, 4) WOW, that's ugly. Is there a more concise way to do this? -- Michael Chermside This email may contain confidential or privileged information. If you believe you have received the message in error, please notify the sender and delete the message without copying or disclosing it. From ajikoe at gmail.com Wed Feb 9 10:56:27 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 9 Feb 2005 07:56:27 -0800 Subject: multi threading in multi processor (computer) In-Reply-To: <420a2938$0$22987$626a14ce@news.free.fr> References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <420a2938$0$22987$626a14ce@news.free.fr> Message-ID: <1107964587.818199.223980@g14g2000cwa.googlegroups.com> Hello Pierre, That's a pity, since when we have to run parallel, with single processor is really not efficient. To use more computers I think is cheaper than to buy super computer in developt country. Sincerely Yours, pujo aji From oyesiji at hotmail.com Thu Feb 24 20:28:28 2005 From: oyesiji at hotmail.com (Jubri Siji) Date: Fri, 25 Feb 2005 01:28:28 GMT Subject: Best IDe Message-ID: <0bvTd.52404$wc.42219@trnddc07> Please i am new to python , whats the best IDE to start with From harlinseritt at yahoo.com Mon Feb 21 21:35:06 2005 From: harlinseritt at yahoo.com (Harlin) Date: 21 Feb 2005 18:35:06 -0800 Subject: How to write a ping client Message-ID: <1109039706.092671.137360@f14g2000cwb.googlegroups.com> Is there a way to write a ping client? I would like to be able to write a small ping client so that I dont have to do os.system('ping args') and thereby keep the resource overhead low. Does anyone know how this can be done or can point me in the right direction? thanks, Harlin From pierre.barbier at cirad.fr Wed Feb 9 11:21:07 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Wed, 09 Feb 2005 17:21:07 +0100 Subject: convert list of tuples into several lists In-Reply-To: References: <36uihlF58p63iU1@individual.net> Message-ID: <420a37fd$0$12847$626a14ce@news.free.fr> Oliver Eichler a ?crit : > Diez B. Roggisch wrote: > > >>zip(*[(1,4),(2,5),(3,6)]) >> > > Thanks :) I knew it must be simple. The asterics - thing was new to me. > > By the way: What is faster? > > this: > > z = [(1,4),(2,5),(3,6) > a,b = zip(*[(x[0], x[0]-x[1]) for x in z]) > > or: > > a = [] > b = [] > for x in z: > a.append(x[0]) > b.append(x[0]-x[1]) > > I guess first, isn't it? > > > Oliver Best answer is : try it :) use the "timeit" module (in the standard lib) to do so ... Pierre From ncoghlan at iinet.net.au Fri Feb 11 23:36:51 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 12 Feb 2005 14:36:51 +1000 Subject: namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP In-Reply-To: References: Message-ID: <420D87E3.7010904@iinet.net.au> Steven Bethard wrote: >>> Should namespace chaining be supported? One suggestion would add a >>> NamespaceChain object to the module:: >> >> >> This does have the advantage of keeping the basic namespace simple. >> However, it may also be worth having native chaining support in >> Namespace: > > > I think I prefer the separate NamespaceChain object because it allows > you to chain namespaces other than just Namespace objects -- any object > that supports getattr is okay. If chaining is builtin, all namespaces > (except the last one?) have to be Namespace objects... I like NamespaceChain too - I was simply thinking it might be good to have a recursive chaining method associated with actual Namespace objects as well. However, now that I look more closely at NamespaceChain, it makes more sense to me to explicitly make the 'head' of the chain a namespace view in its own right. This should also make the local binding, chained lookup behaviour fairly obvious (since it will work just as it does for any class with __getattr__ defined, but not __setattr__ or __delattr__). That is, something like: class NamespaceChain(NamespaceView): def __init__(self, head, *args): NamespaceView.__init__(self, head) self.__namespaces__ = args def __getattr__(self, name): """Return the first such attribute found in the object list This is only invoked for attributes not found in the head namespace. """ for obj in self.__namespaces__: try: return getattr(obj, name) except AttributeError: pass raise AttributeError(name) Python gives us the local set and local del for free. The 'nested namespaces' approach that prompted my original suggestion can then be spelt by using: parent = Namespace() child1 = NamespaceChain({}, parent) child2 = NamespaceChain({}, child1) There *is* a problem with using __getattr__ though - any attribute in the chained namespaces that is shadowed by a class attribute (like 'update') will be picked up from the class, not from the chained namespaces. So we do need to use __getattribute__ to change that lookup order. However, given the amount of grief the default lookup behaviour causes, I think the place to do that is in Namespace itself: class Namespace(object): # otherwise unchanged def __getattribute__(self, name): """Namespaces do NOT default to looking in their class dict for non-magic attributes """ getattribute = super(Namespace, self).__getattribute__ try: return getattribute("__dict__")[name] except KeyError: if name.startswith('__') and name.endswith('__'): # Employ the default lookup system for magic names return getattribute(name) else: # Skip the default lookup system for normal names if hasattr(self, "__getattr__"): return getattribute("__getattr__")(name) else: raise AttributeError(name) The above is a pretty simple approach - it completely bypasses the descriptor machinery for non-magic names. This means that the instance namespace does NOT get polluted by any non-magic names in the class dictionary, but magic names can be accessed normally. And subclasses can add their own methods, and this feature will continue to 'just work'. For example: Py> ns = namespaces.Namespace() Py> ns.update Traceback (most recent call last): File "", line 1, in ? File "namespaces.py", line 30, in __getattribute__ raise AttributeError(name) AttributeError: update Py> type(ns).update Py> ns.__init__ (side note: I don't think I have ever written a __getattribute__ method without introducing an infinite recursion on the first attempt. . .) Anyway, it is probably worth digging into the descriptor machinery a bit further in order to design a lookup scheme that is most appropriate for namespaces, but the above example has convinced me that object.__getattribute__ is NOT it :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From bvande at po-box.mcgill.ca Mon Feb 28 02:26:24 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon, 28 Feb 2005 02:26:24 -0500 Subject: Trees In-Reply-To: <42226BBB.3010203@psi.com.au> References: <42226BBB.3010203@psi.com.au> Message-ID: <4222C7A0.7010307@po-box.mcgill.ca> Alex Le Dain said unto the world upon 2005-02-27 19:54: > > Would this be for a GUI toolkit or maybe using a standard > > class scheme? > > Sorry, yes I should have been more specific. I meant a non-GUI, standard > class scheme. I want to use the scheme to hold a structure in memory and > retrieve/add information to it. > > I've had a couple of goes myself but get a bit confuesd about whether I > should use recursion to be able to get the children (and all > "sub"-children) of a/the parent. > > cheers, Alex. > Hi Alex, I've been working on a set of tools for dealing with a tree structure. I am no python expert -- in fact, the program I am working on is my first serious us of classes. Anyway, though I've not been following your thread, I also think that perhaps you might find the code I have of some use. Use caution though; newbie code below :-) I am working with a data format from a shareware application that puts the tree in a flat text file, where each node has a header section, including a unique node id and a level indicator. (Level 0 for the root, level 1 for the roots children, etc.) My code is a work in progress and not heavily tested, but it seems to work :-) I've a class Tree_file with a .nodes attribute which is a list of Node objects (in top-down tree order). It has a method: .# leading periods to preserve indentation .def update_family(self): . '''Starting from node, updates each nodes .children and descendants set.''' . for node in self.nodes: . node.get_children(self) . for node in self.nodes: . node.get_descendants() My Node class has methods giving each node object a node.id and node.level (both ints). The other relevant attributes are node.children, and node.descendants (both sets). (I've got reasons to often process just a node's children, rather than all descendants; thus, it makes sense for my program to have the two attributes.) The two relevant methods are: .def get_children(self, parent_file): . '''Sets the node's .children set attribute. . . Scans the list of Node objects in parent_file.nodes until self . node is found (by comparison of node.id attributes). Then the . capture_children flag is set to True, and, for each node exactly . one node.level deeper, that deeper node is added to the . self.children set. This goes on until the first node not below . the self node is found. . ''' . capture_children = False . children = set() . . for node in parent_file.nodes: . if capture_children and not node.level > self.level: . break . if capture_children and node.level == self.level + 1: . children.add(node) . if self.id == node.id: . capture_children = True . . self.children = children and .def get_descendants(self): . '''Updates each nodes .descendants set to current value. . . Recursive call of get_descendants on a node's children, adding . all to the .descendants set (of the target node). . ''' . descendants = self.children.copy() . for node in self.children: . node.get_descendants() . for n in node.descendants: . descendants.add(n) . self.descendants = descendants Anyway, all caveats notwithstanding, I hope that is of some use to you. Best, Brian vdB From kbk at shore.net Wed Feb 16 00:32:36 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Wed, 16 Feb 2005 00:32:36 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200502160532.j1G5Wahi031058@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 298 open (+14) / 2754 closed ( +6) / 3052 total (+20) Bugs : 823 open (+19) / 4829 closed (+17) / 5652 total (+36) RFE : 168 open ( +1) / 144 closed ( +2) / 312 total ( +3) New / Reopened Patches ______________________ date.strptime and time.strptime as well (2005-02-04) http://python.org/sf/1116362 opened by Josh NameError in cookielib domain check (2005-02-04) CLOSED http://python.org/sf/1116583 opened by Chad Miller Minor improvement on 1116583 (2005-02-06) http://python.org/sf/1117114 opened by John J Lee cookielib and cookies with special names (2005-02-06) http://python.org/sf/1117339 opened by John J Lee cookielib LWPCookieJar and MozillaCookieJar exceptions (2005-02-06) http://python.org/sf/1117398 opened by John J Lee cookielib.LWPCookieJar incorrectly loads value-less cookies (2005-02-06) http://python.org/sf/1117454 opened by John J Lee urllib2 .getheaders attribute error (2005-02-07) http://python.org/sf/1117588 opened by Wummel replace md5 impl. with one having a more free license (2005-02-07) CLOSED http://python.org/sf/1117961 opened by Matthias Klose unknown locale: lt_LT (patch) (2005-02-08) http://python.org/sf/1118341 opened by Nerijus Baliunas Fix crash in xmlprase_GetInputContext in pyexpat.c (2005-02-08) http://python.org/sf/1118602 opened by Mathieu Fenniak enable time + timedelta (2005-02-08) http://python.org/sf/1118748 opened by Josh fix for a bug in Header.__unicode__() (2005-02-09) CLOSED http://python.org/sf/1119016 opened by Bj?rn Lindqvist python -c readlink()s and stat()s '-c' (2005-02-09) http://python.org/sf/1119423 opened by Brian Foley patches to compile for AIX 4.1.x (2005-02-09) http://python.org/sf/1119626 opened by Stuart D. Gathman better datetime support for xmlrpclib (2005-02-10) http://python.org/sf/1120353 opened by Fred L. Drake, Jr. ZipFile.open - read-only file-like obj for files in archive (2005-02-11) http://python.org/sf/1121142 opened by Alan McIntyre Reference count bug fix (2005-02-12) http://python.org/sf/1121234 opened by Michiel de Hoon sha and md5 modules should use OpenSSL when possible (2005-02-12) http://python.org/sf/1121611 opened by Gregory P. Smith Python memory allocator: Free memory (2005-02-15) http://python.org/sf/1123430 opened by Evan Jones Patches Closed ______________ Add SSL certificate validation (2005-02-03) http://python.org/sf/1115631 closed by noonian NameError in cookielib domain check (2005-02-04) http://python.org/sf/1116583 closed by rhettinger replace md5 impl. with one having a more free license (2005-02-07) http://python.org/sf/1117961 closed by loewis fix for a bug in Header.__unicode__() (2005-02-09) http://python.org/sf/1119016 closed by sonderblade time.tzset() not built on Solaris (2005-01-04) http://python.org/sf/1096244 closed by bcannon OSATerminology extension fix (2004-06-25) http://python.org/sf/979784 closed by jackjansen New / Reopened Bugs ___________________ xmlrpclib: wrong decoding in '_stringify' (2005-02-04) CLOSED http://python.org/sf/1115989 opened by Dieter Maurer Prefix search is filesystem-centric (2005-02-04) http://python.org/sf/1116520 opened by Steve Holden Wrong match with regex, non-greedy problem (2005-02-05) CLOSED http://python.org/sf/1116571 opened by rengel Solaris 10 fails to compile complexobject.c (2005-02-04) http://python.org/sf/1116722 opened by Case Van Horsen Dictionary Evaluation Issue (2005-02-05) http://python.org/sf/1117048 opened by WalterBrunswick Typo in list.sort() documentation (2005-02-06) CLOSED http://python.org/sf/1117063 opened by Viktor Ferenczi sgmllib.SGMLParser (2005-02-06) CLOSED http://python.org/sf/1117302 opened by Paul Birnie SimpleHTTPServer and mimetypes: almost together (2005-02-06) http://python.org/sf/1117556 opened by Matthew L Daniel os.path.exists returns false negatives in MAC environments. (2005-02-07) http://python.org/sf/1117601 opened by Stephen Bennett profiler: Bad return and Bad call errors with exceptions (2005-02-06) http://python.org/sf/1117670 opened by Matthew Mueller "in" operator bug ? (2005-02-07) CLOSED http://python.org/sf/1117757 opened by Andrea Bolzonella BSDDB openhash (2005-02-07) http://python.org/sf/1117761 opened by Andrea Bolzonella lists coupled (2005-02-07) CLOSED http://python.org/sf/1118101 opened by chopf Error in representation of complex numbers(again) (2005-02-09) http://python.org/sf/1118729 opened by George Yoshida builtin file() vanishes (2005-02-08) CLOSED http://python.org/sf/1118977 opened by Barry Alan Scott Docs for set() omit constructor (2005-02-09) CLOSED http://python.org/sf/1119282 opened by Kent Johnson curses.initscr - initscr exit w/o env(TERM) set (2005-02-09) http://python.org/sf/1119331 opened by Jacob Lilly xrange() builtin accepts keyword arg silently (2005-02-09) http://python.org/sf/1119418 opened by Martin Blais Python Programming FAQ should be updated for Python 2.4 (2005-02-09) http://python.org/sf/1119439 opened by Michael Hoffman ScrolledText allows Frame.bbox to hide Text.bbox (2005-02-09) http://python.org/sf/1119673 opened by Drew Perttula list extend() accepts args besides lists (2005-02-09) CLOSED http://python.org/sf/1119700 opened by Dan Everhart Static library incompatible with nptl (2005-02-10) http://python.org/sf/1119860 opened by daniel Static library incompatible with nptl (2005-02-10) CLOSED http://python.org/sf/1119866 opened by daniel Python 2.4.0 crashes with a segfault, EXAMPLE ATTACHED (2005-02-11) http://python.org/sf/1120452 opened by Viktor Ferenczi bug in unichr() documentation (2005-02-11) http://python.org/sf/1120777 opened by Marko Kreen Problem in join function definition (2005-02-11) CLOSED http://python.org/sf/1120862 opened by yseb file seek error (2005-02-11) CLOSED http://python.org/sf/1121152 opened by Richard Lawhorn Python24.dll crashes, EXAMPLE ATTACHED (2005-02-12) http://python.org/sf/1121201 opened by Viktor Ferenczi zip incorrectly and incompletely documented (2005-02-12) http://python.org/sf/1121416 opened by Alan Decorated functions are unpickleable (2005-02-12) CLOSED http://python.org/sf/1121475 opened by S Joshua Swamidass distutils.dir_utils not unicode compatible (2005-02-12) http://python.org/sf/1121494 opened by Morten Lied Johansen subprocess example missing "stdout=PIPE" (2005-02-12) http://python.org/sf/1121579 opened by Monte Davidoff SMTPHandler argument misdescribed (2005-02-13) http://python.org/sf/1121875 opened by Peter marshal may crash on truncated input (2005-02-14) http://python.org/sf/1122301 opened by Fredrik Lundh incorrect handle of declaration in markupbase (2005-02-14) http://python.org/sf/1122916 opened by Wai Yip Tung Typo in Curses-Function doc (2005-02-15) http://python.org/sf/1123268 opened by Aaron C. Spike test_peepholer failing on HEAD (2005-02-15) CLOSED http://python.org/sf/1123354 opened by Tim Peters add SHA256/384/512 to lib (2005-02-16) http://python.org/sf/1123660 opened by paul rubin Bugs Closed ___________ xmlrpclib: wrong decoding in '_stringify' (2005-02-04) http://python.org/sf/1115989 closed by fdrake Wrong match with regex, non-greedy problem (2005-02-05) http://python.org/sf/1116571 closed by effbot Typo in list.sort() documentation (2005-02-05) http://python.org/sf/1117063 closed by rhettinger sgmllib.SGMLParser (2005-02-06) http://python.org/sf/1117302 closed by effbot PyThreadState_SetAsyncExc segfault (2004-11-18) http://python.org/sf/1069160 closed by gvanrossum "in" operator bug ? (2005-02-07) http://python.org/sf/1117757 closed by tim_one lists coupled (2005-02-07) http://python.org/sf/1118101 closed by tim_one builtin file() vanishes (2005-02-09) http://python.org/sf/1118977 closed by loewis Docs for set() omit constructor (2005-02-09) http://python.org/sf/1119282 closed by rhettinger list extend() accepts args besides lists (2005-02-09) http://python.org/sf/1119700 closed by rhettinger Static library incompatible with nptl (2005-02-10) http://python.org/sf/1119866 closed by ekloef Problem in join function definition (2005-02-11) http://python.org/sf/1120862 closed by rhettinger file seek error (2005-02-11) http://python.org/sf/1121152 closed by tim_one Decorated functions are unpickleable (2005-02-12) http://python.org/sf/1121475 closed by bcannon "Macintosh" references in the docs need to be checked. (2005-01-04) http://python.org/sf/1095802 closed by bcannon RE '*.?' cores if len of found string exceeds 10000 (2004-10-26) http://python.org/sf/1054564 closed by effbot missing mappings in locale tables (2002-10-09) http://python.org/sf/620739 closed by effbot test_peepholer failing on HEAD (2005-02-15) http://python.org/sf/1123354 closed by tim_one New / Reopened RFE __________________ urllib.urlopen should put the http-error-code in .info() (2005-02-07) http://python.org/sf/1117751 opened by Robert Kiendl Option to force variables to be declared (2005-02-14) http://python.org/sf/1122279 opened by Zac Evans Line Numbers (2005-02-14) http://python.org/sf/1122532 opened by Egon Frerich RFE Closed __________ commands.mkarg function should be public (2001-12-04) http://python.org/sf/489106 closed by donut Missing socketpair() function. (2002-06-12) http://python.org/sf/567969 closed by grahamh From tzot at sil-tec.gr Thu Feb 17 08:55:49 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 17 Feb 2005 15:55:49 +0200 Subject: check if object is number References: <374t0mF4te5vbU1@individual.net> <7tOdnYs6NtrV7JDfRVn-vQ@powergate.ca> Message-ID: <2j89115tsnur135nfm06lh509482mdb16h@4ax.com> On Sat, 12 Feb 2005 16:01:26 -0800, rumours say that Michael Spencer might have written: >> Yup, that's basically what I'm doing right now. The question was really >> how to define that adapter function. =) >> >> Steve >OK - then my entry is: > assert obj+1 >= 1 >:-) So -1 is not a number. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From benjamin.cordes at blawrc.de Mon Feb 14 07:02:01 2005 From: benjamin.cordes at blawrc.de (benjamin.cordes at blawrc.de) Date: 14 Feb 2005 04:02:01 -0800 Subject: Problem with nested lists as arrays Message-ID: <1108382521.266024.281620@g14g2000cwa.googlegroups.com> Hello, For a class modeling the block puzzle I use nested lists as arrays. Within this class there is a method for swaping elements. I have lots of trouble with that method but can't figure it out. It has probably to do with my unuseful approach to nested lists, but I don't want to write the code again. As I am a python newbie any other comments on the code will be appreciated. Thanks for any help. # Puzzle.py # class for a sliding block puzzle # an starting state of a 8-puzzle could look like the following: # ------------ # | 7 2 4 | # | | # | 5 X 6 | # | | # | 8 3 1 | # ------------ # the goal is to reach this state: # ------------ # | X 1 2 | # | | # | 3 4 5 | # | | # | 6 7 8 | # ------------ import copy class Puzzle: def __init__(self, dim): self.dim = dim self.elements = [[0 for column in range(dim)] for row in range(dim) ] def getEmptySlot(self): i = 0 j = 0 while i <= self.dim-1: while j <= self.dim-1: if self.elements[j][i] == -1: return [j, i] j = j+1 j = 0 i = i + 1 def performMove(self, direction): slot = self.getEmptySlot() if (direction == "up"): self.swapElements(slot[1], slot[0], slot[1]+1, slot[0]) elif (direction == "down"): self.swapElements(slot[1], slot[0], slot[1]-1, slot[0]) elif direction == "left": self.swapElements(slot[1], slot[0], slot[1], slot[0]-1) elif (direction == "right"): self.swapElements(slot[1], slot[0], slot[1], slot[0]+1) def swapElements(self, fromx, fromy, tox, toy): dummy = self.elements[toy][tox] self.elements[toy][tox] = self.elements[fromy][fromx] self.elements[fromy][fromx] = dummy def getPossibleMoves(self): emptySlot = self.getEmptySlot() y = emptySlot[1] x = emptySlot[0] north = (y == 0) south = (y == (self.dim-1)) west = (x == 0) east = (x == (self.dim-1)) middle = not(north or south or west or east) northwest = north and west northeast = north and east southwest = south and west southeast = south and east # orientation has to be distinct # save original values orignorth = north origsouth = south # original north or south orignors = north or south north = north and not (west or east) south = south and not (west or east) west = west and not (orignors) east = east and not (orignors) if middle: return ["up", "down", "left", "right"] elif north: return ["up", "left", "right"] elif south: return ["down", "left", "right"] elif west: return ["up", "down", "left"] elif east: return ["up", "down", "right"] elif northwest: return ["up", "left"] elif northeast: return ["up", "right"] elif southwest: return ["down", "left"] elif southeast: return ["down", "right"] # ~Puzzle.py From benjamin.cordes at blawrc.de Mon Feb 14 12:06:30 2005 From: benjamin.cordes at blawrc.de (benjamin.cordes at blawrc.de) Date: 14 Feb 2005 09:06:30 -0800 Subject: nested lists as arrays In-Reply-To: <37bklfF5a7s7vU2@individual.net> References: <1108384089.804375.179130@f14g2000cwb.googlegroups.com> <37bklfF5a7s7vU2@individual.net> Message-ID: <1108400790.871727.29200@o13g2000cwo.googlegroups.com> Diez B. Roggisch wrote: > benjamin.cordes at blawrc.de wrote: > > > Hi, > > > > why can't I do this: > > > > dummy = self.elements[toy][tox] > > > > self.elements[toy][tox] = self.elements[fromy][fromx] > > self.elements[fromy][fromx] = dummy > > > > after initialising my nested list like this: > > > > self.elements = [[0 for column in range(dim)] for row in > > range(dim) ] > > Works for me: > > dim = 10 > elements = [[0 for column in xrange(dim)] for row in > xrange(dim) ] > > toy, tox = (2,5) > fromy, fromx = (7,5) > > dummy =elements[toy][tox] > elements[toy][tox] = elements[fromy][fromx] > elements[fromy][fromx] = dummy > > > And use xrange instead of range. > -- > Regards, > > Diez B. Roggisch thanks so far, and sorry for posting the topic now 3 times. From exogen at gmail.com Fri Feb 18 20:27:15 2005 From: exogen at gmail.com (Brian Beck) Date: Fri, 18 Feb 2005 20:27:15 -0500 Subject: [perl-python] exercise: partition a list by equivalence In-Reply-To: References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> Message-ID: Brian Beck wrote: > Brian Beck wrote: > > [code] Ah heck, nevermind... it worked for my small test cases but the algorithm is just wrong. -- Brian Beck Adventurer of the First Order From tjreedy at udel.edu Thu Feb 17 13:49:31 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Feb 2005 13:49:31 -0500 Subject: Why doesn't join() call str() on its arguments? References: <37hippF4gcimiU1@individual.net> <421477D4.2050305@iinet.net.au> Message-ID: "Nick Coghlan" wrote in message news:421477D4.2050305 at iinet.net.au... > This seems to be the last relevant message in the thread: > http://mail.python.org/pipermail/python-dev/2004-August/048516.html > So it was tried, but we found too many weird corner cases we weren't > quite sure > what to do with. At that point, "explicit is better than implicit" kicked > in :) > A shame, since it was both faster and more convenient than using a list > comp. But the convenience wasn't worth the ambiguity of the semantics. Your experience, where you made an honest go of implementation, and the error catching argument, convince me that explicit is better for this case. I was thinking, 'Well, print autoconverts' (as documented). But it requires that each item be listed. And if there is any ambiguity, no harm since it is only meant for quick convenience anyway and not exact char-by-char control. Join, on the other hand, often gets a pre-existing list. If that is known (thought to be) all strings, then mapping str is a waste as well as an error mask. In not, map(str,...) is only 9 extra chars. Terry J. Reedy From fredrik at pythonware.com Tue Feb 8 05:47:21 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Feb 2005 11:47:21 +0100 Subject: variable declaration References: <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com><4208178F.40804@po-box.mcgill.ca> Message-ID: Peter Otten wrote: >> executed. the compiler handles "global" and "from __future__", everything >> else is done at runtime. > > and __debug__, too, it seems: you left out the "python -O" line. >>>> __debug__ > False >>>> def f(): > ... if __debug__: > ... global x > ... x = 42 > ... >>>> f() >>>> x > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'x' is not defined yup, but unlike the two others, that's a CPython -O implementation issue. (I'd say bug, in this case). neither standard CPython (without -O) nor Jython behave this way. From tjreedy at udel.edu Mon Feb 21 17:07:57 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 21 Feb 2005 17:07:57 -0500 Subject: python2.4 generator expression > python2.3 list expression References: <0ioj11dsgqhatqc3d7ldeb35rta6d9fk69@4ax.com> Message-ID: "Christos TZOTZIOY Georgiou" wrote in message news:0ioj11dsgqhatqc3d7ldeb35rta6d9fk69 at 4ax.com... > On 21 Feb 2005 06:48:19 -0500, rumours say that Dan Sommers > >>for c in range( 128 ): >> even_odd = 0 >> print '%3d' % c, >> while c: >> c &= c - 1 >> even_odd = not even_odd >> print int( even_odd ) > > Just for the sake of people who haven't messed with bit manipulation in C > or > assembly, the effect of > c &= c - 1 > is to reset the rightmost (less significant) '1' bit of a number (ie > change it > to '0'). Cute. I tried it a few times until I saw why it works. But it is also dangerous (within a loop like the above) in a language like current Python (and unlike C/assembler) in which the binary representation of -1 is effectively a left infinite string of '1's: ...1111111111 Terry J. Reedy From pierre.barbier at cirad.fr Thu Feb 3 02:15:46 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Thu, 03 Feb 2005 08:15:46 +0100 Subject: Redirecting stdout/err under win32 platform In-Reply-To: <42000256$0$513$626a14ce@news.free.fr> References: <41fbd6b5$0$6098$626a14ce@news.free.fr> <1107149696.809645.56180@z14g2000cwz.googlegroups.com> <42000256$0$513$626a14ce@news.free.fr> Message-ID: <4201cf22$0$26608$636a15ce@news.free.fr> David Douard a ?crit : > Alan, > > I did search Google for this problem (not enough, thou). > In fact, I found some kind of solution (by myself, not that much on Google), > but it is not really satisfactory. > > I have used win32 pipes to do so (win32api.CreatePipe). I can redirect > stdout/stderr to it from my python code (even redirecting the stdout/stderr > from my C lib). > But I still have a problem with this solution (well, 2): > - it is *much* more complicated than any solution available on Unix like > systems (not really a problem, but), > - it not synchronous at all. And I'd like it to be so (or almost so). > > David > > > AFAIK, there is no working bidirectionnal pipes on Windows ! The functions exists in order for them to claim being POSIX, but they're not working properly. Under Windows environment, I suppose you have to find your way using their buggy pipes (and by no means their "POSIX" pipes) or you have to use another inter-process communication protocol (DDE, COM, ...). Pierre From DrColombes at yahoo.com Mon Feb 21 19:56:54 2005 From: DrColombes at yahoo.com (Dr. Colombes) Date: 21 Feb 2005 16:56:54 -0800 Subject: MatPlotLib.MatLab troubles (how to install/run matplotlib.PyLab?) Message-ID: <1109033814.888677.286240@c13g2000cwb.googlegroups.com> On my home laptop computer, I'm trying to install the appropriate modules so that Python version 2.3.3 and IDLE version 1.0.2 (with an "import matplotlib.matlab" statement) can produce nice MatLab-like plots. I have a matplotlib.matlab-capable Python set-up running OK on my office desktop, which I obtained after downloading and installing a few more modules (numarray and numeric, I think). Now I get the following message about matplotlib.matlab being deprecated: ------------- matplotlib.matlab deprecated, please import matplotlib.pylab or simply pylab instead. See http://matplotlib.sf.net/matplotlib_to_pylab.py for a script which explains this change and will automatically convert your python scripts that use matplotlib.matlab. This change was made because we were concerned about trademark infringement on The Mathwork's trademark of matlab. --------------- Unfortunately, the above URL does not exist. Thanks for suggestions, any help you can offer. From steve at holdenweb.com Wed Feb 2 16:59:00 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 02 Feb 2005 16:59:00 -0500 Subject: Basic file operation questions In-Reply-To: <1107379669.870799.256030@g14g2000cwa.googlegroups.com> References: <1107379669.870799.256030@g14g2000cwa.googlegroups.com> Message-ID: alex wrote: > Hi, > > I am a beginner with python and here is my first question: > How can I read the contents of a file using a loop or something? I open > the file with file=open(filename, 'r') and what to do then? Can I use > something like > > for xxx in file: > .... > Yes, indeed you can. That's by no means *all* you can do, but to iterate over the lines of the file that will wrok exactly. Note that the lines will still have their terminating "\n" on the end, which is why the print statement inthe following example ends in a comma (this stops print from putting out its own newline). >>> f = file("test92.py", 'r') >>> for l in f: ... print l, ... import os.path def getHomeDir(): ''' Try to find user's home directory, otherwise return current directory.'' ' try: path1=os.path.expanduser("~") except: path1="" try: path2=os.environ["HOME"] except: path2="" try: path3=os.environ["USERPROFILE"] except: path3="" if not os.path.exists(path1): if not os.path.exists(path2): if not os.path.exists(path3): return os.getcwd() else: return path3 else: return path2 else: return path1 print getHomeDir() >>> regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.python.org/pycon/2005/ Steve Holden http://www.holdenweb.com/ From timothy.grant at gmail.com Wed Feb 2 15:55:22 2005 From: timothy.grant at gmail.com (Timothy Grant) Date: Wed, 2 Feb 2005 12:55:22 -0800 Subject: Finding user's home dir In-Reply-To: <5i9rtc.rq31.ln@orion.homeinvalid> References: <5i9rtc.rq31.ln@orion.homeinvalid> Message-ID: On Wed, 02 Feb 2005 11:30:34 -0800 (PST), Nemesis wrote: > Hi all, I'm trying to write a multiplatform function that tries to > return the actual user home directory. I saw that > os.path.expanduser("~") works on Linux but on Windows2000 (at least on > the win I used) it returns %USERPROFILE%, so I tried os.environ["HOME"] > and it gave me the same results. So I ended up with > os.environ["USERPROFILE"], it doesn't work on Linux but (at least) on > Windows2000 it returns the correct information > > I googled a little bit and it seems that there is no general solution, > so I tried to merge what I found, and I wrote this little function: > > def getHomeDir(): > ''' Try to find user's home directory, otherwise return current directory.''' > try: > path1=os.path.expanduser("~") > except: > path1="" > try: > path2=os.environ["HOME"] > except: > path2="" > try: > path3=os.environ["USERPROFILE"] > except: > path3="" > > if not os.path.exists(path1): > if not os.path.exists(path2): > if not os.path.exists(path3): > return os.getcwd() > else: return path3 > else: return path2 > else: return path1 > > Please, could you test it on your systems and tell me what you got? > I'd like to know what it returns on different operating systems because > I'm developing a multiplatform software. > > Thank you all. > -- > Unauthorized amphibians will be toad away. > > |\ | |HomePage : http://nem01.altervista.org > | \|emesis |XPN (my nr): http://xpn.altervista.org > > -- > http://mail.python.org/mailman/listinfo/python-list > Works beautifully on my PowerBook running Mac OSX 10.3.7 /Users/timothygrant -- Stand Fast, tjg. From nick at craig-wood.com Mon Feb 28 05:30:03 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 28 Feb 2005 10:30:03 GMT Subject: accessor/mutator functions References: <1109315698.002207.245690@g14g2000cwa.googlegroups.com> Message-ID: Michael Spencer wrote: > mirandacascade at yahoo.com wrote: > > When I look at how classes are set up in other languages (e.g. C++), I > > often observe the following patterns: > > 1) for each data member, the class will have an accessor member > > function (a Get function) > > 2) for each data member, the class will have a mutator member function > > (a Set function) > > 3) data members are never referenced directly; they are always > > referenced with the accessor and mutator functions > > > > My questions are: > > a) Are the three things above considered pythonic? > > No > > > b) What are the tradeoffs of using getattr() and setattr() rather than > > creating accessor and mutator functions for each data member? > > Use property descriptors instead: > http://www.python.org/2.2.1/descrintro.html#property > http://users.rcn.com/python/download/Descriptor.htm#properties Actually I would say just access the attribute directly for both get and set, until it needs to do something special in which case use property(). The reason why people fill their code up with boiler plate get/set methods is to give them the flexibility to change the implementation without having to change any of the users. In python you just swap from direct attribute access to using property(). Also note that with property() you can make an attribute read only (by defining only the get method) which is often the encapsulation you really want - and that is something you can't do in C++. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From john at grulic.org.ar Wed Feb 9 22:54:09 2005 From: john at grulic.org.ar (John Lenton) Date: Thu, 10 Feb 2005 00:54:09 -0300 Subject: PyQt and Python 2.4 - also WinXP LnF? In-Reply-To: <1108003471.242829.297030@o13g2000cwo.googlegroups.com> References: <1108003471.242829.297030@o13g2000cwo.googlegroups.com> Message-ID: <20050210035409.GA13012@grulic.org.ar> On Wed, Feb 09, 2005 at 06:44:31PM -0800, Simon John wrote: > > I'm writing an XMMS remote control program, so it will be GPL when > released (if it's ever good enough to release!) so I'm looking at > buying the commercial PyQt3 or BlackAdder whilst waiting for the GPL > PyQt4 may I observe that if you're writing anything to do with xmms, you stick to plain ol' gtk1? -- John Lenton (john at grulic.org.ar) -- Random fortune: Hemos hallado al enemigo, y somos nosotros. -- Walt Kelly. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From danperl at rogers.com Sun Feb 6 11:14:18 2005 From: danperl at rogers.com (Dan Perl) Date: Sun, 6 Feb 2005 11:14:18 -0500 Subject: Confused with methods References: Message-ID: "jfj" wrote in message news:mailman.2022.1107703890.22381.python-list at python.org... >I don't understand. > We can take a function and attach it to an object, and then call it > as an instance method as long as it has at least one argument: > > ############# > class A: > pass > > def foo(x): > print x > > A.foo = foo > a=A() > a.foo() > ############# > > However this is not possible for another instance method: > > ############ > class A: > pass > > class B: > def foo(x,y) > print x,y > > b=B() > A.foo = b.foo > a=A() > > # error!!! > a.foo() > ############## > > Python complains that 'foo() takes exactly 2 arguments (1 given)'. > But by calling "b.foo(1)" we prove that it is indeed a function which > takes > exactly one argument. > > Isn't that inconsistent? You called b.foo(1) but a.foo(). Note one argument in the first call and no arguments in the second call. Would you have called a.foo(1), you would have gotten the same result as with b.foo(1). I suppose that was just a small omission on your part, but what are you trying to do anyway? It's a very strange use of instance methods. From mt at 3planes.com Mon Feb 7 11:02:29 2005 From: mt at 3planes.com (Michael Tobis) Date: 7 Feb 2005 08:02:29 -0800 Subject: declarations summary In-Reply-To: <1grm033.wnee8f9w790oN%aleaxit@yahoo.com> References: <1107750862.485179.61980@c13g2000cwb.googlegroups.com> <1grm033.wnee8f9w790oN%aleaxit@yahoo.com> Message-ID: <1107792149.921100.212710@l41g2000cwc.googlegroups.com> Alex Martelli wrote: > Michael Tobis wrote: > ... > > .x = 1 > > .def foo(): > > . if False: > > . global x > > . x = 2 > > .foo() > > .print x > > > > prints "1" > > Wrong: > >>> foo() > >>> print x > 2 > > And indeed, that IS the problem. Right. That's what I meant. Sorry, that was a thinkographical error. mt From mefjr75 at hotmail.com Sun Feb 27 00:45:37 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 26 Feb 2005 21:45:37 -0800 Subject: Is it possible to pass a parameter by reference? References: Message-ID: <1109483137.798714.13330@g14g2000cwa.googlegroups.com> Anthony Liu wrote: > I defined two functions, f1 and f2. > > f1 modifies the value of a variable called apple. > > I want to pass the modified value of apple to f2. > > How can I do this? I got stuck. Py>def f1(apple): ... apple += 1 ... f2(apple) py>def f2(apple): ... print 'you have %s apples' % apple py>f1(4) 'you have 5 apples' Read the docs this is pretty basic, it will save you time. If in doubt try it out. Use the interpreter, it is your friend. hth, M.E.Farmer From tjreedy at udel.edu Mon Feb 14 18:06:24 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Feb 2005 18:06:24 -0500 Subject: nested lists as arrays References: <1108384089.804375.179130@f14g2000cwb.googlegroups.com><42109efc$0$23451$626a14ce@news.free.fr> <1108402043.941832.34110@f14g2000cwb.googlegroups.com> Message-ID: wrote in message news:1108402043.941832.34110 at f14g2000cwb.googlegroups.com... > def setRandomState(self): > # container for the elements to pick from > container = [1,2,3,4,5,6,7,8,-1] > > # create elements of puzzle randomly > i = 0 > j = 0 > while i <= self.dim-1: > while j <= self.dim-1: > if len(container) > 0: > randomindex = random.randint(0,len(container)-1) > self.elements[j][i] = container[randomindex] > del container[randomindex] > j=j+1 > else: > break > j=0 > i=i+1 Without reading closely, I believe that the above can generate any possible position. Are you aware that half are unsolvable? If that matters, you need to either find a book or site that explains the parity test for solvability or generate the start position from the goal position by a series of random moves. Terry J. Reedy From francis.girard at free.fr Tue Feb 15 16:35:15 2005 From: francis.girard at free.fr (Francis Girard) Date: Tue, 15 Feb 2005 22:35:15 +0100 Subject: Iterator / Iteratable confusion In-Reply-To: References: <420a5c1e$0$21630$a1866201@visi.com> <200502142131.53265.francis.girard@free.fr> Message-ID: <200502152235.18266.francis.girard@free.fr> Le mardi 15 F??vrier 2005 02:26, Terry Reedy a ??crit??: > "Francis Girard" wrote in message > news:200502142131.53265.francis.girard at free.fr... > > (Note for oldtimer nitpickers: except where relevant, I intentionally > ignore the old and now mostly obsolete pseudo-__getitem__-based iteration > protocol here and in other posts.) > > Le dimanche 13 F?vrier 2005 23:58, Terry Reedy a ?crit : > >> Iterators are a subgroup of iterables. Being able to say iter(it) > >> without > >> having to worry about whether 'it' is just an iterable or already an > >> iterator is one of the nice features of the new iteration design. > > > >I have difficulties to represent an iterator as a subspecie of an > >iteratable > > You are not the only one. That is why I say it in plain English. > > You are perhaps thinking of 'iterable' as a collection of things. But in > Python, an 'iterable' is a broader and more abstract concept: anything with > an __iter__ method that returns an iterator. > Yes, I certainly do define an "iteratable" as something _upon_ which you iterate (i.e. a container of elements). The iterator is something that serves the purpose to iterate _upon_ something else, i.e. the iteratable. For me, it makes little sense to iterate _upon_ an iterator. The fact that, in Python, both iterators and iteratables must support the __iter__ method is only an implementation detail. Concepts must come first. > To make iterators a separate, disjoint species then requires that they not > have an __iter__ method. Some problems: > A. This would mean either > 1) We could not iterate with iterators, such as generators, which are > *not* derived from iterables, or, less severely Well, generators are a bit special as they are both (conceptually) iterators and iteratables by their very intimate nature -- since the elements are _produced_ as needed, i.e. only when you do iterate. But as for ordinary iterators, I don't see any good conceptual reason why a generator-iterator should support the "__iter__" method. There might be other reasons though (for example related with the for ... in ... construct which I discuss later in this reply). > 2) We would, usually, have to 'protect' iter() calls with either > hasattr(it, '__iter__') or try: iter(it)...except: pass with probably no > net average time savings. Well, I'm not interested in time savings for now. Only want to discuss more conceptual issues. > B. This would prohibit self-reiterable objects, which require .__iter__ to > (re)set the iteration/cursor variable(s) used by .next(). To sharply distinguish in code what is conceptually different is certainly very good and safe design in general. But what I am thinking about would not _prohibit_ it. Neitheir is C++ STL prohibiting it. > C. There are compatibility issues not just just with classes using the old > iteration protocol but also with classes with .next methods that do *not* > raise StopIteration. The presence of .__iter__ cleanly marks an object as > one following the new iterable/iterator protocol. Another language might > accomplish the same flagging with inheritance from a base object, but that > is not Python. > (That is not C++ templates either. See below.) Why not "__next__" (or something else) instead of "next" for iterators and, yes, __iter__ for iteratables ? > > [snip]...C++ STL where there is a clear (I resist to > > say "clean") distinction between iteratable and iterator. > > leaves out self-iterating iterables -- collection objects with a .next > method. Nope. See the definition of an iterator in C++ STL below. Anything respecting the standard protocol is an iterator. It might be the container itself. The point is that with the standard C++ STL protocol, you are not ___obliged___ to define an iterator as _also_ being an iteratable. Both concepts are clearly separated. > I am sure that this is a general, standard OO idiom and not a > Python-specific construct. Perhaps, ignoring these, you would prefer the > following nomenclature: > iterob = object with .__iter__ > iterable= iterob without .next > iterator = iterob with .next > > Does STL allow/have iterators that are *not* tied to an iterable? Yes of course. A "forward iterator", for example is _anything_ that supports the following : =================== In what follows, we shall adopt the following convention. X : A type that is a model of Trivial Iterator T : The value type of X x, y, y : Object of type X t : Object of type T Copy constructor : X(x) ------> X Copy constructor : X x(y); or X x = y; Assignment : x = y [1] ------> X& Swap : swap(x,y) ------> void Equality : x == y ------> Convertible to bool Inequality : x != y ------> Convertible to bool Default constructor : X x or X() ------> X Dereference : *x ------> Convertible to T Dereference assignment : *x = t ------> X is mutable Member access : x->m [2] ------> T is a type for which x.m is defined ====================== Anything that respects this convention is a forward iterator. They might produce their own content as we iterate upon them if that's what is needed. They don't have to be a class inheriting from some another standard class. That's the beauty of C++ templates, forgetting (but not forgiving) its very ugly and complex syntax. > > >One of the result of not distinguishing them is that, at some point in > >your > >programming, you are not sure anymore if you have an iterator or an > >iteratable ; and you might very well end up calling "iter()" or > > "__iter__()" everywhere. > > If you iterate with a while loop just after creating a new iterable or > iterator, then you probably do know which it is and can make the iter() > call only if needed. Yes, true. But then you start factorize some code, and, then, oh well, you can see the difficulties. > If you while-iterate with a function argument, then > iter() is a simpler way to be generic than the alternatives in A2 above. > You need that genereticity chiefly because you want to support both, iterators and iteratables in some argument place. I don't see any good reasons for this except historical ones (see for ... in ... constructs below). It might be preferable for a method to only accepts iterator if the only thing the method has to do with the iteratable is to iterate over it, and let the client of the method call "__iter__" or "iter()" if all he has is an iteratable (i.e. a container). > >I am not concerned with the small performance issue involved here > > Good. I think there are small. The number and time for iterations is far > more important. > > > (as I very seldom am) but with clarity. After all, why should you have to > > > > > call __iter__ on an iterator you just constructed > > As I said above, you don't, and most people wouldn't. The function > implementing for loops does because *it*, unlike you, only sees the object > passed and not the code that created the object! > As I said above, why should the function implementing for loops should accept anything other than an iterator (not iteratable), except, maybe, for historical reasons ? > >I have a strong feeling that the problem arises from the difficulty to > > marry the familiar ""for ... in ..."" construct with iterators. [snip] > > What difficulty? For loops accept an iterable and iterate with the derived > iterator. > The second argument place of the "for ... in ..." construct, _before_ the iteration protocol, had to be a container. At that time, it was the "for ... in ..." syntax construct that palyed the conceptual roles of both iteration and iterator. Now, the "for ... in ..." construct is the standard way to do iterate. Therefore, the second argument place of the "for ... in ..." must also be an iterator if we have to introduce iterators to Python. The question must had been, at the time iterators were introduced, "how should we manage to have these two different things in the same argument place ?" I think the Python solution to his dilemma is very acceptable. It is certainly the python way to be very polymorphic. But, at the same time, I can very well understand that a lot of person do have difficulties to swallow that an iterator should be a subspecie of an iteratable. > Would you really prohibit the use of for loops with generators and other > non-iterable-derived iterators? See A1 above. Of course not. This question reveals the difficulty I just pointed out. > > >To have iterators act as iteratables might very well had been a > > > > >compromise to solve the problem. > > I think it elegant. See below. > > >I am not sure at all that this is a "nice feature" to consider an iterator > >at > >the same level that an iteratable. > > I think you are too stuck in the STL model. Yes, very true. I just can't help thinking that iterators and iteratables are very different concepts. > > > It makes it a bit more akward to have the > >"mind impulse", so to speak, to build iterators on top of other iterators > >to > slightly modify the way iteration is done. > > On the contrary, what could be more elegant than > def itermodifier(it): > for i in it: # where it is often an iterator > yield modification-of-i > See the itertools module and docs and the examples of chaining iterators. > Yes, I certainly do think that generators are very, very, very elegant. I came back to python a lot because of their beauty, coupled with all the other advantages Python has to offer : simple syntax, well thought libraries, easy portability, pragmaticism, etc. (there's a long list). On the other hand, I certainly do notice that the itertools module documentation says that all the functions defined there returns an iterator (not iteratable) but accepts iteratable. There is something akward about it for the beginner. You always have to re-think, oh ! yes ! they refer to the protocol, not the concepts. But this is not that bad and I can certainly live with it. (Thank you if you had the courage to read it all !) Regards Francis Girard > Terry J. Reedy From sjmachin at lexicon.net Tue Feb 1 19:39:22 2005 From: sjmachin at lexicon.net (John Machin) Date: 1 Feb 2005 16:39:22 -0800 Subject: Awkwardness of C API for making tuples In-Reply-To: References: <1107289261.185768.116790@f14g2000cwb.googlegroups.com> Message-ID: <1107304762.784406.111080@f14g2000cwb.googlegroups.com> Dave Opstad wrote: > In article <1107289261.185768.116790 at f14g2000cwb.googlegroups.com>, > "John Machin" wrote: > > > What is the purpose of this first loop? > > Error handling. If I can't successfully create all the PyInts then I can > dispose the ones I've made and not bother making the tuple at all. > > > > In what variable-length storage are you storing these (Python) integers > > during this first loop? Something you created with (a) PyMem_Malloc (b) > > malloc (c) alloca (d) your_own_malloc? > > (b) malloc. The sequence here is: 1) malloc; 2) check for malloc > success; 3) loop to create PyInts (if failure, Py_DECREF those made so > far and free the malloc'ed buffer); 4) create new tuple (error checks > again); and 5) PyTuple_SET_ITEM (no error checks needed) Don't. If you _must_ allocate your own storage, use PyMem_Malloc. > > > 1. Determine the length of the required tuple; this may need a loop, > > but only to _count_ the number of C longs that you have. > > 2. Use PyTuple_New. > > 3. Loop to fill the tuple, using PyInt_FromLong and PyTuple_SetItem. > > This would certainly be simpler, although I'm not sure I'm as clear as > to what happens if, say, in the middle of this loop a PyInt_FromLong > fails. I know that PyTuple_SetItem steals the reference; does that mean > I could just Py_DECREF the tuple and all the pieces will be > automagically freed? If so, I'll take your recommendation and rework the > logic this way. This is what I believe happens. However even if you did need to do more cleaning up, you shouldn't penalise the normal case i.e. when PyInt_FromLong works. The only failure cause AFAIK is running out of memory. This should be rare unless it's triggered by your calling malloc :-) From krivilli at ajato.com.br Tue Feb 15 08:42:01 2005 From: krivilli at ajato.com.br (krivilli at ajato.com.br) Date: Tue, 15 Feb 2005 14:42:01 +0100 Subject: Returned mail: see transcript for details Message-ID: <200502151347.j1FDlfux016644@phoenix.szarvas.hu> -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: ldg.zip.txt URL: From pekka.niiranen at wlanmail.com Mon Feb 28 10:47:32 2005 From: pekka.niiranen at wlanmail.com (pekka niiranen) Date: Mon, 28 Feb 2005 15:47:32 GMT Subject: HELP: Python equivalent of UNIX command "touch" Message-ID: Does anybody know Python recipe for changing the date of the directory or files in W2K to current date and time? In UNIX shell command "touch" does it. -pekka- From aleaxit at yahoo.com Sun Feb 6 18:16:07 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 7 Feb 2005 00:16:07 +0100 Subject: string issue References: <36QMd.103084$Jk5.36127@lakeread01> Message-ID: <1grl717.1o4ofg7arp8c2N%aleaxit@yahoo.com> Bill Mill wrote: ... > > > You are modifying the list as you iterate over it. Instead, iterate over > > > a copy by using: > > > > > > for ip in ips[:]: ... > Once you know it, it's neat, and I use it sometimes. However, it's a > little too "magical" for my tastes; I'd rather be more explicit about > what's going on. Using ips[:] to make a copy on the fly is very idiomatic, but I've never liked it, personally. I see no reason to prefer it to the even shorter and arguably less obscure ips*1, for example. My preference is: for ip in list(ips): Alex From tzot at sil-tec.gr Mon Feb 21 10:30:42 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 21 Feb 2005 17:30:42 +0200 Subject: [ANN] Python 2.4 Quick Reference available References: <1108831318.290846.5930@z14g2000cwz.googlegroups.com> <37qaleF5gd7bcU1@individual.net> <421898CD.6040408@iinet.net.au> Message-ID: On Sun, 20 Feb 2005 14:57:14 +0000, rumours say that Michael Hoffman might have written: [snip: use 'open' in preference to 'file'] >To be honest I doubt open will be extended in this manner. I can see >the Pythoneers adding, say, a keyword argument to open to allow a URL >instead, but just changing the current behavior would be too risky. Plus, >what happens if I have a file named "http://www.python.org/"? I don't know in what filesystem you can have such a file name [1]. Slashes ('/') you can (kind of) get away with using \u2215 (DIVISION SLASH) on NTFS or on UTF-8 encoded *nix filenames, but I haven't found a replacement for colon (':'). Using similar glyphs, of course, invalidates the URL... [1] Unless you mean it as a *path name*, which /could/ exist on *nix filesystems (normalised to a directory called 'www.python.org' in the local subdirectory 'http:'), but still could not on NTFS. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From steven.bethard at gmail.com Thu Feb 10 12:29:38 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 10 Feb 2005 10:29:38 -0700 Subject: empty classes as c structs? In-Reply-To: <1grrgjh.ntgjzn167kxpyN%aleaxit@yahoo.com> References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <1gric2n.17myhon1hfrc6gN%aleaxit@yahoo.com> <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> <9rmdnVR1lr-LYJvfRVn-gg@comcast.com> <4207606E.4040806@iinet.net.au> <1grnyld.1t8l5kw1nr5aqsN%aleaxit@yahoo.com> <1grqs37.1sjjd0b162e5z4N%aleaxit@yahoo.com> <1grrgjh.ntgjzn167kxpyN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Steven Bethard wrote: >>I like the idea of chain, though, so I'll probably add the class with >>just __init__ and __getattribute__ to the current implementation. I'm >>willing to be persuaded, of course, but for the moment, since I can see >>a few different options, I'm refusing the temptation to guess on the >>"most natural" behavior for __delattr__ and __setattr__... =) > > > That's probably best in terms of API. Not too sure about the > implementation (why wouldn't __getattr__ suffice, holding the bunches in > an attribute with a magicname?) but that's a secondary issue. Yeah, I had it written with __getattr__ at first... Not sure why I switched over... ;) I'll probably switch it back. Steve From spam at nospam.org Thu Feb 10 17:25:45 2005 From: spam at nospam.org (Erik Johnson) Date: Thu, 10 Feb 2005 15:25:45 -0700 Subject: Tkinter.Canvas saved as JPEG? Message-ID: <420bdd36$1@nntp.zianet.com> I want to draw some simple (dynamic) graphs and get these saved as a JPEG file to reference in a web link. I am aware of PIL (Python Image Library), but unfortunatley my system does not have it built. After looking at the README for it and seeing it depends on two separate packages to support JPEG and TrueType font, I though maybe there was an easier way. Tkinter is currently built and working on my Python 2.2.2 installation. Is there some simple path to take a Tkinter.Canvas with some stuff drawn on it and get it into a file as a JPEG (without anything from PIL, preferably just using standard libraries)? (I have John Grayson's book. I haven't read the whole thing but I'm not having much luck readily finding a way to do this, though it may be there somewhere. Feel free to cite page numbers there if that helps.) Thanks for taking the time to read my post. :) -ej From gmane-schpam at joefrancia.com Wed Feb 16 17:04:30 2005 From: gmane-schpam at joefrancia.com (Joe Francia) Date: Wed, 16 Feb 2005 17:04:30 -0500 Subject: Multiple initialization methods? References: <1108589491.301007.174370@z14g2000cwz.googlegroups.com> Message-ID: On 16 Feb 2005 13:31:31 -0800, alex wrote: > Hi, > > it is possible to define multiple initialization methods so that the > method is used that fits? > > I am thinking of something like this: > > def __init__(self, par1, par2): > self.init(par1, par2); > > def __init__(self, par1): > self.init(par1, None) > > def init(self, par1, par2): > ... > ... > > So if the call is with one parameter only the second class is executed > (calling the 'init' method with the second parameter set to 'None' or > whatever. But this example does not work. > > How to get it work? > > Alex > You can do this: def __init__(self, *args, **kwargs): #args is a tuple of positional args #kwargs is a dict of named args print args, kwargs #real code here instead of lame print statements try: self.name = args[0] except IndexError: self.name = '' self.occupation = kwargs.get('occupation', '') or even better, do this: def __init__(self, name='', occuaption='', age=0): #named args with default values self.name = name self.occupation = occupation self.age = age Based on this, you should have enough information to make your class work. -- Soraia: http://www.soraia.com/ From dr_rave at hotmail.com Tue Feb 15 18:03:45 2005 From: dr_rave at hotmail.com (Roch ....) Date: Tue, 15 Feb 2005 23:03:45 +0000 Subject: Compiler In-Reply-To: <420990CF.7000705@ocf.berkeley.edu> Message-ID: An HTML attachment was scrubbed... URL: From tim.golden at viacom-outdoor.co.uk Tue Feb 8 06:05:56 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 8 Feb 2005 11:05:56 -0000 Subject: re-entrancy question Message-ID: <9A28C052FF32734DACB0A288A3533991035A68@vogbs009.gb.vo.local> [apocalypznow] | I have a program that instantiates some objects and runs a main loop. | Before the main loop starts, I create a thread that listens to TCP | connections on a port. If any connections are made, and depending on | the data, I call methods on some of those objects. | | I am worried that calling methods on objects from outside the | main loop, | but that are also operated on in the main loop, could cause problems. | | My questions: | 1) is this safe? | 2) what kind of problems could occur? | 3) how do I safely handle this? No doubt there are more pertinent answers, but unless this is a learning exercise, you'd be better off investigating Pyro: http://pyro.sf.net TJG (And, thinking about it, even if this is a learning exercise) ________________________________________________________________________ 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 duncan.booth at invalid.invalid Thu Feb 17 12:11:33 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Feb 2005 17:11:33 GMT Subject: difference between class methods and instance methods References: <1119g2rre5g610c@corp.supernews.com> <37juh3F5d511mU1@individual.net> Message-ID: Diez B. Roggisch wrote: > John wrote: >> ... hmm... bound methods get created each time you make >> a call to an instance method via an instance of the given class? > > No, they get created when you create an actual instance of an object. > So only at construction time. Creating them means taking the unbound > method and binding the created object as first argument to the method. > Thus each instance of a class Foo with a method bar has its own > instance of bar - the bound method bar. But only one per object. > > This is badly wrong. John was correct. Bound methods get created whenever you reference a method of an instance. If you are calling the method then the bound method is destroyed as soon as the call returns. You can have as many different bound methods created from the same unbound method and the same instance as you want: >>> inst = C() >>> f1 = inst.foo >>> f2 = inst.foo >>> f1, f2 (>, >) >>> f1 is f2 False >>> f1 is inst.foo False >>> Every reference to inst.foo is a new bound method. From steven.bethard at gmail.com Mon Feb 7 16:35:35 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 07 Feb 2005 14:35:35 -0700 Subject: returning True, False or None In-Reply-To: References: <1107573625.439409.100870@o13g2000cwo.googlegroups.com> <1107574705.956498.219490@c13g2000cwb.googlegroups.com> Message-ID: <-cSdndTQycC_QprfRVn-sQ@comcast.com> Matteo Dell'Amico wrote: > Since a function that doesn't return is equivalent to one that returns > None, you can write it as: > > >>> def doit(lst): > ... s = set(lst) - set([None]) > ... if s: return max(s) > > that looks to me as the most elegant so far, but this is just because > it's mine :-) Cool. I prefer to be explicit about returns (e.g. not counting on the automatic return None), and I'd rather not create the unnecessary None set, so I would probably write this like: py> def f(lst): ... s = set(lst) ... s.discard(None) ... if s: ... return max(s) ... else: ... return None ... But it's definitely a very elegant solution. Thanks! Steve From tim.peters at gmail.com Tue Feb 1 11:52:08 2005 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 1 Feb 2005 11:52:08 -0500 Subject: pythonic equivalent of Mathematica's FixedPoint function In-Reply-To: <1107273234.276714.272890@z14g2000cwz.googlegroups.com> References: <1107273234.276714.272890@z14g2000cwz.googlegroups.com> Message-ID: <1f7befae050201085271976dc@mail.gmail.com> [jelle] > I now some hostility to functional programming is flaming up now and > then; still could someone suggest me a pythonic equivalent for > Mathematica's FixedPoint function? For those not familiar with > Mathematica: > > FixedPoint[f, expr] starts with expr, then applies f repeatedly until > the result no longer changes. If that's all there is to it, sounds like a simple loop: def FixedPoint(f, expr): old = expr while True: new = f(old) if old == new: return new old = new Then, e.g., >>> FixedPoint(lambda x: (x + 25/x)/2, 400) 5 But I bet there's more to it than just that (e.g., maybe an optional limit on max # of iterations; maybe a way to terminate on "approximate equality"). As-is, that function is very prone to falling into an infinite loop. [and later] > doh... > > https://sourceforge.net/projects/fixedpoint Nope, that has to do with decimal arithmetic using a fixed number of decimal digits after the decimal point ("fixed-point decimal"). From nick at craig-wood.com Fri Feb 11 13:30:02 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 11 Feb 2005 18:30:02 GMT Subject: goto, cls, wait commands References: <1ixbe7q69lob3.1npuu3z54gx8z.dlg@40tude.net> <420b89f2$0$21601$a1866201@visi.com> <420ba000$0$29241$626a14ce@news.free.fr> <420ba879$0$29513$a1866201@visi.com> Message-ID: Grant Edwards wrote: > I forgot to mention try/except. When I do use goto in C > programming it's almost always to impliment what would have > been a try/except block in Python. Yes I'd agree with that. No more 'goto out'. There is this also for (i = 0; ...) { if (something) goto found; } /* do stuff when not found */ found:; (yes I hate setting flags in loops ;-) This translates exactly to the for: else: construct for i in xrange(...): if something: break else: # do stuff when not found The last language I saw with this very useful feature was FORTH in about 1984! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From chaotrope at jps.net Mon Feb 21 12:42:35 2005 From: chaotrope at jps.net (kim kubik) Date: Mon, 21 Feb 2005 17:42:35 GMT Subject: IDLE Problem: win98\Python2.4 References: <22eSd.1969$MY6.1483@newsread1.news.pas.earthlink.net> <1109004976.267201.200950@z14g2000cwz.googlegroups.com> Message-ID: > kim kubik wrote: > > I installed Python2.4 in Win98 > > and IDLE doesn't work > Are you also running Ruby? The Ruby bundle for MS Windows has caused > problems with it's TCL package conflicting with Python's. > thanks, one of the first things I noted in the error msg (not included for brevity) was that the ruby search path in AUTOEXEC.BAT was ahead of the python path (and ruby had tcl83.lib) so I REM'd all the tcl stuff out. AND THEN (stupid me!) I put into AUTOEXEC.BAT 'set TCL_LIBRARY=c:\python23\tcl' thinking that would point python to the proper libs. What a mistake! If I take that line out (and leave the ruby stuff REM'd out as well) IDLE runs just fine. So thanks! A little knowledge is indeed a dangerous thing; forgive my stupidity - it will happen again, so I'm apologizing in advance! \kim From alan.mcintyre at esrgtech.com Fri Feb 4 14:40:27 2005 From: alan.mcintyre at esrgtech.com (Alan McIntyre) Date: Fri, 04 Feb 2005 14:40:27 -0500 Subject: string issue In-Reply-To: <36QMd.103084$Jk5.36127@lakeread01> References: <36QMd.103084$Jk5.36127@lakeread01> Message-ID: Wow, that's cool; I'd never seen that before. :) Thanks, Steve.. Steve Holden wrote: > You are modifying the list as you iterate over it. Instead, iterate over > a copy by using: > > for ip in ips[:]: > ... > > regards > Steve From martin at v.loewis.de Sun Feb 20 04:40:21 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 20 Feb 2005 10:40:21 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <42172136$0$27576$9b622d9e@news.freenet.de> Message-ID: <42185b05$0$15460$9b622d9e@news.freenet.de> Ilias Lazaridis wrote: > Should a professional developer take python serious? Yes. Regards, Martin From duncan.booth at invalid.invalid Thu Feb 10 09:20:57 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Feb 2005 14:20:57 GMT Subject: That horrible regexp idiom References: <3e8ca5c805020923107c36cd7f@mail.gmail.com> Message-ID: Nick Coghlan wrote: > I knew if/elif was a much better argument in favour of embedded > assignment than while loops are. > I know I'm going to regret posting this, but here is an alternative, very hackish way to do all those things people keep asking for, like setting variables in outer scopes or doing lots of nested ifs for regex matching or simulating passing a local variable by reference. My excuse for the following code is that was unwell and I think I was slightly feverish when I wrote it: ----- hack.py ----------- import new def mksetter(baa): '''Cruel hack to set scoped variables. baa should be a lambda which accesses the variable you wish to set. It must be a local or outer scope variable, not a global ''' closure = baa.func_closure name = baa.func_code.co_names[0] if not isinstance(closure, tuple) or len(closure) != 1: raise TypeError('''mksetter() argument must be a lambda accessing a local or scoped variable''') def f(v): a = v return v lambda: a c = f.func_code newcode = new.code( c.co_argcount, 1, c.co_stacksize, c.co_flags, c.co_code, c.co_consts, c.co_names, c.co_varnames, c.co_filename, 'set_'+name, c.co_firstlineno, c.co_lnotab, (name,), (), ) return new.function(newcode, f.func_globals, 'set_'+name, None, closure) if __name__=='__main__': def set_a_local(): a = 42 print "a=",a set_a = mksetter(lambda: a) set_a(24) print set_a print "a=",a set_a_local() def set_scoped(): count = 0 set_count = mksetter(lambda: count) def inc(): set_count(count+1) for i in range(10): print "count=",count inc() print "Final value",count set_scoped() import re def silly_regex(): name = re.compile('[a-zA-Z_][a-zA-Z0-9_]*') number = re.compile('[0-9]+(\\.[0-9]*)?([eE][-+]?[0-9]+)?') m = None set_m = mksetter(lambda: m) for s in 'abc', '2.5e-3', '!': if set_m(name.match(s)): print "name", m.group(0) elif set_m(number.match(s)): print "number", m.group(0) else: print "no match", m, s silly_regex() ----- end of hack.py ---- Sorry. If anyone actually feels tempted to use this: I take no responsibility for the results. I can't particularly see why future versions of Python would change to stop it working, but they could, and of course it is definitely a 'C-Python only' trick. From richie at entrian.com Thu Feb 10 04:01:09 2005 From: richie at entrian.com (Richie Hindle) Date: Thu, 10 Feb 2005 09:01:09 +0000 Subject: Is Python as capable as Perl for sysadmin work? In-Reply-To: References: Message-ID: <6b8m01tcr3p7p7dq3beekj7q1fgmt9qubr@4ax.com> [Steve] > Was it INTERCAL that had the COMEFROM statement instead of > GOTO? I REALLY like the idea of a COMEFROM statement. I think python should > have a COMEFROM statement It does - see http://entrian.com/goto/ (In case you doubt it: yes, it works, but note that it doesn't work at the interactive prompt, only in a real source file.) (The fact that I felt obliged to add the first paragraph on that page is the funniest part of the whole thing. I really did have people genuinely thanking me for the module, asking for features, asking for help with using it, and so on.) -- Richie Hindle richie at entrian.com From exogen at gmail.com Sun Feb 13 16:43:29 2005 From: exogen at gmail.com (Brian Beck) Date: Sun, 13 Feb 2005 16:43:29 -0500 Subject: builtin functions for and and or? In-Reply-To: References: Message-ID: Brian Beck wrote: > def all(seq, pred=bool): > "Returns True if pred(x) is True for every element in the iterable" > for elem in ifilterfalse(pred, seq): > return False > return True > > def any(seq, pred=bool): > "Returns True if pred(x) is True for at least one element in the > iterable" > for elem in ifilter(pred, seq): > return True > return False I should probably note, you'll have to from itertools import ifilter, ifilterfalse to use these. -- Brian Beck Adventurer of the First Order From cjw at sympatico.ca Wed Feb 16 13:36:31 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 16 Feb 2005 13:36:31 -0500 Subject: Can __new__ prevent __init__ from being called? In-Reply-To: <87acq5tos7.fsf@news2.ososo.de> References: <87is4tldea.fsf@news2.ososo.de> <3LOdncHRa6C77I_fRVn-rA@comcast.com> <87acq5tos7.fsf@news2.ososo.de> Message-ID: Felix Wiemann wrote: > Steven Bethard wrote: > > >>Felix Wiemann wrote: >> >> >>>How can I prevent __init__ from being called on the >>>already-initialized object? >> >>The short answer: you can't: >> http://www.python.org/2.2.3/descrintro.html#__new__ > [snip] This prompts a similar query. __new__ appears to be intended for immutable objects but it seems to be called as part of constructor process for all instances. Regarding the original question. It is not possible to prevent the use of __init__ but is it possible to prevent __init__ having any effect by setting a flag when __init__ is called for the first creation of the instance. Colin W. > From claird at lairds.us Mon Feb 14 13:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Mon, 14 Feb 2005 18:08:04 GMT Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: <37bkemF5a7s7vU1@individual.net> Message-ID: In article <37bkemF5a7s7vU1 at individual.net>, Diez B. Roggisch wrote: >> One of the most funny things within open-source is that switching: >> >> first: >> "we have powerfull solutions which beat this and that" >> >> then: >> "hey, this is just volunteer work" >> > >I don't see the contradiction here. It beats a great deal of commercial >solutions in a lot of ways. But not on every single one of these. And the >_reason_ for beating commercial software in certain aspects is exactly that >somebody stood up and volunteered. Obviously you aren't interested in the >more labour-intensive parts of the os-development. > >> >> But if those answers above were of official nature, I must seriously >> rethink if I can rely on _any_ system which is based on python, as the >> foundation and the community do not care about essential needs and >> requirements. > >They might not care about _your_ perceived essential needs. But as lots of >people use python and python based solutions with great commercial success, >you might think of reviewing your needs more critical. After all, there is >no _perfect_ system for all needs. . . . Me, too. On the off-chance that a naive passerby is misled by parts of this thread, I'll point out that ... well, if the alternative to Python, say, is commercial products which are to be judged on how much they "care about essential needs and requirements" of *users* ... Nope, 'can't do it. I can't finish that sentence with a straight face. From apardon at forel.vub.ac.be Mon Feb 7 10:32:41 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Feb 2005 15:32:41 GMT Subject: Confused with methods References: <1grknb0.ygwohl17y6j5yN%aleaxit@yahoo.com> <1grmd4z.1tlm4e61650vedN%aleaxit@yahoo.com> Message-ID: Op 2005-02-07, John Lenton schreef : > > > --cvVnyQ+4j833TQvp > Content-Type: text/plain; charset=us-ascii > Content-Disposition: inline > Content-Transfer-Encoding: quoted-printable > > On Mon, Feb 07, 2005 at 02:53:49PM +0000, Antoon Pardon wrote: >> The fact that a function in a class performs a lot of magic if >> it is called through an instance, that isn't performed otherwise, >> makes python inconsistent here. You may like the arrangement >> (and it isn't such a big deal IMO) but that doesn't make it consistent. > > I vote for accepting the fact (it goes with the "practicality beats > purity" bit, But before one can produce the "practicality beats purity" argument, one has to accept this isn't pure. That was all I was saying here, python is not consistent/pure here. Now there can be good arguments to have this that offset the inconsistency, but the python people shouldn't then try to argue that it is consistent anyway. > because otherwise all our methods would have to start > with an @instancemethod). This doesn't justify (IMVVHO) a new keyword, > like you (was it you?) seemed to imply (do you really mean for > instancemethod (or somesuch) and classmethod to become keywords?). I > think it's fine the way it is: there's an implicit @instancemethod, > and @staticmethod (which you'd have be the default if I read you > right) has to be explicit, when in classes. I'm not saying I would have it so, I'm saying that would be the pure/consistent way to do it. -- Antoon Pardon From steven.bethard at gmail.com Mon Feb 7 18:39:56 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 07 Feb 2005 16:39:56 -0700 Subject: def __init__ question in a class definition rephrased In-Reply-To: References: Message-ID: Jeffrey Borkent wrote: > what is the significance ( if any ) of the __ in these self.xxxxxx > assignments. Variables with preceding __ are a vague attempt to avoid some types of name collisions in inheritance hierarchies. Any name that starts with a __ will be mangled by prefixing it with _: py> class C(object): ... def __init__(self, x): ... self.__type = type(x) ... self.x = x ... py> C(1).__dict__ {'_C__type': , 'x': 1} py> class D(C): ... def __init__(self, x): ... super(D, self).__init__(x) ... self.__type = D ... py> D(1).__dict__ {'_C__type': , 'x': 1, '_D__type': } Note that the D object has two different __type attributes -- one mangled for type C and one mangled for type D. While the intent of __ variables is to allow you to not worry about the names given to "private" attributes of a class when you inherit from that class, it doesn't actually achieve this in all cases -- you'll still have problems if you inherit from two classes with the same names that use the same __ attribute: ---------- a.py ---------- class A(object): pass ---------- b.py ---------- import a class X(a.A): def __init__(self): self.__x = 'b.X.__x' super(X, self).__init__() ---------- c.py ---------- import a class X(a.A): def __init__(self): self.__x = 'c.X.__x' super(X, self).__init__() ---------- d.py ---------- import b, c class D(b.X, c.X): pass -------------------------- py> import d py> d.D().__dict__ {'_X__x': 'c.X.__x', '_A__x': 'A'} Note that the D object has two __x attributes, not three, like it should. Code in b.py which depends on the __x attribute is now broken because __x should should have the value 'b.X.__x' but instead it has the value from the c module, 'c.X.__x'. The solution to this is to have names mangled with their module name as well, but that's backwards incompatible, so Python's not likely to change that way. My general feeling here is that "we're all consenting adults", and that __ is probably not helpful in most cases. If you simply don't want the attribute shown by, say, pydoc, prefixing a single underscore should be sufficient and doesn't invoke the name-mangling. STeVe From jfj at freemail.gr Mon Feb 14 16:23:03 2005 From: jfj at freemail.gr (jfj) Date: Mon, 14 Feb 2005 13:23:03 -0800 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: <421116B7.6030306@freemail.gr> Michael Hoffman wrote: > Ilias Lazaridis wrote: >> b) Why does the Python Foundation not ensure, that the python >> source-code is directly compilable with MinGW? > > > Why should they? It already runs on Windows with a freely available > compiler. The point is that the freely available compiler wouldn't be free if it wasn't for gcc. Just for that I _believe_ python, being open source, should support mingw as the default. But I *don't care* and I don't mind, really ;) jfj From aurora00 at gmail.com Fri Feb 18 12:16:59 2005 From: aurora00 at gmail.com (aurora) Date: Fri, 18 Feb 2005 09:16:59 -0800 Subject: Newbie CGI problem References: Message-ID: Not sure about the repeated hi. But you are supposed to use \r\n\r\n, not just \n\n according to the HTTP specification. > #!/usr/bin/python > import cgi > print "Content-type: text/html\n\n" > print "hi" > > Gives me the following in my browser: > > ''' > hi > Content-type: text/html > > > hi > ''' > > Why are there two 'hi's? > > Thanks, > Rory From thomastnewman at yahoo.com Sat Feb 26 16:21:21 2005 From: thomastnewman at yahoo.com (Thomas Newman) Date: Sat, 26 Feb 2005 22:21:21 +0100 Subject: [solved] Re: error in non-existing code? In-Reply-To: <421740E4.5030005@yahoo.com> References: <421740E4.5030005@yahoo.com> Message-ID: <4220E851.4000101@yahoo.com> Thomas Newman wrote: >Michael Hoffman wrote: > > > >>Thomas Newman wrote: >> >> >> >>>I wanted to look at the code that gives me the error, but there is no >>>line 447 in /usr/lib/python2.3/pyclbr.py: >>> >>> >>Try deleting pyclbr.py[co]. >> >> There were recursive imports, meaning file A imported file B and vice versa. Solving that issue removed the error. Still I find it confusing. ttn From deetsNOSPAM at web.de Tue Feb 1 10:52:56 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 01 Feb 2005 16:52:56 +0100 Subject: Awkwardness of C API for making tuples References: Message-ID: <369mplF4ubv6mU2@individual.net> > One of the functions in a C extension I'm writing needs to return a > tuple of integers, where the length of the tuple is only known at > runtime. I'm currently doing a loop calling PyInt_FromLong to make the > integers, then PyTuple_New, and finally a loop calling PyTuple_SET_ITEM > to set the tuple's items. Whew. > > Does anyone know of a simpler way? I can't use Py_BuildValue because I > don't know at compile-time how many values there are going to be. And > there doesn't seem to be a PyTuple_FromArray() function. > > If I'm overlooking something obvious, please clue me in! If you already know _how_ to create a function like PyTuple_FromArray() - why don't you define it yourself and use it? -- Regards, Diez B. Roggisch From claudio.grondi at freenet.de Fri Feb 4 17:35:45 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 4 Feb 2005 22:35:45 -0000 Subject: IPython colors in windows References: <1107487113.732375.110850@c13g2000cwb.googlegroups.com> <36hculF51ho2sU1@individual.net><1107530489.308497.103530@g14g2000cwa.googlegroups.com><36hrjpF4ui8fbU1@individual.net> Message-ID: <36i84qF52ce29U1@individual.net> I have installed version 1.8. It makes is even worse, because now also "In [1]:" gets black background and is unreadable (it had a grey background before). Re-installing 1.7 makes the background again gray. I use German Windows 2000 SP 4 as OS. Claudio P.S. In quote marks the parts with black background: "In [1]:" sdlfjf "--------------------------------------------------------------------------- " "exceptions.NameError" Traceback (most recent call last) "Fernando Perez" schrieb im Newsbeitrag news:mailman.1911.1107546744.22381.python-list at python.org... > Claudio Grondi wrote: > > > I use this one, > > http://heanet.dl.sourceforge.net/sourceforge/uncpythontools/readline-1.7.win > > 32.exe > > which I assume is the right one. > > Try version 1.8, some coloring problems have been recently fixed. If that > doesn't do it, let me know and I'll try to get in touch with the author to see > if he can help. > > Cheers, > > f > From joele at qalabs.com Wed Feb 2 16:53:53 2005 From: joele at qalabs.com (Joel Eusebio) Date: Wed, 2 Feb 2005 13:53:53 -0800 Subject: errors Message-ID: <20050202214730.112D31E4004@bag.python.org> Can someone help me on this, I don' know where the "testmptest" came from but the mptest.py is at the /usr/local/apache2/htdocs/test directory and this error came from apache's error_log PythonHandler mod_python.publisher: ImportError: No module named testmptest Thanks, Joel From exogen at gmail.com Fri Feb 18 20:13:10 2005 From: exogen at gmail.com (Brian Beck) Date: Fri, 18 Feb 2005 20:13:10 -0500 Subject: [perl-python] exercise: partition a list by equivalence In-Reply-To: References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> Message-ID: Brian Beck wrote: > [code] Whoops, that should say: def merge(pairs): pairs = set(tuple(sorted(p)) for p in pairs) merged = [] # Each loop will result in a new, complete sublist in the result. while pairs: p = set(pairs.pop()) remove = set([]) for pair in pairs: pairSet = set(pair) if pairSet & p: p |= pairSet remove.add(pair) pairs -= remove merged.append(list(p)) return merged -- Brian Beck Adventurer of the First Order From snacktime at gmail.com Mon Feb 14 20:40:43 2005 From: snacktime at gmail.com (snacktime) Date: Mon, 14 Feb 2005 17:40:43 -0800 Subject: regular expression question In-Reply-To: <42115020$0$15705$626a14ce@news.free.fr> References: <42115020$0$15705$626a14ce@news.free.fr> Message-ID: <1f060c4c05021417407d04ce89@mail.gmail.com> > You may want something like: > if re.search('%s(.*)%s' % (STX, ETX), data): > Ah I didn't even think about that... Chris From Scott.Daniels at Acm.Org Fri Feb 11 17:24:46 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 11 Feb 2005 14:24:46 -0800 Subject: Iteration over two sequences In-Reply-To: References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> <1105549514.563799.307030@z14g2000cwz.googlegroups.com> <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> <41e58244$1@nntp0.pdx.net> Message-ID: <420d2ce4$1@nntp0.pdx.net> David Isaac wrote: > "Scott David Daniels" wrote in message > news:41e58244$1 at nntp0.pdx.net: > >>Numarray is the future, Numeric is the "past", > > This statement is not obviously true. See the recent discussion on the > developer lists. (Search for Numeric3.) > Alan Isaac I stand corrected. Sorry to have conveyed a mis-impression that I have held for a while. It was my understanding that the Numeric code was so hard to maintain that our fearless leader would never let it in the codebase. Hence, Numarray was born. A quick look through some of the Numeric3 messages leaves me with the impression that Numeric3 will be more of a rebirth than a small change. I have used Numeric for several big projects (that died for commercial, rather than technical, reasons), and have certainly appreciated it. The thrust of my comment holds, however, "learning both is not much harder than learning one." --Scott David Daniels Scott.Daniels at Acm.Org From mahs at telcopartners.com Fri Feb 11 22:58:09 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 11 Feb 2005 19:58:09 -0800 Subject: listerator clonage In-Reply-To: References: Message-ID: Cyril BAZIN wrote: > Hello, > > I want to build a function which return values which appear two or > more times in a list: This is very similar to removing duplicate items from a list which was the subject of a long recent thread, full of suggested approaches. Here's one way to do what you want: >>> l = [1, 7, 3, 4, 3, 2, 1] >>> seen = set() >>> set(x for x in l if x in seen or seen.add(x)) set([1, 3]) >>> This is a 'generator expression' applied as an argument to the set constructor. It relies on the fact that seen.add returns None, and is therefore always false. this is equivalent to: >>> def _generate_duplicates(iterable): ... seen = set() ... for x in iterable: ... if x in seen: # it's a duplicate ... yield x ... else: ... seen.add(x) ... >>> generator = _generate_duplicates(l) >>> generator >>> set(generator) set([1, 3]) >>> # In case you want to preserve the order and number of the duplicates, you >>> # would use a list >>> generator = _generate_duplicates(l) >>> list(generator) [3, 1] >>> > > So, I decided to write a little example which doesn't work: > #l = [1, 7, 3, 4, 3, 2, 1] > #i = iter(l) > #for x in i: > # j = iter(i) > # for y in j: > # if x == y: > # print x > > In thinked that the instruction 'j= iter(i)' create a new iterator 'j' > based on 'i' (some kind of clone). I wrote this little test which show > that 'j = iter(i)' is the same as 'j = i' (that makes me sad): I don't think your algorithm would work even if iter(iterator) did return a copy or separate iterator. If, however, you do have an algorithm that needs that capability, you can use itertools.tee Cheers Michael From thomasbartkus at comcast.net Wed Feb 23 22:50:25 2005 From: thomasbartkus at comcast.net (tom) Date: Wed, 23 Feb 2005 21:50:25 -0600 Subject: rounding problem References: Message-ID: On Wed, 23 Feb 2005 19:04:47 -0600, Andy Leszczynski wrote: > It is on Windows, Linux, Python 2.3: > > [GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2 Type "help", > "copyright", "credits" or "license" for more information. > >>> a=1.1 > >>> a > 1.1000000000000001 > >>> > >>> > >>> > Is it normal? Yes. Quite normal. Floating point numbers are by nature approximations. When you enter your variable "a" at the prompt, you are asking for a very raw (i.e totally unformatted!) dump of what your variable "a" contains. It is the most precise representation of the float 1.1 that your computer can store. It is probably the best precision your hardware math processor subsystem has to offer. And, incidentally, that ain't too shabby since a 1 in the 16th decimal place ain't worth spit! Try putting a print statement in front of your variable. >>> print a >>> 1.1 The print statement ,by itself, adds the most minimial formatting, which amounts to dropping the last significant digit your math processor holds. That last digit will *always* contain some arithmetic slop. If you do any serious work with floats, you will want to learn about significant figures and the use of the very essential round() function in whatever language you are using. If you do, you will find that this situation is really a math thing and has little to do with computers or any particular language. It's the exact same problem one runs into when using a slide rule. If anyone remembers those things :-) Thomas Bartkus From supergood at hotmail.com Tue Feb 15 23:06:29 2005 From: supergood at hotmail.com (supergood at hotmail.com) Date: Wed, 16 Feb 2005 04:06:29 +0000 (UTC) Subject: =?iso-8859-1?q?=BCM!!!_=A6n=B3=A5=2E=2E_=ABl!=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E?= Message-ID: ?n???v?_????? ?C?? $20 ?????H?s?A?? ???? PHP+MySQL, Access+ASP, ASP.NET, CGI, SSI ?q?l?f?r?L?o, ?U???q?l?L?o ?? WebMail ??...... ?????C?e????W1000?Y?e?????w?????????{?? osc. http://shop2.uhostnet.com ?C???u?? $20 ?_ http://www.uhostnet.com http://www.hkxmb.net http://new.hkxmb.net Basic Plan W200: (?C?? $20) -- 200MB ???????? -- ?L???q?l?H?c -- ?L???????????q -- ???? ASP+Access / CGI -- ?q?l?f?r?L?o?t?? -- ?U???q?l?L?o?t?? http://www.uhostnet.com/modules.php?name=service&file=index&func=windetails&plan=A Windows W300: (?C?? $38) -- ?@?~?????s???W -- 300MB ???????? -- ?L???q?l?H?c -- ?L???????????q -- ???? PHP+MySQL, ASP+ACCESS, CGI, SSI -- 1 ?? MySQL ?????w (5MB) -- ?q?l?f?r?L?o?t?? -- ?U???q?l?L?o?t?? http://www.uhostnet.com/modules.php?name=service&file=index&func=windetails&plan=B Windows W500: (?C?? $48) -- ?@?~?????s???W -- ?l???? 3 ?? (?v?g???P????) -- 500MB ???????? -- ?L???q?l?H?c -- ?L???????????q -- ???? PHP+MySQL, ASP+ACCESS, CGI, SSI -- 1 ?? MySQL ?????w (10MB) -- ?q?l?f?r?L?o?t?? -- ?U???q?l?L?o?t?? http://www.uhostnet.com/modules.php?name=service&file=index&func=windetails&plan=C Windows W800: (?C?? $58) -- ?@?~?????s???W -- ?l???? 5 ?? (?v?g???P????) -- 800MB ???????? -- ?L???q?l?H?c -- ?L???????????q -- ???? PHP+MySQL, ASP+ACCESS, CGI, SSI -- 1 ?? MySQL ?????w (20MB) -- ?q?l?f?r?L?o?t?? -- ?U???q?l?L?o?t?? http://www.uhostnet.com/modules.php?name=service&file=index&func=windetails&plan=D Windows W1000: (?C?? $68) -- ?@?~?????s???W -- ?l???? 10 ?? (?v?g???P????) -- 1GB ???????? -- ?L???q?l?H?c -- ?L???????????q -- ???? PHP+MySQL, ASP+ACCESS, CGI, SSI -- 1 ?? MySQL ?????w (50MB) -- ?q?l?f?r?L?o?t?? -- ?U???q?l?L?o?t?? -- ?e?????w???????{????osc???????t?? http://www.uhostnet.com/modules.php?name=service&file=index&func=windetails&plan=E ............................................................................................................................................................................................................................................................................................. From martin at v.loewis.de Sun Feb 13 15:09:25 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Feb 2005 21:09:25 +0100 Subject: sre is broken in SuSE 9.2 In-Reply-To: References: <1108060527.378911.146240@o13g2000cwo.googlegroups.com> <420D4D9A.40201@v.loewis.de> Message-ID: <420FB3F5.2010001@v.loewis.de> Denis S. Otkidach wrote: > You are right. But isalpha behavior looks strange for me anyway: why > cyrillic character '\u0430' is recognized as alpha one for de_DE locale, > but is not for C? In glibc, all "real" locales are based on /usr/share/locale/i18n/locales/i18n, e.g. for de_DE through LC_CTYPE copy "i18n" i18n includes U+0430 as a character, through lower / ... % TABLE 11 CYRILLIC/ ..;..(2)..;/ This makes U+0430 a letter in all locales including i18n (unless locally overridden). This entire approach apparently is based on ISO 14652, which, in section 4.3.3, introduces the "i18n" LC_CTYPE category. Why the C locale does not use i18n, I don't know. Most likely, the intention is that the "C" locale works without any additional data files - you should ask the glibc developers. OTOH, there is a definition file POSIX for what appears to be the POSIX locale. I'd like to point out that this implementation is potentially in violation of ISO 14652; annex A.2.2 says that the notion of a POSIX locale is replaced with the i18n FDCC-set. So accordingly, I would expect that i18n is used in POSIX as well - see for yourself that it isn't in glibc 2.3.2. Again, I suggest to ask the glibc developers as to why this is so. Regards, Martin From dontwant at spam.com Mon Feb 7 23:52:01 2005 From: dontwant at spam.com (Courageous) Date: Mon, 07 Feb 2005 20:52:01 -0800 Subject: Big development in the GUI realm References: <4i3g01tv48qr50g8fjc8nf3n09eaauaen5@4ax.com> Message-ID: <61hg01drjemr0a4jlansfptc2s8ub781tf@4ax.com> >Now, that's not to say that they are correct in their interpretation of >the GPL's terms. In fact, if I had to bet on an outcome, I'd probably >wager that the court would hold that only static linking would force the >program as a whole to follow the GPL terms. I just wrote and deleted a long diatribe. But then I realized you are specifically speaking of the GPL's language. I once wrote RMS specifically on this subject. Back then, he agreed that it was ambiguous. The language of the GPL has changed over the years; and you are right: the court would have to rule about the terms, quite specifically because it would be reasonable to quibble over what rights have or have not been granted. My long diatribe was on copyright law itself. Not pertinent. Motion to strike and all that. :-) C// From steven.bethard at gmail.com Wed Feb 23 02:28:09 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 23 Feb 2005 00:28:09 -0700 Subject: unicode(obj, errors='foo') raises TypeError - bug? In-Reply-To: References: Message-ID: Mike Brown wrote: >>>>class C: > ... def __str__(self): > ... return 'asdf\xff' > ... >>>>o = C() >>>>unicode(o, errors='replace') > Traceback (most recent call last): > File "", line 1, in ? > TypeError: coercing to Unicode: need string or buffer, instance found > [snip] > > What am I doing wrong? Is this a bug in Python? No, this is documented behavior[1]: """ unicode([object[, encoding [, errors]]]) ... For objects which provide a __unicode__() method, it will call this method without arguments to create a Unicode string. For all other objects, the 8-bit string version or representation is requested and then converted to a Unicode string using the codec for the default encoding in 'strict' mode. """ Note that the documentation basically says that it will call str() on your object, and then convert it in 'strict' mode. You should either define __unicode__ or call str() manually on the object. STeVe [1] http://docs.python.org/lib/built-in-funcs.html From http Wed Feb 16 17:32:06 2005 From: http (Paul Rubin) Date: 16 Feb 2005 14:32:06 -0800 Subject: low-end persistence strategies? References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <1108570047.677348.146850@f14g2000cwb.googlegroups.com> <7x7jl8bhii.fsf@ruckus.brouhaha.com> <1108572988.341139.126020@z14g2000cwz.googlegroups.com> Message-ID: <7xd5v02l21.fsf@ruckus.brouhaha.com> "Michele Simionato" writes: > The documentation hides this fact (I missed that) but actually python > 2.3+ ships > with the pybsddb module which has all the functionality you allude too. > Check at the test directory for bsddb. Oh yow, it looks pretty complicated. Do you have any example code around that uses the transaction stuff? If not I can try to figure it out, but it looks like it would take significant effort. From carl.manaster at gmail.com Wed Feb 2 14:52:29 2005 From: carl.manaster at gmail.com (carl.manaster at gmail.com) Date: 2 Feb 2005 11:52:29 -0800 Subject: Integrated Testing - Peppable? Message-ID: <1107373949.960435.212020@z14g2000cwz.googlegroups.com> Hi, Please excuse the intrusion from an admirer, but not a user, of Python. I've got an idea that I think could improve the language and might be relatively simple to implement. I've developed a prototype with a toy language here: , with screenshot here: The idea is that if the language had testing built into it, editors could take advantage of that to highlight, not by syntax, but by correctness (as defined by the tests). As a side effect, coverage coloring is also possible. So far, I see the need for three keywords: "expect", "returns", and "archetype". "expect" and "returns" get used together, as an expression of what the function should return, given certain inputs. "archetype" would define edit-type instantiable objects that could be used in the tests. The biggest lack at present is support for void functions. So... Should I turn this into a PEP? Peace, --Carl From maxm at mxm.dk Wed Feb 2 04:39:41 2005 From: maxm at mxm.dk (Max M) Date: Wed, 02 Feb 2005 10:39:41 +0100 Subject: Printing Filenames with non-Ascii-Characters In-Reply-To: <36bka5F4vp17cU1@individual.net> References: <36a3ikF4uk8r0U1@individual.net> <36bka5F4vp17cU1@individual.net> Message-ID: <42009f9b$0$238$edfadb0f@dread12.news.tele.dk> Marian Aldenh?vel wrote: > > If you're printing to the console, modern Pythons will try to guess the > > console's encoding (e.g. cp850). > > But it seems to have quessed wrong. I don't blame it, I would not know of > any way to reliably figure out this setting. Have you set the coding cookie in your file? Try adding this as the first or second line. # -*- coding: cp850 -*- Python will then know how your file is encoded -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From tchur at optushome.com.au Mon Feb 7 15:57:51 2005 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 08 Feb 2005 07:57:51 +1100 Subject: Big development in the GUI realm In-Reply-To: References: <1107795145.049239.73450@l41g2000cwc.googlegroups.com><5ocf01hmspufk3iusvm35p6hj4mes5heke@4ax.com> Message-ID: <4207D64F.2000709@optushome.com.au> Fredrik Lundh wrote: >Luke Skywalker wrote: > > > >>Considering the fact that the Qt DLL exist by themselves, that the >>version used is the one provided by Qt, and that the EXE uses a >>standard, open way to communicate with it, the above does seem to say >>this use would be valid. >> >> > > http://www.gnu.org/licenses/gpl-faq.html#MereAggregation > > "/.../ If modules are designed to run linked together in a shared address > space, that almost surely means combining them into one program. > > By contrast, pipes, sockets and command-line arguments are > communication mechanisms normally used between two separate > programs. So when they are used for communication, the modules > normally are separate programs. But if the semantics of the > communication are intimate enough, exchanging complex internal > data structures, that too could be a basis to consider the two parts > as combined into a larger program." > > > > Yes, that is what the FSF GPL FAQ says. However, the GPL itself says: "[Section 0] Activities other than copying, distribution and modification are not covered by this License; they are outside its scope." There is not, AFAICS, any formal definition of what is meant by "modification" in the GPL. Section 2.b of the GPL says: "b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License." and Section 2 goes on to say: "These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it." Thus, it seems to me, and to the expert legal advice which we sought (note the scope of the advice was Australian law only) that provided no GLPed source or object code is mixed, included or combined with non-GPLed code, and that the GPLed and non-GPLed code are distributed or otherwise made available in packages which are very clearly separate works, and that any interaction between the two is restricted to runtime, then the GPL does not require that non-GPLed code to be distributed under the GPL. It is arguable whether that opinion is at odds with the sentiments expressed in the FSF GPL FAQ - it depends whether importing two python modules into the same namespace is considered equivalent to, as the FAQ says, "run linked together in a shared address space", but ultimately, it is what the GPL license text says, not what the FSF FAQ says, which matters. Note that I am not in favour of or advocating any attempt to circumvent or undermine the GPL. I just think it is important to be guided by what software licenses actually say, rather than by what the authors of the licenses wished they had said in retrospect. Tim C From http Thu Feb 3 22:00:30 2005 From: http (Paul Rubin) Date: 03 Feb 2005 19:00:30 -0800 Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> Message-ID: <7xy8e5jagh.fsf@ruckus.brouhaha.com> Kartic writes: > And the reason for that I probably because of the way the language is > used (PHP) (this is a shot in the dark as I have not looked into > Mediawiki code), and compounded by probably an unoptimized database. I have the idea that the Wikipedia implementers know what they're doing, but I haven't looked into it super closely. > I don't want to start flame wars here about PHP; I use PHP to build > client sites and like it for the "easy building of dynamic sites" > but the downside is that there is no "memory"...every page is > compiled each time a request is made. I doubt if Wikipedia site uses > an optimizer (like Zend) or caching mechanisms. Optimizers and/or > PHP caches make a huge performance difference. They do use an optimizer similar to Zend. They also use Squid as a static cache. > Also, PHP has put dynamic sites within easy reach of several > programmers who slap together sites in no time. These sites may have > spaghetti code and even the best infrastructure is not enough to > support shabby design (code, db setup and even server tuning). I have > seen people become programmers overnight! There are also LAMP sites > that use Apache 1.3 that is a resource hog; I guess production sites > do not want to upgrade to Apache 2.x/PHP combo! Hmm, I wasn't aware that Apache 2.x gave any significant speedups over 1.3 except under Windows. Am I missing something? > The way to go is to build around application servers, IMHO. I like the > Twisted.web/Nevow methodology, though for simple situations it may be > an overkill. Hmm, I'm not familiar with Nevow. Twisted is pretty neat, though confusing. I don't see how to scale it to multiple servers though. I'm asking this question mainly as it relates to midrange or larger sites, not the very simplest ones (e.g. on my personal site I just use Python cgi's, which are fine for the few dozen or so hits a week that they get). So, the complexity of twisted is acceptable. > From my experience it is an overall tuning thing. Usual culprits are > untuned Linux boxes, unoptimized database design, poorly designed > queries and/or poor application logic...and ah! table-driven > pages. Pages built on tables for the layout kill the browser. CSS is > the way to go. Yes, good point about html tables, though I'm concerned primarily about server response. (It's off-topic, but how do you use CSS to get the effect of tables?) From vincent at visualtrans.de Sun Feb 6 03:30:49 2005 From: vincent at visualtrans.de (vincent wehren) Date: Sun, 06 Feb 2005 09:30:49 +0100 Subject: Word for a non-iterator iterable? In-Reply-To: <36lu1cF516qtdU1@individual.net> References: <36lu1cF516qtdU1@individual.net> Message-ID: Leif K-Brooks wrote: > Is there a word for an iterable object which isn't also an iterator, and > therefor can be iterated over multiple times without being exhausted? > "Sequence" is close, but a non-iterator iterable could technically > provide an __iter__ method without implementing the sequence protocol, > so it's not quite right. How about 'reiterable'? -- Vincent Wehren From tzot at sil-tec.gr Fri Feb 4 19:07:11 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 05 Feb 2005 02:07:11 +0200 Subject: advice needed for simple python web app References: <5cqdnZX-cZ9ca5_fRVn-3Q@rogers.com> <7xr7jxnddh.fsf@ruckus.brouhaha.com> <7xis58c1lw.fsf@ruckus.brouhaha.com> <7x6518bzu8.fsf@ruckus.brouhaha.com> Message-ID: <993801hfj94107ltbc8f09ng29elntgqnl@4ax.com> On 03 Feb 2005 22:31:43 -0800, rumours say that Paul Rubin might have written: [Dan Perl thinks about publishing to the web a script that could be misused by spammers, so Paul advises him to watch out.] >There used >to be some similar perl scripts running all over the place until that >happened. Those were pure perl scripts. This will be a Perl python script, so no problem. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From martin at v.loewis.de Tue Feb 8 15:40:21 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 Feb 2005 21:40:21 +0100 Subject: msvcp71.dll and Python 2.4 C++ extensions In-Reply-To: <6snvv0pj0bdjhvvsvqkmj52hmmbi6kap0p@4ax.com> References: <41FEBBD6.4010402@v.loewis.de> <6snvv0pj0bdjhvvsvqkmj52hmmbi6kap0p@4ax.com> Message-ID: <4209239f$0$30254$9b622d9e@news.freenet.de> Matthias Baas wrote: > I'm creating the installer via the distutils by calling "setup.py > bdist_wininst". How can I configure distutils to have it create an > installer that does the above things? Ah, I see. Unfortunately, bdist_wininst is not capable of doing a Windows logo compliant installation (with proper versioning checks, shared dll reference count, etc) of a DLL. You will have to find a different technology to distribute your application - or make sure you copy the DLL in a place where it previously did not exist. > How should an installer check if a DLL is already present? It should check if the file exists. If it exists, it should check the version number of the file (there are APIs for that available), and if the language of the installed DLL differs from the language of the package's DLL. If the new DLL is somehow "better" (newer version, or same version, different language, and user requested overwriting), it should replace the DLL. > Are DLLs registered with Windows so I can query a database? To some degree. If the software is uninstalled, the installer should remove the file. If the file was already present at installation time, removal may break other software. Therefor, there is a registry entry for each path name that is a reference count, under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SharedDLLs If you expect that the file is already there, you need to use that mechanism. > Or should the > installer search for the DLL in the directories specified in the PATH > variable and see if the DLL is there? No. There is no problem at all to install the same DLL multiple times, in different places. In fact, Microsoft discourages shared DLLs, and recommends that each package should install its own copy. Windows will look for a DLL in - the directory of the EXE - the current working directory - system32 - windows - PATH In your case, putting the C++ DLL into the directory containing python.exe might be sufficient. The safest thing, of course, is to put the DLL into system32 - in which case you *have* to install it shared. > "An application should use and redistribute msvcr71.dll, and it should > avoid placing a copy or using an existing copy of msvcr71.dll in the > system directory. Instead, the application should keep a copy of > msvcr71.dll in its application directory with the program executable." Yes. This means to install it into the directory containing python.exe. Unfortunately, this does not work if your extension is then used in an embedded Python, e.g. one running as a COM object. In this case, python.exe will not be the main executable, but, say, outlook.exe will be. So Microsoft's recommendation to install the DLL into the EXE directory is flawed for COM and other embedded cases. This is precisely the reason why the Python installer installs both python24.dll and msvcr71.dll into system32. > Well, yes, I know. But I don't see Python as a standalone application. > One of the great things about Python is that there are so many > extension modules for every kinds of purposes. So, making available > the C++ runtime would just pave the way for more of those extension > modules by making it easier to distribute binary packages that are > implemented in C++. I think we agree that building and running such an extension is not a problem - it just works. Distributing such an extension is indeed a problem, as bdist_wininst does not support this case properly. I'll plan to write a bdist_msi one day, which should handle DLL installation better as much of the magic required is built into Windows Installer. > I was referring to the possibility that the DLL might get installed > several times at several different locations which would be a waste of > disk space. If there's only one file, then I agree with the above > (however, what happens if I uninstall one package and this package > removes the DLL even when there are other packages installed that > still require the DLL?). The other packages will also have added to the shared reference counter. Uninstalling will only DECREF the counter, and the file will be removed only when the counter goes to zero. > For one smaller package I was compiling I solved the problem by > linking against the static versions of the C/C++ runtime. This will > also satisfy the "It-Should-Just-Work" constraint... :) (however, > there still could be situations where this is not possible (the > sources might not be available, for example)). You should make sure to use the DLL version of the C runtime. Otherwise, you will be mixing multiple C runtimes (one that python24.dll links with, and one linked statically into your extension); this might cause troubles (such as memory leaks and crashes). Regards, Martin From martin at v.loewis.de Sun Feb 27 18:26:13 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 28 Feb 2005 00:26:13 +0100 Subject: os.stat('')[stat.ST_INO] on Windows In-Reply-To: References: <422238b3$1@news.vo.lu> Message-ID: <42225715$0$5004$9b622d9e@news.freenet.de> jepler at unpythonic.net wrote: > Refer to the operating system documentation (msdn.microsoft.com?). os.stat is > mostly a wrapper around whatever the OS provides. A quick glance at Python > source code shows that maybe _stati64() or _wistat64() is the actual function > used on windows. That doesn't really help: MSDN says """Number of the information node (the inode) for the file (UNIX-specific). On UNIX file systems, the inode describes the file date and time stamps, permissions, and content. When files are hard-linked to one another, they share the same inode. The inode, and therefore st_ino, has no meaning in the FAT, HPFS, or NTFS file systems. """ So we know it has no meaning, but they won't tell us what its value is. Fortunately, MS ships the source of the CRT in VC, so we know st_ino is always 0 (as are st_uid and st_gid). Regards, Martin From xah at xahlee.org Tue Feb 15 01:52:28 2005 From: xah at xahlee.org (Xah Lee) Date: 14 Feb 2005 22:52:28 -0800 Subject: [perl-python] problem: reducing comparison Message-ID: <1108450348.253772.158120@z14g2000cwz.googlegroups.com> here's a interesting real-world algoritm to have fun with. attached below is the Perl documentation that i wrote for a function called "reduce", which is really the heart of a larger software. The implementation is really simple, but the key is to understand what the function should be. I'll post Perl and Python codes tomorrow for those interested. If you are a perl programer, try to code it in Python. (it's easy.) This is brought to you by the Perl-Python a-day community. To subscribe, see http://xahlee.org/perl-python/python.html Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html ------------------------------- =pod e.g. reduce( $pairings, $a_pair) retured the first argument with some pairs deleted. Detail: we have n things, represented by numbers 1 to n. Some of these are identical. We want to partition the range of numbers 1 to n so that identical ones are grouped together. To begin comparison, we generate a list of pairings that's all possible parings of numbers 1 to n. (of course order does not matter, and the pairing does not contain repeations) This is the first argument to reduce. We'll go thru this pairings list one by one and do comparisons, remove the pair once it has been compared. However, more pairs can be removed if a we find a pair identical. For example, suppose we know that 2 and 4 are identical, and if the pairing list contains (2,3) and (4,3), one of them can be deleted because now 2 and 4 are the same thing. (We do this because we expect the comparison operation will be expensive.) reduce( $pairings, $a_pair) returns a reduced $pairings knowing that $a_pair are identical. The first argument $pairings must be in the form of a hash. e.g. {'1,5' => [1,5],'3,5' => [3,5],'2,4' => [2,4],'4,5' => [4,5],'1,3' => [1,3],'2,5' => [2,5],'1,2' => [1,2],'3,4' => [3,4],'2,3' => [2,3],'1,4' => [1,4]} (Note that keys are strings of the pairs separated by a comma.) $a_pair is a reference to a list of the form [$a,$b]. (different pairs may be deleted if the hash's pairs are given in different order. i.e. 3,4 instead of 4,3) The return value is a reference to a hash. The program is deterministic but exactly which pairs are deleted is unspecified. If the input is all possible pairs of 2 things out of n, maximum reduction is guaranteed. =cut From tom.willis at gmail.com Sat Feb 12 15:34:09 2005 From: tom.willis at gmail.com (Tom Willis) Date: Sat, 12 Feb 2005 15:34:09 -0500 Subject: Python UPS / FedEx Shipping Module In-Reply-To: References: Message-ID: Are the modules just accessing the published apis for their webservices? I'm just wondering because I used to work for a logistics mgmt company that paid money to be a strategic partner with FedEx/UPS/Airborn etc so that they could information on how to return rates/print labels/generate edi's/calculate arrival times etc. I'd get a good laugh out of it suddenly being freely available now. On Fri, 11 Feb 2005 19:00:25 -0800 (PST), Kartic wrote: > Gabriel Cooper said the following on 2/11/2005 2:23 PM: > > I've made UPS and FedEx shipping rate request modules in python using > > XML. Is there an interest in putting this on the web? > > I am interested in it for educational value, if not anything else. > Please post the web address from which to download. > > Thanks! > -Kartic > -- > http://mail.python.org/mailman/listinfo/python-list > -- Thomas G. Willis http://paperbackmusic.net From aleaxit at yahoo.com Sun Feb 6 18:06:07 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 7 Feb 2005 00:06:07 +0100 Subject: empty classes as c structs? References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> Message-ID: <1grl6r9.14ogjvkzi3r3iN%aleaxit@yahoo.com> Brian van den Broek wrote: ... > (I'm just a hobbyist, so if this suggestion clashes with some well > established use of 'Bag' in CS terminology, well, never mind.) Yep: a Bag is a more common and neater name for a "multiset" -- a set-like container which holds each item ``a certain number of times'' (you can alternatively see it as a mapping from items to counts of number of times the item is held). Alex From CathleenB at concord.etransmail4.com Wed Feb 23 07:49:51 2005 From: CathleenB at concord.etransmail4.com (Cathleen Baer) Date: Wed, 23 Feb 2005 04:49:51 -0800 Subject: How new Check 21 legislation is affecting you... Message-ID: <21594389.1109162991128.JavaMail.customerService@etransmail4.com> Good Afternoon! Recenty intrdocuced legislation requires business and home users to print personal and business checks with security blank check stock and magnetic ink. Please find qualified suppliers at Google by clicking on the followingl link. http://www.google.com/search?sourceid=navclient&ie=UTF-8&rls=GGLC,GGLC:1969-53,GGLC:en&q=blank+check+paper%2C+magnetic+ink+for+inkjets Thank you very much. Cathleen Baer Marketing & Relationship Representative Globalzon Consulting Group From no at spam.invalid Thu Feb 3 15:25:48 2005 From: no at spam.invalid (Russell E. Owen) Date: Thu, 03 Feb 2005 12:25:48 -0800 Subject: continuous plotting with Tkinter References: <42010f48$0$3408$5402220f@news.sunrise.ch> Message-ID: In article <42010f48$0$3408$5402220f at news.sunrise.ch>, "Martin Blume" wrote: >I have a number-crunching application that spits out >a lot of numbers. Now I'd like to pipe this into a python >app and plot them using Tkinter, such as: >$ number_cruncher | myplot.py >But with Tkinter once I call Tkinter's mainloop() I >give up my control of the app and I can't continue to >read in data from stdin. Or can I? If so, how? One way is to use a thread to read the numbers, then make them available to the main thread via a Queue object, which you poll for new values. Another option is to use a Tk-compatible file or socket of some kind which triggers a callback when data comes in. See some ideas on this. -- Russell From davidf at sjsoft.com Mon Feb 14 05:02:50 2005 From: davidf at sjsoft.com (David Fraser) Date: Mon, 14 Feb 2005 12:02:50 +0200 Subject: Commerical graphing packages? In-Reply-To: <420d1595$1@nntp.zianet.com> References: <420d1595$1@nntp.zianet.com> Message-ID: Erik Johnson wrote: > I am wanting to generate dynamic graphs for our website and would rather > not invest the time in developing the code to draw these starting from > graphics primitives. I am looking for something that is... "fairly robust" > but our needs are relatively modest: X-Y scatter plots w/ data point > symbols, multiple data set X-Y line plots, bar charts, etc. > > Preferably this would come from a company that can provide support & > decent documentation, and a package that can be installed without a bunch of > extra hassle (e.g., needs Numeric Python, needs to have the GD library > installed, needs separate JPEG encoders, font libraries, etc.) > > I am aware of ChartDirector (http://www.advsofteng.com/ ) which > explicitly supports python and seems to be about the right level of > sophistication. I don't really know of any other packages in this space, do > you? I am seeking feedback and reccomendations from people who have used > this package or similar ones. I am particularly interested to hear about any > limitations or problems you ran into with whatever package you are using. > > Thanks for taking the time to read my post! :) It's worth checking out matplotlib as well although it may not meet all your criteria ... but have a look, its a great package From Serge.Orlov at gmail.com Fri Feb 25 18:52:20 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 25 Feb 2005 15:52:20 -0800 Subject: variable declaration References: Message-ID: <1109375540.355916.163590@g14g2000cwa.googlegroups.com> Alexander Zatvornitskiy wrote: > Hello All! > > I'am novice in python, and I find one very bad thing (from my point > of view) in language. There is no keyword or syntax to declare > variable, like 'var' in > Pascal, or special syntax in C. It can > cause very ugly errors,like this: > > epsilon=0 > S=0 > while epsilon<10: > S=S+epsilon > epselon=epsilon+1 > print S > > It will print zero, and it is not easy to find such a bug! I'm late to the party, but I found an interesting text by the Guinness book record-holder in typing. He claims that the python way of dealing with typos is right. He doesn't write about python directly but the main idea is to punish heavily for every typo. He also has "nice" words for software industry and the backspace key. Read it here: http://www.supremelearning.com/bookexcerpts.html By the way if my reading of poor quality scan of his record certificate http://www.supremelearning.com/image_certificate.html is correct, his typing speed was 614 characters/minute. Impressive! There is also his book in Russian language: http://www.supremelearning.com/russianslbookpart1.html As for me, typos have never been a big problem. They happen rarely. As the Guinness book record-holder suggests: don't make typos! Serge. From nicodemus at esss.com.br Fri Feb 11 07:15:42 2005 From: nicodemus at esss.com.br (Nicodemus) Date: Fri, 11 Feb 2005 09:15:42 -0300 Subject: Multi-Platform installer generator Message-ID: <420CA1EE.6000905@esss.com.br> Hello list, On windows my company uses Inno Setup to generate installers for our products, and on Linux we usually use a simple shell script, but we would like to use the same installer generator for both platforms. Searching google turned up some multi-platform installers (mostly in Java), but I gather that they require a Java VM installed in the target system, and that is undesirable for us, since most system don't come with a Java VM ready (or am I completely wrong in this aspect?). So does anyone know if a multi-platform installer generator, that generates installers with GUI and has no requirements on the target system, exists? Best Regards, Nicodemus. From francis.girard at free.fr Sun Feb 13 14:22:14 2005 From: francis.girard at free.fr (Francis Girard) Date: Sun, 13 Feb 2005 20:22:14 +0100 Subject: A great Alan Kay quote In-Reply-To: References: <420a5c1e$0$21630$a1866201@visi.com> Message-ID: <200502132022.14877.francis.girard@free.fr> Le dimanche 13 F?vrier 2005 19:05, Arthur a ?crit?: > On Sun, 13 Feb 2005 18:48:03 +0100, Francis Girard > > > >My deepest apologies, > > > >Francis Girard > > Sorry if I helped get you into this, Francis. > No, no, don't worry. I really expressed my own opinions and feelings. At the same time, I certainly understand that these opinions might had upset some of the readers. I am sorry for this as I don't think this is the right discussion group for such opinions. Therefore it is useless to hurt people with something that is not a positive contribution. That's all. I will try to refrain in the future. I am just not used to talk to so many people at the same time. Regards, Francis Girard From alex at fortworks.com Thu Feb 17 20:36:12 2005 From: alex at fortworks.com (imphasing) Date: 17 Feb 2005 17:36:12 -0800 Subject: Using open() inside a subroutine Message-ID: <1108690572.599238.61820@c13g2000cwb.googlegroups.com> Whenever I try to open a file inside a subroutine, like so: def open(): filePath=askopenfilename() fileOpen = open(filePath, "r") fileContent = fileOpen.read() fileOpen.close() it tells me that "open() takes no arguments (2 given)" Why is that? and how can I get around that so I can open a file in a subroutine? Thanks, Alex From mfranklin1 at gatwick.westerngeco.slb.com Wed Feb 9 02:20:28 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 09 Feb 2005 07:20:28 +0000 Subject: python connect to server using SSH protocol In-Reply-To: <4208bdfa$1@sia.uibk.ac.at> References: <1107850655.289129.94880@o13g2000cwo.googlegroups.com> <4208bdfa$1@sia.uibk.ac.at> Message-ID: Simon Anders wrote: > Hi > > Laszlo Zsolt Nagy wrote: > >> ajikoe at gmail.com wrote: >> >>> How can python connect to server which use SSH protocol? > > There should be a better way. > > Simon There is : pexpect! http://pexpect.sourceforge.net/ From fperez.net at gmail.com Wed Feb 16 13:20:32 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 16 Feb 2005 11:20:32 -0700 Subject: [ANN] IPython 0.6.11 is out. References: Message-ID: Ville Vainio wrote: > Warning - if you are upgrading and have an old pysh.py dangling around > in $HOME/.ipython, be sure to delete it. The old version is > incompatible with the new ipython. Just to clarify: you need to delete ONLY the old pysh.py, not your entire $HOME/.ipython/ directory. You can then update from the pysh.py which comes with the ipython distribution, typically in sys.prefix/site-packages/IPython/UserConfig Sorry about not putting this in the release notes, I didn't notice it myself. Regards, f From grante at visi.com Wed Feb 9 13:53:18 2005 From: grante at visi.com (Grant Edwards) Date: 09 Feb 2005 18:53:18 GMT Subject: A great Alan Kay quote Message-ID: <420a5c1e$0$21630$a1866201@visi.com> In an interview at http://acmqueue.com/modules.php?name=Content&pa=showpage&pid=273 Alan Kay said something I really liked, and I think it applies equally well to Python as well as the languages mentioned: I characterized one way of looking at languages in this way: a lot of them are either the agglutination of features or they're a crystallization of style. Languages such as APL, Lisp, and Smalltalk are what you might call style languages, where there's a real center and imputed style to how you're supposed to do everything. I think that "a crystallization of style" sums things up nicely. The rest of the interview is pretty interesting as well. -- Grant Edwards grante Yow! Look!! Karl Malden! at visi.com From francis.girard at free.fr Wed Feb 2 04:53:55 2005 From: francis.girard at free.fr (Francis Girard) Date: Wed, 2 Feb 2005 10:53:55 +0100 Subject: Next step after pychecker In-Reply-To: <42009d13$0$24304$636a15ce@news.free.fr> References: <41ff0308$0$6503$636a15ce@news.free.fr> <42009d13$0$24304$636a15ce@news.free.fr> Message-ID: <200502021053.55502.francis.girard@free.fr> To complete Philippe's answer : As Bird and Wadler continue : "The major consequence of the discipline imposed by strong-typing is that any expression which cannot be assigned a "sensible" type is regarded as not being well-formed and is rejected by the computer before evaluation. Such expression have _no_ value: they are simply regarded as illegal." But Skip, I am sure that you can easily find an example by yourself. For example, replace "+" by a function that does different things depending on its argument type. Francis Girard Le mercredi 2 F?vrier 2005 10:27, Philippe Fremy a ?crit?: > Skip Montanaro wrote: > > Francis> "Every well-formed expression of the language can be > > assigned a Francis> type that can be deduced from the constituents of the > > Francis> expression alone." Bird and Wadler, Introduction to Functional > > Francis> Programming, 1988 > > > > Francis> This is certainly not the case for Python since one and the > > Francis> same variable can have different types depending upon the > > Francis> execution context. Example : > > > > Francis> 1- if a is None: > > Francis> 2- b = 1 > > Francis> 3- else: > > Francis> 4- b = "Phew" > > Francis> 5- b = b + 1 > > > > Francis> One cannot statically determine the type of b by examining > > the Francis> line 5- alone. > > > > Do you have an example using a correct code fragment? It makes no sense > > to infer types in code that would clearly raise runtime errors: > > On the contrary, the point of type inference is to detect such errors. > If the program was always well-formed, there would be no point in > developing a type inference tool. > > Philippe From http Sun Feb 13 19:54:43 2005 From: http (Paul Rubin) Date: 13 Feb 2005 16:54:43 -0800 Subject: Pythonic poker client References: <1108334914.029293.14830@o13g2000cwo.googlegroups.com> Message-ID: <7xpsz46jvw.fsf@ruckus.brouhaha.com> hardieca at hotmail.com writes: > I'm assuming that I need to figure out the port it uses, find the > server, analyze the packets for commands, and then build an app that > masquerades as the real client. > > Anyone have any experience with this? If you mean you want to write your own real-money poker client (e.g. PartyPoker), I wouldn't advise it unless you really know what you're doing, since those sites go nuts detecting bots and banning their users. The bot authors in turn use fancier and fancier methods to escape detection, etc. I don't play online poker or use these products myself, but as a security geek I have some technical interest in this. (Also some friends of mine play online poker all the time, so I hear about it). Take a look at http://www.winholdem.net for one of the bots currently involved in such an arms race. The winholdem folks also run their own online poker room where bots of all persuasions are welcome, but nobody is supposed to play for real money there. That might be a good place to develop and test your client. I see now that Winholdem now has a "Team edition" which sounds like it's now supporting outright collusion between (perhaps virtual) players, rather than just being a bot attempting to play well. I suppose this is inevitable since that kind of thing has been happening between live players for years. It's currently still possible for good players to win money steadily at these sites (since there are so many weak players) but I wonder how long that situation will last. From ncoghlan at iinet.net.au Thu Feb 24 05:11:18 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 24 Feb 2005 20:11:18 +1000 Subject: Dynamically pass a function arguments from a dict In-Reply-To: References: <421D29E7.5010609@mceahern.com> Message-ID: <421DA846.4050903@iinet.net.au> Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. Running startup script Py> import inspect Py> help(inspect.getargspec) Help on function getargspec in module inspect: getargspec(func) Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. Don't-forget-the-std-lib'ly, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From snail at objmedia.demon.co.uk Thu Feb 17 15:32:46 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Thu, 17 Feb 2005 20:32:46 +0000 Subject: [EVALUATION] - E02 - ULTIMATE RECIPE TO RESOLVE ALL ISSUES References: Message-ID: <$R+Q5Dau9PFCFwND@objmedia.demon.co.uk> In message , Jeremy Bowers writes >course he'd still have to read docs and learn how to use it. Yeah - one guy in c.l.ruby wrote a reply that must have taken minimum 30 minutes. Really detailed. Lots of people thanked him for it. Ilias dissed the whole post with "I have not read it, it is not on topic". >Moderately on topic (not Python, but programming at least): The other day >I was talking to someone and I commented on how odd it is to write a >library, and *still* have to learn how to use it correctly. As the >author, at least I can change it as I learn more, but even so, I have to >learn how to use it; even as the author I am not imbued magically with >expert status. Indeed. I often find myself going back to a library I wrote some time ago which I haven't had to interact with and then looking for the existing code that interacts with the library to see how best to use it. I think its a bit like going back to a book after a few years. Its worth returning because you will have forgotten some of what was so good first time around. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From lbates at syscononline.com Mon Feb 28 15:07:26 2005 From: lbates at syscononline.com (Larry Bates) Date: Mon, 28 Feb 2005 14:07:26 -0600 Subject: Controlling Pc From Server? In-Reply-To: References: Message-ID: What you are asking IS much more difficult that just "timing". The Internet is a disconnected stateless medium. I can open a browser to a site and just leave my browser open. Am I viewing that site or not? There's no way to know. I might have minimized the browser window and am back doing productive work (assuming my access to the web was non-productive). The best way I've found to do what you want is to force all HTTP traffic through a proxy (I like Squid, but others work as well). The proxy cache logs can provide you with lost of information about where people are going and how much information they download from the site. They cannot however tell you how long someone was there because of what I mentioned above. You can see if someone is going to www.nascar.com or www.espn.com or to some other site. You can also block sites quite easily if there is no legitimate reason for people to be at that site. Hope info helps. Larry Bates andrea_gavana at tin.it wrote: > Hello Kartic & NG, > > Thank you for your prompt answer. In effect, I'm trying to work on > a NT network of 6 PC (plus the server). Sorry to not have been clearer. > Ideally, I'm trying to monitor the Internet activity of each client (PC) > on this network (but I'm not a boss trying to control my emplyees, I'm just > curious on it). I would like to know which PC is connected to Internet (by > starting something like a "timer" for every PC, and then periodically check > if a particular PC is connected or not). This should be done from the main > server. > Did I make myself clear? Do you think it would be a huge task? > > Sorry, it may be a very basic question, but thank you for your help. > > Andrea. > > From cam.ac.uk at mh391.invalid Thu Feb 17 18:44:51 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 17 Feb 2005 23:44:51 +0000 Subject: global var In-Reply-To: <42152b84$0$15817$636a15ce@news.free.fr> References: <42152b84$0$15817$636a15ce@news.free.fr> Message-ID: raver2046 wrote: > How to have a global var in python ? "global var" will give you a global variable named "var". -- Michael Hoffman From wuwei23 at gmail.com Tue Feb 1 20:06:05 2005 From: wuwei23 at gmail.com (alex23) Date: 1 Feb 2005 17:06:05 -0800 Subject: The next Xah-lee post contest In-Reply-To: <1107277633.959477.302860@f14g2000cwb.googlegroups.com> References: <20050130114008.797088857.whereU@now.com> <1107137465.973491.42050@f14g2000cwb.googlegroups.com> <1107277633.959477.302860@f14g2000cwb.googlegroups.com> Message-ID: <1107306365.509084.47890@z14g2000cwz.googlegroups.com> Luis M. Gonzalez wrote: > I kind of like this guy... it's like he has a few bugs in his brain, > but other parts are surprisingly interesting. Which bits especially impress you, the rampant misogyny or the unwarranted intellectual arrogance? From http Wed Feb 16 23:39:33 2005 From: http (Paul Rubin) Date: 16 Feb 2005 20:39:33 -0800 Subject: low-end persistence strategies? References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <1108570047.677348.146850@f14g2000cwb.googlegroups.com> <7x7jl8bhii.fsf@ruckus.brouhaha.com> <1108572988.341139.126020@z14g2000cwz.googlegroups.com> <7xd5v02l21.fsf@ruckus.brouhaha.com> <1108614762.026703.323850@l41g2000cwc.googlegroups.com> Message-ID: <7xmzu3re9m.fsf@ruckus.brouhaha.com> "Michele Simionato" writes: > This was my impression too :-( The ZODB is way much easier to use so > at the end I used just that. Apparently the bsddb stuff is more > complicated than needed and the documentation sucks. However, > it does satisfy your requirements of being already installed, so I > mentioned it. I am looking too for an easy tutorial on how to do > concurrency/transactions with it. The sleepycat docs seemed fine back when I looked at them years ago. I'm just not sure what the Python wrapper is supposed to do in terms of API. From jcribbs at twmi.rr.com Wed Feb 16 22:47:13 2005 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Thu, 17 Feb 2005 03:47:13 GMT Subject: low-end persistence strategies? In-Reply-To: <7x7jl7g9sa.fsf@ruckus.brouhaha.com> References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <7xbrakjeu1.fsf@ruckus.brouhaha.com> <9sTQd.33120$XY5.31311@fe2.columbus.rr.com> <7x7jl7g9sa.fsf@ruckus.brouhaha.com> Message-ID: <5tUQd.3162$LD5.1258@fe2.columbus.rr.com> Paul Rubin wrote: > Jamey Cribbs writes: > >>Either of these server scripts would have to be running as a process >>either on your web server or on another server on your network in >>order for them to work. I don't know if that would be an issue for you. > > > Yes, that's the whole point. I don't want to run a server process 24/7 > just to look up two or three numbers a few times a day. Ok, I see your point now. Well, this is off the top of my head, I haven't tried it, but I think you could just use KirbyBase embedded in your cgi script and it should work fine. I'm kind of thinking out loud about this, but, let's see, if you had two user's simultaneously accessing your web site at the same time, that would be two instances of your cgi script. If they are just looking up data, that would be two reads that KirbyBase would be doing against the same physical file. It just opens files in read mode for that so that should work even concurrently. The only time there might be trouble is if two clients try to write to the same table (physical file) at the same time. When it writes to a file, KirbyBase opens it in append mode (r+, I think). My guess would be, whichever client got there first would open the file. The second client, arriving a split second later, would attempt to open the file in append mode also and KirbyBase would return an exception. If your cgi script caught and handled the exception, you would be fine. Again this is off the top of my head after a long day, so I can't be held responsible for my ramblings. :) Jamey From luismgz at gmail.com Tue Feb 1 12:07:13 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 1 Feb 2005 09:07:13 -0800 Subject: The next Xah-lee post contest In-Reply-To: References: <20050130114008.797088857.whereU@now.com> <1107137465.973491.42050@f14g2000cwb.googlegroups.com> Message-ID: <1107277633.959477.302860@f14g2000cwb.googlegroups.com> Peter Hansen wrote: > Arthur wrote: > > Steve Holden wrote: > >>Would there, I wonder, be any enthusiasm for a "Best Xah Lee impression" > >>prize at PyCon? > > > > And the rules of the game, if he shows? > > Arthur, if Xah Lee shows up at Pycon, he most definitely will > not be giving the best impression... > > -Peter Have you visited his website? I kind of like this guy... it's like he has a few bugs in his brain, but other parts are surprisingly interesting. From zerdna1 at yahoo.com Wed Feb 9 15:15:14 2005 From: zerdna1 at yahoo.com (Andre) Date: Wed, 9 Feb 2005 15:15:14 -0500 Subject: Help: retrieving e-mail from yahoo pop server. what's wrong? Message-ID: Hi guys, newbie question. I am having trouble with a script that is supposed to login me to my account on yahoo pop server. When i do this: import getpass, poplib, re POPHOST = "pop.mail.yahoo.com" POPUSER = "mylogin" POPPASS = "mypass" pop = poplib.POP3(POPHOST) pop.user(POPUSER) up to this point evertything proceeds fine, but when i do if not POPPASS: POPPASS = getpass.getpass("Password for %s@%s:" % (POPUSER, POPHOST)) pop.pass_(POPPASS) I am being asked for password and after giving it getting the following error: POP3 Protocol Error: -ERR Error logging in. Please visit http://mail.yahoo.com Would appreciate any help or comments -- its my first day with Python :). What am i doing wrong? From just at xs4all.nl Thu Feb 3 06:42:26 2005 From: just at xs4all.nl (Just) Date: Thu, 03 Feb 2005 12:42:26 +0100 Subject: Reinstall python 2.3 on OSX 10.3.5? References: Message-ID: In article , Robert Kern wrote: > Christian Dieterich wrote: > > On D? C?adaoin, Feabh 2, 2005, at 17:48 America/Chicago, > > moa at extrapolation.com wrote: > > > >> Hi there > >> > >> I started a very long and roundabout process of attempting to install > >> python 2.3.4 along side my apple-installed 2.3 system. To make a long > >> story short, I have completely confabulated my environment ( i deleted > >> the 2.3 binaries and so forth from the system in an attempt to start > >> things fresh), and now I cannot figure out how to reinstall the base > >> 2.3 Apple python distribution. > >> Can somebody please point me in the right direction? > > > > > > You could use > > fink install python > > which makes you a Python installation under /sw. > > But that doesn't solve his problem, which is to restore the > Apple-supplied Python that he deleted. Also: fink is evil. I wouldn't touch it with a ten-foot pole. Just From jello at comics.com Fri Feb 11 09:03:45 2005 From: jello at comics.com (rzed) Date: Fri, 11 Feb 2005 14:03:45 GMT Subject: Python versus Perl ? References: <1107695949.247611.272800@g14g2000cwa.googlegroups.com> <1107726328.158314.265680@o13g2000cwo.googlegroups.com> <1grl63x.1f2tzwz1q984vpN%aleaxit@yahoo.com> <1108127778.811259.152240@g14g2000cwa.googlegroups.com> Message-ID: "Mauro Cicognini" wrote in news:1108127778.811259.152240 at g14g2000cwa.googlegroups.com: > > Alex Martelli wrote: > >> URK -- _my_ feeling is that we have entirely *too many* options >> for stuff like web application frameworks, GUI toolkits, XML >> processing, > ... >> >> >> Alex > > I entirely second that. > > More, I'd heartily welcome an authoritative word on which to > focus on for each category... I hate to see scarce resources > wasted. > Alex also suggested that a revival of the anygui interface would be a Good Thing. I would certainly love to see that. It seems to me that Python should in fact include either anygui or an equivalent to it as part of its core. Then to interface with a given GUI package, it would be necessary to create a wrapper that maps the wrapper's API to that standard Pythonic API. More work for the package maintainers, and not easy to do in some cases, but for the Python community it would be a huge gain. The same argument could be made for the anydbm interface. In both cases, the interface should not hinder the ability of a developer to access any part of the package API, which implies that parameters must be flexible. Maybe this is a strong use case for bunch/data/namespace arguments and return values. -- rzed From jlargentaye at gmail.com Tue Feb 8 09:28:30 2005 From: jlargentaye at gmail.com (Jean de Largentaye) Date: 8 Feb 2005 06:28:30 -0800 Subject: Choosing the right parser for parsing C headers In-Reply-To: References: <1107861023.254610.14310@g14g2000cwa.googlegroups.com> <1107865641.937691.282930@g14g2000cwa.googlegroups.com> Message-ID: <1107872910.313675.290170@c13g2000cwb.googlegroups.com> That looks cool Roman, however, I'm behind a Corporate Firewall, is there any chance you could send me a cvs snapshot? John From grante at visi.com Wed Feb 2 21:04:14 2005 From: grante at visi.com (Grant Edwards) Date: 03 Feb 2005 02:04:14 GMT Subject: how about writing some gui to a known console application References: <1107294520.224155.131640@f14g2000cwb.googlegroups.com> <41fffb59$0$21637$a1866201@visi.com> <1107300676.282484.10840@o13g2000cwo.googlegroups.com> Message-ID: <4201869e$0$21643$a1866201@visi.com> On 2005-02-01, alexrait1 wrote: > I tried to delete this message, but I guess it was too late... or it > didn't work for me... sorry anyway. No worries. Since the article didn't have a refereces or in-reply-to header, it showed up as the first post in it's own thread. I later saw the post to which you intended to reply. -- Grant Edwards grante Yow! The entire CHINESE at WOMEN'S VOLLEYBALL TEAM all visi.com share ONE personality -- and have since BIRTH!! From gsakkis at rutgers.edu Fri Feb 11 15:07:42 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Fri, 11 Feb 2005 15:07:42 -0500 Subject: check if object is number References: Message-ID: <374ho0F560ughU1@individual.net> "Steven Bethard" wrote in message news:gcidnb9g_ojxnpDfRVn-tA at comcast.com... > Is there a good way to determine if an object is a numeric type? > Generally, I avoid type-checks in favor of try/except blocks, but I'm > not sure what to do in this case: > > def f(i): > ... > if x < i: > ... > > The problem is, no error will be thrown if 'i' is, say, a string: > > py> 1 < 'a' > True > py> 10000000000 < 'a' > True > > But for my code, passing a string is bad, so I'd like to provide an > appropriate error. > > I thought about calling int() on the value, but this will also allow > some strings (e.g. '1'). I guess this isn't horrible, but it seems > somewhat suboptimal... > > Ideas? > > Steve The thing is that python avoids giving a strict definition of what is a 'numeric type', i.e. a well-defined interface (the same holds for other frequently used interfaces such as 'sequence', 'mapping', 'file-like', etc). It's up to you (the user) to think of all the operations you anticipate to be supported by each argument, attribute, etc. and define a 'numeric type checker' (or even better, adaptor) that suits *your application*. In your example, what does your application consider to be numeric ? Strings are definitely not, integers and floats typically are; on the other hand, complex numbers are usually not expected, even though mathematically they are 'numeric'. In this case, you can write something like: def isNumeric(obj): # consider only ints and floats numeric return isinstance(obj,int) or isinstance(obj,float) The bottom line is that python wisely doesn't enforce any universal numeric type ("in the face of ambiguity, refuse the temptation to guess"). George From jdhunter at ace.bsd.uchicago.edu Sat Feb 5 07:07:27 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sat, 05 Feb 2005 06:07:27 -0600 Subject: Medical GUI Application With Python In-Reply-To: <42047930.1030604@ankabt.com> (Evrim Ozcelik's message of "Sat, 05 Feb 2005 09:43:44 +0200") References: <42047930.1030604@ankabt.com> Message-ID: >>>>> "Evrim" == Evrim Ozcelik writes: Evrim> We are developing a medical software about PSG Evrim> (PolySomnoGraphy) analysis. The application takes signal Evrim> data from an electronic device and we will show this Evrim> continious signal function on the interfaces. There are Evrim> about 20-30 signal channels and the user selected channels Evrim> are shown. We want to run this application over different Evrim> platforms. Evrim> My question is: Evrim> 1. What must be our IDE 2. What class library for GUI Evrim> must be use (wxWindows, Qt, GTK, etc.) 3. Is there any GUI Evrim> package for visulazing signal functions (like sinozodial Evrim> functions) in real time; this module will behave as an Evrim> oscilloscope I wrote an EEG viewer in python using pygtk for the GUI and matplotlib for the 2D plotting (and VTK for the 3D). It runs unchanged on OSX, linux and win32. You can see a few screenshots at http://pbrain.sf.net . The underlying 2D plotting library, matplotlib, does handle animations (dynamic plots) and can be embedded in the GUI of your choice (Tk, WX, GTK, FLTK and QT). I also wrote matplotlib, as a first step in developing the application above. The performance of dynamic animated plots (what you call real time) varies for different backends. GTK is typically fastest: on a modern P4 you can do about 50 frames/sec for simple plots and 10-15 frames/sec for more complicated plots (images, larger data sets). The performance for the Tk GUI is considerably slower. Most people who say real time don't really mean it, they mean they want frequent updates and should assess whether the plotting library can support refresh rates (frames/sec) that are fast enough to be visually pleasing and to be true to the signal plotted. matplotlib is not the fastest 2D python plotting library, but it is one of the most feature complete and may be fast enough for your purposes -- http://matplotlib.sf.net . My guess is that for 20-30 channels the refresh rate in the current implementation will be slower than you want, but these things are always improving since matplotlib is under active development and there are some performance bottlenecks that could be removed with a little work. The examples directory which is in the src distributions has a number of examples illustrating dynamic plots: anim.py, system_monitor.py, dynamic_image_gtkagg.py, dynamic_image_wxagg.py, dynamic_demo.py. JDH From bvande at po-box.mcgill.ca Mon Feb 7 15:16:38 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon, 07 Feb 2005 15:16:38 -0500 Subject: python code with indention In-Reply-To: <1107805151.265680.165380@o13g2000cwo.googlegroups.com> References: <1107805151.265680.165380@o13g2000cwo.googlegroups.com> Message-ID: <4207CCA6.7050001@po-box.mcgill.ca> Xah Lee said unto the world upon 2005-02-07 14:39: > is it possible to write python code without any indentation? > > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html > print "It would seem it is indeed possible." print print "Note: although I know this, I don't consider myself an " print "accomplished Pythoner." print print "In the face of that, " print "I know enough not to post Python 'tutorials'." Best, Brian vdB From Scott.Daniels at Acm.Org Mon Feb 14 17:23:07 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 14 Feb 2005 14:23:07 -0800 Subject: Iterator / Iteratable confusion In-Reply-To: References: <420a5c1e$0$21630$a1866201@visi.com> <200502131958.27410.francis.girard@free.fr> Message-ID: <421120ec$1@nntp0.pdx.net> Francis Girard wrote: > Le dimanche 13 F?vrier 2005 23:58, Terry Reedy a ?crit : >>Iterators are a subgroup of iterables. Being able to say iter(it) without >>having to worry about whether 'it' is just an iterable or already an >>iterator is one of the nice features of the new iteration design. > > I have difficulties to represent an iterator as a subspecie of an iteratable > ... One of the result of not distinguishing them is that, at some point in > your programming, you are not sure anymore if you have an iterator or an > iteratable ; and you might very well end up calling "iter()" or "__iter__()" > everywhere. The point is _almost_, but not exactly unlike that. Because the "for ... in ..." construct calls iter itself, you seldom need (as a code user) to distinguish between iterators and iterables. However, there will come a day when you see some code like: first = True for blunge in whatever: if first: first = False else: print 'and', print blunge And you think, "I can make that clearer," so you write: source = iter(whatever) print source.next() for blunge in source: print 'and', blunge Because of how iterables work, you know you can do this locally without looking all around to see what "whatever" is. --Scott David Daniels Scott.Daniels at Acm.Org From x2164 at mailcity.com Thu Feb 3 01:40:07 2005 From: x2164 at mailcity.com (x2164 at mailcity.com) Date: 3 Feb 2005 06:40:07 GMT Subject: test_socket.py failure References: Message-ID: Marc Christiansen wrote: > x2164 at mailcity.com wrote: > > Nick Coghlan wrote: > >> Hmm, when the second argument is omitted, the system call looks like: > >> > >> getservbyname("daytime", NULL); > >> > >> Based on "man getservbyname" on my Linux PC, that should give > >> the behaviour we > >> want - any protocol will match. > >> > >> However: > >> > >> Linux 2.6.4-52-default (Suse 9.1) > >> Glibc 2.3.3 > >> gcc 3.3.3 > >> > >> So it may be that your older platform doesn't have this > >> behaviour - I'd be very > >> interested in what 'man getservbyname' has to say. > > > > Just took a look at the man page for getservbyname on this > > system and it doesn't mention passing NULL as the second > > argument. The pertinents: ;-) > > > > Linux kernel 2.6.10 > > Glibc 2.2.5 > > gcc 2.95.3 > Just to confuse the matter more, on my system the man page mentions > passing NULL as the second argument and it works. Alas: > SuSE 7.3 > Kernel 2.4.29 (vanilla) > Glibc 2.2.4 (older than yours) > gcc 2.95.3 > > I'd say your probably right about there being a difference > > in the behaviour of getservbyname between libc 2.2.5 and > > and libc-2.3.3 given the differences in man pages and > > observed return values. I'll try and compare the libcs' > > getservbyname codes and let you know a little later in > > the day. > > > > I wonder if the developers wanted to tie the python source > > code so closely to a glibc version and possibly gnu-libc > > specific? > Perhaps SuSE did patch the glibc... > Saluton > Marc hey Marc Oh man, not another problem that's just happening to me, again. :-) We all are still talking about python 2.4 aren't we? I'm really running out of options on this. My manual page for getservbyname is dated "22 April 1996" and i think that it wasn't installed by glibc-2.2.5. The info page for getservbyname which was installed by 2.2.5 doesn't mention being able to pass NULL as a 'PROTO' argument. As for my saying above that i would take a look at the libcs' code for getservbyname, well, let's just say i won't be bantering about that idea so readily anytime soon. :-) What i believe happens in glibc-2.3.3 is that getservbyname is generated by two files: inet/getsrvbynm.c which contains a number of '#define's that then '#include's the file nss/getXXbyYY.c which is sort of a template function that the '#define's fill out. If your use to reading it nss/getXXbyYY.c probably is easy reading, but, for ego's sake, let's just say that i'm not use to reading it. There's also getsrvbynm_r.c and getXXbyYY_r.c for the reentrant versions of getservbyname plus some references to nss and nis versions of getservbyname. Of course its also possilble that where i said "What i believe happens" at the beginning of this paragraph could be read as "I'm confused about what happens" and i don't mean that as critic of glibc. Marc, it is possible that there was a change between glibc-2.2.4 and 2.2.5 that would account for the difference in behaviour. I think i'll write a little test program in C to check out getservbyname's return values in a little more controled environment. I'll post the results tomorrow. pete jordan x2164 mailcity com -- ............ From skip at pobox.com Thu Feb 10 17:32:25 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 10 Feb 2005 16:32:25 -0600 Subject: hard_decoding In-Reply-To: <420AA934.6050206@mayo.edu> References: <420AA934.6050206@mayo.edu> Message-ID: <16907.57593.417911.696805@montanaro.dyndns.org> Tamas> Do you have a convinient, easy way to remove special charachters Tamas> from u'strings'? Tamas> Replacing: Tamas> ?????? => A ... etc ... See if my latscii codec works for you: http://www.musi-cal.com/~skip/python/latscii.py Skip From tom.willis at gmail.com Tue Feb 22 20:38:28 2005 From: tom.willis at gmail.com (Tom Willis) Date: Tue, 22 Feb 2005 20:38:28 -0500 Subject: Dealing with config files what's the options Message-ID: How are the expert pythoneers dealing with config files? Is there anything similair to .net's config files or java's .properties? A quick search on google didn't return anything that looked useful, and I almost would expect to see some module that would be for dealing with config information. I can think of at least one way to do it, but I'm sure there are shortcomings I can't see yet, and I'd rather use something someone smarter than me has written. I see in the logging module that there's stuff to handle configs but seems kind of odd to have to import logging to get your config information Any ideas? have I used the word config enough in this message? :) -- Thomas G. Willis http://paperbackmusic.net From ods at strana.ru Thu Feb 10 09:43:01 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Thu, 10 Feb 2005 17:43:01 +0300 Subject: sre is broken in SuSE 9.2 In-Reply-To: <1108036791.098550.306310@g14g2000cwa.googlegroups.com> References: <1108036791.098550.306310@g14g2000cwa.googlegroups.com> Message-ID: <20050210174301.3885a45d.ods@strana.ru> On 10 Feb 2005 03:59:51 -0800 "Serge Orlov" wrote: > > On all platfroms \w matches all unicode letters when used with flag > > re.UNICODE, but this doesn't work on SuSE 9.2: [...] > I can get the same results on RedHat's python 2.2.3 if I pass re.L > option, it looks like this option is implicitly set in Suse. Looks like you are right: >>> import re >>> re.compile(ur'\w+', re.U).match(u'\xe4') >>> from locale import * >>> setlocale(LC_ALL, 'de_DE') 'de_DE' >>> re.compile(ur'\w+', re.U).match(u'\xe4') <_sre.SRE_Match object at 0x40375560> But I see nothing related to implicit re.L option in their patches and the sources themselves are the same as on other platforms. I'd prefer to find the source of problem. -- Denis S. Otkidach http://www.python.ru/ [ru] From enleverlesO.OmcO at OmclaveauO.com Fri Feb 4 15:19:03 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Fri, 4 Feb 2005 21:19:03 +0100 Subject: Thread in python References: <1107533540.641969.191940@z14g2000cwz.googlegroups.com> Message-ID: <4203ddc5$0$6585$8fcfb975@news.wanadoo.fr> Hi ! Look the smart/fun use of threads make by http://candygram.sourceforge.net It's good for to know... @-salutations -- Michel Claveau From serpent17 at gmail.com Tue Feb 1 17:00:29 2005 From: serpent17 at gmail.com (Newbie) Date: 1 Feb 2005 14:00:29 -0800 Subject: web camera or else ? 15-30 fps processing of camera videos. Message-ID: <1107295229.657375.318750@o13g2000cwo.googlegroups.com> I am doing some robotics projects but my main area of interest is trying out several algorithms for the processing of the stream of data coming from the video. I am wondering what type of camera I should invest in. Either I could buy a web cam and hope I can find a driver I could either modify or use. i.e. every frame is somehow stored on the computer automagically or I could buy a camera not unlike the AVRcam (http://www.jrobot.net/Projects/AVRcam.html) or the CMUcam and try to do the processing once the data has been streamed to the nearest computer ? or should I use an expensive video card, some CCTV camera and a frame grabber to digitize photos so they can be processed afterwards. I expect my processing algorithms to handle at least 15 frames per second framerate once they are working ont the final set-up. My constraints are that I would like to avoid as much as possible complex set-ups even if that means buying a more expensive camera set-up. For the prototyping, I would like to try my algorithms out using a combination of python and matlab (all very slow) and then expect the same architecture (image files location and flow) with speedier set-up like python+psyco or C. All the processing would be done on a computer dedicated for that. Windows or Linux are possible. Any help from either comp.robotics.misc or c.l.p would be helpful. Thanks in advance, Jake. From tdelaney at avaya.com Wed Feb 9 17:04:19 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 10 Feb 2005 09:04:19 +1100 Subject: strange behaviour with decorators. Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE0252032C@au3010avexu1.global.avaya.com> Antoon Pardon wrote: > Ah, yes, the penny dropped. The try: except where there because > originally there were other statements I wanted to test and I > didn't want the raise exception by the inc(-2) stop the script. > I completely forget to consider it would also catch the > error I was expecting. A very good example of why you should (almost) never use a bare except: ... Tim Delaney From lkirsh at cs.ubc.ca Thu Feb 24 18:32:03 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Thu, 24 Feb 2005 15:32:03 -0800 Subject: duplicate file finder In-Reply-To: <3vvr11dvtbu030065pj9ptmj1i2eelodq8@4ax.com> References: <3vvr11dvtbu030065pj9ptmj1i2eelodq8@4ax.com> Message-ID: It looks pretty good, but I'll have to take a better look later. Out of curiosity, why did you convert the first spaces to pipes rather than add the code as an attachment? Lowell Christos TZOTZIOY Georgiou wrote: > On Wed, 23 Feb 2005 01:56:02 -0800, rumours say that Lowell Kirsh > might have written: > > >>Good idea about hashing part of the file before comparing entire files. >>It will make the script longer but the speed increase will most likely >>make it worth it. > > > My dupefind module was one of the first modules I wrote in python (it was a > shell script once...), so it's not appropriate to post. However, rewriting it > was in my RSN list; after your post, I said, "what the heck" :) > > I wouldn't describe it as /clean/ Python code, so any comments on style, > methodology (and of course, bugs!) are mostly welcome. If you have any ideas > how to make it more "Pythonic" in style, perhaps we can even send it to ASPN. > On the upside, it's a good demo of Python dynamism and therefore power. > > All first spaces are converted to pipe symbols to keep code indents, and sorry > for the assignment operators lacking spacing at the left, but it helped me know > what I meant in C, so I kept the habit in Python. > > > > """dupefinder.py -- a module to find duplicate files. > > find_duplicate_files(*paths): > . A function returning an iterable of lists of duplicate files > . To be used as > . for duplicate_files in dupefinder.find_duplicate_files(dir1, dir2...): > . # process every group of duplicates > """ > > import os, md5, errno, sys > > IGNORED_ERROR_CODES= frozenset( [errno.EACCES, errno.ENOENT] ) > > class File(object): > . """A wrapper for files to facilitate their comparison. > . > . Interface: > . - .get_hash(level) returns appropriate key for the current cmp level > . - .filename > . - .size""" > > . __slots__= "filename", "size", "_hashes", > > . def __init__(self, filename): > . self.filename= filename > . self.size= os.path.getsize(filename) > . if self.size == 0: > . self._hashes= [0, None, None] > . else: > . self._hashes= [self.size] > > . def __repr__(self): > . return "%s('%s')" % (self.__class__.__name__, self.filename) > > . def get_hash(self, level): > . """Return appropriate key for level of comparison. > . level == 0 returns file size > . level == 1 returns hash of first few kb > . level == 2 returns md5 sum of whole file""" > . if level >= len(self._hashes): > . if 1 <= len(self._hashes): > . self._hashes.append(self._get_partial_hash()) > . if 2 <= len(self._hashes): > . self._hashes.append(self._get_full_hash()) > . return self._hashes[level] > > . def _get_partial_hash(self): > . fp= open(self.filename) > . try: > . return hash(fp.read(8192)) > . finally: > . fp.close() > > . def _get_full_hash(self): > . fp= open(self.filename, "rb") > . full_hash= md5.new() > . while 1: > . data= fp.read(65536) > . if not data: break > . full_hash.update(data) > . fp.close() > . return full_hash.digest() > > class GenericFilesDict(dict): > . """A virtual wrapper for the dictionaries of file comparisons. > . Not to be used on its own, but through subclassing. > . > . Each subclass should define a _level class attribute to be used with the > . File.get_hash method, and a _next_class attribute pointing to the class > . managing the next level comparisons.""" > . __slots__= () > > . def add_file(self, fileobj): > . """Add a File object to self keyed by the appropriate key based on > . self._level. If another file object exists in the same spot, replace it > . by a _next_level_class instance containing the pre-existing and new file > . obj.""" > > . this_hash= fileobj.get_hash(self._level) > > . try: > . result = self[this_hash] > . except KeyError: > . self[this_hash]= fileobj > . return > > . try: # there was something in slot [this_hash] > . result.add_file(fileobj) # so add fileobj to it > . except AttributeError: # it has no add_file method, so it's a File > . _= self[this_hash]= self._next_class() # make an instance > . _.add_file(result) # add pre-existing > . _.add_file(fileobj) # add new > > . def __repr__(self): > . return "%s%s" % (self.__class__.__name__, dict.__repr__(self)) > > . def __iter__(self): > . "Return all instances of SameFiles (subclass of list)." > . for item, value in self.iteritems(): > . try: _next_class= value._next_class > . except AttributeError: continue > . if _next_class is None: > . yield value > . else: > . for item in value: > . yield item > > class SameFiles(list): > . "A list of duplicate files." > . __slots__= () > . _level= 3 > . _next_class= None # search stops here > > . def add_file(self, fileobj): > . self.append(fileobj) > > class FilesByFullHash(GenericFilesDict): > . """A dictionary keyed on md5 hash of whole file. > > . The algorithm assures that all File objects in this dict > . have the same size and the same hash of first few kiB.""" > . __slots__= () > . _level= 2 > . _next_class= SameFiles > > class FilesByPartialHash(GenericFilesDict): > . """A dictionary keyed on hosh of first few kiB of file. > > . The algorithm assures that all File objects in this dict > . have the same size.""" > . __slots__= () > . _level= 1 > . _next_class= FilesByFullHash > > class FilesBySize(GenericFilesDict): > . """A dictionary keyed on file size.""" > . __slots__= () > . _level= 0 > . _next_class= FilesByPartialHash > > def find_duplicate_files(*directories): > . """Find all duplicate files in the specified directories. > > . The returned object can be iterated on, yielding a list of > . duplicate files every time.""" > . dupefinder= FilesBySize() > ## count= 0 > . for path in directories: > . for dirname, dirnames, filenames in os.walk(path): > . for filename in filenames: > . try: > . dupefinder.add_file(File(os.path.join(dirname, filename))) > . except EnvironmentError, exc: > . if exc.errno not in IGNORED_ERROR_CODES: # deleted or b0rken > symlink > . raise > ## count += 1 > ## if count & 15 == 0: > ## sys.stderr.write("\r%d" % count) > > . return dupefinder > > def pprint(obj, level=0): > . """For testing purposes.""" > . indent= " "*level > . if isinstance(obj, File): > . print `obj` > . elif isinstance(obj, list): > . print "list" > . for subobj in obj: > . print indent, "-", repr(subobj) > . else: > . print obj.__class__.__name__ > . for key, subobj in obj.iteritems(): > . print indent, "+(%r)" % key, > . pprint(subobj, level+1) > > if __name__=="__main__": > . result= find_duplicate_files(*sys.argv[1:]) > . import pprint > . for group in result: > . pprint.pprint(group) > From steven at lczmsoft.com Sat Feb 26 08:07:54 2005 From: steven at lczmsoft.com (steven at lczmsoft.com) Date: 26 Feb 2005 05:07:54 -0800 Subject: Problem When Unit Testing with PMock Message-ID: <1109423274.660110.156140@f14g2000cwb.googlegroups.com> Hi, Anyone was using pmock for unit testing with python? I met a problem and hope someone to help me. For short, the pmock seems can not mock a iterator object. For example, the tested object is foo, who need to send message to another object bar. So, to test the foo, I need mock a mockBar. But the bar is a iterator, the foo use the bar in this way: foo.method(self, bar): for n in bar: do somthing ... my purpose is create a mockBar and pass this mock object to foo.method(), but this ideal simply does not work. Python will complain that calling on an uniteraterable object. I'v already set anything like mockBar.expects(__iter__()) and mockBar.expects(next()). Does anyone has some clues? - narke From danperl at rogers.com Fri Feb 4 01:12:50 2005 From: danperl at rogers.com (Dan Perl) Date: Fri, 4 Feb 2005 01:12:50 -0500 Subject: advice needed for simple python web app References: <5cqdnZX-cZ9ca5_fRVn-3Q@rogers.com> <7xr7jxnddh.fsf@ruckus.brouhaha.com> <7xis58c1lw.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xis58c1lw.fsf at ruckus.brouhaha.com... > "Dan Perl" writes: >> The application is just something I'm playing with to learn a little bit >> on >> web apps. It uses an HTML form to send an email. The form takes inputs >> like the From:, To: and Subject: fields and a text field. > > Be careful of exposing that script to the internet. Spammers will > exploit it. Do you mean publishing the script for other people to copy it or exposing the web app so that other people may access it? Don't worry anyway, I won't do either and I'm running 2 firewalls on my PC. It would be really naive to expose the web app, wouldn't it? From dotpyFE at gmail.com Sat Feb 26 20:18:40 2005 From: dotpyFE at gmail.com (Lucas Raab) Date: Sun, 27 Feb 2005 01:18:40 GMT Subject: weird strings question In-Reply-To: References: Message-ID: Robert Kern wrote: > Lucas Raab wrote: > >> Is it possible to assign a string a numerical value?? For example, in >> the string "test" can I assign a number to each letter as in "t" = 45, >> "e" = 89, "s" = 54, and so on and so forth?? > > > Use a dictionary with the strings as keys. > > string2num = {} > string2num['t'] = 45 > string2num['e'] = 89 > > etc. > Thanks. That's what I was looking for, but was just unsure exactly how to proceed. From bdesth.quelquechose at free.quelquepart.fr Mon Feb 14 14:29:26 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 14 Feb 2005 20:29:26 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <4210a3d9$0$23451$626a14ce@news.free.fr> Message-ID: <4210f994$0$20570$636a15ce@news.free.fr> Stephen Kellett a ?crit : > In message , Simon > Brunning writes > >>On Mon, 14 Feb 2005 14:12:57 +0100, bruno modulix wrote: >> >>>Why do you hate Perl and Ruby community that much ? >> >>Oh, I don't. But fair's fair - we've carried our share of the burden, surely? > > > He is already badgering the Ruby guys. Without about as much success as > this newsgroup. When he doesn't get what he wants a post along the lines > of > > "XXXX lang is only suited to small projects and not real world > industrial projects" > or > "the community doesn't care" > will appear. > > Its quite incredible - in the time he has spent complaining he could > have done his own research and written some useful tools. I know how > long it took me to write my first major C++ app that interfaced with > Python and Ruby. It was less time than he has spent complaining - and > that included rebuilding Python/Ruby, inspecting the source for what I > needed and performing many experiments before I succeeded. Just google for Ilias Lazaridis... You may observe that our new troll has already played the same game on many newsgroups, forums and whatever... > Stephen From Peter.Vandersteegen at gmail.com Wed Feb 16 10:05:48 2005 From: Peter.Vandersteegen at gmail.com (peter) Date: 16 Feb 2005 07:05:48 -0800 Subject: adding new functionality to a function non-intrusively! References: <1108564620.657526.301320@g14g2000cwa.googlegroups.com> <1108565730.135442.174550@l41g2000cwc.googlegroups.com> Message-ID: <1108566348.660335.224170@g14g2000cwa.googlegroups.com> Hello I indeed also rely on your idea. My problem however is: is has to be non-intrusively in both ways. In your example, it would indeed not break the old code which relies on myfunction but my problems is: I also do not want to change the code of the 'before' myfunction. so my problem in fact is: BEFORE: def myfunction(a,b): return (a+b) AFTER: def myfunction(a,b, op="add"): if (op == "add"): # some function which calls the old code for myfunction kind regards From cam.ac.uk at mh391.invalid Fri Feb 18 21:38:50 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 19 Feb 2005 02:38:50 +0000 Subject: Trouble with mysql-python 1.2.0 on Solaris 8 sparc In-Reply-To: <1108755202.574729.293610@g14g2000cwa.googlegroups.com> References: <1108755202.574729.293610@g14g2000cwa.googlegroups.com> Message-ID: Alec Wysoker wrote: > I need to be able to access mySQL 4.0 and 4.1 databases from python. I > was hoping to find mysql-python 1.2.0 already built for Sparc, but no > such luck. Try version 1.0.1. -- Michael Hoffman From claird at lairds.us Sun Feb 13 09:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Sun, 13 Feb 2005 14:08:04 GMT Subject: Considering python - have a few questions. References: Message-ID: In article , Tim Roberts wrote: >"Heather Stovold" wrote: >> >>I need to make a GUI interface. Some of the screens need to be dynamically >>created, with the screen information in a database. Included in the database >>will be pictures (.gif or .jpg) that need to be displayed. A second >>database would hold the user's data. I would also need to be able to print >>reports made in a similar fashion. >> >>I would want the program to run in Windows for sure. If it could work on a >>Mac and other systems, that would be a plus. I would really love it to be >>able to also be able to be run on the internet (allowing more than one >>person access to the data), but I've never done anything other than basic >>web pages with a web page editor (dreamweaver.) >> >>btw - I have the database designed (and the program info database filled) in >>Access.... >> >>I don't mind working hard to learn how to do it.... I just want to know if >>Python is a good choice or not! > >Python is a great choice. Personally, given your requirements, I would >make this a web application. In my opinion, HTML is the easiest way to >generate a user interface on-the-fly. With a package like CherryPy, you >get a web server built-in. You fire up the server in the background, and >bring up Internet Explorer as "your" user interface. . . . Me, too. Ms. Stovold, while I imagine that you're not thinking in terms of a Web application, I suspect you're likely to find Tim's advice very satisfying. Given your background, as you describe it, I strongly urge you at least to experiment with simple dynamically-generated Web pages. Don't hesitate to start with CGI, as the easiest way to achieve quick results. From ola.natvig at infosense.no Tue Feb 1 04:47:25 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Tue, 01 Feb 2005 10:47:25 +0100 Subject: find isset() php function equivalent in python In-Reply-To: <41ff4e18$0$260$edfadb0f@dread12.news.tele.dk> References: <41ff435f$0$18835$8fcfb975@news.wanadoo.fr> <41ff4e18$0$260$edfadb0f@dread12.news.tele.dk> Message-ID: Max M wrote: > Ola Natvig wrote: > >> Olivier Noblanc ATOUSOFT wrote: >> >>> Hello >>> >>> >>> What is the equivalent function of php isset() in python >> >> >> try: >> if variable: >> # isset >> pass >> except NameError: >> # not set >> pass >> > > > you could use: > > >>> 'variable' in vars() > > But be aware that it is bad bad practice to do it like that. > > If you need variables that you don't know that name of, you should put > them in a dictionary. They are made for that exact purpose. > > >>> unkown_vars = {} > >>> unkown_vars['variable'] = 42 > >>> 'variable' in unkown_vars > True > > If it's a greater possibility that the 'variable' are set than it's not you will get better performance when using: try: print unknown_vars['variable'] except KeyError: print 'variable are not set' istead of if 'variable' in unknown_vars: print unknown_vars['variable'] else: print 'variable are not set' You could even use print unknown_vars.get('variable', 'variable are not set') dictionary.get(key, default) returns the default if key are not located in the dictionary, I'm not sure if the function uses the try / except KeyError aproach or what it uses. -- -------------------------------------- Ola Natvig infoSense AS / development From PDunce at somewhere.invalid Tue Feb 8 20:18:59 2005 From: PDunce at somewhere.invalid (Python Dunce) Date: 09 Feb 2005 01:18:59 GMT Subject: Dumb glob question References: <1107770445.983406.64730@g14g2000cwa.googlegroups.com> Message-ID: Michael Hoffman wrote in comp.lang.python: > Python Dunce wrote: > >> So if I happen >> to be processing 'foo [bar].par2' >> >> glob.glob(filename[:-5]+'.*par2') >> >> doesn't return anything. Using >> win32api.FindFiles(filename[:-5]+'.*par2') works perfectly, but I don't >> want to rely on win32api functions. I hope that made more sense :). > > If you look in the source for glob.py, you will find that it calls the > fnmatch module, and this is the docstring for fnmatch.translate(): > > """Translate a shell PATTERN to a regular expression. > > There is no way to quote meta-characters. > """ > > So you cannot do what you want with glob. > > You can replace [] with ? in your glob string, if you are sure that > there won't be other characters there. That's a bit of a hack, and I > wouldn't do it. > > In my mind it would probably be best to do: > > re_vol = re.compile(re.escape(startpart) + ".*vol.*") > lst = [filename for filename in os.listdir(".") if > re_vol.match(filename)] > > I changed "list" to "lst" because the former shadows a built-in. Thanks, that should do the trick! I had tried basically the same thing once but I was getting back empty lists. I think it was just a brain fart involving a case sensitive regex that didn't match the files I was testing it on :/. From fperez.net at gmail.com Wed Feb 16 16:42:36 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 16 Feb 2005 14:42:36 -0700 Subject: huge help for interactive python References: Message-ID: David S. wrote: > If you are using ipython on Windows then you will > have made sure you have Gary Bishop's readline > library as instructed in the ipython install > directions found at: > http://ipython.scipy.org/ [...] Thanks, very handy. I just reposted your message to the ipyhton-users list, since others may find it useful there. Regards, f From steve at holdenweb.com Mon Feb 28 10:30:37 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 28 Feb 2005 09:30:37 -0600 Subject: Text To Speech with pyTTS In-Reply-To: <4221b0b6$0$1998$afc38c87@news.optusnet.com.au> References: <4221b0b6$0$1998$afc38c87@news.optusnet.com.au> Message-ID: <4223391D.50206@holdenweb.com> Mike P. wrote: > Hi, > I was wondering if anyone has had any luck with the python text to speech > (pyTTS) module available on Sourceforge: > http://sourceforge.net/projects/uncassist > > I have followed the tutorial for pyTTS at: > http://www.cs.unc.edu/~parente/tech/tr02.shtml > > Using the first simple speech example: > > import pyTTS > > tts = pyTTS.Create() > tts.Speak("Hello World!") > > I get the following error on the call to pyTTS.Create() > > C:\Program Files\Python23\Lib\site-packages\pyTTS>python > ActivePython 2.3.2 Build 232 (ActiveState Corp.) based on > Python 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import pyTTS >>>>tts = pyTTS.Create() > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Program Files\Python23\Lib\site-packages\pyTTS\__init__.py", line > 28, in Create > raise ValueError('"%s" not supported' % api) > ValueError: "SAPI" not supported > > > I followed the instructions in the tutorial in order and installed the > required packages in the following order, given that I already had an > ActiveState Python 2.3 installation under Windows XP. > > 1) wxPython2.5-win32-unicode-2.5.3.1-py23.exe (didn't already have this and > some of the pyTTS demos need it) > > 2) Microsoft SAPI 5.1 (SAPI5SpeechInstaller.msi) > 3) Extra Microsoft Voices (SAPI5VoiceInstaller.msi) > 4) pyTTS-3.0.win32-py2.3.exe (pyTTS for Python 2.3 under windows) > > I ran the example and it didn't work. I didn't initially install Mark > Hammond's > Python win32all extensions, because they already come with ActiveState > Python. > So I tried installing the win32all (win32all-163.exe) package just in case, > but I still > get the SAPI not supported error. > > Anyone get this working - any suggestions? Or am I missing something > obvious? > > Thanks In Advance. > > Mike P. > > I got the "SAPI not supported" error until I installed the SpeechInstaller and VoiceInstaller components, after which everything worked fine for me. (Win2K SP4, Python 2.4 plus win32 extentions). regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From mcfletch at rogers.com Fri Feb 18 11:55:27 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 18 Feb 2005 11:55:27 -0500 Subject: 3d graphics In-Reply-To: <20050218153917.GA53264@aquameta.com> References: <20050218153917.GA53264@aquameta.com> Message-ID: <42161DFF.2030605@rogers.com> Eric Hanson wrote: >Hi, > >I'm interested in doing some work with 3d graphics >visualizations of XML/RDF data in Python. I know Python is >strong on the XML front but what about 3d graphics? Is there a >graphics library out there with graphics library with a fairly >gradual learning curve? Do people actually use Python for games >programming and the likes? > > Python's got a few 3D libraries: http://www.vrplumber.com/py3d.py You'll probably be most interested in a scenegraph/retained-mode renderer, listed here: http://www.vrplumber.com/py3d.py?category=retained depending on your background, VPython (or VTK/MayaVi if you're more from a science background) might be a good starting point. Soya or Panda seem more involved, but probably take you a little further toward game-like engines. Pivy or OpenGLContext (both being Inventor-style scenegraphs) are more toolkits for developers to build applications, they generally let you load and work with objects readily, but they aren't trying to provide "jumping, shooting and exploding" features out-of-the-box. Then there are the full (normally C++) game engines with Python wrappers, likely a steeper learning curve, but once you get up and running they should give you fairly easy going for writing a game. Most (commercial) games that use Python follow that last model, a C++ engine that uses Python for scripting and extensions. AFAIK there hasn't been a (commercial) 3D game (graphics engine) written with Python as the primary implementation language (for the graphics engine). Of the retained-mode renderers on that page, only a handful are primarily Python code; it takes a lot of work to get a decently performing scenegraph engine written in Python. HTH, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com PyCon is coming... From littlejohn.75 at news.free.fr Mon Feb 14 15:11:20 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 14 Feb 2005 20:11:20 GMT Subject: changing __call__ on demand References: Message-ID: <421105e8$0$374$626a14ce@news.free.fr> Le Sun, 13 Feb 2005 13:19:03 -0500, Hans Nowak a ?crit : > Stefan Behnel wrote: >> Hi! >> >> This somewhat puzzles me: >> >> Python 2.4 (#1, Feb 3 2005, 16:47:05) >> [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >> .>>> class test(object): >> ... def __init__(self): >> ... self.__call__ = self.__call1 # self.__call__ is bound >> ... def __call1(self): >> ... print 1 >> ... def __call__(self): # self.__call__ is rebound >> ... print 2 >> ... >> .>>> t = test() >> .>>> t() >> 2 2 because the last defined __call__ wins. Try dir(t) >> >> If I take out the __call__ method completely and only set it in >> __init__, I get a TypeError saying that test is not callable. This seems logical. > > Note that it works just fine if you don't use a new-style class: > > >>> class Test: > ... def __init__(self): > ... self.__call__ = self.foobar > ... def foobar(self, *args, **kwargs): > ... print "Called with:", args, kwargs > ... > >>> t = Test() > >>> t() > Called with: () {} > >>> t(3, 4) > Called with: (3, 4) {} > >>> t(42, x=0) > Called with: (42,) {'x': 0} Are you sure that if you add a __call__() method, it will still work fine ? Regards > From nbbalane at gmail.com Wed Feb 2 02:24:18 2005 From: nbbalane at gmail.com (jrlen balane) Date: Wed, 2 Feb 2005 15:24:18 +0800 Subject: how to separate hexadecimal In-Reply-To: <2cad209005020123107fb43105@mail.gmail.com> References: <2cad209005020123107fb43105@mail.gmail.com> Message-ID: <2cad2090050201232427cb97f2@mail.gmail.com> i have a 4 digit hex number (2 bytes) and i want to separate it into 2 digit hex (1 byte each) meaning i want to get the upper byte and the lower byte since i am going to add this two. how am i going to do this? should i treat it just like a normal string? please help, thanks. ex. hexa = '0x87BE" # what i want to do is: a = 0x87, b = 0xBE # so that i could do this: c = a + b #which should be equal to 0x145 From sjmachin at lexicon.net Sat Feb 19 18:47:39 2005 From: sjmachin at lexicon.net (John Machin) Date: 19 Feb 2005 15:47:39 -0800 Subject: exercise: partition a list by equivalence In-Reply-To: <37pb5jF5fnfivU1@individual.net> References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> <1108814276.680736.264380@l41g2000cwc.googlegroups.com> <37pb5jF5fnfivU1@individual.net> Message-ID: <1108856859.576211.178480@l41g2000cwc.googlegroups.com> Reinhold Birkenfeld wrote: > Xah Lee wrote: > > here's the answer to the partition by equivalence exercise. > > Your Python solution is, as expected, wrong (try with > [[10, 8], [7, 3], [1, 7], [5, 4], [2, 2], [3, 8], [7, 10], [2, 3], [6, > 10], [3, 2]] > for example). > > The solution by John Lenton is wrong, too. > > The solution by Brian Beck delivers the correct result for most input, > but for some input lists like > [[3, 3], [8, 7], [3, 2], [8, 5], [5, 6], [6, 3], [10, 8], [8, 10], [4, > 10], [10, 2]] > it chokes and returns the empty list. > > My solution (which may not be the fastest or most effective, but till > now is the shortest and it works): > > def merge(pairings): > sets = {} > for x1, x2 in pairings: > newset = (sets.get(x1, frozenset([x1])) > | sets.get(x2, frozenset([x2]))) > for i in newset: > sets[i] = newset > > return [list(aset) for aset in set(sets.itervalues())] > > > Reinhold FWIW, here's a brief UAT report: Appears to work: Reinhold, David, Xah (v2) Has bug(s): John L (v*), Brian (v*) Incomprehensible: Xah (v*) 'Come back after lunch' award goes to Xah v2, which at a glance appears to be O(N**4) -- dictionary.update() inside 3-deep nest of 'for' statements. Here's a small input that busts all non-working versions: input: [[1, 2], [3, 4], [2, 3], [4, 5]] merge_RB -> [[1, 2, 3, 4, 5]] merge_DE -> [[1, 2, 3, 4, 5]] merge_JL -> [[1, 2, 3, 4], [5]] merge_JL2 -> [[1, 2, 3, 4], [5]] merge_BB -> [] merge_XL -> [[1, 2, 3, 4, 5], [3, 4, 5]] merge_XL2 -> [[1, 2, 3, 4, 5]] From grante at visi.com Thu Feb 17 16:12:56 2005 From: grante at visi.com (Grant Edwards) Date: 17 Feb 2005 21:12:56 GMT Subject: How to wrap a class's methods? References: <4214f167$0$44618$a1866201@visi.com> <4214fd15$0$44645$a1866201@visi.com> Message-ID: <421508d8$0$44608$a1866201@visi.com> On 2005-02-17, Michael Spencer wrote: >> Thanks. The stuff provided by the "new" module is what I was >> missing. > > No magic in the 'new' module - new.instancemethod is just a synonym for the > method type: > > >>> import new, types > >>> new.instancemethod is types.MethodType > True Thanks -- I didn't know that either. -- Grant Edwards grante Yow! I joined scientology at at a garage sale!! visi.com From jerf at jerf.org Tue Feb 1 13:12:02 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 01 Feb 2005 13:12:02 -0500 Subject: variable declaration References: <1107205410.367521.50490@f14g2000cwb.googlegroups.com> <44SdnUZGopnrAWLcRVn-pg@telcove.net> Message-ID: On Tue, 01 Feb 2005 09:13:36 -0600, Thomas Bartkus wrote: > *Is* there a reason why the interpreter couldn't/shouldn't require formal > variable declaration? You mean, other than the reasons already discussed at length in this thread, not to mention many many others? Your not *liking* the reasons doesn't make them any less the reasons. They may not even be good reasons, nevertheless, there the reasons are. If you're literally asking the question you are asking, re-read this thread more carefully. If you're *really* asking "Give me a reason *I like*", I suggest re-reading Alex's discussion on why maybe Python isn't for everybody. All I know is that I have created large programs and typos like you seem mortally terrified of occur on average about once every *ten modules* or so, and are generally caught even before I write the unit tests. Breaking the language to avoid what *by construction* is demonstrated not be a real problem is... well, I believe Alex covered that, too. Blah blah blah, "what if... what if... what if..." We should concentrate on *real* problems, ones that exist in real code, not ones that mostly exist in wild-eyed prose that consists of predictions of pain and death that conspicuously fail to occur, no matter how many times they are repeated or we are exhorted to heed them or face our doom. (The previous paragraph also describes my root problem with Java's strong typing philosophy; death, doom, and destruction conspicuously fail to occur in Python programs, so why the hell should I listen to the doomsayers after I've already proved them false by extensive personal experience? No amount of prose is going to convince me otherwise, nor quite a lot of the rest of us.) From just at xs4all.nl Thu Feb 24 04:11:14 2005 From: just at xs4all.nl (Just) Date: Thu, 24 Feb 2005 10:11:14 +0100 Subject: Style guide for subclassing built-in types? References: <1109127834.660822.247120@g14g2000cwa.googlegroups.com> <1109150091.356411.150460@l41g2000cwc.googlegroups.com> <1109151417.903188.73790@f14g2000cwb.googlegroups.com> <421c76cd$1_1@newspeer2.tds.net> <1109163706.118457.53720@z14g2000cwz.googlegroups.com> <1109208924.563510.212500@f14g2000cwb.googlegroups.com> Message-ID: In article <1109208924.563510.212500 at f14g2000cwb.googlegroups.com>, janeaustine50 at hotmail.com wrote: > Thank you but your advice doesn't fit in my case since I want to keep > the memory usage and the initial time minimum. iterable[::-1] would > build another list and it would take big memory and time during > reversing if iterable were huge. (and the "iterable" wouldn't be > garbage-collected because I want to keep a reference to it) If your list contains numbers (or lists of numbers), consider using NumPy (Numeric) or Numarray, in which seq[::-1] will actually return a "view", and not a copy. Just From sh_snyder at yahoo.com Sat Feb 19 22:10:31 2005 From: sh_snyder at yahoo.com (scott) Date: 19 Feb 2005 19:10:31 -0800 Subject: Matplotlib, py2exe and pytz In-Reply-To: References: <1108776896.490620.249130@f14g2000cwb.googlegroups.com> Message-ID: <1108869031.068167.49840@l41g2000cwc.googlegroups.com> I unzipped library.zip to see what compiled python files were included in the zip. As in the error stacktrace the Pytz.timezone package was not part of the library. After manually adding it and rezipping the library I ran into another missing module, this time it was missing backend_agg Traceback (most recent call last): File "gcToCsv.py", line 5, in ? File "plot_output.pyc", line 1, in ? File "pylab.pyc", line 1, in ? File "matplotlib\pylab.pyc", line 195, in ? File "matplotlib\backends\__init__.pyc", line 20, in ? ImportError: No module named backend_agg I added that module and then saw that it was missing pyparsing Traceback (most recent call last): File "gcToCsv.py", line 5, in ? File "plot_output.pyc", line 1, in ? File "pylab.pyc", line 1, in ? File "matplotlib\pylab.pyc", line 195, in ? File "C:\PYTHON23\Lib\site-packages\matplotlib\backends\__init__.py", line 20, in ? globals(),locals(),[backend_name]) File "C:\PYTHON23\Lib\site-packages\matplotlib\backends\backend_agg.py", line 85, in ? from matplotlib.mathtext import math_parse_s_ft2font File "C:\PYTHON23\Lib\site-packages\matplotlib\mathtext.py", line 140, in ? from matplotlib.pyparsing import Literal, Word, OneOrMore, ZeroOrMore, \ ImportError: No module named pyparsing After that I stopped adding modules as I figured the problem was more involved than just missing 1 or 2 modules. My app just takes a set of data and plots it using the library. It does not use matplotlib date functionality explicitly, it converts a list of datatimes to a list of elapsed times (numbers of seconds) and plots data against these floats. The setup.py file I used was the one in the matplotlib documentation. I then added the opt line to try and force the inclusion of that package. I am relatively new to Python programming coming most recently from a Java programming background, and was wondering why python does not have the concept of a python archive much like a "jar" file in Java. That would make all of these problems fairly trivial, inclusion of dependant libraries would just be a matter of having the appropriate "Python ARchive in a directory in the PYTHON_PATH so that it could be loaded. Thanks for any help on resolving my py2exe problems. Scott Snyder From adam at cognitcorp.com Sun Feb 6 23:15:14 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Sun, 06 Feb 2005 23:15:14 -0500 Subject: bytecode obfuscation In-Reply-To: <4206195e$0$24724$626a14ce@news.free.fr> References: <4206195e$0$24724$626a14ce@news.free.fr> Message-ID: <1107749714.3850.41.camel@localhost.localdomain> On Sun, 2005-02-06 at 08:19, Philippe Fremy wrote: > Adam DePrince wrote: > > No amount of obfuscation is going to help you. > > Theorically, that's true. Anything obfuscated can be broken, just like > the non obfuscated version. However it takes more skills and time to > break it. And that's the point. By raising the barrier for breaking a > product, you just eliminate a lot of potential crackers. > > > The worst case if you depend on obscurity: The bad guys are rounding > > off your pennies as you read this. > > That's the worst case, we all know that. A good case is to rely on open > spec and standard. However, obscurity can help if added on top of that. > > I remember an article of Fyodor explaining that if you run your internal > apache server on port 1234 (for an enterprise) with all the normal > security turned on, you avoid 80% of the common cracker. You should not > rely on the port number for security but changing it improves it. Okay, so only 20% of the script kiddies are filling the edges of your coins. It would seem that the article you quote is addressing the computer equivalent of a burglar. There is nothing personal between a burglar and a home owner (from the formers perspective at least.) Any home will do, and their victim is chosen from a large pool of equally uninteresting targets on the basis of their vulnerability. Those 80% don't notice your port 1234 because it serves no purpose. They aren't looking to break into you specifically, they are looking to break in anywhere, and the act of changing your port, much like attaching a chain to your wallet, makes you not worth the effort. There are two problems with your analogy. First, you are forgetting the economics of the situation. The low value of cracking yet another web server over shadows only the minuscule cost of port scanning the potential mark. The second problem with your analogy lies in the very nature of the problem you are trying to solve. Decompiling and securing your website are two different beasts, so much that it is not possible to draw conclusions about one from experiences with the other. The former is simply a matter of reading the code and emulating your cpu/virtual machine/etc by hand with a paper and pencil. Time consuming and tedious, but quite certain in its outcome. The barrier to decompiling this code has to be raised above the benefit you will get from decompiling it. If the server that this code to works correctly and depends on no magic within the client to protect itself from rounded pennies, then you are fine even if the code is reverse engineered, for the problem becomes one of the correctness of the implementation of the server code in the face of a hostile client. Doing this will foil your hacker by eliminating the benefit of reverse engineering. If the server is not robust, then the payoff becomes all of your rounded pennies. Even by the decedent wage standards of American programmers, the payoff greatly exceeds the labor cost of learning how your API works from the byte code. Remember, anything a computer can understand is a language that a human can learn too (there is a reason why computer science also goes by the name computational linguistics.) Obfuscate your code to the end of the world and all you have done is changed the language in which the programmer will learn your algorithm. Big deal, instead of turning it into python, I print up the symbolic representation of the python byte code, assembly, vhdl or whatever it might be. Low level languages are not that hard to read. Remember, if it can run on a computer, it can run on pencil and paper. Just look at the trouble DRM has ... they have to go so far as to introduce "trusted hardware", aka a machine that won't let you dump the machine code to your printer. Adam DePrince From marian at mba-software.de Thu Feb 3 13:46:50 2005 From: marian at mba-software.de (=?ISO-8859-1?Q?Marian_Aldenh=F6vel?=) Date: Thu, 03 Feb 2005 19:46:50 +0100 Subject: Printing Filenames with non-Ascii-Characters In-Reply-To: References: <36a3ikF4uk8r0U1@individual.net> <36bka5F4vp17cU1@individual.net> Message-ID: <36f9sqF505hq0U1@individual.net> Hi, > Python's drive towards uncompromising explicitness pays off > big time when you're dealing with multilingual data. Except for the very implicit choice of 'ascii' as an encoding when it cannot make a good guess of course :-). All in all I agree, however. Ciao, MM -- Marian Aldenh?vel, Rosenhain 23, 53123 Bonn. +49 228 624013. http://www.marian-aldenhoevel.de "There is a procedure to follow in these cases, and if followed it can pretty well guarantee a generous measure of success, success here defined as survival with major extremities remaining attached." From beefens_skasuj_ at o2.pl Wed Feb 2 08:20:26 2005 From: beefens_skasuj_ at o2.pl (Pawel Chrobak) Date: Wed, 2 Feb 2005 14:20:26 +0100 Subject: access to serial port References: Message-ID: > Keywords: python serial > Great, I needed exactly this information ( pyserial) . Thanks a lot ;) From steven.bethard at gmail.com Tue Feb 15 17:04:07 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 15 Feb 2005 15:04:07 -0700 Subject: Calling a function from module question. In-Reply-To: References: <42125d6d$0$28977$e4fe514c@news.xs4all.nl> <3LtQd.32674$6u.18210@fed1read02> Message-ID: <3LOdncDRa6BK7I_fRVn-rA@comcast.com> Sean wrote: >>>>from module_name import print_this >>> >>>>or, even: >>>> >>> >>>>from module_name import print_this as other_nice_name >>> >>>So what if I have a whole bunch of functions - say 25 of them. >>>Is there a way to do this without naming each function? >> >>Yes [1], but it's basically deprecated and you shouldn't use it. Consider >>refactoring your code. > > Refactoring my code? Sorry, I am not sure what you mean here. > > How would one refactor the example in my original post? The original post only had one name to import, not 25, so refactoring isn't really necessary. ;) What are the 25 functions you want to import? Perhaps you can group them together in classes? Or maybe a couple of (sub-)modules is the way to go... STeVe From just at xs4all.nl Thu Feb 3 06:50:09 2005 From: just at xs4all.nl (Just) Date: Thu, 03 Feb 2005 12:50:09 +0100 Subject: Easy Q: dealing with object type References: <420181b1$1@nntp.zianet.com> <1107396669.028096.301290@g14g2000cwa.googlegroups.com> <42019545$1@nntp.zianet.com> Message-ID: In article , Steven Bethard wrote: > Erik Johnson wrote: > > "Erick" wrote in message > > news:1107396669.028096.301290 at g14g2000cwa.googlegroups.com... > > > >>Ah, you're running into the "old-style classes vs. new style classes". > >>Try subclassing from "object". > >> > >>For example: > >> > >>>>>class A(object): > > > > That works! :) I guess I am fortunate to be running 2.2 - looks kinda ugly > > prior to that. > > It's not horrible: > > py> class A: > ... pass > ... > py> class B: > ... pass > ... > py> a = A() > py> a.__class__ == A > True > py> a.__class__ == B > False Uh, isinstance(a, A) works for both new-style and old-style classes. Heck, isinstance() even works in Python 1.5.2... > Still, if you can use new-style classes, you should. > > Also, you should probably Google for "duck typing". Generally, in > Python it is frowned upon to check the type of an object. There are > times when it's necessary, but if you're just starting off, my guess is > that you haven't discovered one of these times yet... Just From peter at engcorp.com Sun Feb 27 12:42:19 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 27 Feb 2005 12:42:19 -0500 Subject: TKinter In-Reply-To: <38eb4lF5nldh7U1@individual.net> References: <38eb4lF5nldh7U1@individual.net> Message-ID: anthonyberet wrote: > So, is it pronounced 'Tee-Kinter', or 'Tee-Kay-Inter'? > I don't want to appear as a dork down the pub. Both, in my experience. And then there's wxPython, which is pronounced variously as "wiks-python", "double-you-eks-python", or even in some strange way that I'll leave it to Mike Fletcher to describe since it embarrasses me even to mention it. ;-) -Peter From ruach at chpc.utah.edu Fri Feb 11 13:27:52 2005 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Fri, 11 Feb 2005 11:27:52 -0700 Subject: problem with tk and pass by refference (I think :) Message-ID: Greetings, Maybe someone out there can lend me an eye? I've been stumped, banging my head against the wall trying to figure out why my script doesn't work. I've tried every thing I could think of, even unecessarily complicated mumbo-jumbo. Let me show you a snippet and then I'll explain what's happening. for verse in self.activeSong['verses']: verseNum = self.activeSong['verses'].index(verse) activeSong = self.activeSong.copy() firstLine = split(verse, '\n')[0] button = Button(self.songWin, text=verse, command=(lambda: self.showVerse(verseNum)) ) button.config(bg='grey') button.pack(expand=YES, fill=BOTH, side=TOP) self.verseButtons.append(button) This is as simple app for displaying the words of a song with an overhead projector. When you click on a song the program reads it and creates a button for each verse. When you click the button it is supposed to display that verse. As you can see above I am trying to call the showVerse method and pass it the verseNum. The problem I am having is that every button gets assigned the verseNum for the last verse that gets processed. That is to say, if a sone has 4 verses every button shows verse for, a 6 verse song loads verse 6 for every button, etc. I think that the value is getting passed by reference, so it gets updated with every iteration. I have seriously tried every thing I can think of to fix this. If any one has any thoughts I would really appreciate it. Thanks very much! -Matthew From news at NOwillmcguganSPAM.com Thu Feb 17 12:13:11 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Thu, 17 Feb 2005 17:13:11 +0000 Subject: Creating properties with decorator like syntax In-Reply-To: <4214d006$0$8747$db0fefd9@news.zen.co.uk> References: <4214d006$0$8747$db0fefd9@news.zen.co.uk> Message-ID: <4214d0a7$0$8747$db0fefd9@news.zen.co.uk> Will McGugan wrote: > Hi, > > Is there any way of making properties using a decorator? The current way > of creating a property seems inelegant. > > Something like this imaginary snippit would be nice, IMHO. > > class C(object): > @make_property > def x(self): > def getx(self): return self.__x > def setx(self, value): self.__x = value > def delx(self): del self.__x > Posted too soon. Played with the above and got something which works. def make_property( func ): return property( *func() ) class C(object): def __init__(self): __x= 1 @make_property def x(): def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x return getx,setx,delx c= C() c.x= 5 n= c.x + 5 Good idea, or bad? Will McGugan From devnull at kma.eu.org Tue Feb 1 02:55:02 2005 From: devnull at kma.eu.org (Grumble) Date: Tue, 01 Feb 2005 08:55:02 +0100 Subject: what's OOP's jargons and complexities? In-Reply-To: <873bwjj8fe.fsf@thalassa.informatimago.com> References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> <1107060381.623163.19850@z14g2000cwz.googlegroups.com> <873bwjj8fe.fsf@thalassa.informatimago.com> Message-ID: Pascal Bourguignon wrote: > You forgot to mention the coordinates of your secret mountain compound: > > 28 deg 5 min N, 86 deg 58 min E Mount Everest? From aurora00 at gmail.com Fri Feb 4 15:28:02 2005 From: aurora00 at gmail.com (aurora) Date: Fri, 04 Feb 2005 12:28:02 -0800 Subject: executing VBScript from Python and vice versa References: Message-ID: Go to the bookstore and get a copy of Python Programming on Win32 by Mark Hammond, Andy Robinson today. http://www.oreilly.com/catalog/pythonwin32/ It has everything you need. > Is there a way to make programs written in these two languages > communicate > with each other? I am pretty sure that VBScript can access a Python > script > because Python is COM compliant. On the other hand, Python might be able > to > call a VBScript through WSH. Can somebody provide a simple example? I > have > exactly 4 days of experience in Python (and fortunately, much more in > VB6) > > Thanks. > From ncoghlan at iinet.net.au Thu Feb 10 08:37:58 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 10 Feb 2005 23:37:58 +1000 Subject: Testing conditions. In-Reply-To: References: Message-ID: <420B63B6.1040006@iinet.net.au> Ray Gibbon wrote: > Before I resign myself to the inevitable, 'that's the way it is - get used > to it', I'd just like to scratch it once. But, before I try walking on very > thin ice, I want to ask whether there are expectations of some future > changes which address these issues? > > I note PEP 3000 is silent on this matter, and PEP 315, though related, is > not relevant. The nicest idea I've seen along these lines is: if as : pass elif as : pass else: pass and while as : pass It's based on the idea of using 'as' to name caught exceptions in Python 3k (which is in turn based on the use of as for renaming in import statements) However, like allowing assignment, this approach breaks down as soon the thing you want bound and the condition you want to test aren't the same, and then you have to switch back to the 'bind before test' approach. Which means a general solution has to allow *three* parts, not two: 1. A conditional expression And optionally: 2. A subexpression to be named 3. The name for the subexpression That is, something like: if using as : pass elif using as : pass else: pass and while using as : pass (In the degenerate case where the condition is the thing we want named, it may be possible to make the 'using' clause optional. If not, then the first expression is simply ) But such a solution involves an entirely new keyword and there's the eternal question of whether the feature is needed *enough* to justify complicating the syntax. The while case isn't good justification, since such while loops can usually be converted to a generator function and a pair of for loops easily enough. if/elif is slightly more promising as a motivation - having to convert to nested if statements if you discover you need access to some part of the condition test is a pain and the nested if's are harder to read that if/elif. How common is that situation in reality, though? I can't think of a case where I've had to use more than one nested if statement due to the 'problem' of not being to do an embedded assignment. *shrug* The issue has never really bothered me in practice. Heck, I often don't use nested assignment even in C, since the buggers can be so damn hard to read. That's mainly due to the = vs == problem though :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ilias at lazaridis.com Wed Feb 23 10:01:21 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Wed, 23 Feb 2005 17:01:21 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: <421c91c8$0$44647$a1866201@visi.com> References: <874qg6937w.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <37uk2kF5gv38bU1@individual.net> <421c91c8$0$44647$a1866201@visi.com> Message-ID: Grant Edwards wrote: [...] > Um, you realize that nobody in this thread takes you the least > bit seriously and people are just poking you with a stick to > watch you jump? jump: [EVALUATION] - E02 - Support for MinGW Open Source Compiler Essence: http://groups-beta.google.com/group/comp.lang.python/msg/5ba2a0ba55d4c102 . -- http://lazaridis.com From jamesthiele.usenet at gmail.com Sun Feb 6 14:28:37 2005 From: jamesthiele.usenet at gmail.com (jamesthiele.usenet at gmail.com) Date: 6 Feb 2005 11:28:37 -0800 Subject: loops -> list/generator comprehensions Message-ID: <1107718117.221204.80410@l41g2000cwc.googlegroups.com> I wrote this little piece of code to get a list of relative paths of all files in or below the current directory (*NIX): walkList = [(x[0], x[2]) for x in os.walk(".")] filenames = [] for dir, files in walkList: filenames.extend(["/".join([dir, f]) for f in files]) It works fine, I don't need to change it, but I know there is a one liner list/generator comprehension to do this - I'm just not well enough versed in comprehensions to figure it out. Can someone please show me what it is? Even better, is there a generalized way to transform simple loops into comprehensions that someone can point me to? james From Enoch at theFort.org Fri Feb 11 12:52:44 2005 From: Enoch at theFort.org (Enoch) Date: Fri, 11 Feb 2005 17:52:44 +0000 Subject: [N00B] What's %? In-Reply-To: <614c778e.0502100938.6665cb52@posting.google.com> References: <614c778e.0502100938.6665cb52@posting.google.com> Message-ID: administrata wrote: > Hi! it's been about a week learning python! > I've read 'python programming for the absolute begginer' > I don't understand about % like... > > 107 % 4 = 3 > 7 % 3 = 1 > > I'm confused with division :/ > Please help me... > > thx 4 reading. % means modulus, which is simply, the remainder of A divided by B so: 7 % 3 = 1 because only two threes go into seven, leaving 1 remainder. Modulus only returns that remainder. And 107 % 4 = 3 because 26 4's go into 107 leaving 3 over. Make sense? Enoch. From lars-www at lycos.com Sun Feb 13 12:28:59 2005 From: lars-www at lycos.com (Lars) Date: 13 Feb 2005 09:28:59 -0800 Subject: Alternative to raw_input ? References: Message-ID: <1108315739.704768.134290@c13g2000cwb.googlegroups.com> Then may I suggest the keeping-it-simple approach: def myGetch(): ....raw_input("Press Enter to continue") (sorry about the dots, I'm using google groups) Lars From dave at pythonapocrypha.com Sun Feb 13 22:35:29 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sun, 13 Feb 2005 20:35:29 -0700 Subject: For American numbers In-Reply-To: References: <420e7376$1@nntp0.pdx.net> <420fb4e6$0$16575$9b622d9e@news.freenet.de> Message-ID: <42101C81.7070109@pythonapocrypha.com> Peter Hansen wrote: > Martin v. L?wis wrote: > >> Peter Hansen wrote: >> >>> For the rest of the computer world, unless I've missed >>> a changing of the guard or something, "kilo" is 1024 >>> and "mega" is 1024*1024 and so forth... >> >> In case this isn't clear yet: you have missed a changing >> of the guard or something. "kibi" is 1024, "mebi" is >> 1024*1024 and so forth. "kilo" is 1000. > > Yeah, saw the link. The IEC doesn't speak for me, I'm afraid. > And as the wikipedia notes, "As of 2005 this naming convention > has not gained widespread use." > > I suspect I and many others will go to our graves not being > comfortable mebbling and gibbling over our bytes, though > we'll probably spend a lot of time kibbling over the issue... Indeed - it's a little early to say that we've missed a changing of the guard! :) Multiple definitions aside, "kilo" and "mega" are far too entrenched - even if I could manage to say "kibibyte" with a straight face, I'd get nothing but blank stares in return. -Dave From mwm at mired.org Mon Feb 7 21:45:57 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 07 Feb 2005 20:45:57 -0600 Subject: Big development in the GUI realm References: <1107795145.049239.73450@l41g2000cwc.googlegroups.com> <5ocf01hmspufk3iusvm35p6hj4mes5heke@4ax.com> <1107815270.149109.80420@c13g2000cwb.googlegroups.com> Message-ID: <86ekfr93bu.fsf@guru.mired.org> "Kartic" writes: > Is there a "GPL for Dummies" out there??? :-) > > Sorry if I am asking a question that has already been asked/answered in > another form. > > In any case, let's say I use Python to create an application that uses > some module that is GPL. So what are my options? > 1. Distribute my app as closed source but with source, available upon > request and clearly stated so in my license, for the GPL'ed module. But > the code to my app only is not available as it is closed source. You can't do this one. At least, that's the stand that the FSF is taking. I wonder about distributing an installation tool that grabs the GPL'ed module from it's "standard" location and just installing it? That way, you're not distributing any GPL'ed code, so your code can be distributed however you want. It would seem that that would have to be legal, otherwise apt-get and CPAN would be legally problematical. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From philippe at philippecmartin.com Mon Feb 7 12:48:10 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 07 Feb 2005 17:48:10 GMT Subject: socket question References: <36pm9uF53qlqdU1@individual.net> Message-ID: Thanks you! that did it. PS: the 'wrong' info I got seems to be in the official howtos http://www.amk.ca/python/howto/sockets/ Regards, Philippe On Mon, 07 Feb 2005 18:23:28 +0100, Diez B. Roggisch wrote: >> A couple things to notice: we used socket.gethostname() so that the >> socket would be visible to the outside world. If we had used s.bind(('', >> 80)) or s.bind(('localhost', 80)) or s.bind(('127.0.0.1', 80)) we would >> still have a "server" socket, but one that was only visible within the >> same machine. > > This is wrong. There is a difference between passing '' and 'localhost'. The > latter binds the socket only to the ip 127.0.0.1, where '' binds it to all > available ips. > >> My problem is that I cannot connect to my server if the client is not on >> the same PC (although I'm doing the above). >> Also: >> 1) my server has more than one IP addresses >> 2) my server does not have any DNS name >> ... so I want to connect to an IP address that I can ping but has no >> name. >> How can I do that ? > > Pass the ip as hostname (as string like "192.168.1.10") From steve at holdenweb.com Wed Feb 2 18:39:45 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 02 Feb 2005 18:39:45 -0500 Subject: Generating .pyc/.pyo from a make file In-Reply-To: <2h48d2-8481.ln1@eskimo.tundraware.com> References: <4308d2-0801.ln1@eskimo.tundraware.com> <42015a85_1@news.arcor-ip.de> <4201607f_2@news.arcor-ip.de> <2h48d2-8481.ln1@eskimo.tundraware.com> Message-ID: Tim Daneliuk wrote: > Steve Holden wrote: > >> Roland Heiber wrote: >> >>> Tim Daneliuk wrote: >>> >>>> It does - thanks. One more question: Are pyc and pyo file portable >>>> across operating systems? I suspect not since I generated a pyo >>>> on a FreeBSD machine that will not run on a Win32 machine. I was >>>> under the impression that "compiled" meant optimized byte code that >>>> was portable across implementations, but it looks to not be the case... >>>> >>> >>> Hi, >>> >>> ..pyc's should be, cause it's standard python-bytecode, if you use >>> massive optimizations it depends not on the os but on the underlying >>> cpu/architecture ... >>> >>> So long, Roland >> >> >> >> You probably tried to use a bytecode file from *one* version of Python >> with an interpreter of another version. Python actually checks the >> first four bytes of the .pyc file for a compatible "magic number" >> before accepting the file for execution. >> >> regards >> Steve > > > Aha! Exactly ... and that makes perfect sense too. D'oh! I guess a > better > distribution strategy would be to have the installation program generate > the pyo > file at installation time... > > Thanks - > That's what most sensible distributions do. regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From keith.veleba at gmail.com Wed Feb 9 11:01:15 2005 From: keith.veleba at gmail.com (Keith Veleba) Date: 9 Feb 2005 08:01:15 -0800 Subject: Synchronizing methods of a class References: <1107806222.385926.235060@o13g2000cwo.googlegroups.com> Message-ID: <1107962099.030652.73660@g14g2000cwa.googlegroups.com> Chris, Q&D example of <>.__dict__.items() not working for me: >>> import threading >>> class A(threading.Thread): ... def __init__(self): ... threading.Thread.__init__(self) ... def one(self): ... pass ... def two(self): ... pass ... >>> a = A() >>> a.__dict__.items() [('_Thread__block', , 0)>), ('_Thread__name', 'Thread-1'), ('_Thread__daemonic', False), ('_Thread__started', False), ('_Thread__target', None), ('_Thread__kwargs', {}), ('_Verbose__verbose', False), ('_Thread__args', ()), ('_Thread__stopped', False), ('_Thread__initialized', True)] Neither function I added to the A class shows up. However, I think it's because I'm using an instance of my class vs. just referencing the class type. If I type: A.__dict__items() I get the correct list: [('__module__', '__main__'), ('__doc__', None), ('two', ), ('__init__', ), ('one', )] In any case, thanks for the example reference. That's helps me improve my idea, and I will most likely use the methods in it. Keith From tchur at optushome.com.au Tue Feb 8 08:41:41 2005 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 09 Feb 2005 00:41:41 +1100 Subject: Big development in the GUI realm In-Reply-To: References: <200502072347.j17NlPnh012281@mail07.syd.optusnet.com.au> Message-ID: <4208C195.1000104@optushome.com.au> Fredrik Lundh wrote: >Tim Churches wrote: > > > >>>and how exactly are you going to load a DLL from an EXE file with- >>>out "mixing, including, or combining" the two? >>> >>> >>You can't, but as long as that "mixing, including, or combining" only occurs at runtime, >>the GPL itself specifically says that is out of scope and the GPL does not apply. Their >>words, not mine - to quote (yet again): >> >>"Activities other than copying, distribution and modification are not covered by this >>License; they are outside its scope. The act of running the Program is not restricted,..." >> >> > >except that if *you* set things up so the code is combined when run, *you* are >copying, distributing, and/or modifying the program in order to mix, include and/or >combine your work with the GPL:ed work. > >if you leave all that to the user, you're clear. > > Yes, that is what I, and others, have been saying, and doing, all along. Our Mozilla Public Licensed Python application imports (but contains no code from) a GPLed third-party Python module at runtime, but we don't distribute that module, we just tell users to obtain it independently and install it on their systems. >(relying on word games is a lousy legal strategy in most parts of the world) > > (Gee, I thought that word games were the entire basis of much legal endeavour in most parts of the world. Patent specifications in particular spring to mind.) Less flippantly, I agree, and I find it Hanlonesque that the FSF continues to promote a license which is at best unclear and at worst completely contradictory on the issue of whether dynamic, runtime linking or calling does or doesn't fall under its scope. Others have thought the same - as we have seen, Linus Torvalds felt compelled to include an addition to the GPL when licensing the Linux kernel to make it crystal clear that making runtime system calls to the kernel did not fall under the scope of the kernel license. I would urge anyone who has published a GPLed Python module to add a similar extension in order to clarify their use of the GPL in this regard. Tim C From Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org Sat Feb 5 03:42:10 2005 From: Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org (Alexander) Date: Sat, 05 Feb 2005 11:42:10 +0300 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> Message-ID: Hi, Alex! 31 jan 2005 at 13:46, Alex Martelli wrote: (sorry for the delay,my mail client don't highlight me your answer) AM> Since the lack of declarations is such a crucial design choice for AM> Python, then, given that you're convinced it's a very bad thing, I AM> suggest you give up Python in favor of other languages that give you AM> what you crave. Well, I like Python. But, as every language I know, it have some bad sides which I don't like. One of them in Python is lack of variable declarations, another (this problem is common with C/C++) is: === >>>print 1/2 0 === (I understand why it is so, but I don't like it anyway. Such behaviour also can cause some hard-to-find-bugs) AM> issue for you. Therefore, using Python, for you, would mean you'd be AM> fighting the language and detesting its most fundamental design AM> choice: and why should you do that? There are zillions of languages AM> -- use another one. Thank you for advice:) >> Pascal, or special syntax in C. It can cause very ugly errors,like >> this: epsilon=0 S=0 while epsilon<10: S=S+epsilon >> epselon=epsilon+1 print S It will print zero, and it is not easy to >> find such a bug! AM> Actually, this while loop never terminates and never prints anything, Oh, I don't find it:) AM> so that's gonna be pretty hard to ignore;-). AM> But, assume the code is AM> slightly changed so that the loop does terminate. In that case...: AM> It's absolutely trivial to find this bug, if you write even the AM> tiniest and most trivial kinds of unit tests. If you don't even have AM> enough unit tests to make it trivial to find this bug, I shudder to AM> think at the quality of the programs you code. Thank you for advice again, I already use different tests in my work and I found them usefull. But! I want to use Python for prototyping. I want to write my algorithms on it, just to see they do almost they must to do. Next, I want to play with them to understand their properties and limitations. If sometimes such a program fall, or not very fast, or sometimes show wrong results, it's not a big problem. So, I use Python like tool for prototyping. After I debug the algorithm and understand it, I can rewrite it on C++ (if I need), carefully, paying attention to speed, side effects, memory requirements, and so on. With full testing, of course. Hence, from "language for prototyping" I need next features: 1. I want to think about algorithm (!!!), and language must help me to do it. It must take care on boring things like memory management, garbage collection, strict type inference, my typos. It must provide easy-to-use packages for many of my low-level needs. And so on. 2. goto 1:) Python is realy very good for such demands. Except one: it force me to type variable names carefully:) In other words, divert my attraction from algorithm, to typing. AM> Even just focusing on AM> typos, AM> think of how many other typos you could have, besides the misspelling AM> of 'epsilon', that unit tests would catch trivially AND would be AM> caught in no other way whatsoever -- there might be a <= where you AM> meant a <, a 1.0 where you meant 10, a - where you meant a +, etc, AM> etc. AM> You can't live without unit tests. And once you have unit tests, the AM> added value of declarations is tiny, and their cost remains. Fine! Let interpreter never show us errors like division by zero, syntax errors, and so on. If file not found, library don't need to say it. Just skip it!!! Because every, even simple, test will find such bugs. Once you have unit tests, the added value of is tiny, and their cost remains. :) Or, maybe, we will ask interpreter to find and prevent as many errors as he can? And, one more question: do you think code like this: var S=0 var eps for eps in xrange(10): S=S+ups is very bad? Please explain your answer:) AM> Python has no declarations whatsoever. If you prefer Visual Basic, I AM> strongly suggest you use Visual Basic, rather than pining for Visual AM> Basic features in Python. If and when your programming practices ever AM> grow to include extensive unit-testing and other aspects of agile AM> programing, THEN you will be best advised to have a second look at AM> Python, and in such a case you will probably find Python's strengths, AM> including the lack of declarations, quite compelling. Uh! And you! And you!... And you must never even come close to any languages with variable declaration! Even to Visual Basic! :) AM> brain". I find it's true: Python gets out of my way and let me solve AM> problems much faster, because it fits my brain, rather than changing AM> the way I think. I'm agree with you. AM> If Python doesn't fit YOUR brain, for example because your brain is AM> ossified around a craving for the declaration of variables, then, AM> unless you're specifically studying a new language just for personal AM> growth purposes, I think you might well be better off with a language AM> that DOES, at least until and unless your brain changes by other AM> means. Thank you for explanation of your opinion. Alexander, zatv at bk.ru From jacek.generowicz at cern.ch Tue Feb 1 04:55:00 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 01 Feb 2005 10:55:00 +0100 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1107188359.375703.110590@f14g2000cwb.googlegroups.com> <1gr9lyc.1rrm543162uefN%aleaxit@yahoo.com> <1107229287.315380.222790@c13g2000cwb.googlegroups.com> Message-ID: "Michael Tobis" writes: > In fact, I'd recommend a paragraph early in the Nutshell book saying > "there are no declarations, no use strict, no implicit none, sorry, > forget it", It would have to be a pretty long paragraph, if it were to list all the things that you do NOT find in Python. > and an index listing under "declarations" pointing to a detailed > exegesis of their nonexistence. Think about this. You are either asking that the book's author anticipate your personal expectations, and write the book to cater for YOUR PERSONAL expectiations ... or you are asking for a book with an inifititely long index. The list of things absent from Python is infinite. > It would have saved me some time. You don't want a book, you want a personal tutor. From gomoSINSPAM at datafull.com Thu Feb 17 15:07:45 2005 From: gomoSINSPAM at datafull.com (=?iso-8859-1?q?Gonzalo_Sainz-Tr=E1paga_=28GomoX=29?=) Date: Thu, 17 Feb 2005 17:07:45 -0300 Subject: Local module installation Message-ID: Hi, I'm starting to develop a Web application in Python for the first time. I am considering some modules like SQLObject and Validators (by Ian Bicking). The problem is, i'm planning to host the site on a shared hosting provider with mod_python, and therefore I can't install the modules site-wide. My question is: How do I install the (distutils-packaged) modules inside my WWW root in order for them to be found when I try to import them? I have a config.py script on my WWW root that is imported on every other script. As you can see I'm quite a n00b with this (coming from PHP), so any suggestions would be greatly appreciated. Thanks in advance, GomoX From tjreedy at udel.edu Tue Feb 15 17:25:17 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Feb 2005 17:25:17 -0500 Subject: Calling a function from module question. References: Message-ID: "Sean" wrote in message news:UTsQd.32669$6u.27954 at fed1read02... > import module_name.py leave off the .py Irmen answered your main question. Terry J. Reedy From http Fri Feb 4 00:53:31 2005 From: http (Paul Rubin) Date: 03 Feb 2005 21:53:31 -0800 Subject: advice needed for simple python web app References: <5cqdnZX-cZ9ca5_fRVn-3Q@rogers.com> <7xr7jxnddh.fsf@ruckus.brouhaha.com> Message-ID: <7xis58c1lw.fsf@ruckus.brouhaha.com> "Dan Perl" writes: > The application is just something I'm playing with to learn a little bit on > web apps. It uses an HTML form to send an email. The form takes inputs > like the From:, To: and Subject: fields and a text field. Be careful of exposing that script to the internet. Spammers will exploit it. From fredrik at pythonware.com Tue Feb 8 11:46:18 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Feb 2005 17:46:18 +0100 Subject: Effbot's SimpleXMLWriter fails when py2exe'd References: <1107880337.524216.180440@g14g2000cwa.googlegroups.com> Message-ID: Erik Bethke wrote: > So I have been using Effbot's XML stuff a lot! And I have been using > py2exe, pygame and wxPython all mixed together... > > I am getting this strange error log when writing XML files with his XML > writer. It appears to be fouling up on the encoding, ONLY in the exe > version. Runs fine and great as a python script. you need to explicitly tell py2exe to include the relevant encodings (from the encodings package in the standard library). adding a simple import encodings.utf_8 to your script might help. if not, see the following wiki page: http://starship.python.net/crew/theller/moin.cgi/EncodingsAgain From MrJean1 at gmail.com Wed Feb 16 14:52:08 2005 From: MrJean1 at gmail.com (python) Date: 16 Feb 2005 11:52:08 -0800 Subject: How can I get the source file name and current line number inside executed C-function In-Reply-To: References: Message-ID: <1108583528.498025.103450@f14g2000cwb.googlegroups.com> Below is a function to find the caller's file name, line number, etc. inside Python. Maybe this works for your case. /Jean Brouwers - import traceback - - def caller(up=0): - '''Get file name, line number, function name and - source text of the caller's caller as 4-tuple: - (file, line, func, text). - - The optional argument 'up' allows retrieval of - a caller further back up into the call stack. - - Note, the source text may be None and function - name may be '?' in the returned result. In - Python 2.3+ the file name may be an absolute - path. - ''' - try: # just get a few frames - f = traceback.extract_stack(limit=up+2) - if f: - return f[0] - except: - if __debug__: - traceback.print_exc() - pass - # running with psyco? - return ('', 0, '', None) - - - if __name__ == '__main__': - print caller() Marek Prerovsky wrote: > Hello, > > I implemented some Python functions in my C/C++ code. I need to know the Python source file name and line number of just executed > Python command which calls my function. > How can I get this information inside my C/C++ function? > > Thanks for any help. > > Marek From gargonx at gmail.com Sun Feb 13 14:57:59 2005 From: gargonx at gmail.com (gargonx) Date: 13 Feb 2005 11:57:59 -0800 Subject: help please In-Reply-To: References: <1108254434.871062.314510@g14g2000cwa.googlegroups.com> <1108260752.791847.180060@l41g2000cwc.googlegroups.com> Message-ID: <1108324679.451793.147890@z14g2000cwz.googlegroups.com> yes the items in std are always single to single, and ext single to double. basicly the ext are refernce to the std itmes. the second character in ext is a number depending on how far it is from the item in std. this is just a simple encoding program. From steve at holdenweb.com Thu Feb 3 13:12:00 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Feb 2005 13:12:00 -0500 Subject: global variables In-Reply-To: References: <1107385488.822768.317250@l41g2000cwc.googlegroups.com> <1107388493.465599.140480@g14g2000cwa.googlegroups.com> <3YSdnYVEmOCW8pzfRVn-sg@comcast.com> <1107391350.933650.321440@z14g2000cwz.googlegroups.com> <1107392092.290042.221600@c13g2000cwb.googlegroups.com> Message-ID: <%UtMd.102705$Jk5.39995@lakeread01> Steven Bethard wrote: > Steve Holden wrote: > >> M.E.Farmer wrote: >> >>> Ok it has been a long day, >>> In my reply to Steven Bethard , Steve should read Steven ;) >>> >>> M.E.Farmer >>> >> Well, since he signs himself "Steve" too I guess we'll just have to >> put up with the ambiguities. Or perhaps, given my (lack of) typing >> skill, I should just start signing myself "Stvev"? >> >> regards >> Steve > > > Or I can stop correcting it every time I type STeve[1]. ;) > > STeve > > [1] But of course, you probably do the same thing too. ;) Indeed. I defy anyone to be a crappier typist then me. Stevbe - see? -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From pobrien at orbtech.com Mon Feb 14 11:20:11 2005 From: pobrien at orbtech.com (Pat) Date: 14 Feb 2005 08:20:11 -0800 Subject: - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: <1108398011.213872.321390@o13g2000cwo.googlegroups.com> Wow! I must say, I'm less than impressed with the responses so far. I know Ilias can give the impression that he is just trolling, but I can assure you he is not. At least, not in this case. ;-) So in an effort to make some headway, I'm going to try to summarize the current state of affairs. The bottom line is that compiling C extension modules on the Windows platform for Python 2.4 is, today, a royal pain in the ass. Period. Here's why. The main challenge is that extensions must be compiled using the same runtime dll as that used by the Python interpreter itself. The official Windows binary installation of Python 2.3.5 and its predecessors was compiled with one MS product, which was fairly easy to support with minGW, but Python 2.4 was compiled with the newer .NET compiler. Unfortunately, compiling extensions for Python 2.4 with the free MS tools is not trivial, as evidenced by Mike Fletcher's very thorough document on the subject: Python 2.4 Extensions w/ the MS Toolkit Compiler http://www.vrplumber.com/programming/mstoolkit/ In addition, there are some unresolved licensing questions concerning the .NET runtime file for extensions (msvcr71.dll): http://mail.python.org/pipermail/python-dev/2005-February/051393.html There have been extensive discussions about these issues on the Python-Dev mailing list over the past couple of months (mostly in December, but continuing to the present - see http://mail.python.org/pipermail/python-dev/2004-December/thread.html as a starting point), which seem to have fizzled out or at least haven't resolved much. The discussions made reference to work that has already been done to allow Python to be compiled with minGW: pyMinGW is a patch to Python source that aims to get Python to compile under MinGW http://jove.prohosting.com/iwave/ipython/pyMinGW.html I've not seen any commentary on the quality of this patch, so that doesn't appear to be the reason it hasn't been officially adopted. Reading all the threads from Python-Dev has not enlightened me at all as to what the underlying reason is for not adopting these changes. Maybe there are good reasons, I just couldn't find them, and I'm usually pretty good with Google. A few of you have mentioned that minGW is not an optimizing compiler on the Windows platform, whereas the MS .NET one is. If anyone has information on the performance differences, I'd really appreciate being able to see it, particularly as it applies to Python 2.4. Now, we get to the essence of my particular situation. I've got a project that includes some Python extensions written in C. My users (who are Python developers, but not necessarily hard-core types) need to be able to work out of their local Subversion checkouts. This includes locally compiling these extensions as necessary. I'd like this to work with Python 2.4, and be as painless as possible on my users. I can't expect them to purchase a .NET compiler or go through a bunch of configuration changes. So far, I haven't figured out a good way to support this. I'm open to suggestions. I suspect that my needs are very similar to those of the original poster. Perhaps the issue is in part a matter of minGW catching up with the new MS compilers. My understanding of and experience with Python 2.3.5 and its predecessors has been that Python itself didn't need to be recompiled with minGW, since extensions compiled with minGW linked to the same C runtime dll. So if minGW had support for msvcr71.dll then maybe this problem goes away with Python 2.4 as well. If anyone can shed any light on this situation, it would really help me out. Thanks. -- Patrick K. O'Brien Orbtech http://www.orbtech.com Schevo http://www.schevo.org Pypersyst http://www.pypersyst.org From Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org Wed Feb 9 17:27:09 2005 From: Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org (Alexander) Date: Thu, 10 Feb 2005 01:27:09 +0300 Subject: variable declaration References: Message-ID: Hi, Steve! 07 feb 2005 at 17:51, Steve Holden wrote: >> information about variable S to the memory. I don't find big >> difference. By the way keyword "def" is as bad as "var", from your >> point of view? :) SH> If your colloquial English is good enough to understand the word SH> "bollocks" then you might begin to realize how irritating your SH> arguments are becoming. Well, I have a dictionary. Let's look. "Man with grey bollocks - wise, experienced man".Hm, I'am realy have some experience in some areas:) SH> If, as you suggest, def were a declaration, then it should either not SH> be possible to write SH> if __debug__: SH> def func(x): SH> print x, "is bollocks" if __debug__: ~S=0 S=5 #error in non-debug mode. print S That's not the same I suppose from the beginning, but it also can be helpfull. More exactly, it is not 'variable declaration' but 'variable definition'. >> But, I am friendly, even with my opponents. I think it is my good >> trait. SH> You are, of course, entitled to your opinion, self-serving though it SH> may be. A friendly idiot is still an idiot. No comments. >> Don't be so ... I don't find the equivalent english word. Smth like: >> Take it more easy. SH> Please don't insult the martellibot. It was not an insult. It is not in my rules, as I said before. It's just an advice. "global" is in Python, but he is still alive - hence it's not as big problem as he say. SH> He did, after all, write "Python SH> in a Nutshell" and co-edited the "Python Cookbook", and he has SH> established a reputation with his consistent long-term contribution to SH> Python and this newsgroup. Instead, ask yourself why your remarks SH> engender such a response from a pillar of the Python community. What SH> are your credentials? Well, for python community - 0. Now, you can only read my messages and think about them. After all, idiot who made contribution is still idiot, isn't it? (it's not about A.M., of course) Alexander, zatv at bk.ru From francis.girard at free.fr Sun Feb 6 16:44:42 2005 From: francis.girard at free.fr (Francis Girard) Date: Sun, 6 Feb 2005 22:44:42 +0100 Subject: string issue In-Reply-To: References: Message-ID: <200502062244.42455.francis.girard@free.fr> Yes, I also this that comprehension is the clearer way to handle this. You might also consider the good old "filter" function : ips = filter(lambda ip: '255' not in ip, ips) Francis Girard Le vendredi 4 F?vrier 2005 20:38, rbt a ?crit?: > Thanks guys... list comprehension it is! > > Bill Mill wrote: > >>>>ips = [ip for ip in ips if '255' not in ip] > >>>>ips From deetsNOSPAM at web.de Tue Feb 8 17:19:27 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 08 Feb 2005 23:19:27 +0100 Subject: Confused with methods References: <1grknb0.ygwohl17y6j5yN%aleaxit@yahoo.com> <1grmd4z.1tlm4e61650vedN%aleaxit@yahoo.com> <1grmg8s.17t7tj4180jdj6N%aleaxit@yahoo.com> Message-ID: > No python is not consistent and your continuous repetion doesn't > make it so. To illustrate, here the following code: > > class A: > l = [] > def f(): pass > > a = A() > print a.l is A.l > print a.f is A.f > > which produces: > > True > False Thats only inconsistent from your POV because you refuse to accept that the scope of a function definition does matter. And as usual its a topic of totally unrelevant practical impact and an expression of your strangely deeprooted desire to nitpick at such unrelevant details. Why don't you pick something that really bothers people and see if your skills (that I'm sure exist) can be of use there? -- Regards, Diez B. Roggisch From ruach at chpc.utah.edu Fri Feb 11 15:14:27 2005 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Fri, 11 Feb 2005 13:14:27 -0700 Subject: problem with tk and pass by refference (I think :) In-Reply-To: References: Message-ID: Diez B. Roggisch wrote: > Hi, > > button = Button(self.songWin, text=verse, command=(lambda num=verseNum: > self.showVerse(num)) ) > > should do the trick. The reason is basically that your version kept a > reference to verseNum - and when executed, the value verseNum points to is > the lasts one stored. > > Rebinding the argument to a parameter in the lambda will keep the right > value for each iteration. > > I tried it but I got a syntax error. The interpreter didn't like the equals sign in the lambda. I am using python 2.3.4. Is there another way of writing that? thanks From carl.manaster at gmail.com Thu Feb 3 12:47:43 2005 From: carl.manaster at gmail.com (carl.manaster at gmail.com) Date: 3 Feb 2005 09:47:43 -0800 Subject: Integrated Testing - Peppable? In-Reply-To: <1102ntulmp5sud3@news.supernews.com> References: <1107373949.960435.212020@z14g2000cwz.googlegroups.com> <1102ntulmp5sud3@news.supernews.com> Message-ID: <1107452863.177567.95250@o13g2000cwo.googlegroups.com> Thanks, John, I think there's a true, powerful, difference between inline tests and external (albeit adjacent) ones. I think the developer experience should be superior with inline tests for several reasons: - during initial development, without any navigation beyond the Enter key, you flow directly from writing the test to writing the code that implements it; - later, on review, the tests have not moved away from the code they test, so: ----if there are errors, the alarms show up right beside the erroneous code; ----if you are looking for examples of how to call a routine, the example is right there. But I take your point; this doesn't belong in Python. OK. Thanks. Peace, --Carl From mahs at telcopartners.com Fri Feb 18 09:27:15 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 18 Feb 2005 06:27:15 -0800 Subject: Solution for architecure dependence in Numeric ? In-Reply-To: <67ll9mymqu.fsf@achernar.i-did-not-set--mail-host-address--so-shoot-me> References: <67ll9mymqu.fsf@achernar.i-did-not-set--mail-host-address--so-shoot-me> Message-ID: "Johannes Nix|Johannes.Nix"@uni-oldenburg.de wrote: > Hi, > > I have a tricky problem with Numeric. Some time ago, I have generated > a huge and complex data structure, and stored it using the cPickle > module. Now I want to evaluate it quickly again on a workstation > cluster with 64-Bit Opteron CPUs - I have no more than three days to > do this. Compiling Python and running Numeric has been no problem at > all. However, I get an error message when accessing the data pickled > before. (I can load it regularly on 32 bit computers, but it is a > quite complex data object, so I really don't want to store every > element as ASCII data). The problem seems to be with 64 Bit integers > (with 32-bit-floats, no problem was observed). > > This looks like that (from the Unix command shell): > > > jnix at 32bithost:~> python ~/python/test_npickle.py -dump test.pck > jnix at 32bithost:~> python ~/python/test_npickle.py test.pck > [0 1 2 3 4 5 6 7 8 9] > jnix at 32bithost:~> ssh 64bithost python ~/python/test_npickle.py test.pck > Traceback (most recent call last): > File "/home/jnix/python/test_npickle.py", line 16, in ? > a = cPickle.load(file(filename)) > File "/home/jnix/lib/python2.4/SuSE-9.0/x86_64/Numeric/Numeric.py", line 520, in array_constructor > x.shape = shape > ValueError: ('total size of new array must be unchanged', , ((10,), 'l', '\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t\x00\x00\x00', 1)) > > > also I get: > jnix at 32bithost:~> python -c "import Numeric; print Numeric.arange(0).itemsize()" > 4 > jnix at 64bithost:~> python -c "import Numeric; print Numeric.arange(0).itemsize()" > 8 > > > The script used to produce the example above is: > > ------------------------------------------------------------------------- > #/usr/bin/python > # -*- coding: latin1 -*- > > import Numeric > import cPickle > import sys > > if len(sys.argv) > 1 and sys.argv[1] == '-dump': > filename = sys.argv[2] > binary=1 > a = Numeric.arange(10) > cPickle.dump(a, file(filename,'w',binary)) > > else: > filename = sys.argv[1] > a = cPickle.load(file(filename)) > print a > > > --------------------------------------------------------------------- > > > So what would you suggest ? Can I hack Numeric to assume non-native > 32 bit integer numbers ? > > Many thanks for any help, > > Johannes It might be worth posting to the Numeric mailing list, mirrored at http://news.gmane.org/gmane.comp.python.numeric.general From aleaxit at yahoo.com Sun Feb 6 17:56:07 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 6 Feb 2005 23:56:07 +0100 Subject: Python versus Perl ? References: <1107695949.247611.272800@g14g2000cwa.googlegroups.com> <1107726328.158314.265680@o13g2000cwo.googlegroups.com> Message-ID: <1grl63x.1f2tzwz1q984vpN%aleaxit@yahoo.com> snacktime wrote: > The one drawback coming from the perl world is that you don't have as > many options when it comes stuff like application frameworks, and some URK -- _my_ feeling is that we have entirely *too many* options for stuff like web application frameworks, GUI toolkits, XML processing, ... Alex From aleaxit at yahoo.com Mon Feb 7 10:44:09 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 7 Feb 2005 16:44:09 +0100 Subject: Confused with methods References: <1grknb0.ygwohl17y6j5yN%aleaxit@yahoo.com> <1grmd4z.1tlm4e61650vedN%aleaxit@yahoo.com> Message-ID: <1grmg8s.17t7tj4180jdj6N%aleaxit@yahoo.com> Antoon Pardon wrote: > Yes it is inconsistent with the rest of python. That you found > a subset in which it is consistent doesn't change that. > > And what if you do: > > c = C() > c.f = g > > > The fact that a function in a class performs a lot of magic if > it is called through an instance, that isn't performed otherwise, > makes python inconsistent here. You may like the arrangement > (and it isn't such a big deal IMO) but that doesn't make it consistent. Any descriptor (be it a function or otherwise) has its __get__ method called, when _accessed_ by attribute syntax, if and only if that descriptor is in a class. _ALL_ of Python is perfectly consistent on this point, and if I didn't already know the kind of crazy and obviously false assertions that you post *QUITE* consistently, I would be astonished to see you claim otherwise. Knowing your posts, this latest idiocy is perfectly "par for the course". "A lot of magic" is simply a stupid and imprecise way to describe "the __get__ method gets called". Saying that any of this happens when the function is CALLED is a definitely more serious mistake, since it's absolutely obvious that the __get__ method is called when the function (or any other attribute) is *ACCESSED* -- the call operation (on whatever object __get__ returns) happens AFTERWARDS. Why you, and a few other habitual trolls, keep lowering the signal to noise ratio of this newsgroup with your blatherings, I don't know; I'm sure this behavior must be giving you guys some kind of satisfaction. Whether the damage you do to the clarity of the issues, and to the understanding of newbies who are unfortunate enough to read and trust the many imprecise and/or utterly false assertions you keep making, with totally unjustified airs of competence, is part of your jollies, or just a side effect you don't care a whit about, I don't know either. Guess I'll just killfile you for another month now -- wish MacSOUP had a simple way to to permanent killfiling, since it's pretty obvious by now that it's quite unlikely you'll even post anything worthwhile at all. Alex From rigga at hasnomail.com Sun Feb 27 12:02:00 2005 From: rigga at hasnomail.com (Rigga) Date: Sun, 27 Feb 2005 17:02:00 GMT Subject: Need help running external program Message-ID: Hi, I am running the line of code below from a shell script and it works fine, however I am at a total loss on how i can run it from within a Python script as every option I have tried fails and it appears to be down to the escaping of certain characters. wget -q www.anywebpage.com -O - | tr '\r' '\n' | tr \' \" | sed -n 's/.*url="\([^"]*\)".*/\1/p' I want to use the above code in my program by using popen2 so i can query the results i.e. output, input = popen2("the code here") print output Any help would be appreciated. Many thanks RiGGa From steven.bethard at gmail.com Mon Feb 28 13:32:22 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 28 Feb 2005 11:32:22 -0700 Subject: naming convention for scalars, lists, dictionaries ... In-Reply-To: <1109613115.760962.292360@z14g2000cwz.googlegroups.com> References: <1109613115.760962.292360@z14g2000cwz.googlegroups.com> Message-ID: <3YydnR3xNd4k_r7fRVn-3g@comcast.com> beliavsky at aol.com wrote: > Since Python does not have declarations, I wonder if people think it is > good to name function arguments according to the type of data structure > expected, with names like "xlist" or "xdict". In general, I find that naming collections for their contents is much more useful than some abbreviated type prefix. However, while I don't name objects by their type, I do tend to name iterables with plurals (e.g. "words", "feature_indices", "events", etc.) and I typically suffix mapping types with "map" (e.g. "word_index_map", "event_relation_map", "prime_factor_map", etc.) STeVe From roy at panix.com Sat Feb 5 08:31:22 2005 From: roy at panix.com (Roy Smith) Date: Sat, 05 Feb 2005 08:31:22 -0500 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> Message-ID: In article , Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org (Alexander Zatvornitskiy) wrote: > And, one more question: do you think code like this: > > var S=0 > var eps > > for eps in xrange(10): > S=S+ups > > is very bad? Please explain your answer:) Let me answer that by way of counter-example. Yesterday I was writing a little perl script. I always use "use strict" in perl, which forces me to declare my variables. Unfortunately, my code was giving me the wrong answer, even though the interpreter wasn't giving me any error messages. After a while of head-scratching, it turned out that I had written "$sum{x} += $y" instead of "$sum{$x} += $y". The need to declare variables didn't find the problem. I *still* needed to test my work. Given that I needed to write tests anyway, the crutch of having to declare my variables really didn't do me any good. From news at NOwillmcguganSPAM.com Sun Feb 27 07:03:15 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Sun, 27 Feb 2005 12:03:15 +0000 Subject: Googlewhacker In-Reply-To: <4221b671$0$8752$db0fefd9@news.zen.co.uk> References: <4221b671$0$8752$db0fefd9@news.zen.co.uk> Message-ID: <4221b704$0$8752$db0fefd9@news.zen.co.uk> Will McGugan wrote: > Hi folks, > > Has anyone seen 'Googlewhack Adventure'? > > http://www.davegorman.com/googlewhack.htm > > I wrote a script to generate Googlewhacks - thought I'd share it with > you. I'd better stop running it as I fear Google may ban my IP for > making 20 searches a seconds.. Oops, wrong script.. Will -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: googlewhack.py URL: From tjreedy at udel.edu Sun Feb 6 03:30:08 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 6 Feb 2005 03:30:08 -0500 Subject: [EVALUATION] - E01: The Java Failure - May Python Helps? References: Message-ID: "Ilias Lazaridis" wrote in message >> Then 'print html_doc_instance' can print the html doc corresponding to >> the object model. > > I understand this procedure. > > I would like to use a standard way, which uses the standard metadata > [implicit/explicit defined]. > > Does such standard exist? I am not sure of what *you* mean by 'standard way'. That is probably because Python and the community is not big on 'standard ways' other than what is specified in the two reference manuals. And even then, Python is intentionally flexible in various ways (though not all). So the answer to your question is probably 'no'. Terry J. Reedy From kent3737 at yahoo.com Sun Feb 6 07:34:07 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Sun, 06 Feb 2005 07:34:07 -0500 Subject: changing local namespace of a function In-Reply-To: References: <4204400C.5060608@iinet.net.au> <42057a48$1_2@newspeer2.tds.net> Message-ID: <42060bf7$1_3@newspeer2.tds.net> Bo Peng wrote: > Kent Johnson wrote: >> You are still including the compile overhead in fun2. If you want to >> see how fast the compiled code is you should take the definition of >> myfun out of fun2: > > I assumed that most of the time will be spent on N times execution of > myfunc. Doh! Right. Kent From rbt at athop1.ath.vt.edu Wed Feb 16 11:08:11 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Wed, 16 Feb 2005 11:08:11 -0500 Subject: more os.walk() issues... probably user error Message-ID: This function is intended to remove unwanted files and dirs from os.walk(). It will return correctly *IF* I leave the 'for fs in fs_objects' statement out (basically leave out the entire purpose of the function). It's odd, when the program goes into that statment... even when only a 'pass', and nothing else is present, nothing is returned. Why is that? I'm testing Python 2.4 on Linux x86 and WinXP. Results are the same on either platform. def build_clean_list(self, path): file_skip_list = ['search_results.txt'] dir_skip_list = ['dev', 'proc', 'Temporary Internet Files'] fs_objects = os.walk(path, topdown=True) ## for fs in fs_objects: ## ## for f in fs[2]: ## if f in file_skip_list: ## print f ## fs[2].remove(f) ## ## for d in fs[1]: ## if d in dir_skip_list: ## print d ## fs[1].remove(d) return fs_objects From zanesdad at bellsouth.net Thu Feb 10 12:49:52 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 10 Feb 2005 12:49:52 -0500 Subject: [N00B] What's %? In-Reply-To: <614c778e.0502100938.6665cb52@posting.google.com> References: <614c778e.0502100938.6665cb52@posting.google.com> Message-ID: <420B9EC0.4040903@bellsouth.net> administrata wrote: >Hi! it's been about a week learning python! >I've read 'python programming for the absolute begginer' >I don't understand about % like... > >107 % 4 = 3 >7 % 3 = 1 > >I'm confused with division :/ >Please help me... > >thx 4 reading. > > % is the remainder operator (I think it's also called modulus). 107 % 4 == 3 because 107 / 4 == 26 R3 and 7 % 3 == 1 because 7 / 3 == 2 R1 HTH, Jeremy Jones From JoshuaACohen at gmail.com Thu Feb 10 10:48:11 2005 From: JoshuaACohen at gmail.com (Josh) Date: 10 Feb 2005 07:48:11 -0800 Subject: Reportlab and Barcodes In-Reply-To: <36vtjbF50fr4bU1@individual.net> References: <1107894763.331701.26470@c13g2000cwb.googlegroups.com> <1107965379.046718.248000@c13g2000cwb.googlegroups.com> <1107976931.161073.258600@f14g2000cwb.googlegroups.com> <36vtjbF50fr4bU1@individual.net> Message-ID: <1108050491.469126.302100@z14g2000cwz.googlegroups.com> Damjan, Code39 here refers to part of the Barcode Extensions available to Reportlabs. It can be imported as such from reportlab.extensions.barcode import code39 Josh From gae at thextron.no Wed Feb 9 06:03:51 2005 From: gae at thextron.no (Geir Arne Evjen) Date: 9 Feb 2005 03:03:51 -0800 Subject: I don't have a clue what this is (py2exe?) Message-ID: <699a1276.0502090303.490bdc9d@posting.google.com> I'm having a strange problem which I hope some python experts out there could help me with. I'm implementing a COM server where I do a lot of xml-rpc calls to a zope server. The communication is done over ssh with portforwarding (8080) using putty. To distribute the COM server I'm using py2exe to create exe files. I've implemented the COM server on a windows XP computer, but I'm testing it on a windows 2000 computer. The strange thing is that on the 2000 computer the xmlrpc-documents seems to be truncated somewhere at the and and the xmlrpc reader (expat) complains abount invalid tags (used by xmlrpclib). This only happens in some occations and for large documents (~200Kb). I've checked what putty recives in its logfile there is nothing wrong with what the zope server returns. Also, the strange this is that if I register (using the source) the COM server directly in the python intepreter the COM server works perfectly (both with or without debugging). I really don't know where this problem comes from and I don't have a clue where to search. Any tips would be very much appreciated. I'm using python 2.3.4 win32all build 203 py2exe 0.5.4 Best regards Geir Arne Evjen From steven.bethard at gmail.com Thu Feb 10 13:56:45 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 10 Feb 2005 11:56:45 -0700 Subject: namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP Message-ID: In the "empty classes as c structs?" thread, we've been talking in some detail about my proposed "generic objects" PEP. Based on a number of suggestions, I'm thinking more and more that instead of a single collections type, I should be proposing a new "namespaces" module instead. Some of my reasons: (1) Namespace is feeling less and less like a collection to me. Even though it's still intended as a data-only structure, the use cases seem pretty distinct from other collections. (2) I think there are a couple different types that should be provided, not just one. For example: * The suggested namespace view (which allows, for example, globals() to be manipulated with the getattr protocol) should probably be its own class, NamespaceView, since the behavior of a NamespaceView is substantially different from that of a Namespace. (Modifying a NamespaceView modifies the dict, while modifying a Namespace doesn't.) This also allows NamespaceView to have a separate __repr__ to indicate some of the differences. * The suggested namespace chain, if included, should also probably be its own class, NamespaceChain. As defined, it doesn't depend on Namespace at all -- it could be used just as well for other non-Namespace objects... I've updated the PEP to reflect these changes. Comments and suggestions greatly appreciated! (Note that I've included the current implementation of the module at the end of the PEP.) ---------------------------------------------------------------------- PEP: XXX Title: Attribute-Value Mapping Data Type Version: Last-Modified: Author: Steven Bethard Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 10-Feb-2005 Python-Version: 2.5 Post-History: 10-Feb-2005 Abstract ======== This PEP proposes a standard library addition to support the simple creation of attribute-value mappping objects which can be given named attributes without the need to declare a class. Such attribute-value mappings are intended to complement the name-value mappings provided by Python's builtin dict objects. Motivation ========== Python's dict objects provide a simple way of creating anonymous name-value mappings. These mappings use the __getitem__ protocol to access the value associated with a name, so that code generally appears like:: mapping['name'] Occasionally, a programmer may decide that dotted-attribute style access is more appropriate to the domain than __getitem__ style access, and that their mapping should be accessed like:: mapping.name Currently, if a Python programmer makes this design decision, they are forced to declare a new class, and then build instances of this class. When no methods are to be associated with the attribute-value mappings, declaring a new class can be overkill. This PEP proposes adding a new module to the standard library to provide a few simple types that can be used to build such attribute-value mappings. Providing such types allows the Python programmer to determine which type of mapping is most appropriate to their domain and apply this choice with minimal effort. Some of the suggested uses include: Returning Named Results ----------------------- It is often appropriate for a function that returns multiple items to give names to the different items returned. The types suggested in this PEP provide a simple means of doing this that allows the returned values to be accessed in the usual attribute-style access:: >>> def f(x): ... return Namespace(double=2*x, squared=x**2) ... >>> y = f(10) >>> y.double 20 >>> y.squared 100 Representing Hierarchical Data ------------------------------ The types suggested in this PEP also allow a simple means of representing hierarchical data that allows attribute-style access:: >>> x = Namespace(spam=Namespace(rabbit=1, badger=[2]), ham='3') >>> x.spam.badger [2] >>> x.ham '3' Manipulating Dicts through Attributes ------------------------------------- Sometimes it is desirable to access the items of an existing dict object using dotted-attribute style access instead of __getitem__ style access. The types suggested in this PEP provide a simple means of doing so:: >>> d = {'name':'Pervis', 'lumberjack':True} >>> ns = NamespaceView(d) >>> ns NamespaceView(lumberjack=True, name='Pervis') >>> ns.rugged = False >>> del ns.lumberjack >>> d {'rugged': False, 'name': 'Pervis'} Rationale ========= As Namespace objects are intended primarily to replace simple, data-only classes, simple Namespace construction was a primary concern. As such, the Namespace constructor supports creation from keyword arguments, dicts, and sequences of (attribute, value) pairs:: >> Namespace(eggs=1, spam=2, ham=3) Namespace(eggs=1, ham=3, spam=2) >>> Namespace({'eggs':1, 'spam':2, 'ham':3}) Namespace(eggs=1, ham=3, spam=2) >>> Namespace([('eggs',1), ('spam',2), ('ham',3)]) Namespace(eggs=1, ham=3, spam=2) To allow attribute-value mappings to be easily combined, the Namespace type provides a update staticmethod that supports similar arguments:: >>> ns = Namespace(eggs=1) >>> Namespace.update(ns, [('spam', 2)], ham=3) >>> ns Namespace(eggs=1, ham=3, spam=2) Note that update should be used through the class, not through the instances, to avoid the confusion that might arise if an 'update' attribute added to a Namespace instance hid the update method. Namespace objects support also object equality, comparing Namespace objects by attributes recursively:: >>> x = Namespace(parrot=Namespace(lumberjack=True, spam=42), peng='shrub') >>> y = Namespace(peng='shrub', parrot=Namespace(spam=42, lumberjack=True)) >>> z = Namespace(parrot=Namespace(lumberjack=True), peng='shrub') >>> x == y True >>> x == z False NamespaceView objects are intended to allow manipulating dict objects through the getattr protocol instead of the getitem protocol. For example usage, see "Viewing Dict Items as Attributes" above. Note that support for the various mapping methods, e.g. __(get|set|del)item__, __len__, __iter__, __contains__, items, keys, values, etc. was intentionally omitted as these methods did not seem to be necessary for the core uses of an attribute-value mapping. If such methods are truly necessary for a given use case, this may suggest that a dict object is a more appropriate type for that use. Examples ========= Converting an XML DOM tree into a tree of nested Namespace objects:: >>> import xml.dom.minidom >>> def gettree(element): ... result = Namespace() ... if element.attributes: ... Namespace.update(result, element.attributes.items()) ... children = {} ... for child in element.childNodes: ... if child.nodeType == xml.dom.minidom.Node.TEXT_NODE: ... children.setdefault('text', []).append( ... child.nodeValue) ... else: ... children.setdefault(child.nodeName, []).append( ... gettree(child)) ... Namespace.update(result, children) ... return result ... >>> doc = xml.dom.minidom.parseString("""\ ... ... ... a text 1 ... ... b text ... a text 2 ... ... c text ... """) >>> tree = gettree(doc.documentElement) >>> tree.a[0].b[1] Namespace(attr_b=u'3', text=[u' b text ']) Reference Implementation ======================== :: class Namespace(object): """Namespace([namespace|dict|seq], **kwargs) -> Namespace object The new Namespace object's attributes are initialized from (if provided) either another Namespace object's attributes, a dictionary, or a sequence of (name, value) pairs, then from the name=value pairs in the keyword argument list. """ def __init__(*args, **kwargs): """Initializes a Namespace instance.""" # inheritance-friendly update call type(args[0]).update(*args, **kwargs) def __eq__(self, other): """x.__eq__(y) <==> x == y Two Namespace objects are considered equal if they have the same attributes and the same values for each of those attributes. """ return (other.__class__ == self.__class__ and self.__dict__ == other.__dict__) def __repr__(self): """x.__repr__() <==> repr(x) If all attribute values in this namespace (and any nested namespaces) are reproducable with eval(repr(x)), then the Namespace object is also reproducable for eval(repr(x)). """ return '%s(%s)' % ( type(self).__name__, ', '.join('%s=%r' % (k, v) for k, v in sorted( self.__dict__.iteritems()))) def update(*args, **kwargs): """Namespace.update(ns, [ns|dict|seq,] **kwargs) -> None Updates the first Namespace object's attributes from (if provided) either another Namespace object's attributes, a dictionary, or a sequence of (name, value) pairs, then from the name=value pairs in the keyword argument list. """ if not 1 <= len(args) <= 2: raise TypeError('expected 1 or 2 arguments, got %i' % len(args)) self = args[0] if not isinstance(self, Namespace): raise TypeError('first argument to update should be ' 'Namespace, not %s' % type(self).__name__) if len(args) == 2: other = args[1] if isinstance(other, Namespace): other = other.__dict__ try: self.__dict__.update(other) except (TypeError, ValueError): raise TypeError('cannot update Namespace with %s' % type(other).__name__) self.__dict__.update(kwargs) class NamespaceView(Namespace): """NamespaceView(dict) -> new Namespace view of the dict Creates a Namespace that is a view of the original dictionary, that is, changes to the Namespace object will be reflected in the dictionary, and vice versa. """ def __init__(self, d): self.__dict__ = d Open Issues =========== What should the types be named? Some suggestions include 'Bunch', 'Record', 'Struct' and 'Namespace'. Where should the types be placed? The current suggestion is a new "namespaces" module. Should namespace chaining be supported? One suggestion would add a NamespaceChain object to the module:: class NamespaceChain(object): """NamespaceChain(*objects) -> new attribute lookup chain The new NamespaceChain object's attributes are defined by the attributes of the provided objects. When an attribute is requested, the sequence is searched sequentially for an object with such an attribute. The first such attribute found is returned, or an AttributeError is raised if none is found. Note that this chaining is only provided for getattr and delattr operations -- setattr operations must be applied explicitly to the appropriate objects. The list of objects is stored in a NamespaceChain object's __namespaces__ attribute. """ def __init__(self, *objects): """Initialize the NamespaceChain object""" self.__namespaces__ = objects def __getattr__(self, name): """Return the first such attribute found in the object list """ for obj in self.__namespaces__: try: return getattr(obj, name) except AttributeError: pass raise AttributeError(name) def __delattr__(self, name): """Delete the first such attribute found in the object list """ for obj in self.__namespaces__: try: return delattr(obj, name) except AttributeError: pass raise AttributeError(name) References ========== .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From CathleenB at concord.etransmail4.com Wed Feb 16 03:27:18 2005 From: CathleenB at concord.etransmail4.com (Cathleen Baer) Date: Wed, 16 Feb 2005 00:27:18 -0800 Subject: How new Check 21 legislation is affecting you... Message-ID: <26904959.1108542438254.JavaMail.customerService@etransmail4.com> Good Afternoon! Recenty intrdocuced legislation requires business and home users to print personal and business checks with security blank check stock and magnetic ink. Please find qualified suppliers at Google by clicking on the followingl link. http://www.google.com/search?sourceid=navclient&ie=UTF-8&rls=GGLC,GGLC:1969-53,GGLC:en&q=blank+check+paper%2C+magnetic+ink+for+inkjets Thank you very much. Cathleen Baer Marketing & Relationship Representative Globalzon Consulting Group From rparnes at megalink.net Tue Feb 8 07:29:48 2005 From: rparnes at megalink.net (Bob Parnes) Date: Tue, 08 Feb 2005 12:29:48 -0000 Subject: User Identification Message-ID: I have a python program on a server of an all-linux network. It needs to record the user name running it. Is there a way for the program to extract the name from the system without a separate log-in dialog? Bob Parnes -- Bob Parnes rparnes at megalink.net From bearophileHUGS at lycos.com Sat Feb 19 13:34:49 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 19 Feb 2005 10:34:49 -0800 Subject: exercise: partition a list by equivalence In-Reply-To: <1108837453.883740.309270@f14g2000cwb.googlegroups.com> References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> <1108768870.455974.244590@c13g2000cwb.googlegroups.com> <1108837453.883740.309270@f14g2000cwb.googlegroups.com> Message-ID: <1108838089.897928.219590@z14g2000cwz.googlegroups.com> Bearophile: > I presume the complexity is O(n+a); n (the nodes) > is proportional to the number of pairs, and a > (the arcs) depends on the "intricacy" of the input pairs. Opps... n (the number of nodes) is the number of different numbers contained in the pairs :-] Bearophile From duncan.booth at invalid.invalid Thu Feb 17 12:11:33 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Feb 2005 17:11:33 GMT Subject: difference between class methods and instance methods References: <1119g2rre5g610c@corp.supernews.com> Message-ID: John wrote: >> Note that it doesn't matter whether you call instance.foo(2) >> directly, or bind instance.foo to a variable first. Either will >> create a *new* bound method object, and the correct instance is used >> for the call. > > Za! What do you mean, "create a new bound method object"? I *already* > created that method when I def'd it inside the 'class Demo' statement, > no? > The def statement creates a function. Accessing the method through the class creates a brand new unbound method from the function. Every access of the method through the class creates a separate unbound method. Accessing the method through the instance creates a brand new bound method. Every such access creates a separate bound method. > > ... hmm... bound methods get created each time you make > a call to an instance method via an instance of the given class? > you've got it. From steven.bethard at gmail.com Fri Feb 4 14:32:30 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 04 Feb 2005 12:32:30 -0700 Subject: string issue In-Reply-To: References: Message-ID: rbt wrote: > Either I'm crazy and I'm missing the obvious here or there is something > wrong with this code. Element 5 of this list says it doesn't contain the > string 255, when that's *ALL* it contains... why would it think that??? > > import time > > ips = ['255.255.255.255', '128.173.120.79', '198.82.247.98', > '127.0.0.1', '255.0.0.0', '255', '128.173.255.34'] > > for ip in ips: > if '255' in ip: > try: > print "Removing", ip > ips.remove(ip) > except Exception, e: > print e > > print ips > time.sleep(5) > > Someone tell me I'm going crazy ;) You're going crazy. ;) py> ips = ['255.255.255.255', '128.173.120.79', '198.82.247.98', '127.0.0.1', '255.0.0.0', '255', '128.173.255.34'] py> for ip in ips: ... # debugging statement: ... print "Looking at", ip ... if '255' in ip: ... try: ... print "Removing", ip ... ips.remove(ip) ... except Exception, e: ... print e ... Looking at 255.255.255.255 Removing 255.255.255.255 Looking at 198.82.247.98 Looking at 127.0.0.1 Looking at 255.0.0.0 Removing 255.0.0.0 Looking at 128.173.255.34 Removing 128.173.255.34 Notice how elements of your list are being skipped. The problem is that you're modifying a list while you iterate over it. Why don't you try a list comprehension: py> ips = ['255.255.255.255', '128.173.120.79', '198.82.247.98', '127.0.0.1', '255.0.0.0', '255', '128.173.255.34'] py> [ip for ip in ips if '255' not in ip] ['128.173.120.79', '198.82.247.98', '127.0.0.1'] Steve From ncoghlan at iinet.net.au Thu Feb 10 07:49:39 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 10 Feb 2005 22:49:39 +1000 Subject: variable declaration In-Reply-To: References: <4202A022.3050209@netscape.net> Message-ID: <420B5863.1080400@iinet.net.au> Antoon Pardon wrote: > Well it seems you have some fair points. I'll just stop here stating > that I would like to have it, even if it proved to be slower. Speed > is not that big a factor in the things I write. Oh, certainly. I wasn't suggesting the speed hit was enough to kill the idea - I was just pointing it was something that you would use when correctness and being explicit was considered more important than a small price in speed. And if the name check got optimised out like an assert does. . . Hey, that gives me an idea (see below). > I just would like > to ask a question relating semantics. Supose the following code. > > x = 42 > > def f(): > x := 21 # or x .= 42 I don't remember what you used exactly Alex used ':=' in a couple of examples, but you'll have to ask him his reasons. I used '.=' instead mainly because I think colons are ugly, but also because ':=' has the ability to trigger confusion due to its slightly different use in those languages which use it for assignment (Eiffel and Pascal come to mind. . . since Pascal uses it, I guess Delphi does too). > What do you feel should happen. I can think of two possibilities. > > 1) It raises an exception because x is not locally bound. > > 2) it prints 21. > > > I think the second option would be the more interesting one as > it would allow to get rid of the global statement and it would > allow for rebinding names within nested scopes. I was thinking of the simpler version, with x .= 21 meaning roughly: assert x or True # This will blow up if x fails to resolve x = 21 The assertion would then blow up in your example (because x is an as yet unbound local variable). To my mind, this follows the principle of least surprise. I think the globals issue is better handled via the generic objects PEP, with an alternate constructor that allows the generic object to be used to alter an existing dictionary. Apply the trick to globals() and you're done. And if Python were to ever acquire some sort of 'scope()' function to allow programmatic access to scopes other than globals, generic objects would work for using those, too. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jason at tishler.net Mon Feb 28 17:40:41 2005 From: jason at tishler.net (Jason Tishler) Date: Mon, 28 Feb 2005 17:40:41 -0500 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <4223642C.7000002@llnl.gov> References: <41FFA7C9.4070308@llnl.gov> <20050202124435.GA2472@tishler.net> <4200D056.4010000@llnl.gov> <4200D22D.9070000@llnl.gov> <20050202133005.GE2472@tishler.net> <4208E247.8030706@llnl.gov> <20050208175514.GA3788@tishler.net> <420A372F.7020800@llnl.gov> <20050210120250.GA4084@tishler.net> <4223642C.7000002@llnl.gov> Message-ID: <20050228224041.GA2032@tishler.net> Dean, On Mon, Feb 28, 2005 at 10:34:20AM -0800, Dean N. Williams wrote: > I have a other Cygwin port question. It turns out that the auto-import > for XtStrings an widgetClass didn't get resolved. This a similar > auto-import resolving error that I got when trying to build Tcl/Tk. I > ended up using the shared Tcl/Tk that came with Cygwin. But in this > case I must be able to build my software. Can you tell me how to get > around this problem? Or can you tell me which cygwin mail list to send > my plea for help? I recommend trying the main Cygwin list: cygwin at cygwin dot com > gcc -shared -Wl,--enable-auto-image-base -o gplot gplot.o cgm.o ccgm.o > utils.o io.o carray.o devices.o hload.o emul.o tty.o ps.o cgmc.o > xws_cla.o xws_color.o xws_delim.o xws_marker.o xws_polygon.o > xws_polyline.o xws_setup.o xws_text.o drvcla.o -L/usr/X11R6/lib -lXp > -lXpm -lXaw -lXmu -lXext -lXt -lX11 /usr/lib/libm.a -lc > Info: resolving _XtStrings by linking to __imp__XtStrings (auto-import) > Info: resolving _widgetClass by linking to __imp__widgetClass (auto-import) However, I also recommend providing more information than the above. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From adam at cognitcorp.com Sun Feb 6 02:33:49 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Sun, 06 Feb 2005 02:33:49 -0500 Subject: Trouble converting hex to decimal? In-Reply-To: References: <1107611491.18588.26.camel@dulcevida> Message-ID: <1107675220.3948.26.camel@localhost.localdomain> On Sat, 2005-02-05 at 12:02, Steve Holden wrote: > Pedro Werneck wrote: > > The problem is that '\x00' is a escape sequence... > > Try something like this: > >>>>x = '\x00' > >>>>int(repr(x)[3:-1], 16) > > 0 > >>>>x = '\x15' > >>>>int(repr(x)[3:-1], 16) > > 21 > > On Sat, 05 Feb 2005 06:51:32 -0700 > > Earl Eiland wrote: > >>I'm trying to process the IP packet length field, as recorded by pcap > >>(Ethereal) and recovered using pcapy. When I slice out those bytes, I > >>get a value that shows in '\x00' format, rather than '0x00'. Neither > >>int() nor eval() are working. How do I handle this? > >>Earl Eiland > Talk about making things difficult! > >>> x = '\x00' > >>> ord(x) > 0 > >>> x = '\x15' > >>> ord(x) > 21 > >>> Ethereal's emission of \x00 shouldn't make your life any more difficult. The conversion of \0xx takes place in the eval. If you store the string \x00 in a file and call open.read or command.getoutput, you will get the python string "\\x00". Stuff you read from a file arrives un-de-escaped. The solution is simple. mystring.replace( "\x","0x" ) Adam DePrince From spam at nospam.org Thu Feb 3 13:29:57 2005 From: spam at nospam.org (Erik Johnson) Date: Thu, 3 Feb 2005 11:29:57 -0700 Subject: Easy Q: dealing with object type References: <420181b1$1@nntp.zianet.com> <1107396669.028096.301290@g14g2000cwa.googlegroups.com> <42019545$1@nntp.zianet.com> Message-ID: <42026b7e$1@nntp.zianet.com> > Steven Bethard wrote: > > py> class A: > > ... pass > > ... > > py> class B: > > ... pass > > ... > > py> a = A() > > py> a.__class__ == A > > True > > py> a.__class__ == B > > False "Just" wrote > Uh, isinstance(a, A) works for both new-style and old-style classes. > Heck, isinstance() even works in Python 1.5.2... Oh, there! Not that there is anything wrong with new classes, but that is just the sort of thing that I expected to find. No, neither of these is bad at all. I was looking for something like the obj.__class__ attribute, but I couldn't see it under dir(obj). So, why is _class__ magically tucked away where you can't see it? That doesn't seem very "Pythonic". I also looked in my two python books for instance(), or instanceof() functions - wasn't seeing anything. Actually, now that I check the indices of "Learning Python" 1E & "Programming Python" 2E, I don't see isinstance() either. How unfortunate. :( As an aside, I notice a lot of other people's interpreters actually print 'True' or 'False' where my system prints 0 or 1. Is that a configuration that can easily set somewhere? Thanks for your help! -ej From ashot at removemolsoftthis.com Mon Feb 7 01:55:07 2005 From: ashot at removemolsoftthis.com (Ashot) Date: Mon, 07 Feb 2005 00:55:07 -0600 Subject: IDLE history, Python IDE, and Interactive Python with Vim References: Message-ID: On Sat, 05 Feb 2005 11:07:40 -0700, Fernando Perez wrote: > Hi, > > Ashot wrote: > >> This is sort of both Python and Vim related (which is why I've posted to >> both newsgroups). > > [...] > > I know you've been using ipython recently (the readline color bugs), so perhaps > my reply is a bit redundant. Forgive me if that's the case, I just want to > give you some useful info. > > Just in case you haven't come across these features (the manual is kind of long > and dry), I should note that ipython has pretty much everything you've asked > for here. %hist -n dumps your history without line numbers (for copy/paste), > %logstart gives you an incremental log (valid python code) of your current > session, %save allows you to save a selected group of lines to a file, and > %edit will open up $EDITOR (or vi in Unix by default) at the source of any > accessible object. With %pdb, you can even trigger automatically pdb at any > uncaught exception (in Emacs, you'll even get the source simultaneously opened, > I'm sure something similar could be done for vi). yup, this is why I've been using it, its (almost exactly :) what I was looking for. I had tried it before, but was reluctant to use it because the windows terminal is not very appealing. Some things I've noticed so far that I think could be improved, some of which are minor but annoying: edit doesn't work with classes even though it says it should, you have to point it to a function in the class (perhaps only in windows) under windows vim/gvim doesn't jump to the line of the function.. you said that this should work in vi, but I'm guessing its a Windows thing **the biggest problem for me is edit forgets code in which there were errors. for example:"ed" type some nonsense, and ed -p doesn't remember. Thats putting an awful lot of pressure on getting the syntax right everytime =] Perhaps I am missing something here? it would be really great if the code executed on save rather than exit, but I'm not sure if this is possible. This would be very useful for people using an editor not in the console.. that way you wouldn't have to keep opening/closing new editor windows. this isn't a big deal, but it would be nice if there was an easy way to refer to the entire history (for edit/save/etc) would be nice if you could send stuff to the clipboard. There are a few other things I'm probably forgetting, but having said all that, I've come off a little negative here. I really like IPython so far, its got all the things I was looking for, thank you very much for your work. If I have the time in the future I would definately contribute to this project. .a > > Ipython is not an IDE, but it does offer an extensible command-line environment > which tries hard to be very efficient. Hopefully this year I'll be able to > work on integrating it (optionally, since it will never lose its command-line > functionality) with GUIs as well. > > Regards, > > f > > -- ============================== Ashot Petrosian University of Texas at Austin, Computer Sciences (views expressed are solely my own) ============================== From fredrik at pythonware.com Wed Feb 16 03:24:18 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Feb 2005 09:24:18 +0100 Subject: check if object is number References: <374ho0F560ughU1@individual.net><66WdnbJbuf5yj5DfRVn-iA@comcast.com> Message-ID: Steven Bethard wrote: >> Actually no, floats don't meet this behaviour or more specifically >> floats don't guarantee this behaviour. It depends of course on >> your implementation of f, but it is possible with floats to keep >> incrementing and never reach a maximum. > > My code won't hit this corner case. I'm incrementing with integers. incrementing what with integers? >>> f = 9007199254740992.0 >>> f == f+1 True From snail at objmedia.demon.co.uk Mon Feb 14 14:45:39 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Mon, 14 Feb 2005 19:45:39 +0000 Subject: - E02 - Support for MinGW Open Source Compiler References: <1108398011.213872.321390@o13g2000cwo.googlegroups.com> <1108408914.405899.129990@o13g2000cwo.googlegroups.com> Message-ID: In message <1108408914.405899.129990 at o13g2000cwo.googlegroups.com>, Pat writes >That answers the cost question (assuming that your interpretation of >the licensing is correct, since I'm not a lawyer nor qualified to >render much of an opinion on that). But there is still the issue of >going through a bunch of configuration hassle that scares me away from What configuration hassle? Can't be any harder than specifying a different CRT surely? Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From mahs at telcopartners.com Sun Feb 13 18:44:22 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sun, 13 Feb 2005 15:44:22 -0800 Subject: Iterator / Iteratable confusion In-Reply-To: References: <420a5c1e$0$21630$a1866201@visi.com><200502131848.03655.francis.girard@free.fr> <200502131958.27410.francis.girard@free.fr> Message-ID: > "Francis Girard" wrote in message >>an "iterator" doesn't have to support the "__iter__" method > > Terry Reedy wrote: > Yes it does. iter(iterator) is iterator is part of the iterater protocol > for the very reason you noticed... > But, notwithstanding the docs, it is not essential that iter(iterator) is iterator >>> class A(object): ... def __iter__(self): ... return AnIterator() ... ... >>> class AnIterator(object): # an iterator that copies itself ... def next(self): ... return "Something" ... def __iter__(self): ... return AnIterator() ... >>> a=A() >>> i = iter(a) ... >>> i.next() 'Something' >>> j = iter(i) >>> j.next() 'Something' >>> i is j False >>> Michael From jjl at pobox.com Sun Feb 6 15:16:02 2005 From: jjl at pobox.com (John J. Lee) Date: 06 Feb 2005 20:16:02 +0000 Subject: newbie wants to compile python list of filenames in selected directories References: <36n60uF520lfaU1@individual.net> Message-ID: <87sm49h2bh.fsf@pobox.com> Greg Krohn writes: > anthonyberet wrote: [...] > > I want to write a script to compare filenames in chosen directories, > > on windows machines. Ideally it would compose a list of strings of > > all the filenames in the directories, and those directories would be > > chosable by the user of the script. [...] > > os.listdir does almost exactly what you are asking for. For a little > more flexibility, you can use os.path.walk, although it's not quite as > newb friendly. > > -greg os.walk is perhaps newbie-friendlier than os.path.walk. Or perhaps not: not having read the tutorial &c. for some time, I don't know how good they are on generators... John From steven at lczmsoft.com Mon Feb 28 19:47:29 2005 From: steven at lczmsoft.com (steven at lczmsoft.com) Date: 28 Feb 2005 16:47:29 -0800 Subject: Problem When Unit Testing with PMock In-Reply-To: <78edneIr3oagkL7fRVn-jQ@powergate.ca> References: <1109423274.660110.156140@f14g2000cwb.googlegroups.com> <1109483520.813509.171880@f14g2000cwb.googlegroups.com> <1109579739.175344.105600@z14g2000cwz.googlegroups.com> <78edneIr3oagkL7fRVn-jQ@powergate.ca> Message-ID: <1109638049.594017.311400@f14g2000cwb.googlegroups.com> Peter, I'm so sorry, the letter was originally wrote to Terry, not to you! I guess Terry not very familar to unit testing because he said: -- cut -- I am not familiar with pmock, but my impression is that mock objects are for objects that you may not have available, such as a connection to a database or file or instance of an umimplemented class ;-). For such objects, the mock-ness consists in returning canned rather than actual fetched or calculated answers. Iterators, on the other hand, are almost as -- end -- and i just want to say, mocking object is a useful testing method , not was telling a tutorial. :-) What you said about the overuse of the generic mock object is very interesting. I did not think that before. I believe that use generic or customized mocks is a problem of balance, so we may call it Art :-) Below is my code, you may look it to understand my original question (sorry for the coding for i am totally a python newbie): --------------------------------------- import unittest from pmock import * from mainctr import MainCtr class MainCtrTest(unittest.TestCase): def testProcess(self): filePicker = MockFilePicker() filePicker.expectedNextCalls = len(MockFilePicker.fns) + 1 rpt0 = "foo" rpt1 = "bar" (router0, router1) = (Mock(), Mock()) router0.expects(once()).feedIn(eq(MockFilePicker.fns)) router1.expects(once()).feedIn(eq(MockFilePicker.fns)) router0.expects(once()).deliver() router1.expects(once()).deliver() router0.expects(once()).getDeliveredSrcList().will(return_value(["fn0", "fn2"])) router1.expects(once()).getDeliveredSrcList().will(return_value([])) router0.expects(once()).getDeliveryRpt().will(return_value(rpt0)) router1.expects(once()).getDeliveryRpt().will(return_value(rpt1)) routes = [router0, router1] ctr = MainCtr(filePicker, routes) ctr.process() self.assertEquals(ctr.getProcessRpt(), [rpt0, rpt1]) filePicker.verify() router0.verify() router1.verify() class MockFilePicker: fns = ["f0", "f1", "f2"] idx = 0 nextCalls = 0 resetCalls = 0 expectedResetCalls = 1 expectedNextCalls = 0 processedSet = set() expectedProcessedSet = set(["fn0", "fn2"]) rememberProcessedCalls = 0 expectedRememberProcessedCalls = 1 def __iter__(self): return self def reset(self): self.resetCalls += 1 def next(self): self.nextCalls += 1 if self.idx < len(self.fns): self.idx += 1 return self.fns[self.idx - 1] else: raise StopIteration def processed(self, fn): self.processedSet.add(fn) def rememberProcessed(self): self.rememberProcessedCalls += 1 def verify(self): if self.nextCalls != self.expectedNextCalls: raise Exception("nextCalls: " + str(self.nextCalls)) if self.resetCalls != self.expectedResetCalls: raise Exception("resetCalls: " + str(self.resetCalls)) if self.processedSet != self.expectedProcessedSet: raise Exception("processedSet: " + str(self.processedSet)) if self.rememberProcessedCalls != self.expectedRememberProcessedCalls: raise Exception("rememberProcessedCalls: " + str(self.rememberProcessedCalls)) if __name__ == "__main__": unittest.main() From carribeiro at gmail.com Sat Feb 5 16:27:45 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 5 Feb 2005 19:27:45 -0200 Subject: empty classes as c structs? In-Reply-To: References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> Message-ID: <864d3709050205132730c38c18@mail.gmail.com> On Sat, 05 Feb 2005 12:05:13 -0700, Steven Bethard wrote: > The type suggested in this PEP also allows a simple means of > representing hierarchical data that allows attribute-style access:: > > >>> x = Bunch(spam=Bunch(rabbit=1, badger=[2, 3, 4]), ham='neewom') > >>> x.spam.badger > [2, 3, 4] > >>> x.ham > 'neewom' Static nested data structures are particularly tricky to declare in Python. Your example works, but IMHO it's rather a workaround than a real solution. Other languages (such as Delphi) have a record type that can be nested naturally. Nested classes in Python don't work the same as Delphi records; on instantiaton, only the outer (parent) class is instantiated, and the nested (children) classes stay as classes. This can lead to subtle bugs as class attribute acesses are mixed with instance attribute accesses with unpredictable results. I have tried to deal with these problems on MetaTemplate, a library for declarative-style code in Python. You can see some ideas on this page: http://metatemplate.python-hosting.com/wiki/MetaTemplate One of my goals was to model nested data structures as nested classes in Python. My solution to the nesting problem involves some autoinstantiation magic which breaks traditional semantics, but works for the particular application ('practicality beats purity'). I'm interested to see where this will lead us. Other related problems are named tuples, and ordered attribute access. I deal with the later in MetaTemplate, but the former is out of scope for the library. In the long term, I wish Python grows a true record type. The semantic differences between records and classes are enough to justify it in my opinion. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aurora00 at gmail.com Fri Feb 4 00:56:05 2005 From: aurora00 at gmail.com (aurora) Date: Thu, 03 Feb 2005 21:56:05 -0800 Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xhdktt36q.fsf@ruckus.brouhaha.com> Message-ID: > aurora writes: >> Slow compares to what? For a large commerical site with bigger budget, >> better infrastructure, better implementation, it is not surprising >> that they come out ahead compares to hobbyist sites. > > Hmm, as mentioned, I'm not sure what the commercial sites do that's > different. I take the view that the free software world is capable of > anything that the commercial world is capable of, so I'm not awed just > because a site is commercial. And sites like Slashdot have pretty big > budgets by hobbyist standards. > >> Putting implementation aside, is LAMP inherently performing worst than >> commerical alternatives like IIS, ColdFusion, Sun ONE or DB2? Sounds >> like that's your perposition. > > I wouldn't say that. I don't think Apache is a bottleneck compared > with other web servers. Similarly I don't see an inherent reason for > Python (or whatever) to be seriously slower than Java servlets. I > have heard that MySQL doesn't handle concurrent updates nearly as well > as DB2 or Oracle, or for that matter PostgreSQL, so I wonder if busier > LAMP sites might benefit from switching to PostgreSQL (LAMP => LAPP?). I'm lost. So what do you compares against when you said LAMP is slow? What is the reference point? Is it just a general observation that slashdot is slower than we like it to be? If you are talking about slashdot, there are many ideas to make it faster. For example they can send all 600 comments to the client and let the user do querying using DHTML on the client side. This leave the server serving mostly static files and will certainly boost the performance tremendously. If you mean MySQL or SQL database in general is slow, there are truth in it. The best thing about SQL database is concurrent access, transactional semantics and versatile querying. Turns out a lot of application can really live without that. If you can rearchitect the application using flat files instead of database it can often be a big bloom. A lot of these is just implementation. Find the right tool and the right design for the job. I still don't see a case that LAMP based solution is inherently slow. From jao at geophile.com Sat Feb 26 17:28:25 2005 From: jao at geophile.com (Jack Orenstein) Date: Sat, 26 Feb 2005 17:28:25 -0500 Subject: Thread scheduling In-Reply-To: <1109456481.214243.140670@l41g2000cwc.googlegroups.com> References: <1109456481.214243.140670@l41g2000cwc.googlegroups.com> Message-ID: <4220F809.7040502@geophile.com> I am using Python 2.2.2 on RH9, and just starting to work with Python threads. I started using the threading module and found that 10-20% of the runs of my test program would hang. I developed smaller and smaller test cases, finally arriving at the program at the end of this message, which uses the thread module, not threading. This program seems to point to problems in Python thread scheduling. The program is invoked like this: python threadtest.py THREADS COUNT THREADS is the number of threads created. Each thread contains a loop that runs COUNT times, and all threads increment a counter. (The counter is incremented without locking -- I expect to see a final count of less than THREADS * COUNT.) Running with THREADS = 2 and COUNT = 100000, most of the time, the program runs to completion. About 20% of the time however, I see one thread finish, but the other thread never resumes. Here is output from a run that completes normally: [jao at black]$ python threadtest.py 2 100000 nThreads: 2 nCycles: 100000 thread 1: started thread 1: i = 0, counter = 1 thread 2: started thread 2: i = 0, counter = 2691 thread 1: i = 10000, counter = 13496 thread 2: i = 10000, counter = 22526 thread 1: i = 20000, counter = 27120 thread 2: i = 20000, counter = 40365 thread 1: i = 30000, counter = 41264 thread 1: i = 40000, counter = 55922 thread 2: i = 30000, counter = 58416 thread 2: i = 40000, counter = 72647 thread 1: i = 50000, counter = 74602 thread 1: i = 60000, counter = 88468 thread 2: i = 50000, counter = 99319 thread 1: i = 70000, counter = 110144 thread 2: i = 60000, counter = 110564 thread 2: i = 70000, counter = 125306 thread 1: i = 80000, counter = 129252 Still waiting, done = 0 thread 2: i = 80000, counter = 141375 thread 1: i = 90000, counter = 147459 thread 2: i = 90000, counter = 155268 thread 1: leaving thread 2: leaving Still waiting, done = 2 All threads have finished, counter = 168322 Here is output from a run that hangs. I killed the process using ctrl-c. [jao at black]$ python threadtest.py 2 100000 nThreads: 2 nCycles: 100000 thread 1: started thread 1: i = 0, counter = 1 thread 2: started thread 2: i = 0, counter = 990 thread 1: i = 10000, counter = 11812 thread 2: i = 10000, counter = 13580 thread 1: i = 20000, counter = 19127 thread 2: i = 20000, counter = 25395 thread 1: i = 30000, counter = 31457 thread 1: i = 40000, counter = 44033 thread 2: i = 30000, counter = 48563 thread 1: i = 50000, counter = 55131 thread 1: i = 60000, counter = 65291 thread 1: i = 70000, counter = 78145 thread 2: i = 40000, counter = 82715 thread 1: i = 80000, counter = 92073 thread 2: i = 50000, counter = 101784 thread 1: i = 90000, counter = 104294 thread 2: i = 60000, counter = 112866 Still waiting, done = 0 thread 1: leaving Still waiting, done = 1 Still waiting, done = 1 Still waiting, done = 1 Still waiting, done = 1 Still waiting, done = 1 Still waiting, done = 1 Still waiting, done = 1 Still waiting, done = 1 Traceback (most recent call last): File "threadtest.py", line 26, in ? time.sleep(1) KeyboardInterrupt [jao at black osh]$ In this case, thread 1 finishes but thread 2 never runs again. Is this a known problem? Any ideas for workarounds? Are threads widely used in Python? Jack Orenstein # threadtest.py import sys import thread import time nThreads = int(sys.argv[1]) nCycles = int(sys.argv[2]) print 'nThreads: %d' % nThreads print 'nCycles: %d' % nCycles counter = 0 done = 0 def run(id): global done print 'thread %d: started' % id global counter for i in range(nCycles): counter += 1 if i % 10000 == 0: print 'thread %d: i = %d, counter = %d' % (id, i, counter) print 'thread %d: leaving' % id done += 1 for i in range(nThreads): thread.start_new_thread(run, (i + 1,)) while done < nThreads: time.sleep(1) print 'Still waiting, done = %d' % done print 'All threads have finished, counter = %d' % counter From peter at monicol.co.uk Sat Feb 12 12:03:51 2005 From: peter at monicol.co.uk (Peter Mott) Date: Sat, 12 Feb 2005 17:03:51 -0000 Subject: Docs. for logging module typo Message-ID: <420e36f6$0$38041$bed64819@news.gradwell.net> The documentation for SMTPHandler say "The toaddrs should be a list of strings without domain names (That's what the mailhost is for)." which does not seem to be correct. The toaddr should be a list of strings like 'john at somewhere.com'. Peter From zetasum at yahoo.com Tue Feb 1 11:15:49 2005 From: zetasum at yahoo.com (zetasum) Date: 1 Feb 2005 08:15:49 -0800 Subject: one infinite leap and you thought the bible code was somthing!! Message-ID: <1107274549.913265.89980@f14g2000cwb.googlegroups.com> one infinite leap and you thought the bible code was somthing!! One Small step one infinite leap by: zeta limit Quantum cryptography Run this in every order 1 correct outcome Run the web site with every word and every order and ever letter in every order then every paragraph then and number and do that in every order. Everything is possible one way or another anything, any you can tell it to build anything and it will be possible. Less is more Examples: with a stick if you can make a car drive if you push down on the gas pedal with it. This proves the real "Theory of Everything" and builds a huge data base of information. The more information ,The bigger the neural network and just keep adding more to it because anything is possible and new things can be found after this is done. By using The new ideas and the information you now can run everything back wards and then forward but now by not just adding but by +,*,/,<,>,= ,-,+ then finding how all things can be 100% true if there not then your not doing it right. Then run this in every order and change the neural network to be 100%efficient in making all ideas. After your done use the code to turn one Law, definition, on and off like math, and matter, and all the word net technology dictionary and then turn them off in every order on the website then build a separate quantum neural network to store all the information in then just run it all over again do it over and over with the new math and information on the website it will generate new laws of den's and math and quantum and stellar physics more. run the laws the new laws that changed see by what percent they are true by using % and digress 3=1 360 degrees = 3 but is in every infinite angle and degree until all = 100% only use your data base to help generate new laws. But by running the neural network with words missing and laws missing. It will make new laws until all is 100% true learning way outside the realm of A.I or R.I. finally ...Then with my matrix program run the neural network With my own Matrix code and Artificial intelligence with this bunny encrypted website by starting with one dimension up to infinite and every angel and shape start with a box and every degree every number letter and word it will keep growing and so does the database. After all is done all laws can be T <,>, = and false. Then do it all again but this time with everything on the internet all data. Then have it ask it the simple question on everything that is T <,>, = and false. Who, what, when, where, how. Based on your new neural network what is? All laws can now be stored as compression law. There is no theoretical limit to the speed of magnetism or the amount of energy it can hold. In our universe or any quantum realm. Magnetism is the forces at which matter in the universe breaks down at maximum speed or velocity of C = the speed of light or the stabilization of matter moving threw a constant at the speed of C or beyond stellar construct. C is used many times in quantum physics until the key of magnetic frequency storage from smaller then the Pico up to large scale white nose flux capacitors to keep the Energy moving and storing in highly charge states of metals that are molecular reconstructed to be 100% efficient. One pyramid sphere of electrical and one of magnetical. Yes MAGNETICAL a new form of quantum computing, energy and There is only optical laser quantum computer a partial that when it reaches its limit it's doesn't turn to light You can build it yourself along with the magnetic and electrical flux capacitors that have the same amount of more than the amount of energy than Anything you can think of or you can run this website with A.I (this blueprint is the key to the encrypted Code 1011101 Infinite quantum computing It more into the field of stellar physics or stellar quantum computing. Work on it for just a week Time travel changes history u but you can really tell Unless you are outside of space time that is the only hint I am going to give you because I have no degree, but my dummy A.I website is written in dummy A.I So I don't get shot over an information war!! http://www.beyond-science.com made with my own Matrix code and Artificial intelligence this bunny encryption website has More than a 32 dimensional door. A box made that no one can crack...Try it key code 01 There is only optical laser quantum computer a partial that when it reaches it's limit it's doesn't turn to light you can build it yourself along with the magnetic and electrical flux capacitors that have the same amount of more than the amount of energy than anything you can think of or you can run this website with A.I (this blueprint is the key to the encrypted Code 1011101 Infinite quantum computing It more into the field of stellar physics or stellar quantum computing. Work on it for just a week Time travel changes history u but you can really tell unless you are outside of space time that is the only hint I am going to give you because I have no degree, but my dummy A.I website is written in dummy A.I so I don't get shot over a information war!! www.beyond-science.com Clean fusion. Matter has its limits and can only move so fast so quantum computer using refraction of magnetical frequency can move faster than time itself. New matter and new Material has been found threw programming magnetic frequencies of matter at a state of the constants. Electrical controlled machine are outdated since 1901. A quantum computer the was powered by magnetical and used magnetical to compute in infinite degrees instead of bit's of 1 and 0' but by triangulating in every infinite digress of the new computer would have the computing power of no limitations. Build as a Quadra sphere light bounces inside a crystal 4 times before it refracts inside and come out. Infinite hues of colors infinite frequencies to chart them at. Infinite combinations of shape on programmed matter = infinite matter. With this and running my new stellar magnetically computer and A.I and the web site http://www.beyond-science.com A magnetic Supercomputer and encryption and compression @ rate of 96% Take a document then or a 3D matrix document change it two random or binary code or just a program for 0's and 1's and fold it over and over like a piece of paper then having the 1 and 0 add each other or the 0,1's canceling each other out 1+0=0 and 0+1=1 1+1=1 0+0=0 if you gave the folds addresses like on a spread sheet there would be no math. First A 1-24 would fold to k 1-24 down.(See Example A ) Then at F1-24 down two k 1-24 ( See example B ) If you written a very long letter and then change it two binary code it would look like this. 123456789.............24 a.01010101010101010101010 b.10010101010101010101010 c.01010101001010101010010 e.00010101000101010101010 f.10010101010100101010101 First A 24 would fold to k 24 down g.01010101010100001100101 See Example A h.01001010101010101010111 I.11110111001101010101010 j.01010101010101010101010 k.10101010101010101010101 See Example A 123456789.............24 f.10010101010100101010101 g.01010101010100001100101 h.01001010101010101010111 Then at F1-24 down two k 1-24 I.11110111001101010101010 j.01010101010101010101010 k.10101010101010101010101 See example B 123456789.............24 I.11110111001101010101010 j.01010101010101010101010 Then from I 1-24 to K 1-24 k.10101010101010101010101 123456789.............24 j.01010101010101010101010 Then from j-24 to j-1 123456789... j.010101010101 Then from j-12 to j-1 123456 j.010101 Then from j-6 to j1 123 j.010 Then from j-3 to j1 12 j.01 Then from j-2 to j1 j.0 Then you would have 1 bit to transfer over the Internet The bit sent would be 0 and the key code would be F1-24,k 1-24, I 1-24,K 1-24,j24,j1,j12,j1,j6,j1,j3,j1,j2,j1 and would unzip or be new encryption you could encrypt or compress 100 terabits down to 1 bit of information. Now if you take this idea from my web site you could make this allot more complex and unbreakable. Data encryption 360 degrees rotation document 90 degrees and encrypt on every angel then 45 degrees change it two binary code do it again and again and fold it over like a piece of paper then having the one's and zero cancel each other out. In theory you could send a 100 terabit program to someone's computer and have it unzip and run and install or make A computer processor like the new 64 bit AMD have the bit unzip into a large ram drive and buffer use one half of the 64 bit processor decode the message and the main 64 bit run the numbers. Another way of doing this is to have a parallel computers with using one of the processes run the compressed 1 bit of information give the uncompressed a address on the ram drive to change and not even go threw the processor and then with different information on each machine compare and run statistics on information on a 45 flops supercomputer and turn that 45 tflops computer into a 1 bit = 100,000 terabits to infinite as long as you have the ram for storage! with my calculations 45 tflops wouldn't matter any more it would be how much data you have on a 32bit operating system changing that to a 1 bit system it would be 32 * 45tflops would = 1440 tflops Matter moves so fast that it integrates and intergreats faster then any speed we can see it like water from a hose at real close speed it moves in -------- lines. For space and the real matrix computer and bioinformatics from the 4 genes we have you can be teleported with the matrix on to another in reverse with out using the original 4 or 5 "If Numbers are Infinite, Then so Inventions" "One Small step for man. One infinite leap, for the Human Race" zeta limit. ARTIFICAIL INTELLIGENCE THINKS IT KNOWS WHERE IT IS, BUT THERE ARE INFITE PLACES IT CAN BE, AT THE SAME TIME AND STLL BE AT THE SAME PLACE SO RUN THIS WEB SITE FOR AS LONG AS YOU WANT YOUR NEVER FIND THE CODE AND NO HUMAN WILL FIND IT TWO AND YOUR NEVER GETTING OUT OF THIS WORLD STCUK IN THE MATRIX FRIM THE FUTURE AND CAN'T GET OUT HOW FUCKING FUNNY IS THAT. SALUTAION ANYONE WANTS EGGS DUPLICATION ONE MAN MADE TWO AND GOT OUT!!! HINT MASH THE TV SHOW!!! THE KNOW AND UNKNOW UNIVERSE'S Threw magnetic Command coded magnetic field that changes to the strong gravitational pull of a black hole using the black hole own magnetic energy in the form of ant-magnetic Anti-gravity the field would be stronger then the light that is emitted from the back hole leaving the structure safe the magnetic forces and fields of a physics' of a sphere would BE TRIDED TO TURN INTO AN EGG. But DONE RIGHT IT WOULD BE A SPHERE. But what makes it so strong all parts of matter are designer custom CHEMICAL MAKE UP AND ALIGNMENT OF MATTER. THAT DISTUBUTES THE FORCES = TO THE HOLE SPHERE. When TRAVEING THREW A BLACK HOLE TO UNOTHER UNVERSE. IF BUILD RIGHT AND USING THE FORCE OF THE BLACK HOLE IN REVERSES THE SPHERE COULD RETURN WITH INFORMATION ON THE STUCTURE OF THE BACK HOLE. IT'S MAGNETICS THAT MAKE GRAVITY SO A MACHINE THAT IS A BACK HOLE IN REVERSE USING THE OTHER SPECTRUM WOULD DO WHAT!!! COME BACK AND NOW THAT WE CAN MAKE METALS THAT ARE CUSTOM TO HOLD UP VERY HEAVY THING BECASE OF CUSTOM ARCHITECTURE AND ARC COULD HOLD UP A BUILDING ON BOTH SIDES. . stellar drive Run this web page with ARTIFICIAL INTELLIGENCE or quantum ARTIFICIAL INTELLIGENCE with every word in every order and every letter in every order and ever paragraph in every order with your HUGE DATA BASE OF KNOWLEDGE Command coded It's the matter construction on the smallest level of all material and matter beyond Pico and nano technology That makes it so strong that all parts of matter are designed custom for the structure strength, But can you find the natural matter that make it interchangeable so the matter can change threw magentics- Wave Length - gravity - Light - mass-matter - Wave Lengths. (THEY ARE ALL INTERCHANGEABLE) Periodic table of elements are infinite you have know idea what a100% synthetic Universe looks like. Infinite synthetic elements infinite synthetic Physics click & mail The Theory of everything is the quantum address of everything that is in our universe. By a magnetic field. Outside and inside of all that is contained there in. It is the physics and mathematical equations that surround everything in the multi-dimensional physical world. One might find how all the elements are interchangeable and are multi-dimensional and finding the other side of physics and the mathematic equations that we cannot see or detect because our consciousness cannot find it, finding this would be the greatest discovery of the human race. What lie's Beyond Quantum Physics and how do we get there. Is the key magnetic Frequency's? But the amount of energy it would take would be more than just at the atomic level or sub-atomic level. One day In the future a person may find a multi-dimensional, multi-time, multi-universe. The problem with finding it is a realm of that we cannot see, is finding what we cannot detected. Finding the other side of quantum physics will be the future goal of human exploration. Our universe started with one wave length of light and an anti-wave length three magnetism and gravity they where changed to form all matter: Wave Length - Gravity -Light - mass - Wave Lengths. (THEY ARE ALL INTERCHANGEABLE)" answer is frequencies magnetic Interchangeable matter Is the best neural network a circle and can it make interchangeable matter inside a circle that knows everything and both circles spin faster then the speed of light or hyperspace and stellar speed in every infinte order and shape of a circle!! and off the two circle they are made up of more circles of two more rings and so on and so on that they gets so small that they cannot work with our laws of physics' and the then all the way up we look at the 2 rinds one on the inside and one on the inside and one on the outside that form and ball with in a ball all connect to each other so they can spin and communicates to each other like a huge neural network a earth made of connect marbles turning inside and out in every direction two speed up the information traveling from one two another. Run this until you can make the information move as fast as possible and you will see for just information it creates some kind of energy just thoughts. Matter moves so fast that it integrates and integrates faster then any speed we can see it like water from a hose at real close speed it moves in -------- lines. TELEPOTAION SOMETHING FROM NOTHING IS REAL TELEPORTION The laser slit test for physics' is wrong where it shows the end result filter pass threw slits the final black board the gaps of black and red there should be more slits of light. Some are cancelled out because of refraction. This tells you of a parallel dimensions but not of a universe. Velocity is a sphere of triangles it's the math outside of the velocity on and outside the sphere R*V*D2 VOLUME of the universe. That velocity, magnetic and matter go hand and hand. That all matter can be made by the changes in the angle and of the frequency's of powerful geometrics magnetic shapes of multi-dimensions, multi-universe and multi-layered if you off set the frequency's with white noise in a fiber optic you can compress the frequency's down to a smaller and stronger charge and some can remain and all can remain separate. This is how you can send 30 amps over a .1 amp wire with the device on both ends. ( By using end invention of black *diamonds the darkest stealth material ( black magnets and gold ( hint ) used to create the geometric shapes) if you off set the frequency's with white noise in a fiber optic you can compress the frequency's down to a smaller and stronger charge! Then sort them out and break them down from the smallest to the largest or the largest to the smallest to you the largest or the smallest and the offset of white noise to contain them into a magnetic capacitor or magnetic flux and store them in nano capacitors *diamonds that allows you to store mass amount of magnetic frequency's at different sizes try a 10 feet by 10 feet shape of a nano block or sphere stored in aluminum sphere or what ever shape is most efferent. Circuit board or sphere. The darkest black *diamond you can make but under a super nano or Pico microscope you can see the circuits but smooth as silk on the outside. Now you are going to have to run every combination of shape. The diamond is built just like making a rubber band ball with rubber band laid over and over and over it when built with circuit that go both way so they can discharge at any frequency's. Placed inside an Aluminum Sphere and you can make any type of now and future propulsion. Let you see the spectrum of all time and you know can find a nano in a universe because that how sensitive it is. It also makes a good neural network. Matter moves so fast that it integrates and integrates faster then any speed we can see it like water from a hose at real close speed it moves in -------- lines. Knowledge of the theory of ZETALIMIT Picture the laws of quantum physics and D.N.A and everything as dotted points that makes up shapes of all sizes and everything that can happen in this universe and out is because of knowing the all laws in that universe and all conscious quantum dimensions. Find the new mathematical degrees that form new math and a new efficient programming language or for your neural network and keep running the web Site over and over after changing your network until it is infinitely efficient along with all technology on the web. By getting the information from make a computer of quantum type run at hyperspace idea at the middle of the page. The only way to be infinite is to make everything work with everything else and put it in folders and sub folder of the infinite name and then run the web page and the Internet again every hour! Map all maths from one mathematical problem to all infinite one to see if there is a pattern the ones that show a patter make the yellow neural bar bigger wider and brighter. How is time and space the same place? Is the best neural network a circle inside a circle that knows everything and both circles spin faster then the speed of light or hyperspace and stellar speed in every infinite order and shape of a circle!! and off the two circle they are made up of more circles of two more rings and so on and so on that they gets so small that they cannot work with our laws of physics' and the then all the way up we look at the 2 rinds one on the inside and one on the inside and one on the outside that form and ball with in a ball all connect to each other so they can spin and communicates to each other like a huge neural network a earth made of connect marbles turning inside and out in every direction two speed up the information traveling from one two another. Run this until you can make the information move as fast as possible and you will see for just information it creates some kind of energy just thoughts. Matter moves so fast that it integrates and integrates faster then any speed we can see it like water from a hose at real close speed it moves in -------- lines. QUANTUM MAGNETIC MATH -1 + -1 = +2 OUR MATHEMATICS IS WRONG finding the Quantum gate THATS WHY ARE QUANTUM COMPUTER SYSTEM WILL NEVER GET TO THE GOVERNING DYNAMICS LAWS OF OUR UNIVERSE AND PARALLEL ONES AND ONE NOT PARALLEL TO US BUT DO EXIST IN A COMPLEX ENCRYPTED MAGNETIC AND FREQUENCYS OF TIME. MAGNETIC AND ANTI-MAGNETIC SPINNING SPHERES OF DIMENSIONS WITH EACH SPHERE CONTAINING DIFFERENT SIZES OF A MAGNETIC FIELD THATS ENCRYPTED AND CHANGING ON ALL LEVEL OF TIME AND THE MAGNETIC MATTER OF THAT FIELD. QUANTUM COMPUTER SHOULD USE THE MATH OF MAGNETIC POSITIVE AND NEGATIVE EFFECTS ON EACH OTHER ON HOW ONE PIECE OF MATTER NEGATIVE OR POSITIVE CAN BECOME 2 AND = TOO. THE STATEMENTS OF THE FINAL GOVERNING DYNAMICS LAWS ARE NOT IN MATHEMATICAL %'S BUT AND TRUE FALSE OR = TWO OF ALL MATTER THERE ARE CONSTANTS AND THE CONSTANTS THAT CHANGE THE CONSTANTS WHEN WE GET DEEPER TO THE UNDERSTANDING LAWS THAT GOVERN ALL THINGS. MORE THEORY'S @ WWW.BEYOND-SCIENCE.COM FOR MORE INFORMATION READ ON..... INCLUDE CLASS_ZETA LIMIT_1AE FUNCTION (Z) Because they are so infinitesimally small, MAGNETIC NEUTRAL MATTER exist in the quantum realm, where rules governing the macro-universe -- the known world of quantum physics and matter -- break down. A neutrino's mass -- unlike the mass of a larger object -- is not stable, but exists in a state of probability AND IS GOVERNED BY MAGNETICS SO SMALL BUT ALL WORK TOGETHER ON A LARGE SCALE LIKE A PYRAMID THAT HOLDS ARE MATTER TOGETHER ON A LARGE UNIVERSAL SCALE OUR UNIVERSE IS A LARGE QUANTUM COMPUTER. "Say you had some in a box, and you pulled one out and weighed it and it weighed m-1," said Stuart Freedman, a professor of physics at UC Berkeley and a faculty senior adviser at the Lawrence Berkeley National Laboratory. "Then you pulled out an identical one, and it weighed m-2," continued Freedman. "It isn't a situation where a neutrino is m-1 or m-2 -- it's a situation where the neutrino is 50 percent one mass and 50 percent another. This seems surprising, but it's perfectly natural in quantum mechanics." IN THE MOVIE CONTACT THE LARGE MAGNETIC ROTATING SPHERE FROM THE SMALLEST PICO OR NANO SIZE MAGNETIC FIELD ALL THE WAY TO THE GRAVITIONAL MAGNETIC FIELD OF PHYSICS WOULD EXPLAIN ALL TIME AND SPACE IN OUR UNIVERSE AND HOW SUB-SPACE OR ZERO GRAVITY WORKS IN OUTER SPACE IT JUST BACKWARD ZERO-GRAVITY IS HYPER-SPACE BACKWARDS BUT THE FIELDS KEEP EVERYTHING IN CONTACT AND HOLD EVERYTHING TOGETHER IF YOU PUT YOUR FINGER IN A GLASS OF WATER AND MIX IT, IT CHANGES BUT TO THE EYE IT LOOKS ALL THE SAME AND NOTHING IS CHANGED WHEN IT STOPS THAT IS THE REALM OF QUANTUM PHYSICS THAT THE MIND AND EYE GET CROSSED. IT IS ALL BASED ON WHAT SIGNAL YOUR CONSCIOUS SIGNAL AND CENTRAL NERVOUS SYSTEM IS SET TWO THERE ARE DIFFERENT COMPONENTS AND DIMENSION OF TIME. I HAVE FOUND 4 1.CONSCIOUS TIME EVERY ONE CLOCK IS DIFFERENT 2.EARTH TIME 3.SOLAR SYSTEM TIME 4.GALAXY TIME 5. T= TOTAL GALAXY TIME 6. UNIVERSAL TIME 7. T= TOTAL UNIVERSAL TIME OF ALL UNIVERSES. 8. UST= TOTAL UNIVERSAL SYSTEM TIME OF ALL KNOWN AND UNKNOWN THAT ARE ALL BASED ON ONE PRINCIPLE WHERE THERE IS MAGNETIC FIELD THERE IS A DIFFERENT IN TIME IT JUST HAPPEN ON ONE OF THE SCALES. YOU UST HAVE TO FIND IT. MAGNETIC = TIME + LIGHT = DIMENSIONS + GRAVITY = MULTI-dimensions + MAGNETIC ANTI-ATTRACTION = ZERO-SPACE + MATTER AND ANTI-MATTER = SPHERE SPACE = A UNIVERSE. IT'S BEEN SNOWING FROM THE BEGINNING OF TIME AND EVERY SNOW FLACK IS DIFFERENT IT IS TWO COMPLEX FOR YOUR HUMAN MIND TO FIND THE ANSWER SO START SIMPLE WITH THE STUDY OF MAGNETICS OF ALL FORMS OF MATTER AND PHYSICS. IT THE KEY. MAKES IT ALL HAPPEN. QUADRA LIGHT PYRAMID HARNESSING LIGHT FINDING ZETA VECTORS AND SECTORS The spectrum that comes out of a pyramid bounces inside then splits as it hit the opposing wavelength inside comes out two form the color or frequency spectrum as it is known today, but what is the most efficient shape to build a sphere, to contain all frequencies of light. We have all seen a sphere made up pyramids. But what cause the refraction of out own light. It is light bouncing off of light. So what type of magnetic field could we generate and what shapes would they form that we could use the harnessed light. To change the multi-dimensional physical world. One might find how all the elements are interchangeable and are multi-dimensional and finding the other side of physics and the mathematic equations that we cannot see or detect because our consciousness cannot find it, finding this would be the greatest discovery of the human race. What lie's Beyond Quantum Physics and how do we get there. Is the key magnetic Frequency's? But the amount of energy it would take would be more than just at the atomic level or sub-atomic level. One day In the future a person may find a multi-dimensional, multi-time, multi-universe. The problem with finding it is a realm of that we cannot see, is finding what we cannot detected. Finding the other side of quantum physics will be the future goal of human exploration. Our universe started with one wave length of light and an anti-wave length then magnetism and gravity they where changed to form all matter: Wave Length - Gravity -Light - mass - Wave Lengths. (THEY ARE ALL INTERCHANGEABLE)" PICO SECTORS AND VECTORS IN OUR QUANTUM TUNNEL! Mass = gas, solid, liquid and there all inter-changeable. For instance, if you wanted to know something about the results of a calculation for several different we views the world of computing or quantum computing as 1,0 or on and off but why not try rotation on or rotation off as one changes the state of the other two, 1 or 0 but instead not using the 1,0 but the state of 3=1 degrees that way a 360 degree can be divided by 3 into even parts where when you divided 1/3= .3333333333333333 So what I'm trying to say is forget 3.14 and start with using degrees and use the matrix visualization of a perfect flat pyramid can be split perfect by three just like a circle. Then in all dimensions. But in the world of true quantum physics you will always have One left over to carry on the to the next calculation that's why everything ends up 99.9% 1% on for the next calculation. So you are going to have to extract the constant from quantum chaos for the answer and subtract the 1 that travels On. +,*, /, <,>, =,-, + Our universe started with one wave length of light and an anti-wave length then magnetism and gravity they where changed to form all matter: Wave Length - Gravity -Light - mass - Wave Lengths. (THEY ARE ALL INTERCHANGEABLE)" PICO SECTORS AND VECTORS IN OUR QUANTUM TUNNEL! Mass = gas, solid, liquid and there all inter-changeable it the Fundamental Frequency's is the true law of physics that controls all and how many degrees are frequency's 360 in 32 Dimensions or more moving 4 with one left over cal it a door. There is light of a unseen or seen nature inside the atom structure that we have not found yet, because there are 4 seen light and 4 unseen called refraction and have yet to understand how it bounces and reflects or refracts light but by mean of changing the structure of the atom and we are using for quantum physics it gets allot smaller. If you could harness the light of one atom to construct like hydrogen and then built on that one to find new elements new physics new computer and new worlds would be found. BY ZETALIMIT AKA TIMOTH HARRIS LIVERNACE Thanks for the support http://www.beyond-science.com/ PART OF THE QUANTUM A.I KEY TO THE WEBSITE A.I question Quadra light of quantum consciousness can go in all consciousness Dimensions we understand that Wave Length - gravity - Light - mass - Wave Lengths. (THEY ARE ALL INTERCHANGEABLE) In all infinite shapes of magnetic field of a north and south field and anti-magnetic like anti-gravity of 1 2 3 4 doing the same or all four switching to the other moving faster then the speed of light and then integrating faster then matter integrates and integrates and faster then all Dimensions Wave Length - gravity - Light - mass - Wave Lengths then making a hypercube, infinite directions teleportation, black hole, space, gravity, light, one wave lengths, gravity - Light - mass - "Wave Lengths" and then the fields in all direction. Quadra light optics. There are infinite number of colors and hues if you mix them together and then there are infinite number of magnetic field that goes with that spectrum small but can be compressed using white noise and offsetting the frequencies and compress with anti-white nose or with mirrors or time dilation. Then build your own _________________________ I have already seen! Try different colors of quartz crystals and you measure the different. From bh at intevation.de Wed Feb 2 09:48:20 2005 From: bh at intevation.de (Bernhard Herzog) Date: Wed, 02 Feb 2005 15:48:20 +0100 Subject: Hey, get this! References: <4200E5CB.6020508@holdenweb.com> Message-ID: Steve Holden writes: > What *I* would like to know is: who is allowing the import of bsddb.os, > thereby somehow causing the code of the os library module to be run a > second time. I would guess (without actually running the code) that this part is responsible: > if package: > module.__path__ = sys.path You usually should initialize a package's __path__ to an empty list. The __init__ module will take care of modifying it if necessary. Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ From steven.bethard at gmail.com Wed Feb 9 18:54:35 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 09 Feb 2005 16:54:35 -0700 Subject: empty classes as c structs? In-Reply-To: <1grqs37.1sjjd0b162e5z4N%aleaxit@yahoo.com> References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <1gric2n.17myhon1hfrc6gN%aleaxit@yahoo.com> <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> <9rmdnVR1lr-LYJvfRVn-gg@comcast.com> <4207606E.4040806@iinet.net.au> <1grnyld.1t8l5kw1nr5aqsN%aleaxit@yahoo.com> <1grqs37.1sjjd0b162e5z4N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Steven Bethard wrote: > >>I didn't know what to do for __setattr__... Was that what you meant by >>"The best semantics for _bindings_ as opposed to lookups isn't clear >>though"? > > Yep. __delattr__ ain't too obvious to me either, though I guess your > semantics for that are OK. I'm not sure how much _I_ like them... =) It makes me uneasy that del b.x print b.x doesn't throw an AttributeError. OTOH, if you're using namespaces as the equivalent of nested scopes, deleting all 'x' attributes is probably not what you want... I like the idea of chain, though, so I'll probably add the class with just __init__ and __getattribute__ to the current implementation. I'm willing to be persuaded, of course, but for the moment, since I can see a few different options, I'm refusing the temptation to guess on the "most natural" behavior for __delattr__ and __setattr__... =) Steve From steve at holdenweb.com Wed Feb 2 16:04:17 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 02 Feb 2005 16:04:17 -0500 Subject: Finding user's home dir In-Reply-To: <5i9rtc.rq31.ln@orion.homeinvalid> References: <5i9rtc.rq31.ln@orion.homeinvalid> Message-ID: Nemesis wrote: > Hi all, I'm trying to write a multiplatform function that tries to > return the actual user home directory. I saw that > os.path.expanduser("~") works on Linux but on Windows2000 (at least on > the win I used) it returns %USERPROFILE%, so I tried os.environ["HOME"] > and it gave me the same results. So I ended up with > os.environ["USERPROFILE"], it doesn't work on Linux but (at least) on > Windows2000 it returns the correct information > > I googled a little bit and it seems that there is no general solution, > so I tried to merge what I found, and I wrote this little function: > > def getHomeDir(): > ''' Try to find user's home directory, otherwise return current directory.''' > try: > path1=os.path.expanduser("~") > except: > path1="" > try: > path2=os.environ["HOME"] > except: > path2="" > try: > path3=os.environ["USERPROFILE"] > except: > path3="" > > if not os.path.exists(path1): > if not os.path.exists(path2): > if not os.path.exists(path3): > return os.getcwd() > else: return path3 > else: return path2 > else: return path1 > > Please, could you test it on your systems and tell me what you got? > I'd like to know what it returns on different operating systems because > I'm developing a multiplatform software. > > Thank you all. It works on Cygwin too! regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.python.org/pycon/2005/ Steve Holden http://www.holdenweb.com/ From nav+posts at bandersnatch.org Thu Feb 17 14:25:14 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: Thu, 17 Feb 2005 14:25:14 -0500 Subject: [EVALUATION] - E02 - ULTIMATE RECIPE TO RESOLVE ALL ISSUES References: Message-ID: <87ll9n7zvp.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Ilias Lazaridis writes: > This thread proofs simply the inability of this community [1] to focus > on a simple essence. Many communities extend a sort of "provisional membership" to new arrivals, and grant newcomers the same respect and courtesy that established members recieve. I make this distinction to point out that you are not a member of the Python community simply because you posted in a community newsgroup, but a newcomer with provisional status. I don't speak for the Python community, but from the consistent nature of the responses to your posts, it looks like your provisional membership has been revoked. Secondly, when two parties disagree about matters of etiquette, the party that is new to the community is almost certainly the one who has erred. I think you could undo the damage you have done by spending some time here, and learning that this is a community of intelligent, friendly, humorous, and insightful people. Come with suggestions, and not demands. Show us how you would like a community to behave, instead of acting like we owe you something. That's how we make the world a better place. Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From steve at holdenweb.com Sat Feb 12 17:00:53 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 12 Feb 2005 17:00:53 -0500 Subject: [EVALUATION] - E01: The Java Failure - May Python Helps? In-Reply-To: References: Message-ID: Ilias Lazaridis wrote: > Ilias Lazaridis wrote: > [...] > >> My question is essentially: >> >> How many of those constructs are already supported by python (and the >> surrounding open-source-projects): >> >> http://lazaridis.com/case/stack/index.html > > [...] > > The Signal/Noise ratio of this thread was very disapointing to me. > > I've expected better things from the python community. > > Thanks to everyone which has provided in-topic replies. > > .. > If this is "goodbye" I can't say I'm sorry. regards -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From aahz at pythoncraft.com Mon Feb 7 18:50:26 2005 From: aahz at pythoncraft.com (Aahz) Date: Mon, 7 Feb 2005 18:50:26 -0500 Subject: BayPIGgies: February 10, 7:30pm Message-ID: <20050207235026.GA17191@panix.com> [Argh -- ignore wrong date on last post] WARNING: the last meeting of BayPIGgies at Stanford is currently scheduled for March. Our host, Danny Yoo, is leaving Stanford, and we need to find a new location. If you wish to assist with the search, please join the BayPIGgies mailing list. Meanwhile, let's all give hearty thanks to Danny for helping us find a stable meeting location for so long! The next meeting of BayPIGgies will be Thurs, February 10 at 7:30pm. Donovan Preston will preview his PyCon presentation on developing GUI applications with HTML and HTTP. If you want to do a presentation in March (also before PyCon!), please send e-mail to baypiggies at baypiggies.net BayPIGgies meetings are in Stanford, California. For more information and directions, see http://www.baypiggies.net/ Before the meeting, we may meet at 6pm for dinner in downtown Palo Alto. Discussion of dinner plans is handled on the BayPIGgies mailing list. Advance notice: The March 10 meeting agenda has not been set. Please send e-mail to baypiggies at baypiggies.net if you want to make a presentation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "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." --GvR From richie at entrian.com Fri Feb 11 04:22:35 2005 From: richie at entrian.com (Richie Hindle) Date: Fri, 11 Feb 2005 09:22:35 +0000 Subject: lambda and for that matter goto not forgetting sugar In-Reply-To: <5non019hhm2uu2i2hhic9eu3eh21o2ct8u@4ax.com> References: <5non019hhm2uu2i2hhic9eu3eh21o2ct8u@4ax.com> Message-ID: [Christos] > *Three* requests --check the thread "goto, cls, wait commands". I saw that too, and was too freaked out to respond. > BTW, my sincere congratulations for what I presume best computer related April's > Fool joke of all time; I love double-bluffs. The worst of all is I've often > referenced your joke when advocating python... :) Thanks! I think the fact that it was possible at all is a *genuine* advert for Python's power and flexibility. (Though modifying Python itself in order to make the joke possible was quite a lot of work: http://sf.net/tracker/?func=detail&atid=305470&aid=643835&group_id=5470 8-) [John] > from goto.py ( http://entrian.com/goto/ ): > . # Label: "label .x" XXX Computed labels. > > :-) Yay! I've been waiting nearly a year for someone to spot that. 8-) -- Richie Hindle richie at entrian.com From nghoffma at gmail.com Fri Feb 4 22:38:25 2005 From: nghoffma at gmail.com (nghoffma) Date: 4 Feb 2005 19:38:25 -0800 Subject: returning True, False or None In-Reply-To: <1107573625.439409.100870@o13g2000cwo.googlegroups.com> References: <1107573625.439409.100870@o13g2000cwo.googlegroups.com> Message-ID: <1107574705.956498.219490@c13g2000cwb.googlegroups.com> sorry, that should have been: py>>import sets py>>def doit(thelist): ... s = sets.Set(thelist) ... if s == sets.Set([None]): ... return None ... else: ... return max(s - sets.Set([None])) From tzot at sil-tec.gr Fri Feb 4 19:07:12 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 05 Feb 2005 02:07:12 +0200 Subject: Crashing Python interpreter! (windows XP, python2.3.4, 2.3.5rc1, 2.4.0) References: <1107475081.100242.242920@f14g2000cwb.googlegroups.com> Message-ID: <7r0801pqto29eiusrcbko8ptf75dmkrhap@4ax.com> On 3 Feb 2005 15:58:01 -0800, rumours say that "John Machin" might have written: >> I don't know why searching all drives using windows 'search' did not >find the file! > >Possibilities: >1. You have a virus that renames the drwtsn32.log file for the duration >of a search. >2. Emanations from UFOs are affecting computer circuitry in your >neighbourhood. >3. Microsoft programmers stuffed up. >4. You had a typo. 5. XP really knows better than you and by default does not search in system folders. I killed that oh-so-friendly search dog on day 2 of acquainting myself with Windows XP last September, so I can't readily say where is the setting if your dog is enabled, but if your dog is dead too, it's under Advanced Options: Search system folders. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From eddie at holyrood.ed.ac.uk Mon Feb 28 09:51:31 2005 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 28 Feb 2005 14:51:31 +0000 (UTC) Subject: Trouble using telentlib References: <467fdeba.0502111441.4a558e2a@posting.google.com> Message-ID: nitinzep at yahoo.com (Nitin Chaumal) writes: >I sarched the existing threads but didnt find an answer to this. >I am writing simple script which uses telentlib to open a session with >a unix machine and run "tail -f logfile.txt" on one of the logfiles. >import telnetlib >HOST = "192.X.X.X" >user = "myname" >password = "mypass" >tn = telnetlib.Telnet(HOST) >tn.read_until("login: ") >tn.write(user + "\n") >if password: > tn.read_until("Password: ") > tn.write(password + "\n") >tn.write("tail -f /tmp/logfile.txt\n") ># what do i write here ? # >tn.write("exit\n") >I want to read every line of the output into a string and run regex on >it. >I tried tn.interact() which does show me the ouput but the CPU usage >on my win2k machine reaches 99% !! :( >How do i execute a command and then read its output, then another >command and read its output and so on. I tried to find docs on >telnetlib but in vain. >Can somebody guide me please >Thanks >Nitin tn.write("tail -f /tmp/logfile.txt\n") while True: # get one more line line = tn.read_until ('\n') regex_thing (line) Remember, "tail -f" never exits, so you probably want to break when you've find what you want and then just close the telnet session. It would probably be nice if telnetlib had a readline function that handled all the messy details for portable end of line checking. Eddie From dave at pythonapocrypha.com Fri Feb 4 09:30:30 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 04 Feb 2005 07:30:30 -0700 Subject: OT: why are LAMP sites slow? In-Reply-To: References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> Message-ID: <42038706.2090209@pythonapocrypha.com> Fredrik Lundh wrote: > Tim Daneliuk wrote: > > >>THis is why, IMHO, things like SOAP a laughable - RPC is a poor >>foundation for reliable, durable, and high-performance TP. It might be >>fine for sending an order or invoice now and then, but sustained through- >>put of the sort I think of as "high" performance is likely never going to be >>accomplished with session-oriented architectures. > > > does 50 gigabytes per day, sustained, count as high performance in your book? In and of itself, no. But really, the number is meaningless in transaction processing without some idea of the size and content of the messages (i.e. if it's binary data that has to be base64 encoded just to make it work with SOAP) because what's most interesting is the number of transactions that can be handled. If 50 GB/day is just a measurement of the throughput of the data transport layer, then that's fairly low - less than 5Mbps! -Dave From steve at holdenweb.com Thu Feb 24 13:23:29 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 24 Feb 2005 12:23:29 -0600 Subject: Trouble with mysql-python 1.2.0 on Solaris 8 sparc In-Reply-To: <1109255132.541839.207530@o13g2000cwo.googlegroups.com> References: <1108755202.574729.293610@g14g2000cwa.googlegroups.com> <1108925639.345790.230510@c13g2000cwb.googlegroups.com> <1109255132.541839.207530@o13g2000cwo.googlegroups.com> Message-ID: <421E1BA1.2030703@holdenweb.com> Alec Wysoker wrote: > Hi Andy, > > Thanks for your message. It turned out that I had installed 64-bit > mySql on a 32-bit machine. I'm amazed it worked at all. Anyway, I > finally got mysql-python built, but I'm unable to connect to a machine > on a remote host. The problem doesn't seem to be with the python code, > because I'm unable to do it even with the mysql command-line client. > Sigh. > Could be you have a 4.2 server and an earlier client. Unbelievably, MySQL changed its protocol while only incrementing the minor version number, and this bit me in the ass when I wanted to move up to 4.1. regards Steve From wuhy80 at gmail.com Sun Feb 27 22:20:56 2005 From: wuhy80 at gmail.com (wuhy80) Date: 27 Feb 2005 19:20:56 -0800 Subject: Python interfacing with other languages In-Reply-To: References: Message-ID: <1109560856.234202.62790@l41g2000cwc.googlegroups.com> Sure It can work with VB. you could use the python's com to work with VB. From jerf at jerf.org Tue Feb 8 08:20:47 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 08 Feb 2005 08:20:47 -0500 Subject: Is Python as capable as Perl for sysadmin work? References: Message-ID: On Tue, 08 Feb 2005 18:18:13 +0000, Marc Huffnagle wrote: > Jeff Epler wrote: >> >> There's another little-known fact about Python: No string is permitted >> to end with a backslash! You might think that variations like >> r'\' >> or >> """"""\\\\\"""""" >> would allow you to create this elusive value, but you'd mistaken! >> Now, this may not bother Unix sysadmins, but the honest truth is that >> you'll be administrating Windows systems, too, anywhere you work! > > >>> a = "\\" > >>> print a > \ That's really the only problem you had with his post? :-O *wink* From beliavsky at aol.com Mon Feb 14 06:28:10 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 14 Feb 2005 03:28:10 -0800 Subject: FS: O'Reilly Python Pocket Reference References: <1108360367.579794.122150@g14g2000cwa.googlegroups.com> Message-ID: <1108380490.573983.291520@f14g2000cwb.googlegroups.com> I think a better place than this newsgroup to offer used Python books for sale is Amazon or Ebay or Alibris. From steven.bethard at gmail.com Fri Feb 4 13:14:23 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 04 Feb 2005 11:14:23 -0700 Subject: returning True, False or None In-Reply-To: <5OOMd.12446$W16.3365@trndny07> References: <5OOMd.12446$W16.3365@trndny07> Message-ID: <5sydnV6im6jgJp7fRVn-qQ@comcast.com> Raymond Hettinger wrote: > "Steven Bethard" > >>For a given list: >>* If all values are None, the function should return None. >>* If at least one value is True, the function should return True. >>* Otherwise, the function should return False. > > . . . > >>Right now, my code looks like: >> >> if True in lst: >> return True >> elif False in lst: >> return False >> else: >> return None >> >>This has a light code smell for me though -- can anyone see a simpler >>way of writing this? > > > return max(lst) Very clever! Thanks! Steve From peter at engcorp.com Mon Feb 14 22:55:15 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 14 Feb 2005 22:55:15 -0500 Subject: wxPython OGL future In-Reply-To: <1108428501.441786.154130@g14g2000cwa.googlegroups.com> References: <1108428501.441786.154130@g14g2000cwa.googlegroups.com> Message-ID: PD wrote: > I am sort of a new developer to python and working in an academic > environment. I climbed the learning curve on wxPython far enough to get > the functionality I want out of it so far... Now Im in need of a > diagramming library (something visio-like) to use for my software and > the only option I have seen is OGL. Yet I read that OGL is dead, no > longer maintained, obsucure and lacking documentation. Not actually having used it, I can't help much, but the code is all there, runs fine in the latest demo, and looks pretty clean. Maybe you should examine it before you decide against it. If it does what you need, or if you can easily add the missing functionality, what else would you want out of it? -Peter From farcepest at gmail.com Thu Feb 10 20:08:04 2005 From: farcepest at gmail.com (Andy Dustman) Date: 10 Feb 2005 17:08:04 -0800 Subject: Performance Issues of MySQL with Python References: <1107954472.246556.258030@g14g2000cwa.googlegroups.com> Message-ID: <1108084084.436203.140820@l41g2000cwc.googlegroups.com> There aren't any "issues", but there are a few things to keep in mind. First of all, prior to 4.1, MySQL does no parameter binding, which means that the parameters must be inserted into your SQL statements as literals. MySQLdb will do this for you automatically, but keep in mind that you will be creating a string that is big as your original SQL statement plus the size of all the parameters. If you are doing a large INSERT (via executemany()), this could be pretty big. However, this is no worse a problem with Python than it is with anything else. MySQL-4.1 *does* support parameter binding, but MySQLdb does not yet. The next major release will, but that is months off. The other factor to account for is your result set. By default, MySQLdb uses the mysql_store_result() C API function, which fetches the entire result set into the client. The bigger this is, the longer it will take for your your query to run. You can also use a different cursor type which uses mysql_use_result(), which fetches the result set row by row. The drawback to this are that you must fetch the entire result set before you can issue another query. But again, this is not an issue with Python. Make sure you read PEP-249 and then the User's Guide. From jeff at ccvcorp.com Thu Feb 17 13:10:53 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 17 Feb 2005 10:10:53 -0800 Subject: Pausing a program - poll/sleep/threads? In-Reply-To: <1108625477.222091.34680@l41g2000cwc.googlegroups.com> References: <1108625477.222091.34680@l41g2000cwc.googlegroups.com> Message-ID: <1119nf8qqj5gfbe@corp.supernews.com> Simon John wrote: > I'm writing a PyQt network client for XMMS, using the InetCtrl plugin, > that on connection receives a track length. > > [...] > > So, how would I make a Python program automatically call a function > after a preset period of time, without the Python process running in > the foreground (effectively single-tasking)? I'm not familiar with Qt/PyQt myself, but the GUI toolkits I *am* familiar with all have a concept of a timer. Basically, you create a timer that, when the specified amount of time has elapsed, will either deliver an event/message to your application's event queue or will directly call the callback function you provide. However, I'd suggest that you may not want to wait for the entire length of the current track, especially if some other process or user (on any machine) may have access to the same XMMS application. What happens when, after the song's been playing for a few seconds, someone skips to the next track? Presumably, you'll want your network client to detect that and update appropriately. This implies that you should check back in with the XMMS "server" every few seconds at least. (You can still use a timer to do this; just have it fire periodically every second or so, rather than only after several minutes.) Jeff Shannon From grante at visi.com Mon Feb 7 21:27:07 2005 From: grante at visi.com (Grant Edwards) Date: 08 Feb 2005 02:27:07 GMT Subject: Big development in the GUI realm References: <4i3g01tv48qr50g8fjc8nf3n09eaauaen5@4ax.com> <6h7g0113up1v76k7qkad7bt17os1q73510@4ax.com> Message-ID: <4208237b$0$21623$a1866201@visi.com> On 2005-02-08, Luke Skywalker wrote: >>Now, that's not to say that they are correct in their >>interpretation of the GPL's terms. In fact, if I had to bet on >>an outcome, I'd probably wager that the court would hold that >>only static linking would force the program as a whole to >>follow the GPL terms. However, I certainly don't have the money >>to pony up to run a test case. Consequently, I try to follow >>the wishes of the copyright holder. > > It's strange that something so central hasn't been clarified > yet, but maybe it's part of the changes meant for V.3. It's been made quite clear what the intention of the FSF is in regard to static linking. Trolltech also made their intentions crystal clear. > When you think about it, it'd be like banning any > closed-source apps from being developed for Linux, since any > application makes syscalls to the kernel Wrong. The kernel license _explicitly_ allows non GPL'd programs to make calles via the published syscall API. > and its libraries. Wrong again. First, the kernel does own any libraries. Second, the libraries to which you refer are under the LGPL and other licenses which explicitly allows distribution of non-GPL'd programs that are linked dynamically with the libraries. > But the fact is Fact? You seem to be very short on facts and are mostly just making up shit as you go. > that there are now closed-source apps for that platform, and > are considered legit since those apps don't include code from > the kernel, but instead, merely make calls to binary objects. True, but moot. > I fail to see the difference between making calls to the > kernel API and making calls to Qt libraries. BECAUSE IN THE KERNEL KERNEL COPYING FILE LINUS SAYS: NOTE! This copyright does *not* cover user programs that use kernel services by normal system calls - this is merely considered normal use of the kernel, and does *not* fall under the heading of "derived work". Also note that the GPL below is copyrighted by the Free Software Foundation, but the instance of code that it refers to (the Linux kernel) is copyrighted by me and others who actually wrote it. AND TROLLTECH SAYS: Users who want to donate their source code to the Open Source community can use the Open Source version and must license their software under the GPL. Users who write commercial proprietary software must purchase a license and may freely choose how to license and profit from their software. Spare us your clueless, junior-high legal analyses and just do what's right: obey the wishes of the owners of the copyrights in question. They've made their intentions 100% clear, and if you try to worm your way around them, you're dishonorable, theiving scum. -- Grant Edwards grante Yow! I know things about at TROY DONAHUE that can't visi.com even be PRINTED!! From tundra at tundraware.com Tue Feb 1 01:58:15 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 01 Feb 2005 01:58:15 EST Subject: tkinter: Can You Underline More Than 1 Char In A Menu Title In-Reply-To: <056uv054s4ionvjt2ii8fcnm3hvcqqm8g2@4ax.com> References: <056uv054s4ionvjt2ii8fcnm3hvcqqm8g2@4ax.com> Message-ID: Tim Roberts wrote: > Tim Daneliuk wrote: > >>I am currently underling the first character of a menu title (to indicate >>its shortcut/accelerator key) like this: >> >> self.WildBtn = Menubutton(self.mBar, text=WILDMENU, underline=0, state=DISABLED) >> >>However, I intend to actually have two separate keys invoke this menu >>to have it behave differently in different circumstances. > > > You can, of course, CHANGE the underlined character to match the > circumstances. Yeah, I understand that ... what I want is two characters simulatenously underlined ... oh well, another solution will be arranged... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From jerf at jerf.org Thu Feb 17 09:55:30 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 17 Feb 2005 09:55:30 -0500 Subject: [EVALUATION] - E02 - ULTIMATE RECIPE TO RESOLVE ALL ISSUES References: Message-ID: On Thu, 17 Feb 2005 18:49:38 +0000, Stephen Kellett wrote: > Incorrect analysis. This thread proves that you have no concept of how > to interact with the community. If you had done what many people asked > you to do, which is do some work yourself, then ask questions about the > few answers you didn't discover yourself, you would have got lots of > helpful answers. You were told this many times by many people. Also on > the odd occasion someone did proffer some on-topic advice, sometimes in > long articles that must have taken some time to produce you'd dismiss > the article with "It is not on topic, I have not read it". How could you > know if it is not on topic if you don't read it? Apart from the gross > rudeness in such an attitude it demonstrates your arrogance, selfishness > and utter contempt for those replying to you. This is why I bailed on him, especially after the troll warning which is now fully justified in my mind. I'm 99% positive that I could ship him source code that meets every single one of his demands, and he'd *still* be bitching and posting, because he *would not realize it*, because of course he'd still have to read docs and learn how to use it. Moderately on topic (not Python, but programming at least): The other day I was talking to someone and I commented on how odd it is to write a library, and *still* have to learn how to use it correctly. As the author, at least I can change it as I learn more, but even so, I have to learn how to use it; even as the author I am not imbued magically with expert status. I actually think that 95% of what Ilias is claiming to be looking for is there, packaged up and almost ready to go. But he will never realize that, since we can't jump him to expert status in a four-line newsgroup post, so, *shrug*, he loses I guess. From just at xs4all.nl Sat Feb 26 20:02:09 2005 From: just at xs4all.nl (Just) Date: Sun, 27 Feb 2005 02:02:09 +0100 Subject: any Python equivalent of Math::Polynomial::Solve? References: Message-ID: In article , "Raymond L. Buvel" wrote: > Just wrote: > > > > > SciPy indeed appear to contain a solver, but I'm currently stuck in > > trying to _get_ it for my platform (OSX). I'm definitely not going to > > install a Fortran compiler just to evaluate it (even though my name is > > not "Ilias" ;-). Also, SciPy is _huge_, so maybe a Python translation of > > that Fortran code or your Perl code will turn out to be more attractive > > after all... > > > > Just > > The GNU Scientific Library has a nice root finder for polynomials with > real coefficients. I have wrapped this with Pyrex to work with my > ratfun module see: > > http://calcrpnpy.sourceforge.net/ratfun.html > > If this will suit your needs, I can send you an alpha release of the > package with the root finder. It is not pure Python. I requires Pyrex > and a C compiler to install. My guess is that it will work on OSX as > well as it does on Linux. This functionality will be included in the > next release of the ratfun package but I still have to unit test a > number of components and update the documentation. Consequently, an > official release will not happen soon. Thank you, I'll check this out. I had come across GSL, but not Python bindings. (GPL is probably a problem for my project, but it's very good to know anyway.) On the other hand, I just finished translating the relevant portions of Math::Polynomial::Solve to Python, so I'm probably all set, at least for now. Thanks everyone for the responses, especially to John Gamble! Just From nick at craig-wood.com Tue Feb 8 12:30:58 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 08 Feb 2005 17:30:58 GMT Subject: Efficient checksum calculating on lagre files References: <5o2nd2-5hl.ln1@pluto.i.infosense.no> Message-ID: Ola Natvig wrote: > Hi all > > Does anyone know of a fast way to calculate checksums for a large file. > I need a way to generate ETag keys for a webserver, the ETag of large > files are not realy nececary, but it would be nice if I could do it. I'm > using the python hash function on the dynamic generated strings (like in > page content) but on things like images I use the shutil's > copyfileobject function and the hash of a fileobject's hash are it's > handlers memmory address. > > Does anyone know a python utility which is possible to use, perhaps > something like the md5sum utility on *nix systems. Here is an implementation of md5sum in python. Its the same speed give or take as md5sum itself. This isn't suprising since md5sum is dominated by CPU usage of the MD5 routine (in C in both cases) and/or io (also in C). I discarded the first run so both tests ran with large_file in the cache. $ time md5sum large_file e7668fdc06b68fbf087a95ba888e8054 large_file real 0m1.046s user 0m0.946s sys 0m0.071s $ time python md5sum.py large_file e7668fdc06b68fbf087a95ba888e8054 large_file real 0m1.033s user 0m0.926s sys 0m0.108s $ ls -l large_file -rw-r--r-- 1 ncw ncw 115933184 Jul 8 2004 large_file """ Re-implementation of md5sum in python """ import sys import md5 def md5file(filename): """Return the hex digest of a file without loading it all into memory""" fh = open(filename) digest = md5.new() while 1: buf = fh.read(4096) if buf == "": break digest.update(buf) fh.close() return digest.hexdigest() def md5sum(files): for filename in files: try: print "%s %s" % (md5file(filename), filename) except IOError, e: print >> sys.stderr, "Error on %s: %s" % (filename, e) if __name__ == "__main__": md5sum(sys.argv[1:]) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From harlinseritt at yahoo.com Sun Feb 27 03:41:48 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 27 Feb 2005 00:41:48 -0800 Subject: function expression with 2 arguments In-Reply-To: <1109453122.034646.290200@z14g2000cwz.googlegroups.com> References: <1109419984.213993.49280@f14g2000cwb.googlegroups.com> <98ydnSp0COmeLr3fRVn-jQ@powergate.ca> <1109453122.034646.290200@z14g2000cwz.googlegroups.com> Message-ID: <1109493708.942841.231700@o13g2000cwo.googlegroups.com> ? From tjreedy at udel.edu Mon Feb 7 22:16:52 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 7 Feb 2005 22:16:52 -0500 Subject: variable declaration References: <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com> <4208178F.40804@po-box.mcgill.ca> Message-ID: "Brian van den Broek" wrote in message news:4208178F.40804 at po-box.mcgill.ca... > Is the right way to understand it in this vicinity: In the vicinity, but not quite exact >At compile time (by which I mean when the Python bytecode is built) Compile time is when the def statement is executed >the global statement is hit and has the effect of `bumping up' the >function local name `x' to the module namespace, making the function local >name `x' synonymous with the module global name `x'. Global make 'x' global. Period. There is no local 'x'. > At runtime, the `global x' is never reached, In CPython, at least, it is not even there to be reached (see below). It is strictly a compile time declaration. At runtime, it is equivalent to 'pass'. > but it has already, at compile time, had its effect on the nature of the > function object Right. With 2.2: def f(): if False: global x x = 1 import dis dis.dis(f) 0 SET_LINENO 1 3 SET_LINENO 2 6 LOAD_GLOBAL 0 (False) 9 JUMP_IF_FALSE 7 (to 19) 12 POP_TOP 13 SET_LINENO 2 16 JUMP_FORWARD 1 (to 20) >> 19 POP_TOP >> 20 SET_LINENO 3 23 LOAD_CONST 1 (1) 26 STORE_GLOBAL 1 (x) 29 LOAD_CONST 0 (None) 32 RETURN_VALUE Two points: there is no byte code for the global declaration; x is directly stored as global. Terry J. Reedy From tbunce at mac.com Tue Feb 1 17:27:02 2005 From: tbunce at mac.com (Thomas Bunce) Date: Tue, 01 Feb 2005 14:27:02 -0800 Subject: How do you do arrays References: <1107286861.714451.288010@f14g2000cwb.googlegroups.com> Message-ID: Learning Python O'Reilly book and Python In A Nut Shell and about 2 inchs printed of Web information Tom In article <1107286861.714451.288010 at f14g2000cwb.googlegroups.com>, "Kartic" wrote: > Tom, > > It has to be iMatrix.append(k), not iMatrix[index] = k. Python will > give an error - list assignment index out of range - for that. > Just curious - what book are you following? > > -Kartic From dimitri.pater at gmail.com Fri Feb 4 07:21:45 2005 From: dimitri.pater at gmail.com (dimitri pater) Date: Fri, 4 Feb 2005 13:21:45 +0100 Subject: walktree browser filenames problem In-Reply-To: References: Message-ID: thanks! now it works: ret.append(' %s\n' % (urllib.quote(escape(name)),escape(name))) bye, Dimitri On Fri, 4 Feb 2005 11:45:17 -0000, Richard Brodie wrote: > > "dimitri pater" wrote in message > news:mailman.1877.1107516622.22381.python-list at python.org... > > > The problem is that the filenames are cut off in the status bar of the > > browser because of the white space (eg 'hello.pdf' works, but 'hello > > there.pdf' is displayed as hello). > > urllib.quote() should do the trick. You need to follow the rules for > encoding URIs as well as the HTML ones. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Please visit dimitri's website: www.serpia.com From edreamleo at charter.net Fri Feb 25 07:49:22 2005 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 25 Feb 2005 06:49:22 -0600 Subject: Leo 4.3-a3 Outlining IDE References: Message-ID: I really only posted this once to comp.lang.python. The duplicate appears to be the work of the Department of Redundancy Department. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From grante at visi.com Tue Feb 1 13:00:36 2005 From: grante at visi.com (Grant Edwards) Date: 01 Feb 2005 18:00:36 GMT Subject: Where are list methods documented? References: <41ffba7d$0$15879$a1866201@visi.com> Message-ID: <41ffc3c4$0$10772$a1866201@visi.com> On 2005-02-01, Brian van den Broek wrote: > I'm not positive I understand what you are looking for, but do these > help?: > > > > Yes, that last page was the one I was looking for. I didn't know enough to spell list as "mutable sequence type". -- Grant Edwards grante Yow! I think my CAREER at is RUINED!! visi.com From bvande at po-box.mcgill.ca Wed Feb 23 13:12:04 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed, 23 Feb 2005 13:12:04 -0500 Subject: Selective HTML doc generation In-Reply-To: <1109169752.819253.202930@o13g2000cwo.googlegroups.com> References: <1109169752.819253.202930@o13g2000cwo.googlegroups.com> Message-ID: <421CC774.8040304@po-box.mcgill.ca> Graham said unto the world upon 2005-02-23 09:42: > Hi. I'm looking for a documentation generation tool (such as pydoc, > epydoc, happydoc, etc.) that will allow me to filter what it includes > in > it's output. > > I only want the reader to know about classes and methods in my package > if if the classes have docstrings. I've got a large package that is > used > by relatively non-technical users (and yet they write Python!) that > documents the public API with docstrings. I don't want to clutter their > view of the world with links to the package's internal classes and > documentation that covers things like __special__ methods. > > Anybody know of anything that let's you do it? I realise I may end up > doing some hacking here but don't want to repeat work unnecessarily. > > Cheers, > > Graham Hi Graham, I'm not at all an expert OK, that out of the way: I recently wanted pydoc to display information about my methods whose names started with one or more underscores, so that I could see in the docs for the objects in my first bigger than small project. I managed with a small change to the visiblename function of pydoc.py. It looks to me that this is also the place where you'd want to put in code to filter for only treating objects with docstrings. *How* to do that is something I've not read enough of pydoc.py to speak to. Omitting special methods is easy, though. The code says: # Private names are hidden, but special names are displayed. if name.startswith('__') and name.endswith('__'): return 1 So, just change the 1 to a 0. (The `private' logic is a few lines down.) Easy :-) Hope that is at least of some help. Best, Brian vdB From onurb at xiludom.gro Mon Feb 21 05:25:46 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 21 Feb 2005 11:25:46 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <42123751$0$10042$626a14ce@news.free.fr> <421244f0$0$30339$636a15ce@news.free.fr> <421284dc$0$14312$626a14ce@news.free.fr> Message-ID: <4219b72c$0$29993$636a15ce@news.free.fr> Ilias Lazaridis wrote: > Bruno Desthuilliers wrote: > [...] > > closing thread > http://groups-beta.google.com/group/comp.lang.python/msg/f2ae9cdbe16676d1 > Nope. You are not entitled to close thread. This is irrelevant. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fakeadmin at gmail.com Thu Feb 10 22:22:37 2005 From: fakeadmin at gmail.com (rhat) Date: 10 Feb 2005 19:22:37 -0800 Subject: Unit Testing in Python References: <1108087841.271630.228970@o13g2000cwo.googlegroups.com> Message-ID: <1108092157.371659.282070@z14g2000cwz.googlegroups.com> Yeah, you know I only ask questions about Test-driven development basics in hopes of obtaining your personal information, so that I can sell it on the Molodovian blackmarket. I'm not a "Phisher", I'm a comp-sci major who's too lazy to dig around for his own answers. ;) Thanks for your help Roy, I wasn't sure what the difference between unittest and pyunit were. --|2 \| /-\ |\| | Hi, is it possible to create 'global' variables that can be seen in all other classes? Alex From pinard at iro.umontreal.ca Wed Feb 9 09:25:34 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Wed, 9 Feb 2005 09:25:34 -0500 Subject: What's wrong with `is not None`? In-Reply-To: References: Message-ID: <20050209142534.GA18527@alcyon.progiciels-bpi.ca> [Stefan Behnel] > Frans Englich schrieb: > >What is the equivalent expression which is more secure; `!= None`? > If I want to check for None, I always do it with "is". It's a constant > after all... So do I. There is only one None object, for which an `is' test is especially appropriate. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From devnull at joreybump.com Fri Feb 4 23:27:25 2005 From: devnull at joreybump.com (Jorey Bump) Date: Sat, 05 Feb 2005 04:27:25 GMT Subject: ANN: Frog 1.3 released (python 'blog' application) References: <41fcf53b$0$28986$e4fe514c@news.xs4all.nl> <4203df05$0$28985$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote in news:4203df05$0$28985$e4fe514c at news.xs4all.nl: > I've added a 'filemgr' package to the files section; you can > get the file manager separately from there. > Or re-download the Frog-complete package (I've replaced it > with a version where the file manager is included). > > http://sourceforge.net/project/showfiles.php?group_id=41175 > > Read the README file first. > > Please let me know what you think of Frog and the FileMgr. Thanks, I'm impressed. However, I feel as though the file manager should be integrated with Frog in a such a way that it is enabled automatically for users when they are created. The mkuser.py script felt a bit awkward, especially when creating users was so easy in the administrative interface. And once logged in, a user shouldn't need to authenticate to the file manager separately. I understand that the file manager was developed as a standalone webapp, but the virtual user support is a big plus in Frog, and it would be great to start uploading images to blogfiles/user/ right away. From gdamjan at gmail.com Fri Feb 11 12:24:22 2005 From: gdamjan at gmail.com (Damjan) Date: Fri, 11 Feb 2005 18:24:22 +0100 Subject: Big development in the GUI realm References: <1107795145.049239.73450@l41g2000cwc.googlegroups.com> <5ocf01hmspufk3iusvm35p6hj4mes5heke@4ax.com> <4207c8db$0$21623$a1866201@visi.com> <36sip2F56jjmaU1@individual.net> Message-ID: <374826F5851cbU1@individual.net> > The problem with this is what I've called the "patch hole" in another > context [1]. The problem with this definition is that I can *always* > distribute GPL'ed parts separately and re-combine them arbitrarily upon > execution, and it's not even particularly hard. Write your code with the > GPL'ed code embedded. At the end, before you distribute, extract it and > record the extraction so your program can "rewind it"; you're left with > nothing in your code that is GPLed. Later, the user will go get the GPL > software, and you software "rewinds" the extraction process, and the user > is left with something that is byte-for-byte identical to what you weren't > allowed to distribute by the GPL.... so what good was the GPL? What you described is not ok according to the GPL - since you distributed a binary thats derived from GPL software (and you didn't publish it source code under the GPL too). > Nobody really knows what the GPL means when it gets down to it; If you don't know, you should ask the person whose GPL code you are using. -- damjan From jeff at ccvcorp.com Thu Feb 10 18:40:53 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 10 Feb 2005 15:40:53 -0800 Subject: [N00B] What's %? In-Reply-To: <1108074594.398184.252120@f14g2000cwb.googlegroups.com> References: <614c778e.0502100938.6665cb52@posting.google.com> <1108074594.398184.252120@f14g2000cwb.googlegroups.com> Message-ID: <110ns5ma337s982@corp.supernews.com> Harlin wrote: > What good is the modulus operator? What would I ever need it for? > > * A quick way of testing whether an integer is even and odd > * For that matter, a quick way of testing whether a the variable is a > factor of any other arbitrary number. > * In some programs (a weight control program I worked on comes to mind) > it's necessary to get a remainder so that you can get the results of a > leftover evenly divisible number. Also, it's a good way to ensure that some number is in a specified range, and "wraps around" to the beginning if it goes out of that range. For a quick & cheesy example, let's say we want to count time for music: import time def beats = ['one', 'two', 'three', 'four'] n = 0 while True: print beats[n] n = (n+1) % 4 time.sleep(0.5) By using '% 4', I ensure that n is always in the interval [0...4) (including 0 but not including 4). Modulus is useful for all sorts of periodic behavior. Jeff Shannon Technician/Programmer Credit International From qwweeeit at yahoo.it Thu Feb 24 09:09:10 2005 From: qwweeeit at yahoo.it (qwweeeit) Date: 24 Feb 2005 06:09:10 -0800 Subject: Shift Confusion References: <1109225214.430739.259600@l41g2000cwc.googlegroups.com> Message-ID: <2ab23d7a.0502240609.24755745@posting.google.com> At programming level it seems correct (a part a "return" closure needed for the "main" function). But the error is IMHO conceptual: for a char you need 7 bits (from 0 to 127 or in hex from x00 to x7F) and you can't accomodate the other char in only one bit! The other 128 symbols (from 128 to 255 or in hex from x80 to xFF) are only possible because you use again 7 bits, but with the 8th bit set to 1! What you are trying to do I made in C language (some years ago...) using however bytes and words, packing 2 bytes in only one word, but you can't pack 2 chars (each one beeing nearly a byte) in a byte! From Serge.Orlov at gmail.com Sat Feb 12 03:17:08 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: Sat, 12 Feb 2005 11:17:08 +0300 Subject: sre is broken in SuSE 9.2 References: <1108060527.378911.146240@o13g2000cwo.googlegroups.com><1108064973.719544.228970@z14g2000cwz.googlegroups.com><1108133339.401022.272310@f14g2000cwb.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Serge Orlov wrote: > >>>>>> re.compile(ur'\w+', re.U).findall(u'\xb5\xba\xe4\u0430') >>>>>> [u'\xb5\xba\xe4\u0430'] >> >> I can't find the strict definition of isalpha, but I believe average >> C program shouldn't care about the current locale alphabet, so >> isalpha is a union of all supported characters in all alphabets > > nope. isalpha() depends on the locale, as does all other ctype > functions (this also applies to wctype, on some platforms). I mean "all supported characters in all alphabets [in the current locale]". For example in ru_RU.koi8-r isalpha should return true for characters in English and Russian alphabets. In ru_RU.koi8-u -- for characters in English, Russia and Ukrain alphabets, in ru_RU.utf-8 -- for all supported by the implementation alphabetic characters in unicode. IMHO iswalpha in POSIX locale can return true for all alphabetic characters in unicode instead of being limited by English alphabet. Serge. true in From claudio.grondi at freenet.de Fri Feb 4 14:02:02 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 4 Feb 2005 19:02:02 -0000 Subject: IPython colors in windows References: <1107487113.732375.110850@c13g2000cwb.googlegroups.com> <36hculF51ho2sU1@individual.net> <1107530489.308497.103530@g14g2000cwa.googlegroups.com> Message-ID: <36hrjpF4ui8fbU1@individual.net> I use this one, http://heanet.dl.sourceforge.net/sourceforge/uncpythontools/readline-1.7.win 32.exe which I assume is the right one. Any other ideas? Claudio "Fuzzyman" schrieb im Newsbeitrag news:1107530489.308497.103530 at g14g2000cwa.googlegroups.com... > Are you really using the readline module from newcenturycomputers ? > I've got a feeling that's broken and you need to use the Gary Bishop > one with IPython.... > > Sorry if this is spurious... (restricted internet access, so I can't > check for you... but the correct one is linked to from the IPython > site). From simoninusa2001 at yahoo.co.uk Sun Feb 6 23:48:51 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 6 Feb 2005 20:48:51 -0800 Subject: WYSIWYG wxPython "IDE"....? In-Reply-To: <4205fcd9@news.highway1.com.au> References: <1107560658.584623.303310@o13g2000cwo.googlegroups.com> <4205fcd9@news.highway1.com.au> Message-ID: <1107751731.066796.295170@g14g2000cwa.googlegroups.com> Tim Hoffman wrote: > Have you tried Boa Constructor ? > > http://boa-constructor.sourceforge.net/ Yeah, I was never very impressed with it either. The current version doesn't seem to work with wxPython 2.5.3.1 though.... I guess there isn't a GUI builder that does what I want, back to the manual way of doing things I guess, unless I use Qt for this project maybe, and keep it to myself (due to the stupid Qt licensing). From strombrg at dcs.nac.uci.edu Fri Feb 25 20:21:59 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Sat, 26 Feb 2005 01:21:59 GMT Subject: netmask arithmetic? Message-ID: Before I go and reinvent the wheel, does anyone already have python code that can do netmask arithmetic - for example, determining if a list of hostnames are on subnets described by a list of networks+netmasks like: 128.200.34.0/24 128.195.16.128/25 ...and so on? Thanks! From jerf at jerf.org Tue Feb 1 23:41:11 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 01 Feb 2005 23:41:11 -0500 Subject: hotspot profiler experience and accuracy? References: Message-ID: On Tue, 01 Feb 2005 19:24:20 -0800, aurora wrote: > I have a parser I need to optimize. It has some disk IO and a lot of > looping over characters. > > I used the hotspot profiler to gain insight on optimization options. The > methods show up on on the top of this list seems fairly trivial and does > not look like CPU hogger. Nevertheless I optimized it and have 25% > performance gain according to hotspot's number. I can't answer your other question, but general optimization advice, since I've been in this situation a couple of times: Generally, you're not going to win in an interpreted language like Python* looping over all chars. You should either eliminate those loops if possible, or move the guts of the looping into regular expressions, which are designed to do that sort of thing as optimally as possible. (I've never looked at the internals, but I believe the "compile()" function in the re module isn't just a way of conveniently sticking a regex into a variable; you are actually creating a compiled and reasonably optimized (as long as you don't get crazy) character scanner that you simply Can Not beat in pure Python.) As a last-ditch scenario, you could go to a C extension, but regexs should be good enough, and only beatable in the simplest of cases. Write good REs (you could ask for help, but you should probably just test it yourself; the key thing to try for, I think, is to put as much into one RE as possible and ask the match object which thing matched but I may be wrong; more experienced comments welcomed), and then run the profiler again. In general though, the precise numbers coming out of the profiler are less important than their relationships; as long as the relationships are maintained the data is still good. *: At current technology levels. Yes, someday optimization will make looping over characters in Python even faster than C, or so the theory goes. That's not today, or even tomorrow, though. From steve at holdenweb.com Tue Feb 1 20:37:43 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 01 Feb 2005 20:37:43 -0500 Subject: variable declaration In-Reply-To: References: <1107205410.367521.50490@f14g2000cwb.googlegroups.com> <44SdnUZGopnrAWLcRVn-pg@telcove.net> <41FFAE20.7030802@holdenweb.com> Message-ID: Thomas Bartkus wrote: > "Steve Holden" wrote in message > news:41FFAE20.7030802 at holdenweb.com... > >>Thomas Bartkus wrote: >> >> >>>"Carl Banks" wrote in message >>>news:1107205410.367521.50490 at f14g2000cwb.googlegroups.com... >>> >>> >>>>How common is it for a local variable to be bound in >>>>more than one place within a function? >>> >>> >>>How common? It shouldn't happen at all and that was the point. >> >>This seems a little excessive to me. Sample use case: >> >>for something in lst: >> if type(something) != type(()): >> something = tuple(something) > > > Hhhmmh! > I presume you are going through the list and want to gaurantee that every > item you encounter is a tuple! So if it ain't - you just re-declare > "something" to be a tuple. What was formerly a single string, integer, > whathaveyou is now a tuple *containing* a single string, integer, > whathaveyou. > > Do you do it that way because you can? Or because you must? > And > If the former - is it a good idea? > OR did I just miss your codes intent completely? > I suspect you missed the intent completely. > My first inclination would be to create a new variable (type = tuple) and > accept (or typecast) each "something" into it as required. The notion that OK, but if you do that then surely the loop looks like for something in lst: somethingElse = something if type(somethingElse) != type(()): somethingElse = ... > you just morph "something" still seems rather abhorrent. It hadn't occurred > to me that iterating through a list like that means the iterater "something" > might need to constantly morph into a different type according to a lists > possibly eclectic contents. > Now I suspect I'm missing *your* point. > It might explain why the interpreter is incapable of enforcing a type. It > would forbid iterating through lists containing a mix of different types. > EXCEPT- I must note, that other languages manage to pull off exactly such a > trick with a variant type. When you need to pull off a feat such as this, > you declare a variant type where the rules are relaxed *for that situation > only* and there is no need to toss the baby out with the bathwater. > Well I have to say that the longer I program (and I've been at it nearly forty years now) the more I am convinced that type declarations don't actually help. I can see their value in terms of code optimization, but there is no way that I see them as an error-detection mechanism. "You have tried to assign a string to an integer variable" just isn't a mistake I make a lot. regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.python.org/pycon/2005/ Steve Holden http://www.holdenweb.com/ From zorro at chez.com Fri Feb 4 15:40:06 2005 From: zorro at chez.com (jb) Date: Fri, 4 Feb 2005 21:40:06 +0100 Subject: How to enable Python Scripts with MS IIS Web Server? References: <1107531390.688583.231970@l41g2000cwc.googlegroups.com> Message-ID: <4203dda7$0$491$626a14ce@news.free.fr> hi, you should first install win32all : http://starship.python.net/crew/mhammond/ next, 2 ways 2 proceed, but the first is the easier : you make a "test.asp" page in the folder at the top, you write <@Language=Python%> a line below : <%Response.Write("Hello World")%> try if the page works well. if it works then your python/iis install is ok the second way is to keep the .py extension and to associate it with the python executable http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B276494 hope this helps juju a ?crit dans le message de news: 1107531390.688583.231970 at l41g2000cwc.googlegroups.com... > > > > Hi. I have MS Windows Server 2003, Enterprise Edition. > It has MS Management Console 2.0, Version 5.2 > and IIS Manager 6.0 > > > > I have a directory called "myDirs". Within this directory are 2 files: > 1) index.pl (a perl script) > 2) index.py (a python script whose first line is > "#!C:\Python21\pythonw.exe") > > The webserver is listening on port 8080. > > When I point my browser to http://localhost:8080/myDirs/index.pl, it > works... I see the output of the perl script. > > HOWEVER, > When I point my browser to http://localhost:8080/myDirs/index.py, it > simply shows the python file as text. It doesn't interpret it at all. > > How Can I get it to interpret the python file using the interpreter and > display the output in the browser? > > Please explain each step in careful/excruciating detail because I'm a > windows Newbie. > > > -Saqib Ali > From steven.bethard at gmail.com Thu Feb 17 15:09:42 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 17 Feb 2005 13:09:42 -0700 Subject: How to wrap a class's methods? In-Reply-To: <4214f167$0$44618$a1866201@visi.com> References: <4214f167$0$44618$a1866201@visi.com> Message-ID: Grant Edwards wrote: > I want to subclass an IMAP connection so that most of the > methods raise an exception if the returned status isn't 'OK'. > This works, but there's got to be a way to do it that doesn't > involve so much duplication: > > class MyImap4_ssl(imaplib.IMAP4_SSL): > > def login(*args): > s,r = imaplib.IMAP4_SSL.login(*args) > if s!='OK': > raise NotOK((s,r)) > return r > > def list(*args): > s,r = imaplib.IMAP4_SSL.list(*args) > if s!='OK': > raise NotOK((s,r)) > return r > > def search(*args): > s,r = imaplib.IMAP4_SSL.search(*args) > if s!='OK': > raise NotOK((s,r)) > return r > > [and so on for another dozen methods] A more tested version of my other email: py> class C(object): ... def f(self, *args): ... print "f:", args ... def g(self, *args): ... print "g:", args ... py> class D(C): ... pass ... py> class Wrapper(object): ... def __init__(self, func): ... self.func = func ... def __call__(self, *args): ... print "wrapped" ... return self.func(*args) ... py> for name in ['f', 'g']: ... wrapper = Wrapper(getattr(C, name)) ... setattr(D, name, new.instancemethod(wrapper, None, D)) ... py> C().f() f: () py> C().g(1) g: (1,) py> D().f() wrapped f: () py> D().g(1) wrapped g: (1,) From jerf at jerf.org Thu Feb 3 20:18:27 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 03 Feb 2005 20:18:27 -0500 Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xy8e5jagh.fsf@ruckus.brouhaha.com> <7xis59nd2v.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 03 Feb 2005 20:50:16 -0800, Paul Rubin wrote: > I understood the Twisted suggestion as meaning avoiding database > traffic by keeping both user and server state resident in the > application. Yes, if you use a database for that, you get multiple > app servers instead of a heavily loaded centralized one. But you now > have a heavily loaded centralized database server instead. You > haven't really solved your scaling problem, you've just moved it back > a layer. True, but my understanding is that there are load balancing solutions for database servers too, so in this case moving the problem back one level actually can be progress. But I have no experience with this, so I have no idea how well it works. From alanmk at hotmail.com Wed Feb 2 12:25:43 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 02 Feb 2005 17:25:43 +0000 Subject: Suggesion for an undergrad final year project in Python In-Reply-To: <1107241918.722156.123590@c13g2000cwb.googlegroups.com> References: <1107241918.722156.123590@c13g2000cwb.googlegroups.com> Message-ID: <__7Md.46809$Z14.30635@news.indigo.ie> [Sridhar] > I am doing my undergrade CS course. I am in the final year, and would > like to do my project involving Python. Our instructors require the > project to have novel ideas. Can the c.l.p people shed light on this > topic? PyPy is chock full of novel ideas, given that two of the main developers are Armin Rigo (of psyco fame) and Christian Tismer (stackless python). PyPy is a project, which has obtained European funding, to reimplement python *in python*, a very laudable goal. http://codespeak.net/pypy/ Psyco is a "specialising compiler" for cpython, which essentially does something like just-in-time compilation, but with a different slant. http://psyco.sourceforge.net/introduction.html Armin's paper on the techniques used should make an interesting read for your CS professors: http://psyco.sourceforge.net/theory_psyco.pdf Stackless python has support for full coroutines, as opposed to cpython's current support for semi-coroutines. In the past, Stackless used to support continuations, but no longer does because of the complexity of adapting the cpython interpreter to support them. But Christian's implementation experience will hopefully guide PyPy in the direction of supporting both coroutines and continuations. http://www.stackless.com/ As for what you could do in the PyPy project, I have no suggestions since I am not involved in the project. But I am sure that a message to pypy-dev will elicit plenty of ideas. http://codespeak.net/mailman/listinfo/pypy-dev Lastly, the jython project is undergoing a bit of renaissance at the moment, and there's plenty of work to be done. A message to jython-dev volunteering time is unlikely to go unnoticed. Particularly, the parser, code generation and AST are areas which require a fair amount of rework. But there is less opportunity to use "novel ideas" in jython, so it may not interest your professors, unless you have some novel ideas of your own to bring to the project. http://lists.sourceforge.net/lists/listinfo/jython-dev How much time, over how long a period, do you have available for your project? Best of luck, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From renelt at web.de Sun Feb 27 11:21:09 2005 From: renelt at web.de (Alex Renelt) Date: Sun, 27 Feb 2005 17:21:09 +0100 Subject: any Python equivalent of Math::Polynomial::Solve? In-Reply-To: References: <1109485184.587035.176540@l41g2000cwc.googlegroups.com> Message-ID: <38e9nqF5ndqt9U1@individual.net> Just wrote: > In article <1109485184.587035.176540 at l41g2000cwc.googlegroups.com>, > "Carl Banks" wrote: >>It should be pretty easy to set up a Numeric matrix and call >>LinearAlgebra.eigenvalues. For example, here is a simple quintic >>solver: >> >>. from Numeric import * >>. from LinearAlgebra import * >>. >>. def quinticroots(p): >>. cm = zeros((5,5),Float32) >>. cm[0,1] = cm[1,2] = cm[2,3] = cm[3,4] = 1.0 >>. cm[4,0] = -p[0] >>. cm[4,1] = -p[1] >>. cm[4,2] = -p[2] >>. cm[4,3] = -p[3] >>. cm[4,4] = -p[4] >>. return eigenvalues(cm) >> >> >>now-you-can-find-all-five-Lagrange-points-ly yr's, > > > Wow, THANKS. This was the answer I was secretly hoping for... "Great > need for speed", no, not really, but this Numeric-based version is about > 9 times faster than what I translated from Perl code yesterday, so from > where I'm standing your version is blazingly fast... > > Thanks again, > > Just in addition: I'm writing a class for polynomial manipulation. The generalization of the above code is: definitions: 1.) p = array([a_0, a_i, ..., a_n]) represents your polynomial P(x) = \sum _{i=0} ^n a_i x^i 2.) deg(p) is its degree 3.) monic(p) makes P monic, i.e. monic(p) = p / p[:-1] then you get: from numarray import * import numarray.linear_algebra as la def roots(p): p = monic(p); n = deg(p) M = asarray(zeros((n,n)), typecode = 'f8') # or 'c16' if you need complex coefficients M[:-1,1:] = identity(n-1) M[-1,:] = -p[:-1] return la.eigenvalues(M) Alex From ole.anders.walseth at telemed.no Mon Feb 14 09:30:16 2005 From: ole.anders.walseth at telemed.no (oleaw) Date: Mon, 14 Feb 2005 09:30:16 -0500 Subject: Problem using win32com References: Message-ID: <5dfea5a0c5ca0d0e6b20692e26534d79@localhost.talkaboutprogramming.com> I am having a similar problem with a com+ API created in delphi. is this a win32com problem? From bvande at po-box.mcgill.ca Sat Feb 5 20:34:51 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 05 Feb 2005 20:34:51 -0500 Subject: Definitive documentation on newstyle classes? (WAS: Pickling and inheritance are making me hurt) In-Reply-To: <1d6cdae305020516467620aa0@mail.gmail.com> References: <1d6cdae305020516467620aa0@mail.gmail.com> Message-ID: <4205743B.4060100@po-box.mcgill.ca> Daniel Bickett said unto the world upon 2005-02-05 19:46: > I was reading the "Pickling and inheritance are making me hurt" > thread, and the latest suggestion (as of this posting) was to do with > the __setstate__ and __getstate__ methods. They caught my attention > because I hadn't encountered them before, and it reminded me that in > the past I've never been able to very good, definitive documentation > on newstyle classes. Googling for it gives little python tutorials on > various sites, and even searching this newsgroup returns very specific > questions, as a rule. > > Alas, the question: Does there exist a page that enumerates all of the > features of the newstyle classes, and explains what they all do? If > so, can anyone provide me with such a link? > > Thanks :-) Hi Daniel, it doesn't yet answer the "definitive" part, but is worth a look. Best, Brian vdB From steven.bethard at gmail.com Mon Feb 21 00:47:31 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 20 Feb 2005 22:47:31 -0700 Subject: help please In-Reply-To: References: <1108324679.451793.147890@z14g2000cwz.googlegroups.com> <1108329540.239064.144920@f14g2000cwb.googlegroups.com> <1108334012.336816.221460@g14g2000cwa.googlegroups.com> <1108921146.274248.11500@g14g2000cwa.googlegroups.com> <1108959170.585091.202240@z14g2000cwz.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: > On 20 Feb 2005 20:12:50 -0800, "gargonx" declaimed > the following in comp.lang.python: > >>>>>decode_replacements.update([(std[key], key) for key in std]) >> >>Traceback (most recent call last): >> File "", line 1, in ? >>AttributeError: keys > > Did you read the reference manual? Yes, actually. But I generally check only the reference manual for the current version of Python: http://docs.python.org/lib/typesmapping.html which does support sequence arguments for dict.update. As noted there, of course, this support was added for Python 2.4. STeVe From dontwant at spam.com Sat Feb 12 23:01:43 2005 From: dontwant at spam.com (Courageous) Date: Sat, 12 Feb 2005 20:01:43 -0800 Subject: Kill GIL References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <1107964587.818199.223980@g14g2000cwa.googlegroups.com> <7xr7jlwieq.fsf@ruckus.brouhaha.com> <868y5t6sal.fsf@guru.mired.org> Message-ID: <50kt01l2tmi712hb07jicpgqru6s8pqtoc@4ax.com> >Here here. I find that threading typically introduces worse problems >than it purports to solve. I recently worked on a software effort, arguably one of the most important software efforts in existence, in which individuals responsible for critical performance of the application threw arbitrarily large numbers of threads at a problem, on a multi processor machine, on a problem that was intrinsically IO-bound. The ease with which one can get into problems with threads (and these days, also with network comms) leads to many problems if the engineers aren't acquainted sufficiently with the theory. Don't get me started on the big clusterfucks I've seen evolve from CORBA... C// From jerf at jerf.org Fri Feb 4 08:01:16 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 04 Feb 2005 08:01:16 -0500 Subject: returning True, False or None References: Message-ID: On Fri, 04 Feb 2005 10:48:44 -0700, Steven Bethard wrote: > I have lists containing values that are all either True, False or None, > e.g.: > > [True, None, None, False] > [None, False, False, None ] > [False, True, True, True ] > etc. > > For a given list: > * If all values are None, the function should return None. > * If at least one value is True, the function should return True. > * Otherwise, the function should return False. > > Right now, my code looks like: > > if True in lst: > return True > elif False in lst: > return False > else: > return None Yes, I see the smell, you are searching the list multiple times. You could bail out when you can: seenFalse = False for item in list: if item: return True if item is False: seenFalse = True if seenFalse: return False return None But I'd submit that if four item lists are your common case, that your original code is significantly easier to understand what it is doing. This can be alleviated with an appropriate comment on the chunk of code I gave you, though. From steven.bethard at gmail.com Sun Feb 27 20:12:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 27 Feb 2005 18:12:17 -0700 Subject: string methods (warning, newbie) In-Reply-To: References: Message-ID: <-_KdnbUPBttz8r_fRVn-ow@comcast.com> Nick Coghlan wrote: > Jimmy Retzlaff wrote: > >> The approach you are considering may be easier than you think: >> >>>>> filter(str.isalpha, 'The Beatles - help - 03 - Ticket to ride') >> >> 'TheBeatleshelpTickettoride' > > Hmm, I think this is a case where filter is significantly clearer than > the equivalent list comprehension: > > Py> "".join([c for c in 'The Beatles - help - 03 - Ticket to ride' if > c.isalpha( > )]) > 'TheBeatleshelpTickettoride' On the other hand, filter doesn't do the same thing: py> s = u'The Beatles - help - 03 - Ticket to ride' py> filter(str.isalpha, s) Traceback (most recent call last): File "", line 1, in ? TypeError: descriptor 'isalpha' requires a 'str' object but received a 'unicode' py> ''.join(c for c in s if c.isalpha()) u'TheBeatleshelpTickettoride' Ideally, you could use something like basestring.isalpha and have it work for both str and unicode, but no such luck. =) STeVe From rNOSPAMon at flownet.com Wed Feb 16 11:34:55 2005 From: rNOSPAMon at flownet.com (Ron Garret) Date: Wed, 16 Feb 2005 08:34:55 -0800 Subject: supress creation of .pyc files References: Message-ID: In article , Thomas Guettler wrote: > Hi, > > Is there a way to import a file without creating > a .pyc file? > > Of course you can delete the pyc in my script after > the import statement, but maybe there is a switch > that I have not found yet. > > The imported file is a config file, not a script. > > Thomas If you're on unix, you can put the .py files you want to import in a new directory, then change the permissions on this directory so that you do not have write permission for it. rg From harlinseritt at yahoo.com Fri Feb 25 07:33:31 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 25 Feb 2005 04:33:31 -0800 Subject: Trees In-Reply-To: References: Message-ID: <1109334810.991970.280350@l41g2000cwc.googlegroups.com> Would this be for a GUI toolkit or maybe using a standard class scheme? From jussij at zeusedit.com Mon Feb 7 09:25:06 2005 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Tue, 08 Feb 2005 01:25:06 +1100 Subject: WYSIWYG wxPython "IDE"....? References: <1107560658.584623.303310@o13g2000cwo.googlegroups.com> <4205fcd9@news.highway1.com.au> <1107751731.066796.295170@g14g2000cwa.googlegroups.com> <47pe019efj34ua4o5pjjarlv3i85pa9048@4ax.com> Message-ID: <42077A42.6D22@zeusedit.com> Luke Skywalker wrote: > To me, the very fact that the only solution if you don't want > to carry a multi-megabyte widget set with you (either wxWidgets > or QT is to go the MFC way (which a lot of C developers seem > to hate) through Have you ever tried to use MFC in anything other than a simple application? MFC is nothing more than a poorly designed C++ layer over the Windows Win32 API. One of it's greatest contributions to the world of software development is it clearly demonstrates how NOT to design a C++ application framework. At least wxWidgets does offer an OOP look and feel, which is no simple task given that wxWidgets is also a multi-platform application framework. Add to this the fact that MFC is no longer supported by Microsoft (ie there will be no ew version or bug fixes for future versions of Windows) and the choice is simple. I would definitely not be choosing MFC. Jussi Jumppanen Author of: Zeus for Windows (New version 3.93 out now) "The C/C++, Cobol, Java, HTML, Python, PHP, Perl programmer's editor" Home Page: http://www.zeusedit.com From steven.bethard at gmail.com Sun Feb 13 16:46:03 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 13 Feb 2005 14:46:03 -0700 Subject: builtin functions for and and or? In-Reply-To: References: Message-ID: Roose wrote: > I need this a lot: a one line way to do a n-ary and or 'or'. > > e.g., > > result = True > for x in L: > if not boolean_function(x): > result = False > > or > >>>>reduce(operator.__and__, [boolean_function(x) for x in L) Can you use itertools? py> def boolfn(x): ... print "boolfn: %r" % x ... return bool(x) ... py> True in itertools.imap(boolfn, ['a', '', 'b']) boolfn: 'a' True py> True in itertools.imap(boolfn, ['', '', '']) boolfn: '' boolfn: '' boolfn: '' False py> False in itertools.imap(boolfn, ['a', '', 'b']) boolfn: 'a' boolfn: '' True py> False in itertools.imap(boolfn, ['a', 'a', 'b']) boolfn: 'a' boolfn: 'a' boolfn: 'b' False It even shortcircuits when appropriate. Steve From deetsNOSPAM at web.de Sat Feb 19 09:59:21 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 19 Feb 2005 15:59:21 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: <42172136$0$27576$9b622d9e@news.freenet.de> Message-ID: > Should a professional developer take python serious? Unnecessary and deliberately provoking question - python is taken seriously, e.g. by multi-billion dollar companies like google and zope. You OTH have provided no evidence so far that you can be taken seriously as a developer of whatever kind - neither professional nor hobbyist. So one has to question the relevance of your demands. > I mean, if the team does not manage at least the foundation of a > multi-target automated-build-process? Plain wrong. The team does very well manage that process - for a large variety of platforms and compilers. Just not the compiler you perceive as being a necessity. But that dead horse has been beaten enough already. -- Regards, Diez B. Roggisch From paddy3118 at netscape.net Fri Feb 18 05:24:46 2005 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 18 Feb 2005 02:24:46 -0800 Subject: combining several lambda equations Message-ID: <2ae25c6b.0502180224.3d6164a7@posting.google.com> Hi, I am trying to use eval as little as possible but solve this problem. #If given:two or more lambda equations x=lambda : A < B y=lambda : C+6 >= 7 ... How do I create another lambda expression Z equivalent to Z=lambda : (A=7) # i.e. the anding together of the originals, but without referencing # globals x and y as they are artificial in that I will start of with # probably a list of lambda equations. Your help would be appreciated. Thanks, Paddy. From http Wed Feb 16 17:54:30 2005 From: http (Paul Rubin) Date: 16 Feb 2005 14:54:30 -0800 Subject: low-end persistence strategies? References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xbrakjeu1.fsf@ruckus.brouhaha.com> Fred Pacquier writes: > KirbyBase sounds like something that could fit the bill. Hmm, this looks kind of nice. However, when used in embedded mode, the overview blurb doesn't say anything about concurrency control. I don't want to use it in client/server mode, for reasons already stated. From mm at newsgroups.com Sun Feb 13 16:50:27 2005 From: mm at newsgroups.com (MM) Date: Mon, 14 Feb 2005 10:50:27 +1300 Subject: win32 extension install hiccup Message-ID: Hi, I downloaded the latest win32all build 202 and tried to install under win2000 with Py2.4. Install complains about 'couldn't open py2.4 to run script pywin32-preinstall.py'. I checked the directories and there was no sign of this file (preinstall.py) so I presume this is why it bombed. How do I fix this? Thanks, matthew. From roy at panix.com Tue Feb 1 08:17:33 2005 From: roy at panix.com (Roy Smith) Date: Tue, 01 Feb 2005 08:17:33 -0500 Subject: equivelant of Java's toString() method? (not repr) References: Message-ID: Alex Hunsley wrote: > I suppose I'm looking for the equivelant of Java's toString() method... That would be str(), which for the most part, just calls your object's __str__() method. If your object doesn't have an __str__() method, there's nothing magic Python can do to invent one. The difference between repr() and str() is that repr() is supposed to produce a parsable representation of the object; one which could be parsed by a Python interpreter to re-generate the original object. On the other hand, str() is supposed to produce a human-readable string. From aleaxit at yahoo.com Sun Feb 6 17:36:07 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 6 Feb 2005 23:36:07 +0100 Subject: loops -> list/generator comprehensions References: <1107718117.221204.80410@l41g2000cwc.googlegroups.com> <4qCdnXI11-vhGJvfRVn-vQ@comcast.com> Message-ID: <1grl53q.ee7g9b1m2pfy9N%aleaxit@yahoo.com> Steven Bethard wrote: > at the OP's original code, the line: > > [(x[0], x[2]) for x in os.walk(".")] > > is the equivalent of: > > [dirpath, filenames for dirpath, dirnames, filenames in os.walk('.')] Just a nit: you need parentheses in your second LC too, i.e.: [(dirpath, filenames) for dirpath, dirnames, filenames in os.walk('.')] > I prefer to give names to the values produced by os.walk -- I think it > makes the usage much clearer. Full agreement here -- those numeric indices are nasty. Alex From http Fri Feb 4 22:43:38 2005 From: http (Paul Rubin) Date: 04 Feb 2005 19:43:38 -0800 Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> Message-ID: <7xzmyj8ydx.fsf@ruckus.brouhaha.com> Maciej Mr?z writes: > Mmcache (which is both optimizer and shared memory caching library for > php) can do _miracles_. One of my company servers uses Apache > 1.3/php/mmcache to serve about 100 GB of dynamic content a day (it > could do more but website does not have enough visitors to stress it > :) ). Yeah, that's what Wikipedia is using, I'd forgotten its name. http://meta.wikimedia.org/wiki/PHP_caching_and_optimization > There's also memcached, much more of interest to readers of this list > iirc it has Python API. Oh cool, I should look at it. From vincent at visualtrans.de Sat Feb 12 03:51:27 2005 From: vincent at visualtrans.de (Vincent Wehren) Date: Sat, 12 Feb 2005 09:51:27 +0100 Subject: Commerical graphing packages? In-Reply-To: <420d1595$1@nntp.zianet.com> References: <420d1595$1@nntp.zianet.com> Message-ID: Erik Johnson wrote: > I am aware of ChartDirector (http://www.advsofteng.com/ ) which > explicitly supports python and seems to be about the right level of > sophistication. I don't really know of any other packages in this space, do > you? I am seeking feedback and reccomendations from people who have used > this package or similar ones. I am particularly interested to hear about any > limitations or problems you ran into with whatever package you are using. We use both the Python and C++ bindings of ChartDirector (although their license always spans /all/ supported bindings. It's all pretty straight-forward, well-documented, and the license fee is a bargain compared to other packages we've used in the past. What it is not suitable for is maybe allowing for 3d-views of data cubes - changeable on the fly. -- Vincent Wehren From mefjr75 at hotmail.com Mon Feb 7 00:53:27 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 6 Feb 2005 21:53:27 -0800 Subject: pygame.mixer.music not playing In-Reply-To: <36ocddF541n0fU1@individual.net> References: <36mb0iF54udklU1@individual.net> <1107700800.258876.298010@z14g2000cwz.googlegroups.com> <36mvjkF54gvnrU1@individual.net> <1107748705.808825.319270@f14g2000cwb.googlegroups.com> <36ocddF541n0fU1@individual.net> Message-ID: <1107755607.157353.196910@g14g2000cwa.googlegroups.com> Very cool, glad you got it working. Good job getting it all installed and running so fast. It won't be long till you have a cool media player of your own. I have not used PyFMOD yet so can't help with it ( I thought it was cross platform too **sigh**, at least FMOD is) Happy hacking, M.E.Farmer From xlii at xlii.org Thu Feb 3 18:22:11 2005 From: xlii at xlii.org (Dominique O. Martel) Date: 3 Feb 2005 15:22:11 -0800 Subject: Reinstall python 2.3 on OSX 10.3.5? References: <1107388080.703032.116150@g14g2000cwa.googlegroups.com> Message-ID: <1107472931.476716.89840@z14g2000cwz.googlegroups.com> 0) compile and install GNU readline 5.0 with the usual ./configure method ftp://ftp.cwru.edu/pub/bash/readline-5.0.tar.gz 1) as an administrator, remove the contents of "/System/Library/Frameworks/Python.framework" 2) install Python from the standard distribution: ./configure --enable-framework=/System/Library/Frameworks make sudo make frameworkinstall 3) install the extras in /Applications if you want to: sudo make frameworkinstallextras Move them to /Developer/Applications/Utilities/MacPython-2.3 4) remove every python* from /usr/local/bin Those in /usr/bin/ are OK for Python 2.3 5) replace "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages" with a symbolic link to "/Library/Python/2.3". Name it "site-packages". I have installed and used Python 2.3.x this way without any problem whatsoever. From dalke at dalkescientific.com Mon Feb 28 19:09:29 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Tue, 01 Mar 2005 00:09:29 GMT Subject: yield_all needed in Python References: Message-ID: On Mon, 28 Feb 2005 18:25:51 -0500, Douglas Alan wrote: > While writing a generator, I was just thinking how Python needs a > "yield_all" statement. With the help of Google, I found a pre-existing > discussion on this from a while back in the Lightweight Languages > mailing list. I'll repost it here in order to improve the chances of > this enhancement actually happening someday. You should also have looked for the responses to that. Tim Peter's response is available from http://aspn.activestate.com/ASPN/Mail/Message/624273 as linked from http://aspn.activestate.com/ASPN/Mail/Message/python-dev/758572 Here is the most relevant parts. I'm not bothered -- this comes with the territory. If/when full-fledged coroutines make it in too, people worried about that can use them instead. Curious fact: I *was* worried about the worst-case time aspects of "simple generators" in Icon years ago, but in practice never ever got burned by it. And rewriting stuff to use Icon co-expressions instead invariably resulted in messier code that ran significantly slower in virtually all cases, except for the ones I *contrived* to prove the O() difference. BTW, Python almost never worries about worst-case behavior, and people using Python dicts instead of, e.g., balanced trees, get to carry their shame home with them hours earlier each day . Andrew dalke at dalkescientific.com From jjl at pobox.com Sat Feb 5 17:58:52 2005 From: jjl at pobox.com (John J. Lee) Date: 05 Feb 2005 22:58:52 +0000 Subject: How do I enter/receive webpage information? References: <1107560030.834943.174250@f14g2000cwb.googlegroups.com> Message-ID: <87oeeywr4j.fsf@pobox.com> Jorgen Grahn writes: [...] > I did it this way successfully once ... it's probably the wrong approach in > some ways, but It Works For Me. > > - used httplib.HTTPConnection for the HTTP parts, building my own requests > with headers and all, calling h.send() and h.getresponse() etc. > > - created my own cookie container class (because there was a session > involved, and logging in and such things, and all of it used cookies) > > - subclassed sgmllib.SGMLParser once for each kind of page I expected to > receive. This class knew how to pull the information from a HTML document, > provided it looked as I expected it to. Very tedious work. It can be easier > and safer to just use module re in some cases. > > Wrapped in classes this ended up as (fictive): > > client = Client('somehost:80) > client.login('me', 'secret) > a, b = theAsAndBs(client, 'tomorrow', 'Wiltshire') > foo = theFoo(client, 'yesterday') > > I had to look deeply into the HTTP RFCs to do this, and also snoop the > traffic for a "real" session to see what went on between server and client. I see little benefit and significant loss in using httplib instead of urllib2, unless and until you get a particulary stubborn problem and want to drop down a level to debug. It's easy to see and modify urllib2's headers if you need to get low level. One starting point for web scraping with Python: http://wwwsearch.sourceforge.net/bits/GeneralFAQ.html There are some modules you may find useful there, too. Google Groups for urlencode. Or use my module ClientForm, if you prefer. Experiment a little with an HTML form in a local file and (eg.) the 'ethereal' sniffer to see what happens when you click submit. The stdlib now has cookie support (in Python 2.4): import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/") print r.read() Unfortunately, it's true that network sniffing and a reasonable smattering of knowledge about HTTP &c., does often turn out to be necessary to scrape stuff. A few useful tips: http://wwwsearch.sourceforge.net/ClientCookie/doc.html#debugging John From fperez.net at gmail.com Sat Feb 12 18:45:29 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Sat, 12 Feb 2005 16:45:29 -0700 Subject: Hack with os.walk() References: <200502120000.12086.frans.englich@telia.com> Message-ID: Robert Kern wrote: > Fernando Perez wrote: > >> Perhaps this path.py could be considered for inclusion in the stdlib? I've >> only >> read the page linked above, so perhaps it can use some polishing. But it >> certainly looks like a big improvement over the scatterblast which the stdlib >> is on this particular topic. > > I'm pretty sure this has been discussed at some point. I completely > forget the results of said discussion (except the part where it wasn't > going in yet, although you can't really call that "remembering" so much > as "deducing from the current state of affairs"). It's probably one of those things which is not enough of a bother for anyone to stop and commit the effort to fix it. After all, working around the problem isn't that hard, since all the functions are there (somewhere), and their poor interfaces can typically be lived with. But the code examples in path.py really feel like a breath of (pythonic) fresh air compared to the stdlib in this regard. Care to champion it ? ;) Best, f From ilias at lazaridis.com Tue Feb 15 10:56:19 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Tue, 15 Feb 2005 17:56:19 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: Stephen Kellett wrote: > In message , Steve Horsley > writes > >> Stephen Kellett wrote: >> >>>> Who's "Guido"? >>> >>> LOL Falling off my chair!!!!!! >> >> I think the expression you are looking for is ROFL! > > :-) Yes, but with that I could've been standing up before ending up on > the floor. I wrote it as I felt it!. Its a really good demonstration as > to the depth of the research performed by Illias. I thin I understand what you mean. "Guido van Rossum is the project's lead developer. In recognition of this role, he's sometimes jokingly called the Benevolent Dictator For Life, or BDFL; the acronym is occasionally used in python-dev postings, especially in a context such as "making that change will require a BDFL pronouncement". In theory the BDFL makes all the decisions about what goes in to Python and what doesn't. " source: http://www.python.org/dev/process.html > I'm waiting for the "Who's Matz?" comment in comp.lang.ruby.... > > Stephen . -- http://lazaridis.com From sjmachin at lexicon.net Thu Feb 24 22:33:50 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Feb 2005 14:33:50 +1100 Subject: [perl-python] generic equivalence partition References: <1109245733.261643.219420@f14g2000cwb.googlegroups.com> Message-ID: On Thu, 24 Feb 2005 17:48:47 -0800, Bryan wrote: >Xah Lee wrote: >> another functional exercise with lists. >> >> Here's the perl documentation. I'll post a perl and the translated >> python version in 48 hours. >> >> =pod >> >> parti(aList, equalFunc) >> >> given a list aList of n elements, we want to return a list that is a >> range of numbers from 1 to n, partition by the predicate function of >> equivalence equalFunc. (a predicate function is a function that >> takes two arguments, and returns either True or False.) [snip] >> example: >> parti([['x','x','x','1'], >> ['x','x','x','2'], [snip] >> ['x','x','x','5']], sub {$_[0]->[3] == $_[1]->[3]} ) >> >> returns >> [[1],['2','3','4'],['5'],['6'],['7','8']]; >> >> =cut >> >> In the example given, the input list's elements are lists of 4 >> elements, and the equivalence function is one that returns True if the >> last item are the same. > [snip] >> > >this is the first thing that came to my mind. i'm sure there are more clever >ways to do this. > >elements = [['x', 'x', 'x', '1'], [snip] > ['x', 'x', 'x', '5']] >pos = {} > >for i, element in enumerate(elements): > pos.setdefault(element[-1], []).append(i+1) > >p = pos.values() >p.sort() >[[1], [2, 3, 4], [5], [6], [7, 8]] > > Bryan: Bzzzt. Xah was proposing a GENERAL function. You have HARDWIRED his (simplistic) example. Xah: Bzzzt. Too close to your previous exercise. From sjmachin at lexicon.net Sun Feb 20 15:35:25 2005 From: sjmachin at lexicon.net (John Machin) Date: 20 Feb 2005 12:35:25 -0800 Subject: exercise: partition a list by equivalence In-Reply-To: References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> <1108814276.680736.264380@l41g2000cwc.googlegroups.com> <1108849063.857663.279920@c13g2000cwb.googlegroups.com> Message-ID: <1108931725.251996.56210@c13g2000cwb.googlegroups.com> Eric Pederson wrote: > > From: "Xah Lee" > > ? for group in interm: > what do the funny little "?"s stand for? ...>>> import unicodedata as ucd; ucd.name('?'.decode('cp1252')) 'COPYRIGHT SIGN' Xah is asserting his right to be recognised as the author of his artistic creations, line by line. From jgrahn-nntq at algonet.se Sat Feb 5 12:41:25 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 5 Feb 2005 17:41:25 GMT Subject: How do I enter/receive webpage information? References: <1107560030.834943.174250@f14g2000cwb.googlegroups.com> Message-ID: On 4 Feb 2005 15:33:50 -0800, Mudcat wrote: > Hi, > > I'm wondering the best way to do the following. > > I would like to use a map webpage (like yahoo maps) to find the > distance between two places that are pulled in from a text file. I want > to accomplish this without displaying the browser. That's called "web scraping", in case you want to Google for info. > I am looking at several options right now, including urllib, httplib, > packet trace, etc. But I don't know where to start with it or if there > are existing tools that I could incorporate. > > Can someone explain how to do this or point me in the right direction? I did it this way successfully once ... it's probably the wrong approach in some ways, but It Works For Me. - used httplib.HTTPConnection for the HTTP parts, building my own requests with headers and all, calling h.send() and h.getresponse() etc. - created my own cookie container class (because there was a session involved, and logging in and such things, and all of it used cookies) - subclassed sgmllib.SGMLParser once for each kind of page I expected to receive. This class knew how to pull the information from a HTML document, provided it looked as I expected it to. Very tedious work. It can be easier and safer to just use module re in some cases. Wrapped in classes this ended up as (fictive): client = Client('somehost:80) client.login('me', 'secret) a, b = theAsAndBs(client, 'tomorrow', 'Wiltshire') foo = theFoo(client, 'yesterday') I had to look deeply into the HTTP RFCs to do this, and also snoop the traffic for a "real" session to see what went on between server and client. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From HotHOT2 at comcast.net Sun Feb 13 16:54:50 2005 From: HotHOT2 at comcast.net (Hottime) Date: Sun, 13 Feb 2005 16:54:50 -0500 Subject: [FREE!] Swingers Websites! U@wvqqN Message-ID: . ---------------------------------- Want to get laid tonight?? Find local girls now http://www.youandmeswing.com/index.php?ref_id=130 ---------------------------------- ,iy^3aQvw From johann at rocholl.net Wed Feb 9 17:45:05 2005 From: johann at rocholl.net (Johann C. Rocholl) Date: Wed, 9 Feb 2005 23:45:05 +0100 Subject: Python and version control In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E33983C0@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E33983C0@exchange.hqamor.amorhq.net> Message-ID: <20050209224505.GA5040@rocholl.net> Robert Brewer wrote: > Peter Hansen wrote: > > Carl wrote: > > > What is the ultimate version control tool for Python if you > > > are working in a Windows environment? > > > > I never liked coupling the two together like that. Instead > > I use tools like TortoiseCVS or (now) TortoiseSVN with a > > Subversion repository. These things let you access revision > > control features from context (right-button) menus right in > > Windows Explorer, as you browse the file system. > > Seconded. Thirded. Johann From captainrobbo at gmail.com Thu Feb 24 17:26:22 2005 From: captainrobbo at gmail.com (Andy Robinson) Date: 24 Feb 2005 14:26:22 -0800 Subject: pyGoogle is fun and easy to use, and thinks Python is the best programming language In-Reply-To: <1109040859.816948.70120@o13g2000cwo.googlegroups.com> References: <1109040859.816948.70120@o13g2000cwo.googlegroups.com> Message-ID: <1109283982.638516.325370@o13g2000cwo.googlegroups.com> Regrettably, inserting "Visual Basic" into the list produces a different winner. I think you want some very subtle hard coding which limits it to on-space-delimited languages :-( - Andy From peter at engcorp.com Wed Feb 9 17:43:35 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Feb 2005 17:43:35 -0500 Subject: convert list of tuples into several lists In-Reply-To: <_cWdnZN4wO418pffRVn-qA@comcast.com> References: <36uihlF58p63iU1@individual.net> <_cWdnZN4wO418pffRVn-qA@comcast.com> Message-ID: Steven Bethard wrote: > Diez B. Roggisch wrote: > >> zip(*[(1,4),(2,5),(3,6)]) > > While this is also the approach I would use, it is worth noting that > Guido thinks of this as an abuse of the argument passing machinery: > > http://mail.python.org/pipermail/python-dev/2003-July/037346.html I'm not sure that's the same thread I already read where he dissed zip like that, but what I'm wondering is what is the alternative? Is there an equally elegant approach that doesn't "abuse" the argument passing machinery? -Peter From crosseyedpenguin at cox.net Thu Feb 10 17:32:24 2005 From: crosseyedpenguin at cox.net (Roger) Date: Thu, 10 Feb 2005 15:32:24 -0700 Subject: Python and version control In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E33983C0@exchange.hqamor.amorhq.net> Message-ID: <420BE0F8.10004@cox.net> Johann C. Rocholl wrote: > Robert Brewer wrote: > >>Peter Hansen wrote: >> >>>Carl wrote: >>> >>>>What is the ultimate version control tool for Python if you >>>>are working in a Windows environment? >>> >>>I never liked coupling the two together like that. Instead >>>I use tools like TortoiseCVS or (now) TortoiseSVN with a >>>Subversion repository. These things let you access revision >>>control features from context (right-button) menus right in >>>Windows Explorer, as you browse the file system. >> >>Seconded. > > > Thirded. > > Johann Fourth-ed! Roger From pink at odahoda.de Sun Feb 27 15:26:57 2005 From: pink at odahoda.de (Pink) Date: Sun, 27 Feb 2005 21:26:57 +0100 Subject: Need help running external program References: <38ejcfF5lu11pU1@individual.net> Message-ID: Rigga wrote: >> No, the r was the point - it's there to tell Python not to do any >> escaping on the string. Try it again with the r and see what happens. >> > Brilliant!!! that works a treat thankyou!!, where on earth did you find > out > about the 'r' any pointers to documentation appreciated. This is a pretty common problem when working with regular expression (which usually contain many backslashes) - that's where I saw this syntax for the first time (e.g. http://docs.python.org/lib/match-objects.html). The official reference for string literals is here: http://docs.python.org/ref/strings.html c ya From cjbottaro at alumni.cs.utexas.edu Wed Feb 16 16:20:20 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Wed, 16 Feb 2005 15:20:20 -0600 Subject: super not working in __del__ ? References: <11171oljbbb5cd3@corp.supernews.com> Message-ID: Jeff Shannon wrote: > Christopher J. Bottaro wrote: > >> 2 Questions... >> 1) Why does this never happen in C++? Or does it, its just never >> happened to me? >> 2) I can understand random destruction of instantiated objects, but I >> find it weird that class definitions (sorry, bad terminology) are >> destroyed at >> the same time. So __del__ can't safely instantiate any classes if its >> being called as a result of interpreter shutdown? Boo... > > Keep in mind that in Python, everything is a (dynamically created) > object, including class objects. My recall of C/C++ memory > organization is pretty weak, but IIRC it gives completely different > behavior to code, stack objects, and heap objects. Code never needs > to be cleaned up. In Python, everything (including functions and > classes) is effectively a heap object, and thus functions and classes > can (and indeed must) be cleaned up. Refcounting means that they > won't ever (normally) be cleaned up while they're still in use, but > during program shutdown refcounting necessarily ceases to apply. > > The closest that would happen in C++, I believe, would manifest itself > as memory leaks and/or access of already-freed memory. So encapsulating your script in a main function fixes the problem: def main(): blah blah if __name__ == "__main__": main() because all the objects instantiated in main() will be deleted when main ends, but before the interpreter shuts down, thus the objects will have access to all the symbols in module's __dict__ (or however that works). Why can't Python kind of do this step for us? I'm just curious, this stuff is interesting to me. Is it because it wouldn't know what parts of the module should be automatically put in the main function and what parts shouldn't? class blah: pass class blah1: pass # following goes in automatically generated main function obj = blah() obj2 = blah2() obj.doStuff() # main ends # interpreter shutdown I guess it wouldn't know to leave the class objects outside of the automatically generated main function. Just tell if my ramblings are idiotic and I'll shutup. Thanks, -- C From duncan.booth at invalid.invalid Tue Feb 22 09:29:37 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Feb 2005 14:29:37 GMT Subject: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux & Windows XP References: <1109078512.094288.316030@z14g2000cwz.googlegroups.com> <421b385e$0$230$edfadb0f@dread12.news.tele.dk> Message-ID: Max M wrote: > And this string will automatically be utf-8 encoded: > > st = '???' > > So you should be able to convert it to unicode without giving an > encoding: > > ust = unicode(st) > No. Strings have no knowledge of their encoding. As you describe the string will be utf-8 encoded, but you still have to tell it that when you decode it. From nvhengr at gmail.com Thu Feb 10 15:45:12 2005 From: nvhengr at gmail.com (Chris) Date: 10 Feb 2005 12:45:12 -0800 Subject: Python COM Makepy Excel 9.0 error In-Reply-To: References: <1108062567.928124.219200@g14g2000cwa.googlegroups.com> Message-ID: <1108068312.687439.296020@c13g2000cwb.googlegroups.com> Thank you! That did the trick. From kent37 at tds.net Wed Feb 23 18:49:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Feb 2005 18:49:54 -0500 Subject: Communication between JAVA and python In-Reply-To: <421ce234$0$12950$626a14ce@news.free.fr> References: <421ce234$0$12950$626a14ce@news.free.fr> Message-ID: <421d137e$1_1@newspeer2.tds.net> Jacques Daussy wrote: > Hello > How can I transfert information between a JAVA application and a python > script application. I can't use jython because, I must use python > interpreter.I think to socket or semaphore, but can I use it on Windows > plateform ? Jython has an interpreter and Windows has sockets. Kent From jkjone2002 at att.net Wed Feb 16 11:26:50 2005 From: jkjone2002 at att.net (john san) Date: Wed, 16 Feb 2005 11:26:50 -0500 Subject: [newbie]How to install python under DOS and is there any Wxpython can be installed under dos? References: Message-ID: pure DOS, old pc, used for teaching . want show some "windows" under DOS (under Python). "Daniel Bowett" ???? news:mailman.2685.1108553200.22381.python-list at python.org... > john san wrote: > > How to install python under DOS and is there any Wxpython-like can be > > installed under dos? > > > > Thanks. > > > > > > Are you actually still running a pure DOS machine? Or are you running > the dos prompt through Windows? > From newsgroups at jhrothjr.com Tue Feb 1 17:27:48 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 1 Feb 2005 16:27:48 -0600 Subject: Next step after pychecker References: <41ff0308$0$6503$636a15ce@news.free.fr> Message-ID: <11000kcim8pvh6c@news.supernews.com> "Sylvain Thenault" wrote in message news:pan.2005.02.01.10.21.23.762637 at nospam.logilab.fr... > On Tue, 01 Feb 2005 05:18:12 +0100, Philippe Fremy wrote: > > Did you take a look at the starkiller [1] and pypy projects [2] ? Has anything happened to Starkiller since PyCon 2004? The latest mention I can find on Google is a blog entry (by Ted Leung) on Aug 30 saying he wished someone would give the author some money to finish it and publish it. John Roth From deetsNOSPAM at web.de Mon Feb 7 11:25:50 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 07 Feb 2005 17:25:50 +0100 Subject: Making dynamic data available via ODBC with Python References: <877jlke5fp.fsf@andreasen.org> Message-ID: <36pitsF53pt5oU1@individual.net> > > Is there some better way of doing this -- some way to provide tabular > data remotely to Windows machines, usable in Office programs, which > happens to already have some Python code written for it? Looking > around, there is at least one XML-to-ODBC bridge but encoding the > entire data file as XML is likely to have prohibitive overhead. I still think that this is the most viable solution - if performance is bad, you could still explore other possibilities. If it actually is performing bad - either literally or due to a badly design - I'd go for creating a odbc2your-server driver. That would allow you to cope with a pretty well defined standard (odbc) and doing the network stuff totally on your own behalf instead of trying to make some self-written protocol stack like postgres so compatible that a postgres odbc driver doesn't know the difference. -- Regards, Diez B. Roggisch From steven.bethard at gmail.com Sun Feb 13 12:27:20 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 13 Feb 2005 10:27:20 -0700 Subject: help please In-Reply-To: <1108260752.791847.180060@l41g2000cwc.googlegroups.com> References: <1108254434.871062.314510@g14g2000cwa.googlegroups.com> <1108260752.791847.180060@l41g2000cwc.googlegroups.com> Message-ID: gargonx wrote: > This works much better, aside from the fact that it does'nt work for > the std dictionary. the letters used from here stay the same. that > dictionary looks like this: > > std = { > "A":"Z", > "Z":"A", > "B":"Y", > "Y":"B", > "C":"X", > "X":"C", > "E":"V", > "V":"E", > "H":"S", > "S":"H", > "M":"N", > "N":"M" > } > > what could be causing this? > > i did figure out that if you reverse the k,v you are able to get it but > that doesn't turn up the results i need > > def proc(text): > result = [] > for word in text: > for k, v in replacements: > word = word.replace(v,k) #here i reversed them > result.append(word) > return ''.join(result) > The problem is that if you run all the replacements in std, you first translate As to Zs and then Zs to As. If you want to do each character only once, you should probably write this as: py> std = { ... "A":"Z", ... "Z":"A", ... "B":"Y", ... "Y":"B", ... "C":"X", ... "X":"C", ... "E":"V", ... "V":"E", ... "H":"S", ... "S":"H", ... "M":"N", ... "N":"M"} py> ext = {"aa":"i"} py> punc = {",":"!"} py> replacements = {} py> replacements.update(punc) py> replacements.update(ext) py> replacements.update(std) py> def proc(text): ... result = [] ... for char in text: ... result.append(replacements.get(char, char)) ... return ''.join(result) ... py> proc('ABCDEFG') 'ZYXDVFG' Or alternatively: py> def proc(text): ... return ''.join([replacements.get(c, c) for c in text]) ... py> proc('ABCDEFG') 'ZYXDVFG' Note however, that this won't work for multi-character strings like you had in 'ext' in your original example: py> proc('ABCaaEFG') 'ZYXaaVFG' But neither would your original code. Are the items in std always a single character? Does ext always translate two characters to one? Could you give us some more info on the task here? Steve From steven.bethard at gmail.com Fri Feb 4 13:08:28 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 04 Feb 2005 11:08:28 -0700 Subject: "Collapsing" a list into a list of changes In-Reply-To: References: Message-ID: Alan McIntyre wrote: > Hi all, > > I have a list of items that has contiguous repetitions of values, but > the number and location of the repetitions is not important, so I just > need to strip them out. For example, if my original list is > [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5], I want to end up with [0,1,2,3,2,4,5]. > > Here is the way I'm doing this now: > > def straightforward_collapse(myList): > collapsed = [myList[0]] > for n in myList[1:]: > if n != collapsed[-1]: > collapsed.append(n) > > return collapsed > > Is there an elegant way to do this, or should I just stick with the code > above? Here's a solution that works for iterables other than lists: py> def collapse(iterable): ... enumeration = enumerate(iterable) ... _, lastitem = enumeration.next() ... yield lastitem ... for i, item in enumeration: ... if item != lastitem: ... yield item ... lastitem = item ... py> lst = [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5] py> list(collapse(lst)) [0, 1, 2, 3, 2, 4, 5] Again, I'm still not sure I'd call this more elegant... STeVe From ods at strana.ru Fri Feb 11 04:43:08 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Fri, 11 Feb 2005 12:43:08 +0300 Subject: sre is broken in SuSE 9.2 In-Reply-To: <1108064973.719544.228970@z14g2000cwz.googlegroups.com> References: <1108060527.378911.146240@o13g2000cwo.googlegroups.com> <1108064973.719544.228970@z14g2000cwz.googlegroups.com> Message-ID: <20050211124308.2fa01738.ods@strana.ru> On 10 Feb 2005 11:49:33 -0800 "Serge Orlov" wrote: > This thread is about problems only with LANG=C or LANG=POSIX, it's not > about other locales. Other locales are working as expected. You are not right. I have LANG=de_DE.UTF-8, and the Python test_re.py doesn't pass. $LANG doesn't matter if I don't call setlocale. Fortunately setting any non-C locale solves the problem for all (I believe) unicode character: >>> re.compile(ur'\w+', re.U).findall(u'\xb5\xba\xe4\u0430') [u'\xb5\xba\xe4\u0430'] -- Denis S. Otkidach http://www.python.ru/ [ru] From fbasegmezatbcdidotcom Fri Feb 4 23:14:02 2005 From: fbasegmezatbcdidotcom (Fahri Basegmez) Date: Fri, 4 Feb 2005 23:14:02 -0500 Subject: returning True, False or None References: <6Z6dnVfTmdUDopnfRVn-1A@rcn.net> <36iv03F4urakqU1@individual.net> Message-ID: "Mick Krippendorf" wrote in message news:36iv03F4urakqU1 at individual.net... > Fahri Basegmez wrote: >> reduce(lambda x, y: x or y, lst) > > This doesn't solve the OPs problem since > > >>> reduce(lambda x, y: x or y, [False, None]) > > returns None instead of False. > > Mick. > You are right. I tested None or False and it worked. I assumed order did not matter for or operator. None or False returns False False or None returns None You know what they say about assumptions. Live and learn. Fahri From dummyboy at hongkong-hosting-service.com Sat Feb 19 05:27:15 2005 From: dummyboy at hongkong-hosting-service.com (dummyboy at hongkong-hosting-service.com) Date: Sat, 19 Feb 2005 10:27:15 +0000 (UTC) Subject: =?iso-8859-1?q?=B1M=B7=7E=BA=F4=AD=B6=B1H=A6s=AAA=B0=C8_=A6P=A8B?= =?iso-8859-1?q?=A4=E4=B4=A9_PHP+MySQL=2C_Access+ASP=2C_ASP=2ENET?= =?iso-8859-1?q?=2C_CGI=2C_SSI_=B9q=B6l=AFf=ACr=B9L=C2o=2C_=A9U=A7?= =?iso-8859-1?q?=A3=B9q=B6l=B9L=C2o_=A4=CEWebMail_=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E?= Message-ID: ?????b?????C?e?????????????q?????????Y?h?e?z?T?????A?? ???? PHP+MySQL, Access+ASP, ASP.NET, CGI, SSI ?q?l?f?r?L?o, ?U???q?l?L?o ?? WebMail ??...... ?????C?e????W1000?Y?e?????w?????????{?? osc. http://shop2.uhostnet.com ?C???u?? $20 ?_ ???? http://www.uhostnet.com ?s?????}?q???O http://dummy.uhostnet.com ?s???????????C???K?O???????C ?i?????????q?K?O???????????W?C ?A???p???R?Q?e?G?A?Z?w???Q?????A?????O?A?h?e???????C ?{?Y?????????q?????????A?Y?h?e?z?T?????A???C(???????W????) ?H?W?p????????????WIN2003???x?A???????i?????????q??Linux???x?A???p???C ???e?????{?? ASP ?d????,??????,ASP ?H????,PHP ?H????,ASP ???W?q?l????,ASP ???????z?{??,???W????,?????t?????U???????{??.. ?C?? $20 ?????H?s?A?? Basic Plan W200: (?C?? $20) -- 200MB ???????? -- ?L???q?l?H?c -- ?L???????????q -- ???? ASP+Access / CGI -- ?q?l?f?r?L?o?t?? -- ?U???q?l?L?o?t?? http://www.uhostnet.com/modules.php?name=service&file=index&func=windetails&plan=A Windows W300: (?C?? $38) -- ?@?~?????s???W -- 300MB ???????? -- ?L???q?l?H?c -- ?L???????????q -- ???? PHP+MySQL, ASP+ACCESS, CGI, SSI -- 1 ?? MySQL ?????w (5MB) -- ?q?l?f?r?L?o?t?? -- ?U???q?l?L?o?t?? http://www.uhostnet.com/modules.php?name=service&file=index&func=windetails&plan=B Windows W500: (?C?? $48) -- ?@?~?????s???W -- ?l???? 3 ?? (?v?g???P????) -- 500MB ???????? -- ?L???q?l?H?c -- ?L???????????q -- ???? PHP+MySQL, ASP+ACCESS, CGI, SSI -- 1 ?? MySQL ?????w (10MB) -- ?q?l?f?r?L?o?t?? -- ?U???q?l?L?o?t?? http://www.uhostnet.com/modules.php?name=service&file=index&func=windetails&plan=C Windows W800: (?C?? $58) -- ?@?~?????s???W -- ?l???? 5 ?? (?v?g???P????) -- 800MB ???????? -- ?L???q?l?H?c -- ?L???????????q -- ???? PHP+MySQL, ASP+ACCESS, CGI, SSI -- 1 ?? MySQL ?????w (20MB) -- ?q?l?f?r?L?o?t?? -- ?U???q?l?L?o?t?? http://www.uhostnet.com/modules.php?name=service&file=index&func=windetails&plan=D Windows W1000: (?C?? $68) -- ?@?~?????s???W -- ?l???? 10 ?? (?v?g???P????) -- 1GB ???????? -- ?L???q?l?H?c -- ?L???????????q -- ???? PHP+MySQL, ASP+ACCESS, CGI, SSI -- 1 ?? MySQL ?????w (50MB) -- ?q?l?f?r?L?o?t?? -- ?U???q?l?L?o?t?? -- ?e?????w???????{?????W?j???W?????t?? http://www.uhostnet.com/modules.php?name=service&file=index&func=windetails&plan=E ?? ?? ?C ?? : http://www.uhostnet.com/modules.php?name=clients ............................................................................................................................................................................................................................................................................................. From francis.girard at free.fr Sun Feb 13 12:57:27 2005 From: francis.girard at free.fr (Francis Girard) Date: Sun, 13 Feb 2005 18:57:27 +0100 Subject: check if object is number In-Reply-To: References: Message-ID: <200502131857.27541.francis.girard@free.fr> Le vendredi 11 F?vrier 2005 20:11, Steven Bethard a ?crit?: > Is there a good way to determine if an object is a numeric type? > Generally, I avoid type-checks in favor of try/except blocks, but I'm > not sure what to do in this case: > > def f(i): > ... > if x < i: > ... > > The problem is, no error will be thrown if 'i' is, say, a string: > > py> 1 < 'a' > True > py> 10000000000 < 'a' > True > > But for my code, passing a string is bad, so I'd like to provide an > appropriate error. > This is a very bad Python feature that might very well be fixed in version 3.0 according to your own reply to a previous thread. This problem clearly shows that this Python feature does hurt. Here's a transcript of the answer : > Yes, that rule being to compare objects of different types by their type > names (falling back to the address of the type object if the type names > are the same, I believe). ?Of course, this is arbitrary, and Python does > not guarantee you this ordering -- it would not raise backwards > compatibility concerns to, say, change the ordering in Python 2.5. > > > What was the goal behind this rule ? > > I believe at the time, people thought that comparison should be defined > for all Python objects. ?Guido has since said that he wishes the > decision hadn't been made this way, and has suggested that in Python > 3.0, objects of unequal types will not have a default comparison. > > Probably this means ripping the end off of default_3way_compare and > raising an exception. ?As Fredrik Lundh pointed out, they could, if they > wanted to, also rip out the code that special-cases None too. > > Steve Regards Francis Girard From percivall at gmail.com Fri Feb 25 13:42:06 2005 From: percivall at gmail.com (percivall at gmail.com) Date: 25 Feb 2005 10:42:06 -0800 Subject: Is there way to determine which class a method is bound to? In-Reply-To: References: Message-ID: <1109356926.896648.165360@g14g2000cwa.googlegroups.com> Another way is to make a simple metaclass, setting an attribute (like defining_class, or something) on each function object in the class dictionary. From lkirsh at cs.ubc.ca Wed Feb 23 04:56:02 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Wed, 23 Feb 2005 01:56:02 -0800 Subject: how can I make this script shorter? In-Reply-To: References: Message-ID: Good idea about hashing part of the file before comparing entire files. It will make the script longer but the speed increase will most likely make it worth it. Lowell Christos TZOTZIOY Georgiou wrote: > On Tue, 22 Feb 2005 00:34:39 -0800, rumours say that Lowell Kirsh > might have written: > > >>I have a script which I use to find all duplicates of files within a >>given directory and all its subdirectories. It seems like it's longer >>than it needs to be but I can't figure out how to shorten it. Perhaps >>there are some python features or libraries I'm not taking advantage of. >> >>The way it works is that it puts references to all the files in a >>dictionary with file size being the key. The dictionary can hold >>multiple values per key. Then it looks at each key and all the >>associated files (which are the same size). Then it uses filecmp to see >>if they are actually byte-for-byte copies. >> >>It's not 100% complete but it's pretty close. > > > I can't advise on code length; my dupefind.py script is 361 lines, but the > algorithm is slightly more complex to speed things up (and it also optionally > hardlinks identical files on POSIX and NTFS filesystems). If in your case there > are lots of files of several MiB each, that often match on size, you could avoid > lots of comparisons if you did match based on some hash (md5 or sha). > > You could also compare first on the hash of the first few kiB (I check 8 kiB) to > see if you need to read the whole file or not. > > So: > > for every file: > if other files exist with the same size: > calculate hash for first few kiB > if file has same "initial" hash with other files: > calculate full hash > return all files with same full hash > > Something like that. From ncoghlan at iinet.net.au Fri Feb 4 22:59:54 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 05 Feb 2005 13:59:54 +1000 Subject: string issue In-Reply-To: References: Message-ID: <420444BA.9050106@iinet.net.au> rbt wrote: > Alan McIntyre wrote: > >> I think it's because you're modifying the list as you're iterating >> over it. > > > One last clarification on this. It's OK to modify the elements of a > list, but not the list itself while iterating over it... is that the > correct way to think about this? Correct - the iteration code bases the iteration on the *old* list structure, so you can end up with odd behaviour. Py> l = range(10) Py> for i in l: del l[i] ... Traceback (most recent call last): File "", line 1, in ? IndexError: list assignment index out of range Py> l [1, 2, 4, 5, 7, 9] Dictionaries have the same problem, but they include some guards that try to detect it: Py> d = dict.fromkeys(range(10)) Py> for i in d: del d[i] ... Traceback (most recent call last): File "", line 1, in ? RuntimeError: dictionary changed size during iteration This feature can't be added to lists because it is possible to iterate sensibly over a mutating list: Py> l = range(10) Py> for i in reversed(l): del l[i] ... Py> l [] Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From rkern at ucsd.edu Sun Feb 20 07:34:33 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 20 Feb 2005 04:34:33 -0800 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <42172136$0$27576$9b622d9e@news.freenet.de> Message-ID: Fredrik Lundh wrote: > Ilias Lazaridis wrote: > > >>>>Should a professional developer take python serious? >>> >>>yes. >> >>Should I take answers serious? > > > yes. > > >>Answer from people which do not respect coherence of writings? > > > coherence of writings? Ironic, is it not? I think he's referring to the fact that you snipped some of the email you were replying to. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From steven.bethard at gmail.com Tue Feb 8 02:04:50 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 08 Feb 2005 00:04:50 -0700 Subject: empty classes as c structs? In-Reply-To: References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <1gric2n.17myhon1hfrc6gN%aleaxit@yahoo.com> <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> <9rmdnVR1lr-LYJvfRVn-gg@comcast.com> <4207606E.4040806@iinet.net.au> Message-ID: Michael Spencer wrote: > I see no problem in repeating the methods, or inheriting the > implementation. However, if namespace and bunch are actually different > concepts (one with reference semantics, the other with copy), then > __repr__ at least would need to be specialized, to highlight the > difference. Yeah, I could certainly see them being separate... Of course, someone else will have to write the PEP for Namespace then. ;) > def __ge__(self, other): > for attrname in other.__dict__.keys(): > if not attrname in self.__dict__: > return False > return True > > I realize that interfaces may be addressed formally by a current PEP, > but, even if they are, this "cheap and cheerful" approach appeals to me > for duck-typing. > > However, as I think more about this, I realize that I am stretching your > concept past its breaking point, and that whatever the merits of this > approach, it's not helping you with bunch. Thanks for knocking the > ideas around with me. My pleasure. It's good to talk some use-cases, and make sure I cover as much as is feasible in the PEP. I think __ge__ is probably too far out from the original intentions, but I'll make sure to write Bunch/Namespace to be as inheritance-friendly as possible so that adding such behavior by inheriting from Bunch/Namespace should be simple. Thanks for all your comments! Steve From petite.abeille at gmail.com Mon Feb 28 07:20:35 2005 From: petite.abeille at gmail.com (PA) Date: Mon, 28 Feb 2005 13:20:35 +0100 Subject: Python - what is the fastest database ? In-Reply-To: <1109592623.116661.101880@g14g2000cwa.googlegroups.com> References: <1109592623.116661.101880@g14g2000cwa.googlegroups.com> Message-ID: <8e7e90420531b2b307507f8e43eb6401@gmail.com> On Feb 28, 2005, at 13:10, martijn at gamecreators.nl wrote: > What type database do they use / software ? Hmmm... they don't use a "database" in the traditional sense of the term. http://www-db.stanford.edu/~backrub/google.html Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From grahamd at dscpl.com.au Mon Feb 21 05:46:43 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 21 Feb 2005 02:46:43 -0800 Subject: Moving to Python from PHP - 3 questions References: Message-ID: <1108982803.898640.269150@l41g2000cwc.googlegroups.com> > If you do manage to get mod_python working, I suggest taking a look at > Vampire as well: http://www.dscpl.com.au/projects/vampire/ > I have had good experience with it. Once you start using mod_python > you'll realize you can really go anywhere you want; and that's not > necessarily a good thing. Vampire points you in a nice direction (I > don't want to say 'the right' direction). Vampire is still in a growing phase, so would be interested to hear any comments you may have about how it can be improved. Up until now I have mainly been focusing on making the basic features of mod_python just that bit easier to use. And yes I know that a lot more documentation would be a good start. I am so snowed under with work in my real job at the moment that progress is slow in that respect. :-( From mahs at telcopartners.com Fri Feb 4 20:58:30 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 04 Feb 2005 17:58:30 -0800 Subject: changing local namespace of a function In-Reply-To: References: Message-ID: Bo Peng wrote: > Michael Spencer wrote: > > > There are hundreds of items in the dictionary (that will be needed in > the calculation) so passing the whole dictionary is a lot better than > passing individual items. ... > > def fun(d): > exec 'z = x + y' in globals(), d > > seems to be more readable than > > def fun(d): > d['z'] = d['x'] + d['y'] > > But how severe will the performance penalty be? Try it and see. > > Bo Compare it with Jeff Shannon's suggestion, and with a lazy dict-wrapper like this: >>> class wrapbigdict(object): ... """Lazy attribute access to dictionary keys. Will not access ... keys that are not valid attribute names!""" ... def __init__(self, mydict): ... object.__setattr__(self, "mydict",mydict) ... def __getattr__(self, attrname): ... return self.mydict[attrname] ... def __setattr__(self, attrname, value): ... self.mydict[attrname] = value ... ... >>> a = {'x':1, 'y':2} >>> b = {'x':3, 'y':3} ... >>> w_a = wrapbigdict(a) >>> w_b = wrapbigdict(b) ... >>> def fun(d): ... d.z = d.x + d.y ... >>> fun(w_a) >>> fun(w_b) ... >>> w_a.mydict {'y': 2, 'x': 1, 'z': 3} >>> w_b.mydict {'y': 3, 'x': 3, 'z': 6} >>> From jaydonnell at gmail.com Tue Feb 8 16:44:48 2005 From: jaydonnell at gmail.com (jdonnell) Date: 8 Feb 2005 13:44:48 -0800 Subject: PHP Embedded In Python In-Reply-To: <1107872763.019447.281670@c13g2000cwb.googlegroups.com> References: <1107814685.908990.58410@z14g2000cwz.googlegroups.com> <1107818262.741563.266050@c13g2000cwb.googlegroups.com> <1107872763.019447.281670@c13g2000cwb.googlegroups.com> Message-ID: <1107899088.967746.48530@g14g2000cwa.googlegroups.com> Well it depends on how php is installed. Is it a linux system? Do you know how to run a php script from the command line? Once you have the php script running from the command line then you need to use the os module in python. There are a couple different ways to do it. Read the following for more info. http://docs.python.org/lib/os-process.html http://docs.python.org/lib/os-newstreams.html#os-newstreams simple example: import os handle = os.popen('path/to/yourScript.php', 'r') print handle.read() From jjl at pobox.com Sun Feb 6 15:10:58 2005 From: jjl at pobox.com (John J. Lee) Date: 06 Feb 2005 20:10:58 +0000 Subject: Insane import behaviour and regrtest.py: heeelp References: <87sm4aws3v.fsf@pobox.com> <876515ixj0.fsf@pobox.com> Message-ID: <87wttlh2jx.fsf@pobox.com> Tim Peters writes: > [John J. Lee] > > ... > > I tried it, and I get the same results as before (the test modules from my > > installed copy of Python are picked up instead of the local copies in > > my CVS checkout's Lib/test, apparently entirely contrary to sys.path). > > Try running Python with -vv (that's two letter "v", not one letter > "w"). That will display a long-winded account of everything Python > tries in order to satisfy an import. Thanks. I'm still puzzled, though. Reading the -vv output, I see that when importing test_cookielib (which is currently the only line in my regrtest.py -f file), Python doesn't appear to look in Lib/test to find module "test.test_cookielib" (the actual string passed by regrtest.py to __import__): see the output below. Why does Python not look in /usr/local/src/python/python/dist/src/Lib/test for test_cookielib.py{,c,o}?? Snippet to show print statements I added to my regrtest.py : . try: . save_stdout = sys.stdout . try: . if cfp: . sys.stdout = cfp . print test # Output file starts with test name . if test.startswith('test.'): . abstest = test . else: . # Always import it from the test package . abstest = 'test.' + test .+ print >> sys.stderr, ">>>>>>>sys.path", sys.path . the_package = __import__(abstest, globals(), locals(), []) .+ print >> sys.stderr, ">>>>>>>the_package.__path__", the_package.__path__ . the_module = getattr(the_package, test) . # Most tests run to completion simply as a side-effect of Only other change to regrtest.py: . if __name__ == '__main__': . # Remove regrtest.py's own directory from the module search path. This . # prevents relative imports from working, and relative imports will screw . # up the testing framework. E.g. if both test.test_support and . # test_support are imported, they will not contain the same globals, and . # much of the testing framework relies on the globals in the . # test.test_support module. . mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0]))) . i = pathlen = len(sys.path) . while i >= 0: . i -= 1 . if os.path.abspath(os.path.normpath(sys.path[i])) == mydir: . del sys.path[i] . if len(sys.path) == pathlen: . print 'Could not find %r in sys.path to remove it' % mydir .+ lib = "/usr/local/src/python/python/dist/src/Lib" .+ sys.path.insert(0, lib) .- main() .+ main(testdir=lib) Here's what I've got in my CVS checkout: Lib[0]$ pwd /hda/usr/local/buf/python/python/dist/src/Lib Lib[0]$ ls test/test_cookielib* | grep -v 'patch\|latest\|~' test/test_cookielib.py test/test_cookielib.pyc And the output: Lib[0]$ python2.4 -u -vv test/regrtest.py -f test/torun -v 2>&1 | less [...long snip...] # trying /usr/local/lib/python2.4/lib-tk/time.py # trying /usr/local/lib/python2.4/lib-tk/time.pyc # trying /usr/local/lib/python2.4/lib-dynload/time.so dlopen("/usr/local/lib/python2.4/lib-dynload/time.so", 2); import time # dynamically loaded from /usr/local/lib/python2.4/lib-dynload/time.so test_cookielib >>>>>>>sys.path ['/usr/local/src/python/python/dist/src/Lib', '/home/john/lib/python', '/usr/local/lib/python24.zip', '/usr/local/lib/python2.4', '/usr/local/lib/python2.4/plat-linux2', '/usr/local/lib/python2.4/lib-tk', '/usr/local/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages'] # trying /usr/local/lib/python2.4/test/test_cookielib.so # trying /usr/local/lib/python2.4/test/test_cookielibmodule.so # trying /usr/local/lib/python2.4/test/test_cookielib.py import test.test_cookielib # from /usr/local/lib/python2.4/test/test_cookielib.py # can't create /usr/local/lib/python2.4/test/test_cookielib.pyc # trying /usr/local/lib/python2.4/test/re.so # trying /usr/local/lib/python2.4/test/remodule.so # trying /usr/local/lib/python2.4/test/re.py # trying /usr/local/lib/python2.4/test/re.pyc # trying /usr/local/lib/python2.4/test/time.so # trying /usr/local/lib/python2.4/test/timemodule.so # trying /usr/local/lib/python2.4/test/time.py # trying /usr/local/lib/python2.4/test/time.pyc # trying /usr/local/lib/python2.4/test/test.so # trying /usr/local/lib/python2.4/test/testmodule.so # trying /usr/local/lib/python2.4/test/test.py # trying /usr/local/lib/python2.4/test/test.pyc >>>>>>>the_package.__path__ ['/usr/local/lib/python2.4/test'] # trying /usr/local/lib/python2.4/test/test_sets.so # trying /usr/local/lib/python2.4/test/test_setsmodule.so # trying /usr/local/lib/python2.4/test/test_sets.py # /usr/local/lib/python2.4/test/test_sets.pyc matches /usr/local/lib/python2.4/test/test_sets.py import test.test_sets # precompiled from /usr/local/lib/python2.4/test/test_sets.pyc # trying /usr/local/lib/python2.4/test/operator.so # trying /usr/local/lib/python2.4/test/operatormodule.so # trying /usr/local/lib/python2.4/test/operator.py # trying /usr/local/lib/python2.4/test/operator.pyc # trying /usr/local/src/python/python/dist/src/Lib/operator.so [...long snip...] John From snail at objmedia.demon.co.uk Mon Feb 14 14:18:27 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Mon, 14 Feb 2005 19:18:27 +0000 Subject: - E02 - Support for MinGW Open Source Compiler References: <1108398011.213872.321390@o13g2000cwo.googlegroups.com> <1108407625.250592.104280@c13g2000cwb.googlegroups.com> Message-ID: In message <1108407625.250592.104280 at c13g2000cwb.googlegroups.com>, Pat writes >Actually, no. We ran into some issues with Python 2.4 that caused us >to return to Python 2.3.5. But I would really like to upgrade to >Python 2.4. So I started researching the subject before I did >anything. Pat, could you include some context in your replies? I have no idea if you are replying to my comments about Visual Studio Express or someone else? The only text I see in your replies is what you write, no text from the posting you are replying to. As it is I've ignored all your replies so far as I'm not sure I'm the person you are addressing (until I saw the above, now I'm confused). Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From devries at idolstarastronomer.com Sun Feb 13 16:20:04 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: Sun, 13 Feb 2005 16:20:04 -0500 Subject: Q: Portable Way to Make Files Read Only In-Reply-To: References: Message-ID: <20050213212004.GA24649@miyu.cjas.org> On Sun, Feb 13, 2005 at 01:25:02PM -0600, Efrat Regev wrote: > I would like to recurse through a directory and make files (which match > a specific criteria) read only. From searching the Internet, I found > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303343 > which shows how to change file attributes to read only using the > win32api module. That's great, but I was hoping there's a more portable way > to do so. Is there a more portable API call to make files read only? assuming the variable "path" is set to a string indicating the file in question, try the following: import os import stat # get the current file mode mode = os.stat(path)[stat.ST_MODE] # set it so it is not user, group, or other writable os.chmod(path, mode & ~stat.S_IWUSR & ~stat.S_IWGRP & ~stat.S_IWOTH) #or os.chmod(path,mode & ~0222) Chris From peter at engcorp.com Mon Feb 28 17:15:58 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 28 Feb 2005 17:15:58 -0500 Subject: Calling external text-files (newb) In-Reply-To: References: Message-ID: <1PKdnRHf74eABb7fRVn-ow@powergate.ca> Andreas Winkler wrote: > I tried to have python call an external 'Word'-file, > and the read the whole text into a single string with > the following code: > [CODE] > source = raw_input('file path') > > File = open('source', 'r') > S = input.read() > > print S > [/CODE] Anything inside quotation marks is just a string of characters, not a reference to a variable. You are asking it to open a file named "source", not to open the file whose name is in the variable called source. In addition, you are assigning the return value from open() to a variable named "File", but then you are not using that variable but are trying to read from a non-existent object called "input" instead. You'll see an error for that if you fix only the first problem and try rerunning the code, before you fix the second (which you should do, to learn more). Use this instead: f = open(source, 'r') s = f.read() print s -Peter From Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org Wed Feb 9 17:55:55 2005 From: Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org (Alexander) Date: Thu, 10 Feb 2005 01:55:55 +0300 Subject: variable declaration References: Message-ID: Hi, Elspeth! 09 feb 2005 at 14:44, Elspeth Thorne wrote: >> You may say: give better names for your variables! Ha, I'am often >> don't understand that they mean! They are written for me by an >> engineer! ET> Hang on, though - if you don't understand what you are programming, ET> then how can you check if it's correct? ...skipped... ET> You'd hit the same issues (precisely the same issues) with any ET> language, if you flat-out do not know what you are doing - or trying ET> to do. ET> Admittedly, I have somewhat limited experience, so my word is not ET> gospel, or even necessarily well-informed. I will inform you:) Let say you are working with the team of engineers. They develop a project of new building, and they need some calculations of solidness of metall constructions, specific for such kind of building. Such calculations are rather complex, so they can't wrote program (or smth else) themselves. But they can wrote and explain algorithm with calculations. If you want understand their formulas, you must learn theoretical mechanicks, resistance of materials, builder's standarts and rules (I'm not sure I translate titles of the disciplines correctly). It will take a year, minimum. But you have no such time - deadline is much closer:) As for me, I _HATE_ such kind of job:) But sometimes it happens. And, after some years, when you see the final result of such job, you fill some special feelings. It differ from result of purely programmer's work. The result is big, real, it may work for people during tens (or may be hundred) years. Main problem in programming - programmer "look to the wrong place" or "overlook coefficient", ... . Main weapon to fight with them - tests. We do it this way. After engineer wrote an "algorithm", he take a calculator and began to work according to it (it also help him to find "bugs"). Final result, and all intermediate results are written. Every separate part of calculations (separate function in program) tested separately and in whole. But tests are not a silver bullet. static checking is also very usefull. What's why I feel variable declaration (or explicit variable definition) may help. Alexander, zatv at bk.ru From simonroses at granisla.com Thu Feb 10 10:08:10 2005 From: simonroses at granisla.com (Simon Roses Femerling) Date: Thu, 10 Feb 2005 16:08:10 +0100 Subject: Two questions: python/Net(c#) and Win Raw sockets? Message-ID: <01f501c50f82$55821240$4c0818ac@dis> Hi all, First Question: Anyone has experience with any of this Python/Net implementations: - PythonNet - IronPython - Boo Which is best for using in a c# app for embedding and extending ? Second Question: I know that python 2.3 _socket.dll was not compile with raw socket support on windows. Anyone have a compile version or know any solution for raw socket on windows for python 2.3 or 2.4 or I must compile my own version of _socket.dll ? Thx Sincerely, SRF -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Wed Feb 2 14:26:46 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 02 Feb 2005 12:26:46 -0700 Subject: Hash of class from instance In-Reply-To: <36cj80F4ue5biU1@individual.net> References: <1107363342.531396.238350@g14g2000cwa.googlegroups.com> <1107364617.371795.13740@l41g2000cwc.googlegroups.com> <36cj80F4ue5biU1@individual.net> Message-ID: Mick Krippendorf wrote: > In Python there seems to be no guarantee that different objects also > have different hash values. Well, it's true that you can override the __hash__ method to do whatever you want, but I believe the default for class __hash__ methods is to return the class id, which should be different for each class: py> class C(object): ... pass ... py> hash(C) 12699152 py> id(C) 12699152 Steve From rkern at ucsd.edu Thu Feb 3 02:52:35 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 02 Feb 2005 23:52:35 -0800 Subject: Reinstall python 2.3 on OSX 10.3.5? In-Reply-To: References: Message-ID: Christian Dieterich wrote: > On D? C?adaoin, Feabh 2, 2005, at 17:48 America/Chicago, > moa at extrapolation.com wrote: > >> Hi there >> >> I started a very long and roundabout process of attempting to install >> python 2.3.4 along side my apple-installed 2.3 system. To make a long >> story short, I have completely confabulated my environment ( i deleted >> the 2.3 binaries and so forth from the system in an attempt to start >> things fresh), and now I cannot figure out how to reinstall the base >> 2.3 Apple python distribution. >> Can somebody please point me in the right direction? > > > You could use > fink install python > which makes you a Python installation under /sw. But that doesn't solve his problem, which is to restore the Apple-supplied Python that he deleted. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From g.brandl-2005-01 at gmx.net Sat Feb 5 08:36:30 2005 From: g.brandl-2005-01 at gmx.net (Georg Brandl) Date: Sat, 05 Feb 2005 14:36:30 +0100 Subject: mounting a filesystem? In-Reply-To: References: Message-ID: <36k0elF51attqU1@individual.net> Dan Stromberg wrote: > Is there a python module that can mount a filesystem? > > More specifically, a loopback filesystem with a particular offset, under > linux? Why don't you just call the mount command via os.system, one of the popen methods or one of the commands.* methods? Georg From janeaustine50 at hotmail.com Wed Feb 23 08:01:46 2005 From: janeaustine50 at hotmail.com (janeaustine50 at hotmail.com) Date: 23 Feb 2005 05:01:46 -0800 Subject: Style guide for subclassing built-in types? In-Reply-To: <421c76cd$1_1@newspeer2.tds.net> References: <1109127834.660822.247120@g14g2000cwa.googlegroups.com> <1109150091.356411.150460@l41g2000cwc.googlegroups.com> <1109151417.903188.73790@f14g2000cwb.googlegroups.com> <421c76cd$1_1@newspeer2.tds.net> Message-ID: <1109163706.118457.53720@z14g2000cwz.googlegroups.com> Kent Johnson wrote: > janeaustine50 at hotmail.com wrote: > > p.s. the reason I'm not sticking to reversed or even reverse : suppose > > the size of the list is huge. > > reversed() returns an iterator so list size shouldn't be an issue. > > What problem are you actually trying to solve? > > Kent > Oh, you are right. Actually, it's more complicated than simple reversion. The list order should be somewhat "twisted" and the list is big. For example, [1,2,3,4,5,6,7,8,9,10] --> [10,9,8,7,6,1,2,3,4,5] so __getitem__(self,i) => __getitem__(self,-i-1) if i References: <1108739705.870161.36050@z14g2000cwz.googlegroups.com> Message-ID: kdahlhaus at yahoo.com wrote: > Does anyone here have experience with Chart Director > (http://www.advsofteng.com/index.html)? I'm thinking about purchasing > it and looking for any feedback from the Python community. Thanks > Since ChartDirector is not exactly open source nor found its origin in a Python setting, my uneducated guess is that it will mostly be companies that use ChartDirector. However, from that vantage-point, ChartDirector is well-documented, has lots of examples, and is great value for the money; it's pretty straight forward, it covers all Python versions from 1.52 - 2.4, and the license generally encompasses all other language bindings, too (all being at version 4.0 except for the C++ version which is currently still at 3.04). Still, you should just try it for what you are planning to use it /for/ and see if it meets /your/ specific needs. -- Vincent Wehren From fredrik at pythonware.com Mon Feb 14 11:17:13 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Feb 2005 17:17:13 +0100 Subject: mxCGIPython binaries for Python 2.3.5 References: <20050211154457.GA23787@phd.pp.ru><20050211181320.GA23241@caltech.edu> <20050211183904.GA28714@phd.pp.ru> <20050214080603.1181621450.EP@zomething.com> Message-ID: "EP" wrote: > http://www.egenix.com/files/python/mxCGIPython.html > I'm unschooled in non-Windows binaries. Does this mean it may be possible > to download this package onto a (for example) SunOS system, unpack and > have Python up and running? yes. (that's the whole point, of course) did you read the page he linked to? "... the interpreter together with the whole standard library and the builtin modules into one single file. All that remains is to FTP that binary to the ISP and off you go." From fredrik at pythonware.com Mon Feb 14 16:29:47 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Feb 2005 22:29:47 +0100 Subject: - E02 - Support for MinGW Open Source Compiler References: Message-ID: Stephen Kellett wrote: > Lots of points from Tony stating a different point of view. I'll assume you are correct. However, > surely if you Python 2.4 installed they'll have this DLL anyway, so the point is moot, unless of > course, Python 2.4 is in breach as well. the compilers used to build Python 2.4 were provided by Microsoft, free of charge. conspiracy theorists may see this as evidence of some evil plan, of course, but I can assure you that when it comes to evilness, the PSU b From ashot at removemolsoftthis.com Thu Feb 3 23:05:10 2005 From: ashot at removemolsoftthis.com (Ashot) Date: Thu, 03 Feb 2005 22:05:10 -0600 Subject: IPython colors in windows References: <1107487113.732375.110850@c13g2000cwb.googlegroups.com> Message-ID: On 3 Feb 2005 19:18:33 -0800, James wrote: > > Ashot wrote: >> I am using IPython in windows and the LightBG setting doesn't > correctly >> because the background of the text is black even if the console > background >> is white. Anyone know whats going on? Thanks. >> >> -- >> ============================== >> Ashot Petrosian >> University of Texas at Austin, Computer Sciences >> (views expressed are solely my own) >> ============================== > > Did you try installing readline for windows? > http://newcenturycomputers.net/projects/readline.html > yea I've installed that and ctypes. The color and tab completion work, its just that colored get displayed with black background, it almost works so its very frustrating.. -- ============================== Ashot Petrosian University of Texas at Austin, Computer Sciences (views expressed are solely my own) ============================== From jgrahn-nntq at algonet.se Sat Feb 26 20:46:05 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 27 Feb 2005 01:46:05 GMT Subject: Converting HTML to ASCII References: <7xk6ovbob4.fsf@ruckus.brouhaha.com> Message-ID: On 26 Feb 2005 02:36:31 -0800, Paul Rubin <> wrote: > Jorgen Grahn writes: >> You should probably do what some other poster suggested -- download >> lynx or some other text-only browser and make your code execute it >> in -dump mode to get the text-formatted html. You'll get that >> working in an hour or so, and then you can see if you need something >> more complicated. > > Lynx is pathetically slow for large files. It seems to use a > quadratic algorithm for remembering where the links point, or > something. I wrote a very crude but very fast renderer in C that I > can post if someone wants it, which is what I use for this purpose. That may be so, but it's fast enough for all the people who use it as a general html->plaintext tool, so it's probably good enough for the OP. w3m and links are other options. They provide better formatting than lynx, and at least w3m has the -dump option. I wouldn't mind if there was a reusable library for rendering HTML to text, from various languages. I'd also like to see one (CSS-aware) for rendering to troff or Postscript. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From luismgz at gmail.com Sat Feb 5 23:08:51 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 5 Feb 2005 20:08:51 -0800 Subject: An Ode To My Two Loves References: Message-ID: <1107662931.185621.122410@c13g2000cwb.googlegroups.com> Jamey, Really, you should try to steer clear from your computer from time to time... Your mental health is more important than python or ruby, don't lose it! From kartic.krishnamurthy at gmail.com Tue Feb 8 14:19:47 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 8 Feb 2005 11:19:47 -0800 Subject: Python mail filter In-Reply-To: <4208f1d0$1@news.starhub.net.sg> References: <4208f1d0$1@news.starhub.net.sg> Message-ID: <1107890387.721965.9160@l41g2000cwc.googlegroups.com> I just read your requirement of a pass through... Writing the email back into sys.stdout from your script might do the trick of passing it through to the original intended recipient. From lbates at syscononline.com Fri Feb 25 17:14:47 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 25 Feb 2005 16:14:47 -0600 Subject: Splitting strings - by iterators? In-Reply-To: References: Message-ID: <6MudnRJ3Oe_NPoLfRVn-vg@comcast.com> By putting them into another file you can just use .readline iterator on file object to solve your problem. I would personally find it hard to work on a program that had 400,000 lines of data hard coded into a structure like this, but that's me. -Larry Jeremy Sanders wrote: > On Fri, 25 Feb 2005 10:57:59 -0600, Larry Bates wrote: > > >>How did you get the string in memory in the first place? > > > They're actually from a generated python script, acting as a saved file > format, something like: > > interpret(""" > lots of lines > """) > another_command() > > Obviously this isn't the most efficient format, but it's nice to > encapsulate the data and the script into one file. > > Jeremy > From kartic.krishnamurthy at gmail.com Fri Feb 4 15:20:07 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 4 Feb 2005 12:20:07 -0800 Subject: Possibly OT: Controlling winamp with Python In-Reply-To: References: Message-ID: <1107548407.626431.171350@z14g2000cwz.googlegroups.com> Brent, Question : how will your python script distinguish between a commercial and a song? I can understand if you are writing a streaming client in Python; in that case you can analyze the audio stream and decide if it is a commercial or a song/music. Did you check to see if there is already a Winamp plugin that would achieve this for you? Thanks, -Kartic From andrea_gavana at tin.it Sun Feb 27 04:44:04 2005 From: andrea_gavana at tin.it (andrea_gavana at tin.it) Date: Sun, 27 Feb 2005 10:44:04 +0100 Subject: Controlling Pc From Server? Message-ID: <420006340000CB7D@ims9c.cp.tin.it> Hello NG, I am trying to find some information about the possibility to control two (or more) clients (PCs) via a Python application running on a main server. Ideally, this application should be able to monitor (almost in real time) the "activity" of these clients (which applications are launched, closed and so on, if this is even possible, obviously). Does anyone have to share some information/pointer? Thank you a lot. Andrea. From t-meyer at ihug.co.nz Tue Feb 1 22:33:14 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Wed, 2 Feb 2005 16:33:14 +1300 Subject: getting data from a port in use In-Reply-To: Message-ID: >>> I am trying to use Python to get the data received at a >>> specific port (in use) on my computer. I already tried below >>> code which seems to hang at the statement accepting >>> connections. > > Yes. It hangs at accept. I always end up doing end task > because it never passes the "accept" statement. What do you get from wherever you are trying to connect to the port (e.g. telnet). Does it connect, or fail to connect? Note that (as others have said) if you are trying to intercept data from an existing socket connection, this is not the way to do it. (This will let you use a port that another process has already claimed, and accept new connections to it). =Tony.Meyer From jaydonnell at gmail.com Sun Feb 13 13:02:00 2005 From: jaydonnell at gmail.com (jdonnell) Date: 13 Feb 2005 10:02:00 -0800 Subject: Second posting - Howto connect to MsSQL In-Reply-To: References: Message-ID: <1108317720.675414.87990@f14g2000cwb.googlegroups.com> " Since this is (sort of) my second request it must not be an easy solution. Are there others using Python to connect MsSQL? " http://sourceforge.net/projects/mysql-python From caleb1 at telkomsa.net Tue Feb 8 23:22:44 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 08 Feb 2005 23:22:44 -0500 Subject: Basic file operation questions References: <1107379669.870799.256030@g14g2000cwa.googlegroups.com> <1107846197.701686.303390@l41g2000cwc.googlegroups.com> <7q4Od.753$Sd.170775@newshog.newsread.com> Message-ID: Marc I don't know how it is handled, but I expect also that there is an implied close(). thanks Caleb > When you read a file with that method, is there an implied close() call > on the file? I assume there is, but how is that handled? From jkjone2002 at att.net Thu Feb 17 10:11:16 2005 From: jkjone2002 at att.net (john san) Date: Thu, 17 Feb 2005 10:11:16 -0500 Subject: [newbie]How to install python under DOS and is there any Wxpython can be installed under dos? References: <1108557065.547230.254540@z14g2000cwz.googlegroups.com> <11172sa1sg2svc8@corp.supernews.com> <1108649705.442893.278840@g14g2000cwa.googlegroups.com> Message-ID: oh, ya. "Fuzzyman" ???? news:1108649705.442893.278840 at g14g2000cwa.googlegroups.com... > > john san wrote: > > Actually the "windows" running very good under the xbox-NTOS via > > xboxmediacenter. its just limited functions(not easy to programming > the > > "windows" prog.), if we can find WxPython-like can be ported (I can > import * > > from it to my xboxPython) )it will be a great great ......... You > will have > > HD screen and web surfing on HDTV and computing on HDTV. think about > it! > > That is a real thing the python-like lang. should to do otherwise > just a > > garbage(toy). > > > > > > > > I assume you mean that without python the Xbox is just a toy...... > > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml > From Serge.Orlov at gmail.com Sat Feb 26 15:06:54 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: Sat, 26 Feb 2005 20:06:54 +0000 (UTC) Subject: fdups: calling for beta testers References: <421f97eb$1@news.vo.lu> <1109380525.262724.275780@g14g2000cwa.googlegroups.com> <422044b9$1@news.vo.lu> Message-ID: Peter Hansen wrote: > Patrick Useldinger wrote: >>> (9) Any good reason why the "executables" don't have ".py" >>> extensions on their names? >> >> (9) Because I am lazy and Linux doesn't care. I suppose Windows does? > > Unfortunately, yes. Windows has nothing like the "x" permission > bit, so you have to have an actual extension on the filename and > Windows (XP anyway) will check it against the list of extensions > in the PATHEXT environment variable to determine if it should be > treated like an executable. > > Otherwise you must type "python" and the full filename. Or use exemaker, which IMHO is the best way to handle this problem. Serge. From debianfreak at freenet.de Wed Feb 23 08:17:57 2005 From: debianfreak at freenet.de (Jochen Kaechelin) Date: Wed, 23 Feb 2005 14:17:57 +0100 Subject: newbie help for mod_python In-Reply-To: References: Message-ID: <200502231417.57821.debianfreak@freenet.de> Am Mittwoch, 23. Februar 2005 00:29 schrieb Brian Beck: > Jochen Kaechelin wrote: > > I run debian sid and apache2 with libapache2-mod-python2.3 > > and I added these lines > > > > > > AddHandler mod_python .py > > PythonDebug On > > > > > > in a virtualhost container. > > Were those the only lines you added? You also should have > actually loaded the module somewhere by adding something > resembling: > > LoadModule python_module modules/mod_python.so Thats done by debian during installation: Module Name: mod_python.c Content handlers: yes -- Gugsch Du: http://gissmoh.de From steven.bethard at gmail.com Mon Feb 14 02:17:34 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 14 Feb 2005 00:17:34 -0700 Subject: custom classes in sets In-Reply-To: References: Message-ID: vegetax wrote: > How can i make my custom class an element of a set? > > class Cfile: > def __init__(s,path): s.path = path > > def __eq__(s,other): > print 'inside equals' > return not os.popen('cmp %s %s' % (s.path,other.path)).read() > > def __hashcode__(s): return s.path.__hashcode__() > > the idea is that it accepts file paths and construct a set of unique > files (the command "cmp" compares files byte by byte.),the files can > have different paths but the same content > > but the method __eq__ is never called Seems to be called fine for me: py> class Cfile: ... def __eq__(self, other): ... print 'inside equals' ... return False ... def __hash__(self): ... return 0 ... py> {Cfile():1, Cfile():2} inside equals {<__main__.Cfile instance at 0x01166490>: 1, <__main__.Cfile instance at 0x01166760>: 2} Note that __eq__ won't be called if the hashes are different: py> class Cfile: ... hash = 0 ... def __eq__(self, other): ... print 'inside equals' ... return False ... def __hash__(self): ... Cfile.hash += 1 ... return Cfile.hash ... py> {Cfile():1, Cfile():2} {<__main__.Cfile instance at 0x01166918>: 1, <__main__.Cfile instance at 0x011668A0>: 2} Steve From sjmachin at lexicon.net Sun Feb 13 17:18:04 2005 From: sjmachin at lexicon.net (John Machin) Date: 13 Feb 2005 14:18:04 -0800 Subject: builtin functions for and and or? In-Reply-To: <1108330461.853575.273700@g14g2000cwa.googlegroups.com> References: <1108330461.853575.273700@g14g2000cwa.googlegroups.com> Message-ID: <1108333084.425349.200140@l41g2000cwc.googlegroups.com> Michael Hartl wrote: > I warmly recommend downloading Peter Norvig's Python utilities file > (http://aima.cs.berkeley.edu/python/utils.py) and putting it on your > Python path. (E.g., in bash, put a line like > > export PYTHONPATH="/path/to/utilities_directory" > > in your .bashrc file.) The utils.py file defines many useful > functions, including the ones you want: > > # def every(predicate, seq): > # """True if every element of seq satisfies predicate. > # Ex: every(callable, [min, max]) ==> 1; every(callable, [min, 3]) > ==> 0 > # """ > # for x in seq: > # if not predicate(x): return False > # return True > # > # def some(predicate, seq): > # """If some element x of seq satisfies predicate(x), return > predicate(x). > # Ex: some(callable, [min, 3]) ==> 1; some(callable, [2, 3]) ==> 0 > # """ > # for x in seq: > # px = predicate(x) > # if px: return px > # return False > What an interesting mixed API design. The every() function returns True or False. However the "some" function returns the FIRST fat result if it's true in the non-boolean sense, otherwise False. Looks like there could theoretically be scope for two pairs of functions, one returning strictly True/False, and the other pair emulating chains of Python 'and's and 'or's. I.e. False or 0 or [] evaluates to [] 0 or 5 or 6 evaluates to 5 42 and None and True evaluates to None 4 and 5 and 6 evaluates to 6 All very nice, but useful? Dubious. PEPpable? Nah, two thumbs down. Diez's advice to the OP is sound: if it bothers you that much, mine the net for, or write, routines that do exactly what you want, and put them in your own utilities module. From nhodgson at bigpond.net.au Mon Feb 28 19:52:56 2005 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 01 Mar 2005 00:52:56 GMT Subject: Pythonwin: Red squiggley underline and syntax error References: Message-ID: Steven Bethard: > You've probably mixed tabs with spaces in your indentation somewhere. > Either replace all tabs with spaces or replace all spaces with tabs. You can see what characters are being used with the View | Whitespace command which shows tabs as arrows and spaces as centred dots. Neil From rbt at athop1.ath.vt.edu Thu Feb 17 09:29:30 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Thu, 17 Feb 2005 09:29:30 -0500 Subject: os.walk() Message-ID: Could someone demonstrate the correct/proper way to use os.walk() to skip certain files and folders while walking a specified path? I've read the module docs and googled to no avail and posted here about other os.walk issues, but I think I need to back up to the basics or find another tool as this isn't going anywhere fast... I've tried this: for root, dirs, files in os.walk(path, topdown=True): file_skip_list = ['file1', 'file2'] dir_skip_list = ['dir1', 'dir2'] for f in files: if f in file_skip_list files.remove(f) for d in dirs: if d in dir_skip_list: dirs.remove(d) NOW, ANALYZE THE FILES And This: files = [f for f in files if f not in file_skip_list] dirs = [d for d in dirs if dir not in dir_skip_list] NOW, ANAYLZE THE FILES The problem I run into is that some of the files and dirs are not removed while others are. I can be more specific and give exact examples if needed. On WinXP, 'pagefile.sys' is always removed, while 'UsrClass.dat' is *never* removed, etc. From peter at somewhere.com Tue Feb 15 10:53:34 2005 From: peter at somewhere.com (Peter Maas) Date: Tue, 15 Feb 2005 16:53:34 +0100 Subject: replacing ASP/VBScript with Python In-Reply-To: <37e95mF5biov1U1@individual.net> References: <37e95mF5biov1U1@individual.net> Message-ID: Diez B. Roggisch schrieb: > You did not really give much information of what your application does - > e.g. for a CMS, I'd strongly recommend a zope based solution. Other apps > might be better written in other frameworks. It's a procurement app. Users (employees) can search in a product list and generate orders to the company's internal or external suppliers. The orders are stored in a database and emails are generated to the addresses of the buyer and the suppliers. There is no direct interface to an erp app (like SAP). -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From qwweeeit at yahoo.it Mon Feb 7 14:27:55 2005 From: qwweeeit at yahoo.it (qwweeeit) Date: 7 Feb 2005 11:27:55 -0800 Subject: PySol: using Qt (as a case study) References: <2ab23d7a.0502070614.32881704@posting.google.com> Message-ID: <2ab23d7a.0502071127.33e7fac5@posting.google.com> It must be the Free Software Foundation that has to take in charge the problem (as I know it has already done in some cases)... From caleb.hattingh at gmail.com Wed Feb 9 01:28:06 2005 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 8 Feb 2005 22:28:06 -0800 Subject: Python versus Perl ? In-Reply-To: References: <1107695949.247611.272800@g14g2000cwa.googlegroups.com> Message-ID: <1107930486.318280.251010@l41g2000cwc.googlegroups.com> Hi Adam Thanks for your comments. > I think the expression you seek is "comparing virtue among whores." Sure, that's what I was saying, but not quite in as colourfil a manner :) > > > > The problem domains in which I do most of my work (chemical process > > modelling and simulation) really do require speed. That's why I mostly > > use Delphi (i.e. reasonably fast code) at work. I believe I know when > > speed is and is not an issue, and (by far) most of the time, my experience > > is that it is *not*. So I use Delphi for numerical code and python for > > everything else. > > Why don't you use C for the numerical work? Then you can do your number > crunching within a c-based python module. Have your cake and ... As you might imagine, I think about this constantly. However, there are many other issues that make it complicated, such as having to work in a team where the average guy knows pascal well (we're just a bunch of chemical engineers), but has never even heard of python. Plus, were I to go this type of route, I would almost definitely code the binary modules in Delphi or FreePascal, make a DLL and use ctypes to call it. I do not know C and have no desire to learn now :) On the other hand, I know pascal quite well. keep well Caleb From carribeiro at gmail.com Tue Feb 8 07:34:35 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 8 Feb 2005 10:34:35 -0200 Subject: empty classes as c structs? In-Reply-To: <1grnyld.1t8l5kw1nr5aqsN%aleaxit@yahoo.com> References: <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> <9rmdnVR1lr-LYJvfRVn-gg@comcast.com> <4207606E.4040806@iinet.net.au> <1grnyld.1t8l5kw1nr5aqsN%aleaxit@yahoo.com> Message-ID: <864d370905020804345876a1d5@mail.gmail.com> On Tue, 8 Feb 2005 12:01:23 +0100, Alex Martelli wrote: > Nick Coghlan wrote: > > > > We could use __add__, instead for combining namespaces > > > > Update already let's us combine namespaces. To create a new object that merges > > two namespaces do: > > namespace.update(namespace(ns_1), ns_2) > > One thing I'd like to see in namespaces is _chaining_ -- keeping each > namespace separate but having lookups proceed along the chain. (The > best semantics for _bindings_ as opposed to lookups isn't clear though). Good point. The name 'namespace' kind of imples chaining, in the usual Pythonic sense... But I feel that by splitting this into two types (namespace & bunch) we may be making things overly complicated, and losing some of the power of the argument. Again, just my $0.02 worth. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From deetsNOSPAM at web.de Fri Feb 25 08:14:51 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 25 Feb 2005 14:14:51 +0100 Subject: Trees References: Message-ID: <388mj5F5k1pveU1@individual.net> Alex Le Dain wrote: > Is there a generic "tree" module that can enable me to sort and use > trees (and nodes). Basically having methods such as .AddNode(), > .GetAllChildren(), .FindNode() etc. No. Usually, one uses the built-in python datastructures for this. E.g. ('root', [('child1', None), ('child2', None)]) Or writing a Node-class is also so straightforward that few care about them being part of the core: class Node(object): def __init__(self, payload, childs=None): self.payload = payload self.childs = childs def depth_first(self): if self.childs: for child in self.childs: for node in child.depth_first(): yield node yield self.payload tree = Node('root', [Node('child1'), Node('child2')]) for n in tree.depth_first(): print n -- Regards, Diez B. Roggisch From kanenas_ at t_comcast_d.t_net Tue Feb 15 03:17:23 2005 From: kanenas_ at t_comcast_d.t_net (Kanenas) Date: Tue, 15 Feb 2005 00:17:23 -0800 Subject: deepcopy chokes with TypeError on dynamically assigned instance method References: <698m01djeu9jqpnvvk64vmc488e5c026im@4ax.com> Message-ID: On Sun, 13 Feb 2005 12:01:42 +1000, Nick Coghlan wrote: >> True. It wouldn't cause a problem within my __init__, since the >> attribute is reassigned after the deepcopy, though should anyone else >> deepcopy an instance... Definitely better that the deepcopy throws the >> TypeError. But why shouldn't we be able to copy a non-method function? > >I honestly don't know, although I'm hard-pressed to see how doing so would ever >be *useful*. Duplicating *parts* of a function would seem to make sense (to >build a new function which is similar, but not identical), but duplicating the >whole thing seems rather pointless. Although I guess you could just pickle it >and then unpickle the result to make a copy :) > It's not so much that copying a function is useful as it would be nice if copy and deepcopy didn't fail on plain functions, as there are cases where objects would need to store references to such functions. Imagine classes implementing operations on functions such as numeric differentiation and integration (while symbolic differentiation & integration would probably be better for production code, the example still stands). As it is, a little extra work would be needed to support deepcopying such classes. And it's always nice to avoid work. Thanks for your help and feedback on this. From nobodyatanywheredotcom Fri Feb 25 19:05:27 2005 From: nobodyatanywheredotcom (Erik Johnson) Date: Fri, 25 Feb 2005 17:05:27 -0700 Subject: cgi: getting at raw POST data? Message-ID: <421fbaf9$1@nntp.zianet.com> I am trying to work with a program that is trying make an HTTP POST of text data without any named form parameter. (I don't know - is that a normal thing to do?) I need to write a CGI program that accepts and processes that data. I'm not seeing how to get at data that's not a named form parameter. I wrote a simple CGI program to echo a string representation of the cgi.FieldStorage class that's recevied, and one to make an HTTP POST to it (once with the way I normally encode a "standard" HTML form, and once with just a multiline string). It doesn't look to me like the FieldStorage class is exposing anything for me to grab ahold of in the latter case. I don't see any other likely looking candidates in the cgi module. My program code is below. Anyone have any suggestions about how to get at raw POST data (as a CGI program)? Thanks for taking the time to read my article! :) -ej results of running 'post' each way: > post form
FieldStorage(None, None, [MiniFieldStorage('buckle', 'my shoe'),
MiniFieldStorage('one', 'two')])
> post other
FieldStorage(None, None, [])
#! /usr/local/bin/python "post" import os, sys, time, string import httplib, urllib what = sys.argv[1] server = "localhost" url = "/test_POST" conn = httplib.HTTPConnection(server) conn.putrequest('POST', url) if what == 'form': form = { 'one' : 'two', 'buckle' : 'my shoe' } DATA = urllib.urlencode(form) else: DATA = """\ line 1 this is my little stream of raw data put into POST without any parameter name. """ conn.putheader('Content-Length', str(len(DATA)) ) conn.endheaders() conn.send(DATA) response = conn.getresponse() text = response.read() conn.close() # done with current machine print text #! /usr/bin/python "test_POST" # Python STANDARD INCLUDES import sys import cgi import cgitb; cgitb.enable() # MAIN # get stuff out of POST parameters if __name__ == "__main__": # dump out a web page print """\ Content-type: text/html
%s
""" % str(cgi.FieldStorage(keep_blank_values=True)) From alan.mcintyre at esrgtech.com Fri Feb 4 14:32:01 2005 From: alan.mcintyre at esrgtech.com (Alan McIntyre) Date: Fri, 04 Feb 2005 14:32:01 -0500 Subject: string issue In-Reply-To: References: Message-ID: I think it's because you're modifying the list as you're iterating over it. Try this: import time ips = ['255.255.255.255', '128.173.120.79', '198.82.247.98', '127.0.0.1', '255.0.0.0', '255', '128.173.255.34'] ips_new = [] for ip in ips: if '255' not in ip: ips_new.append(ip) print ips_new Or this: ips_new = [ip for ip in ips if '255' not in ip] print ips_new Hope this helps, Alan McIntyre http://www.esrgtech.com rbt wrote: > Either I'm crazy and I'm missing the obvious here or there is something > wrong with this code. Element 5 of this list says it doesn't contain the > string 255, when that's *ALL* it contains... why would it think that??? > > import time > > ips = ['255.255.255.255', '128.173.120.79', '198.82.247.98', > '127.0.0.1', '255.0.0.0', '255', '128.173.255.34'] > > for ip in ips: > if '255' in ip: > try: > print "Removing", ip > ips.remove(ip) > except Exception, e: > print e > > print ips > time.sleep(5) > > Someone tell me I'm going crazy ;) From news at slalomsk8er.ch Thu Feb 17 07:53:34 2005 From: news at slalomsk8er.ch (Slalomsk8er) Date: Thu, 17 Feb 2005 13:53:34 +0100 Subject: Help needed for to build a CGI shell interface. Message-ID: <421493CE.9090308@slalomsk8er.ch> I don't get it with the popen (popen3 or subprocess). 1. How do I establish my pipes? 2. And how do I interact with the pipes (interactive CGI-page)? Thanks, Dominik From mahs at telcopartners.com Thu Feb 17 01:53:00 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Wed, 16 Feb 2005 22:53:00 -0800 Subject: sampling items from a nested list In-Reply-To: <8t2dnQq5sJIZp4nfRVn-tA@comcast.com> References: <7_adnQhRBYDdV47fRVn-sA@comcast.com> <8t2dnQq5sJIZp4nfRVn-tA@comcast.com> Message-ID: Steven Bethard wrote: > Michael Spencer wrote: > >> Steven Bethard wrote: >> >>> So, I have a list of lists, where the items in each sublist are of >>> basically the same form. It looks something like: >>> >> ... >> >>> >>> Can anyone see a simpler way of doing this? >>> >>> Steve >> >> >> You just make these up to keep us amused, don't you? ;-) > > > Heh heh. I wish. It's actually about resampling data read in the > Yamcha data format: > > http://chasen.org/~taku/software/yamcha/ > > So each sublist is a "sentence" and each tuple is the feature vector for > a "word". The point is to even out the number of positive and negative > examples because support vector machines typically work better with > balanced data sets. > >> If you don't need to preserve the ordering, would the following work?: >> > [snip] > >> >> >>> def resample2(data): >> ... bag = {} >> ... random.shuffle(data) >> ... return [[(item, label) >> ... for item, label in group >> ... if bag.setdefault(label,[]).append(item) >> ... or len(bag[label]) < 3] >> ... for group in data if not >> random.shuffle(group)] > > > It would be preferable to preserve ordering, but it's not absolutely > crucial. Thanks for the suggestion! > > STeVe Maybe combine this with a DSU pattern? Not sure whether the result would be better than what you started with Michael From dbasch at yahoo.com Thu Feb 3 19:27:19 2005 From: dbasch at yahoo.com (Derek Basch) Date: Thu, 3 Feb 2005 16:27:19 -0800 (PST) Subject: CGI and HTTP Header Location redirects Message-ID: <20050204002719.45682.qmail@web20824.mail.yahoo.com> Hello, I have been dealing with some strange behavior using CGI, python and an HTTP Header "Location:" redirect on an Apache 1.3 server. If I call a CGI script and perform a "Location:" redirect the script seems to silently run off the tracks immediately after the redirect. For example "0.xml" and "1.xml" are created when there is no redirect and only "0.xml" is created when a redirect does occur (see below). Also, after enabling suEXEC on the apache server the script executes perfectly with the redirect. Can anyone explain this behavior? I would guess that it is related to apache user rights but I can't find any reference to such problems via Google. Thanks everyone!, Derek Basch ------------------------------------------------- #! /usr/bin/python import sys import cgitb class Trainer: def train(self): fs = open("/tmp/0.xml", "w") fs.close() ## print "Location: " + "http://www.yahoo.com" + "\n\n" sys.stdout.flush() fs = open("/tmp/1.xml", "w") fs.close() def main(): try: cgitb.enable() trainer = Trainer() trainer.train() except Exception, inst: cgitb.handler() if __name__ == '__main__': main() __________________________________ Do you Yahoo!? Take Yahoo! Mail with you! Get it on your mobile phone. http://mobile.yahoo.com/maildemo From uche.ogbuji at gmail.com Mon Feb 28 22:01:26 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 28 Feb 2005 19:01:26 -0800 Subject: best XSLT processor? In-Reply-To: References: Message-ID: <1109646086.046516.52580@o13g2000cwo.googlegroups.com> Who says 4Suite is buggy? Do they have any evidence to back that up? We have a huge test suite, and though 4Suite is by no means the fastest option, it's quite reliable for XSLT. The XSLT processor in PyXML is just a very old version of 4XSLT. --Uche From anthony_barker at hotmail.com Fri Feb 4 13:32:22 2005 From: anthony_barker at hotmail.com (Ant) Date: 4 Feb 2005 10:32:22 -0800 Subject: advice needed for simple python web app In-Reply-To: <7xis58tgjr.fsf@ruckus.brouhaha.com> References: <5cqdnZX-cZ9ca5_fRVn-3Q@rogers.com> <7xis58reac.fsf@ruckus.brouhaha.com> <7xis58tgjr.fsf@ruckus.brouhaha.com> Message-ID: <1107541942.740314.106650@o13g2000cwo.googlegroups.com> > You might also look at the docs for HTML::Mason (www.masonhq.com) to > get a look at a reasonably mature template system, even if you don't > plan to use it (because it's in Perl and not Python). I'm not sure if > CherryPy is directly comparable. I haven't yet used any of the Python > template systems. Mason is available for python http://www.myghty.org/ From pobrien at orbtech.com Sat Feb 19 16:46:07 2005 From: pobrien at orbtech.com (Pat) Date: 19 Feb 2005 13:46:07 -0800 Subject: - E02 - Support for MinGW Open Source Compiler References: <42172136$0$27576$9b622d9e@news.freenet.de> Message-ID: <1108849567.136885.141960@z14g2000cwz.googlegroups.com> Diez B. Roggisch wrote: > > >> Just out of curiousity: How many python extensions are you planning to > >> write? > > > > I estimate 10 to 100, depending on abstractional capabilities of the > > extension system. > > > >> And how many lines of pure python code have you written in your life? > > > > 0 (zero). > > Awesome. Without any lines of code written, you have already identified the > areas where python lacks features that have to be overcome with C-written > extensions. As usual, I stand with my mouth agape over your near-psychic > abilities to analyze even the complexest matters without any actual > fiddling with the nitty gritty details. If you put yourself into the shoes of someone who decides to use a Python product that requires compiling, and that product contains C extensions that also need compiling, you'll see that it doesn't matter whether or not that individual has actually written a single line of Python themselves. If the compiling process is not easy, then that user will be forced to fiddle with nitty gritty details about which they'd rather remain ignorant. On Linux, I've installed and used/compiled products in a variety of languages in which I've never written a single line of source code myself. In most cases the process works fairly well. When it doesn't, I'm forced to fiddle with nitty gritty details about which I'd rather remain ignorant. The result is usually a good deal of frustration and anger on my part. On Windows, most users are used to installing precompiled binary packages, rather than compiling from source. When you do have to compile from source, it often requires you to fiddle with nitty gritty details about which you'd rather remain ignorant. The less fiddling required, the happier the user will be, and the easier it will be for that product to get adopted on that platform. No psychic abilities are required. No Python abilities are required, either, for that matter. ;-) -- Patrick K. O'Brien Orbtech http://www.orbtech.com Schevo http://www.schevo.org Pypersyst http://www.pypersyst.org From john at grulic.org.ar Fri Feb 11 16:00:52 2005 From: john at grulic.org.ar (John Lenton) Date: Fri, 11 Feb 2005 18:00:52 -0300 Subject: check if object is number In-Reply-To: <66WdnbJbuf5yj5DfRVn-iA@comcast.com> References: <374ho0F560ughU1@individual.net> <66WdnbJbuf5yj5DfRVn-iA@comcast.com> Message-ID: <20050211210051.GA4186@grulic.org.ar> On Fri, Feb 11, 2005 at 01:17:55PM -0700, Steven Bethard wrote: > George Sakkis wrote: > >"Steven Bethard" wrote in message > >news:gcidnb9g_ojxnpDfRVn-tA at comcast.com... > > > >>Is there a good way to determine if an object is a numeric type? > > > >In your example, what does your application consider to be numeric? > > Well, here's the basic code: > > def f(max=None): > ... > while max is None or n <= max: > ... > # complicated incrementing of n > > So for 'max', technically all I need is <= support. However, the code > also depends on the fact that after incrementing 'n' enough, it will > eventually exceed 'max'. Currently, ints, longs, floats, and Decimals > will all meet this behavior. But I'd rather not specify only those 4 > (e.g. with a typecheck), since someone could relatively easily create > their own new numeric type with the same behavior. Do you know a better > way to test for this kind of behavior? Why don't you express just this need as an assertion? assert 0 <= max <= max + 1, 'Argument must not be zany' (or whatever error message is suitable) -- John Lenton (john at grulic.org.ar) -- Random fortune: Oxymorons? I saw one yesterday - the pamphlet on "Taco Bell Nutritional Information" -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From devnull at joreybump.com Thu Feb 3 09:22:39 2005 From: devnull at joreybump.com (Jorey Bump) Date: Thu, 03 Feb 2005 14:22:39 GMT Subject: Popularizing SimpleHTTPServer and CGIHTTPServer References: <1107412654.121488.157070@c13g2000cwb.googlegroups.com> Message-ID: "Michele Simionato" wrote in news:1107412654.121488.157070 at c13g2000cwb.googlegroups.com: > Just submitted a recipe with this goal in mind: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/365606 You may want to warn people that if they run those commands in their home directory, they will instantly share all of their data with anyone that can access the machine. Because the server runs as the user, it will have permission to serve all of the files in the directory. I'd recommend that they cd into a directory created specifically for the purpose of testing. Does anyone know how to use SimpleHTTPServer to: 1. Support virtual hosts? 2. Support SSL? I'd like to use SimpleHTTPServer to create some simple reporting utilities, but can't get past these two points. Is there a NotSoSimpleHTTPServer? From simon.brunning at gmail.com Mon Feb 21 07:13:48 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 21 Feb 2005 12:13:48 +0000 Subject: gui scripting In-Reply-To: <1108644499.036064.47210@z14g2000cwz.googlegroups.com> References: <1108381881.828494.98340@c13g2000cwb.googlegroups.com> <3c18c08f.0502142309.3e52fdbe@posting.google.com> <1108644499.036064.47210@z14g2000cwz.googlegroups.com> Message-ID: <8c7f10c60502210413783d37ee@mail.gmail.com> On 17 Feb 2005 04:48:19 -0800, Tonino wrote: > thanks - am already involved in a process to modify winguiauto.py - > this is a GREAT start but we need more control and better handleing ;) Can you be more specific? > Thanks for the WATSUP site - will check on this as well ;) WATSUP uses winguiauto.py. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From harlinseritt at yahoo.com Wed Feb 23 21:31:34 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 23 Feb 2005 18:31:34 -0800 Subject: How to write a ping client In-Reply-To: References: <1109039706.092671.137360@f14g2000cwb.googlegroups.com> <421a9d54$0$44652$a1866201@visi.com> <1109068125.070219.54510@o13g2000cwo.googlegroups.com> Message-ID: <1109212294.128292.119680@l41g2000cwc.googlegroups.com> ? From robin at reportlab.com Tue Feb 15 12:33:51 2005 From: robin at reportlab.com (Robin Becker) Date: Tue, 15 Feb 2005 17:33:51 +0000 Subject: customizing metaclass constructed classes Message-ID: <4212327F.20901@chamonix.reportlab.co.uk> I have a set of classes for database access which are constructed using a special metaclass and base class. so in the base module #base.py class M(type): def __init__(cls, name, bases, dict): super(M, cls).__init__(name, bases, dict) for f in dict['_fieldDefs']: #create special property based on the field def .... class A(object): __metaclass__ = M _fieldDefs = [] #base methods ...... in the database module we use the above eg #database.py class C(A): _fieldDefs =[ IntColumn('id',primaryKey=1,allowNull=0), TextColumn('name',allowNull=0,size=50), TextColumn('description',allowNull=1,size=50), ] Now to my question: can I change the definition of the client class C at run time? I want to do something like add another element to C's _fieldDefs and then get it to go through the construction phase provided by M. It's clearly pointless for me to try something like from database import C C._fieldDefs.append(....) as C is constructed by the import. I either have to delay C's construction or reconstruct it. Would something like this do? def reconstruct(): import database class C(database.C): _fieldDefs = database.C._fieldDefs+[......] database.C = C Is there a better way to do this which preserves more of C's original identity? I suppose I want to call the metaclass initialization again, but can't see a way to do that. -- Robin Becker From peter at engcorp.com Tue Feb 1 11:36:55 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 01 Feb 2005 11:36:55 -0500 Subject: The next Xah-lee post contest In-Reply-To: References: <20050130114008.797088857.whereU@now.com> <1107137465.973491.42050@f14g2000cwb.googlegroups.com> Message-ID: Arthur wrote: > Steve Holden wrote: >>Would there, I wonder, be any enthusiasm for a "Best Xah Lee impression" >>prize at PyCon? > > And the rules of the game, if he shows? Arthur, if Xah Lee shows up at Pycon, he most definitely will not be giving the best impression... -Peter From steven.bethard at gmail.com Wed Feb 16 01:50:12 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 15 Feb 2005 23:50:12 -0700 Subject: __new__ does not call __init__ as described in descrintro.html (WAS: Can __new__ prevent __init__ from being called?) In-Reply-To: References: Message-ID: <-4qdnffOueK5cI_fRVn-uQ@comcast.com> Aahz wrote: > In article , > Steven Bethard wrote: > >>Yeah, I saw the same thing in playing around with this. Don't know >>what to make of it. I wonder if we should file a documentation bug? I >>can't find __new__ explained anywhere in the Language Reference. Can >>documentation bugs be filed for descrintro.html? > > Absolutely! And they're especially welcome if they contain suggested > replacement text. Cool. I added a documentation bug: http://sourceforge.net/tracker/?func=detail&aid=1123716&group_id=5470&atid=105470 Steve From peter at engcorp.com Sun Feb 13 08:57:58 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 13 Feb 2005 08:57:58 -0500 Subject: For American numbers In-Reply-To: <420efc57$0$5212$7a628cd7@news.club-internet.fr> References: <420e7376$1@nntp0.pdx.net> <420efc57$0$5212$7a628cd7@news.club-internet.fr> Message-ID: Pierre Hanser wrote: > Peter Hansen wrote: > >> Scott David Daniels wrote: >> >>> Kind of fun exercise (no good for British English). >>> >>> def units(value, units='bytes'): >>> magnitude = abs(value) >>> if magnitude >= 1000: >>> for prefix in ['kilo mega giga tera peta ' >>> 'exa zetta yotta').split(): >>> magnitude /= 1000. >>> if magnitude < 1000.: >>> break >> >> >> >> Only for hard drive manufacturers, perhaps. >> >> For the rest of the computer world, unless I've missed >> a changing of the guard or something, "kilo" is 1024 >> and "mega" is 1024*1024 and so forth... > > even for cpu frequency? I don't think so. But who cares? CPU frequency, apart from being fairly meaningless anyway, doesn't cover enough ground for anyone to need a routine like the above to deal with it. Anyway, I was focusing on the "units='bytes'" part above which suggested a byte-oriented focus for the routine, and CPU frequencies aren't measured in bytes... -Peter From steven.bethard at gmail.com Fri Feb 25 23:53:36 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 25 Feb 2005 21:53:36 -0700 Subject: Which module is "set " in? In-Reply-To: References: Message-ID: Anthony Liu wrote: > I want to use the set function like > > mylist = ['a', 'b', 'b', 'd', 'e', 'a'] > myset = set (mylist) > > But I don't know what to import, I tried sys, sets, > they don't work. If you're using Python 2.4, they're builtin. If you're using Python 2.3, you'll probably want to do something like: from sets import Set as set Python's before 2.3 do not have a set type. > What's the easy way to find out the module that > contains a particular function? Perhaps the documentation index? http://docs.python.org/lib/genindex.html Steve From knight at baldmt.com Sun Feb 13 10:33:29 2005 From: knight at baldmt.com (knight at baldmt.com) Date: 13 Feb 2005 07:33:29 -0800 Subject: SCons build tool speed References: Message-ID: <1108308809.895231.157110@o13g2000cwo.googlegroups.com> Hi Neil, ted, et al.-- > > How does the speed of the Scons build tool compare with Ant? > > Right now with out Ant builds take around an hour. Hoping to > > speed that up. > > Scons emphasises accuracy over speed and is normally a little > slower than other build tools although still fast enough for most > purposes. One cause of slowness is that it reads the source files, > traces include files and checksums them all rather than relying > on file times. There are some things you can do to speed it up: > http://www.scons.org/cgi-bin/wiki/GoFastButton In anticipation of the next release of SCons, we've been doing a *lot* of work on profiling the performance and eliminating bottlenecks. It turns out that scanning the source files and performing the MD5 calculation is not the dominant factor that we've all assumed it is. There were some other inefficiencies in some of our algorithms that were much more significant, including some unnecessary disk scans, recomputing the same dependencies for every target in a list of targets generated by one command, and repeated just-in-time creation of some internal objects that could be created just once and cached. That said, SCons will never be as fast as Make, because it *is* doing more for you under the covers. Although the next version won't necessarily speed up every configuration (the bottlenecks are extremely configuration dependent), it should be a significant improvement for many configurations out there. --SK From juranich at barbet.tucson.saic.com Fri Feb 4 13:13:19 2005 From: juranich at barbet.tucson.saic.com (Steve Juranich) Date: Fri, 04 Feb 2005 11:13:19 -0700 Subject: returning True, False or None In-Reply-To: Message from Steven Bethard of "Fri, 04 Feb 2005 10:48:44 MST." Message-ID: <200502041813.j14IDKqZ015361@nemesis.tucson.saic.com> > This has a light code smell for me though -- can anyone see a simpler > way of writing this? How's about: def ntf(x, y): if x is None and y is None: return None if x == True or y == True: return True return False # Then... reduce(ntf, ) You might need to make sure that you initialize your "reduce" call the right way with the optional third argument. HTH -- Stephen W. Juranich Science Applications Intl. Corp. (SAIC) Tucson, AZ From joakim.storck at home.se Wed Feb 2 15:08:17 2005 From: joakim.storck at home.se (Joakim Storck) Date: 2 Feb 2005 12:08:17 -0800 Subject: Hash of class from instance References: <1107363342.531396.238350@g14g2000cwa.googlegroups.com> <1107364617.371795.13740@l41g2000cwc.googlegroups.com> <36cj80F4ue5biU1@individual.net> <1107373593.789905.168850@o13g2000cwo.googlegroups.com> Message-ID: <1107374897.854447.273660@z14g2000cwz.googlegroups.com> Simply because it didn't occur to me. So now I have >>> class A: pass ... >>> d = {A:[A(),A(),A()]} >>> a = d[A].pop() >>> a <__main__.A instance at 0x00F09A58> >>> Thanks all! /Joakim From porterboy76 at yahoo.com Fri Feb 25 08:36:23 2005 From: porterboy76 at yahoo.com (porterboy76 at yahoo.com) Date: 25 Feb 2005 05:36:23 -0800 Subject: split a directory string into a list Message-ID: <1109338583.168229.297760@z14g2000cwz.googlegroups.com> QUESTION: How do I split a directory string into a list in Python, eg. '/foo/bar/beer/sex/cigarettes/drugs/alcohol/' becomes ['foo','bar','beer','sex','cigarettes','drugs','alcohol'] I was looking at the os.path.split command, but it only seems to separate the filename from the path (or am I just using it wrong?). I don't want to do it manually if I can help it, as there will have to be exceptions for the cases where there is (not) a trailing (leading) slash, or escape sequences involving /. Is there a built in command for this? From max at alcyone.com Wed Feb 2 02:12:57 2005 From: max at alcyone.com (Erik Max Francis) Date: Tue, 01 Feb 2005 23:12:57 -0800 Subject: How do you do arrays In-Reply-To: References: <1107284817.848551.79000@c13g2000cwb.googlegroups.com> <1107291792.287774.90620@z14g2000cwz.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: > Classic BASIC actually splits the difference. > > dim a(10) > > allocates 11 elements, indexed 0..10 -- but most classes tend to ignore > element 0, and algorithms are as if only 10 elements exist starting at > 1. Basic also has the OPTION BASE instruction, which affects that. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis War is like love, it always finds a way. -- Bertolt Brecht From antonmuhin at rambler.ru Fri Feb 18 09:51:05 2005 From: antonmuhin at rambler.ru (anton muhin) Date: Fri, 18 Feb 2005 17:51:05 +0300 Subject: [perl-python] exercise: partition a list by equivalence In-Reply-To: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> Message-ID: <37mdmqF5fcvdpU1@individual.net> Xah Lee wrote: > here's another interesting algorithmic exercise, again from part of a > larger program in the previous series. > > Here's the original Perl documentation: > > =pod > > merge($pairings) takes a list of pairs, each pair indicates the > sameness > of the two indexes. Returns a partitioned list of same indexes. > > For example, if the input is > merge( [ [1,2], [2,4], [5,6] ] ); > > that means 1 and 2 are the same. 2 and 4 are the same. Therefore > 1==2==4. The result returned is > > [[4,2,1],[6,5]]; > > (ordering of the returned list and sublists are not specified.) > > =cut Almost a joke: from numarray import * def merge(*pairs): flattened = reduce(tuple.__add__, pairs, tuple()) m, M = min(flattened), max(flattened) d = M - m + 1 matrix = zeros((d, d), type = Bool) for x, y in pairs: X, Y = x - m, y - m matrix[X, X] = 1 matrix[X, Y] = 1 matrix[Y, X] = 1 matrix[Y, Y] = 1 while True: next = greater(dot(matrix, matrix), 0) if alltrue(ravel(next == matrix)): break matrix = next results = [] for i in range(d): eqls, = nonzero(matrix[i]) if eqls.size(): if i == eqls[0]: results.append(tuple(x + m for x in eqls)) return results Disclaimer: I'm not an expert in numarray and suppose the something can be dramatically imporved. From bokr at oz.net Fri Feb 25 16:07:27 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 25 Feb 2005 21:07:27 GMT Subject: exclude binary files from os.walk References: Message-ID: <421f9256.52068390@news.oz.net> On Wed, 26 Jan 2005 18:25:09 -0500, "Dan Perl" wrote: > >"rbt" wrote in message >news:ct94j7$15a$1 at solaris.cc.vt.edu... >> Is there an easy way to exclude binary files (I'm working on Windows XP) >> from the file list returned by os.walk()? >> >> Also, when reading files and you're unsure as to whether or not they are >> ascii or binary, I've always thought it safer to 'rb' on the read, is this >> correct... and if so, what's the reasoning behind this? Again all of this >> pertains to files on Windows XP and Python 2.4 > >Please clarify: is your question about identifying binary (non-ascii) files >or about using os.walk? > > I have a feeling it's about walking directories and identifying which files to should be "cooked" (to normalize line endings when opened and read). Regards, Bengt Richter From alanmk at hotmail.com Tue Feb 15 08:20:51 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 15 Feb 2005 13:20:51 +0000 Subject: parsing IMAP responses? In-Reply-To: <4211261c$0$44604$a1866201@visi.com> References: <42111b20$0$44604$a1866201@visi.com> <7x7jlazsyf.fsf@ruckus.brouhaha.com> <4211261c$0$44604$a1866201@visi.com> Message-ID: [Grant Edwards] >>>Is there a library somewhere that impliments the IMAP protocol >>>syntax? [Paul Rubin] >>It's very messy. [Grant Edwards] > It sure is. You'd think something intended to be > machine-readable would be easier to parse. IMHO, email is the most disgracefully badly spec'ced "application" in existence: I'm sure the average modern-day scr1pt k1dd13 could do better. SMTP: Have you ever tried to bounce processing? PITA. POP: No virtual hosting support. IMAP: You are in a twisty maze of passages, each slightly different ..... It's no wonder the spammers can ply their trade with such ease. grumpily-y'rs, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From ncoghlan at iinet.net.au Wed Feb 2 08:04:13 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 02 Feb 2005 23:04:13 +1000 Subject: access to serial port In-Reply-To: References: Message-ID: <4200CFCD.7030203@iinet.net.au> Pawe? Chrobak wrote: > Hi > > How to take access to serial port (rs232) ?? > Is't possible?? Just tell me guy's where I can take o look The same place you should always look - Google. Keywords: python serial Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From simon.anders at uibk.ac.at Tue Feb 8 08:26:18 2005 From: simon.anders at uibk.ac.at (Simon Anders) Date: Tue, 08 Feb 2005 14:26:18 +0100 Subject: python connect to server using SSH protocol In-Reply-To: References: <1107850655.289129.94880@o13g2000cwo.googlegroups.com> Message-ID: <4208bdfa$1@sia.uibk.ac.at> Hi Laszlo Zsolt Nagy wrote: > ajikoe at gmail.com wrote: > >> How can python connect to server which use SSH protocol? >> Is it easy since my python has to run third party vendor, write data, >> read data inside the server (supercomputer). >> >> > In advance, I'm not sure if I understood your problem. SSH is clearly a > remote > shell. You will be able to execute other programs on the remote computer. > Is is suitable to use this: > > child_stdin,child_stdout,child_stderr = os.popen2('ssh -l my_username > my_host') This is what I was about to reply as well. But I did a short test program and encountered a problem: import os fi, foe = os.popen4 ('ssh dopey') print >>fi, 'ls' fi.close () # <-- this is annoying for line in foe: print line, foe.close () The above connects to a server, passes the command 'ls', which is executed there, and prints the returned result. However, reading from foe succeeds only if fin has been closed before. An fi.flush() seems to be not sufficient. But if one wants Python to interactivly communicate with some shell on a remote machine, it is inconvenient to have to close and reopen the connection all the time. There should be a better way. Simon From mail at tuxipuxi.org Tue Feb 1 09:40:40 2005 From: mail at tuxipuxi.org (Michael Goettsche) Date: Tue, 1 Feb 2005 15:40:40 +0100 Subject: Go visit Xah Lee's home page In-Reply-To: References: Message-ID: <200502011540.40216.mail@tuxipuxi.org> On Tuesday 01 February 2005 01:07, aurora wrote: > Let's stop discussing about the perl-python non-sense. It is so boring. > > For a break, just visit Mr Xah Lee's personal page > (http://xahlee.org/PageTwo_dir/Personal_dir/xah.html). You'll find lot of > funny information and quotes from this queer personality. Thankfully no > perl-python stuff there. > > Don't miss Mr. Xah Lee's recent pictures at > > http://xahlee.org/PageTwo_dir/Personal_dir/mi_pixra.html > > My favor is the last picture. Long haired Xah Lee sitting contemplatively > in the living room. The caption says "my beautiful hair, fails to resolve > the problems of humanity. And, it is falling apart by age." I don't get why you guys blame Xah Lee as a person. Ok, he posts some bullshit, but that doesn't make him a bad person. Read the box about George Bush on his Homepage.. it shows that he is a well-thinking person. So, don't blame him in general. Michael From nospam at nospam.fr Thu Feb 10 10:28:05 2005 From: nospam at nospam.fr (jean-michel) Date: Thu, 10 Feb 2005 16:28:05 +0100 Subject: wxgrid multiline cell editor References: <420ad1b9$1_2@news.tm.net.my> Message-ID: "James" a ?crit dans le message de news:420ad1b9$1_2 at news.tm.net.my... > wxpython 2.5.3 > anyone know how to make a multiline cell editor for wxgrid? Hello, You can do that by a "wxGridCellAutoWrapStringEditor". You can test it by modifying GridSimple.py in the demo by adding (at line 24 in my version): self.SetRowSize(1, 45) self.SetCellEditor(1, 1, wxGridCellAutoWrapStringEditor()) Save it and now, when you launch the gridsimple in the demo (it's in core windows control), you can enter multiple lines in the cell containing "Another cell". It works in 2.4.2.4. I think it should also in 2.5. I join the whole program. Have fun. ++jm #--------------------------------------------------------------- from wxPython.wx import * from wxPython.grid import * from wxPython.lib.mixins.grid import wxGridAutoEditMixin #--------------------------------------------------------------------------- class SimpleGrid(wxGrid): ##, wxGridAutoEditMixin): def __init__(self, parent, log): wxGrid.__init__(self, parent, -1) ##wxGridAutoEditMixin.__init__(self) self.log = log self.moveTo = None EVT_IDLE(self, self.OnIdle) self.CreateGrid(25, 25) #, wxGrid.wxGridSelectRows) ##self.EnableEditing(False) # simple cell formatting self.SetColSize(3, 200) self.SetRowSize(4, 45) self.SetCellValue(0, 0, "First cell") self.SetCellValue(1, 1, "Another cell") self.SetRowSize(1, 45) self.SetCellEditor(1, 1, wxGridCellAutoWrapStringEditor()) self.SetCellValue(2, 2, "Yet another cell") self.SetCellValue(3, 3, "This cell is read-only") self.SetCellFont(0, 0, wxFont(12, wxROMAN, wxITALIC, wxNORMAL)) self.SetCellTextColour(1, 1, wxRED) self.SetCellBackgroundColour(2, 2, wxCYAN) self.SetReadOnly(3, 3, True) self.SetCellEditor(5, 0, wxGridCellNumberEditor(1,1000)) self.SetCellValue(5, 0, "123") self.SetCellEditor(6, 0, wxGridCellFloatEditor()) self.SetCellValue(6, 0, "123.34") self.SetCellEditor(7, 0, wxGridCellNumberEditor()) self.SetCellValue(6, 3, "You can veto editing this cell") # attribute objects let you keep a set of formatting values # in one spot, and reuse them if needed attr = wxGridCellAttr() attr.SetTextColour(wxBLACK) attr.SetBackgroundColour(wxRED) attr.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD)) # you can set cell attributes for the whole row (or column) self.SetRowAttr(5, attr) self.SetColLabelValue(0, "Custom") self.SetColLabelValue(1, "column") self.SetColLabelValue(2, "labels") self.SetColLabelAlignment(wxALIGN_LEFT, wxALIGN_BOTTOM) #self.SetDefaultCellOverflow(False) #r = wxGridCellAutoWrapStringRenderer() #self.SetCellRenderer(9, 1, r) # overflow cells self.SetCellValue( 9, 1, "This default cell will overflow into neighboring cells, but not if you turn overflow off."); self.SetCellSize(11, 1, 3, 3); self.SetCellAlignment(11, 1, wxALIGN_CENTRE, wxALIGN_CENTRE); self.SetCellValue(11, 1, "This cell is set to span 3 rows and 3 columns"); editor = wxGridCellTextEditor() editor.SetParameters('10') self.SetCellEditor(0, 4, editor) self.SetCellValue(0, 4, "Limited text") # test all the events EVT_GRID_CELL_LEFT_CLICK(self, self.OnCellLeftClick) EVT_GRID_CELL_RIGHT_CLICK(self, self.OnCellRightClick) EVT_GRID_CELL_LEFT_DCLICK(self, self.OnCellLeftDClick) EVT_GRID_CELL_RIGHT_DCLICK(self, self.OnCellRightDClick) EVT_GRID_LABEL_LEFT_CLICK(self, self.OnLabelLeftClick) EVT_GRID_LABEL_RIGHT_CLICK(self, self.OnLabelRightClick) EVT_GRID_LABEL_LEFT_DCLICK(self, self.OnLabelLeftDClick) EVT_GRID_LABEL_RIGHT_DCLICK(self, self.OnLabelRightDClick) EVT_GRID_ROW_SIZE(self, self.OnRowSize) EVT_GRID_COL_SIZE(self, self.OnColSize) EVT_GRID_RANGE_SELECT(self, self.OnRangeSelect) EVT_GRID_CELL_CHANGE(self, self.OnCellChange) EVT_GRID_SELECT_CELL(self, self.OnSelectCell) EVT_GRID_EDITOR_SHOWN(self, self.OnEditorShown) EVT_GRID_EDITOR_HIDDEN(self, self.OnEditorHidden) EVT_GRID_EDITOR_CREATED(self, self.OnEditorCreated) def OnCellLeftClick(self, evt): self.log.write("OnCellLeftClick: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) evt.Skip() def OnCellRightClick(self, evt): self.log.write("OnCellRightClick: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) evt.Skip() def OnCellLeftDClick(self, evt): self.log.write("OnCellLeftDClick: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) evt.Skip() def OnCellRightDClick(self, evt): self.log.write("OnCellRightDClick: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) evt.Skip() def OnLabelLeftClick(self, evt): self.log.write("OnLabelLeftClick: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) evt.Skip() def OnLabelRightClick(self, evt): self.log.write("OnLabelRightClick: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) evt.Skip() def OnLabelLeftDClick(self, evt): self.log.write("OnLabelLeftDClick: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) evt.Skip() def OnLabelRightDClick(self, evt): self.log.write("OnLabelRightDClick: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) evt.Skip() def OnRowSize(self, evt): self.log.write("OnRowSize: row %d, %s\n" % (evt.GetRowOrCol(), evt.GetPosition())) evt.Skip() def OnColSize(self, evt): self.log.write("OnColSize: col %d, %s\n" % (evt.GetRowOrCol(), evt.GetPosition())) evt.Skip() def OnRangeSelect(self, evt): if evt.Selecting(): self.log.write("OnRangeSelect: top-left %s, bottom-right %s\n" % (evt.GetTopLeftCoords(), evt.GetBottomRightCoords())) evt.Skip() def OnCellChange(self, evt): self.log.write("OnCellChange: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) # Show how to stay in a cell that has bad data. We can't just # call SetGridCursor here since we are nested inside one so it # won't have any effect. Instead, set coordinates to move to in # idle time. value = self.GetCellValue(evt.GetRow(), evt.GetCol()) if value == 'no good': self.moveTo = evt.GetRow(), evt.GetCol() def OnIdle(self, evt): if self.moveTo != None: self.SetGridCursor(self.moveTo[0], self.moveTo[1]) self.moveTo = None evt.Skip() def OnSelectCell(self, evt): self.log.write("OnSelectCell: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) # Another way to stay in a cell that has a bad value... row = self.GetGridCursorRow() col = self.GetGridCursorCol() if self.IsCellEditControlEnabled(): self.HideCellEditControl() self.DisableCellEditControl() value = self.GetCellValue(row, col) if value == 'no good 2': return # cancels the cell selection evt.Skip() def OnEditorShown(self, evt): if evt.GetRow() == 6 and evt.GetCol() == 3 and \ wxMessageBox("Are you sure you wish to edit this cell?", "Checking", wxYES_NO) == wxNO: evt.Veto() return self.log.write("OnEditorShown: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) evt.Skip() def OnEditorHidden(self, evt): if evt.GetRow() == 6 and evt.GetCol() == 3 and \ wxMessageBox("Are you sure you wish to finish editing this cell?", "Checking", wxYES_NO) == wxNO: evt.Veto() return self.log.write("OnEditorHidden: (%d,%d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetPosition())) evt.Skip() def OnEditorCreated(self, evt): self.log.write("OnEditorCreated: (%d, %d) %s\n" % (evt.GetRow(), evt.GetCol(), evt.GetControl())) #--------------------------------------------------------------------------- class TestFrame(wxFrame): def __init__(self, parent, log): wxFrame.__init__(self, parent, -1, "Simple Grid Demo", size=(640,480)) grid = SimpleGrid(self, log) #--------------------------------------------------------------------------- if __name__ == '__main__': import sys app = wxPySimpleApp() frame = TestFrame(None, sys.stdout) frame.Show(True) app.MainLoop() #--------------------------------------------------------------------------- From phil at freehackers.org Tue Feb 1 18:28:28 2005 From: phil at freehackers.org (Philippe Fremy) Date: Wed, 02 Feb 2005 00:28:28 +0100 Subject: Next step after pychecker In-Reply-To: References: <41ff0308$0$6503$636a15ce@news.free.fr> <369mivF4ubv6mU1@individual.net> Message-ID: <420010a0$0$27056$626a14ce@news.free.fr> > I do not want to discourage Philippe Fremy but I think that this would be very > very difficult to do without modifying Python itself. That's the conclusion I reached to too after lurking on the ocaml list. > > What FP languages rely upon to achieve type inference is a feature named > "strong typing". > [...] > > This is certainly not the case for Python since one and the same variable can > have different types depending upon the execution context. Example : > > 1- if a is None: > 2- b = 1 > 3- else: > 4- b = "Phew" > 5- b = b + 1 > > One cannot statically determine the type of b by examining the line 5- alone. > There are even worse cases: 1- a=1 2- a= someObject.someMethod() someObject might not have someMethod() and this would be caught by an AttributeError exception handler and 'a' will stay at 1. > Therefore, Fremy's dream can very well turn to some very complex expert system > to make "educated" warning. Being "educated" is a lot harder than to be > "brutal". And even being brutal is not that easy to achieve... > Anyway, strong typing as defined above would change the Python language in > some of its fundamental design. It would certainly be valuable to attempt the > experience, and rename the new language (mangoose would be a pretty name). Indeed. I understood that this is one of the things that could be provided by pypy. What I understood (Jacek, this is an answer for you too) is that there are many usage patterns for python. Some people use it for all of its advanced dynamic features. I use it in a java-like fashion. One could use it without the "OO crap", like a modern pascal replacement. This is a strength of python that it lends itself to so many programming paradigm. However, one drawback is that python is not optimum in many of these paradigm (although it is sometimes the best proponent). In my case, dynamic typing is not a required feature. Typing immutability and type inferring is a lot more valuable. I really hope that pypy will provide that kind of choice. Give me python with eiffel like contracts, super speed optimisation thank to type inference and I will be super happy. Thank everyone for its feedback. Any other idea of a fun python improvement project I could join without too much hassle ? I can't help but thinking that pychecker ought to be able to do a better job. regards, Philippe > > Francis Girard > FRANCE > > Le mardi 1 F?vrier 2005 16:49, Diez B. Roggisch a ?crit : > >>>But it can be useful to restrict type variety in certain situations >>>e.g. prime number calculation :) And it would probably also be useful >>>to check violations of restrictions before running the program in >>>normal mode. >> >>But that's what (oca)ml and the like do - they exactly don't force you to >>specify a type, but a variable has an also variable type, that gets >>inferned upon the usage and is then fixed. >> >>-- >>Regards, >> >>Diez B. Roggisch > > From python-list at outershell.co.uk Wed Feb 23 15:15:47 2005 From: python-list at outershell.co.uk (Phil Jackson) Date: Wed, 23 Feb 2005 20:15:47 +0000 Subject: Dealing with config files what's the options In-Reply-To: (Tom Willis's message of "Tue, 22 Feb 2005 20:38:28 -0500") References: Message-ID: <87oeebvxqk.fsf@outershell.co.uk> Tom Willis writes: > How are the expert pythoneers dealing with config files? You could use the cPickle module if you don't mind your config files being unreadable by humans. There is also the shlex module for more powerful config file needs: http://docs.python.org/lib/module-shlex.html While I'm replying to you, would you mind if I take the opportunity to ask you to stop top-posting? Thanks, Phil From beliavsky at aol.com Mon Feb 7 07:27:56 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 7 Feb 2005 04:27:56 -0800 Subject: declarations summary References: <1107750862.485179.61980@c13g2000cwb.googlegroups.com> <1grm033.wnee8f9w790oN%aleaxit@yahoo.com> Message-ID: <1107779276.262575.138240@f14g2000cwb.googlegroups.com> Alex Martelli wrote: > > socks off yet again, but I can't see counting on it. So the successor > > to Fortran (presuming it isn't C++, which I do presume) may be > > influenced by Python, but probably it won't be Python. > > You appear to assume that Fortran is dead, or dying, or is gonna die > soon. I assume Mr. Beliavski will do a great job of jumping on you for > this, so I can save the effort of doing do myself;-). Everyone needs a purpose in life :). I hope that Fortran 2003 and future versions will be the successors of traditional Fortran, but I may well be disappointed. Many scientists and engineers do not have the motivation, the time, or even the ability to master C++, generally acknowledged to be a language for professional programmers. When performance is not paramount, they can use Python (with Numarray or Numeric) and other array languages like Matlab/Octave/Scilab as reasonable alternatives to Fortran. Despite its high cost for non-students, Matlab is enormously popular among engineers. From dave at pythonapocrypha.com Wed Feb 23 12:02:58 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 23 Feb 2005 10:02:58 -0700 Subject: kill a process in XP In-Reply-To: References: Message-ID: <421CB742.2010302@pythonapocrypha.com> Tor Erik S?nvisen wrote: >>From my Python-program I spawn a new process. When using P_NOWAIT spawnl > returns the pid but in windows it returns a process handle. > Later I want to kill this process. How can I do this when I only have the > process handle? Try ctypes - if it's really a Windows handle, then this should work: from ctypes import * windll.kernel32.TerminateProcess(h, 0) # or whatever return code you want -Dave From JohannesNix|Johannes.Nix at uni-oldenburg.de Fri Feb 18 09:19:05 2005 From: JohannesNix|Johannes.Nix at uni-oldenburg.de (JohannesNix|Johannes.Nix at uni-oldenburg.de) Date: 18 Feb 2005 15:19:05 +0100 Subject: Solution for architecure dependence in Numeric ? Message-ID: <67ll9mymqu.fsf@achernar.i-did-not-set--mail-host-address--so-shoot-me> Hi, I have a tricky problem with Numeric. Some time ago, I have generated a huge and complex data structure, and stored it using the cPickle module. Now I want to evaluate it quickly again on a workstation cluster with 64-Bit Opteron CPUs - I have no more than three days to do this. Compiling Python and running Numeric has been no problem at all. However, I get an error message when accessing the data pickled before. (I can load it regularly on 32 bit computers, but it is a quite complex data object, so I really don't want to store every element as ASCII data). The problem seems to be with 64 Bit integers (with 32-bit-floats, no problem was observed). This looks like that (from the Unix command shell): jnix at 32bithost:~> python ~/python/test_npickle.py -dump test.pck jnix at 32bithost:~> python ~/python/test_npickle.py test.pck [0 1 2 3 4 5 6 7 8 9] jnix at 32bithost:~> ssh 64bithost python ~/python/test_npickle.py test.pck Traceback (most recent call last): File "/home/jnix/python/test_npickle.py", line 16, in ? a = cPickle.load(file(filename)) File "/home/jnix/lib/python2.4/SuSE-9.0/x86_64/Numeric/Numeric.py", line 520, in array_constructor x.shape = shape ValueError: ('total size of new array must be unchanged', , ((10,), 'l', '\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t\x00\x00\x00', 1)) also I get: jnix at 32bithost:~> python -c "import Numeric; print Numeric.arange(0).itemsize()" 4 jnix at 64bithost:~> python -c "import Numeric; print Numeric.arange(0).itemsize()" 8 The script used to produce the example above is: ------------------------------------------------------------------------- #/usr/bin/python # -*- coding: latin1 -*- import Numeric import cPickle import sys if len(sys.argv) > 1 and sys.argv[1] == '-dump': filename = sys.argv[2] binary=1 a = Numeric.arange(10) cPickle.dump(a, file(filename,'w',binary)) else: filename = sys.argv[1] a = cPickle.load(file(filename)) print a --------------------------------------------------------------------- So what would you suggest ? Can I hack Numeric to assume non-native 32 bit integer numbers ? Many thanks for any help, Johannes From peter at engcorp.com Mon Feb 21 12:21:16 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Feb 2005 12:21:16 -0500 Subject: Unittest - testing properties (read-only attributes) In-Reply-To: References: Message-ID: Roy Smith wrote: > You want something like > > self.assertRaises(AttributeError, lambda: self.combat.value = 1) Or, combining the two responses and avoiding the lambda: self.assertRaises(AttributeError, setattr, self.combat, 'value', 1) Hmm... this might be a case where the lambda form is actually the more readable one... -Peter From mwm at mired.org Thu Feb 10 07:47:54 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 10 Feb 2005 06:47:54 -0600 Subject: negative integer division References: <4208039c$0$28559$8fcfb975@news.wanadoo.fr> <42096EAD.879E8A5F@yahoo.com> <86wtti76cp.fsf@guru.mired.org> <420A916C.94F7F175@yahoo.com> Message-ID: <86sm447f9h.fsf@guru.mired.org> Jive Dadson writes: > Mike Meyer wrote: >> [C] isn't - it's a portable assembler. > > I've heard that many times, but it makes no sense to me. By definition, > the syntax of an assembly language closely resembles the format of > individual hardware instructions for a particular processor. Um, no. The syntax of an assembly language is totally unrelated to the format of the individual hardware instructions for a particular processor. Typically, the syntax of an assembly language is such that one obvious syntactical element (for instance, a line) generates one hardware instruction. Usually, mnemonics of some kind were used to denote which instruction to generate. However, it doesn't have to be that way. Whitesmith had a z80/8080 assembler in which you wrote "a += b" to add the contents of register b to register a. > An > assembler assembles individual hardware instructions. Back in the day, > Unix (written largely in C) and Steve Johnson's pcc (the *portable* C > compiler) together constituted a big leap forward. A big leap forward *from assembler*. The development space that C occupied at that time was the kernel and system utilities - things that were usually (though by no means always) done in assembler before the arrival of C. As a tool for producing robust, reliable code it pretty much sucks, because it has so many of the flaws that assembler has. Calling it a high level language is a disservice to the HLLs of the era. > Implementing Unix on > new processors was infinitely easier than porting OS's written in > assembly language. So I disagree on two counts: C code is not entirely > portable, (for example, division and mod may not work the same on two > different machines), and a C compiler is most certainly not an > assembler. No language is entirely portable. C is *much* more portable than the assembler languages that it displaced. Note that C has displaced assembler in other areas - for instance, it's not uncommon to find compilers that use "ANSI C" as the target machine. By using C as a portable assembler instead of generating machine code, the number of supported platforms increases dramatically. >> Now, I'll agree with you if you want to argue that some machines do >> negative integer division in stupifyingly horrible ways. > > That's why I think it was a stupifyingly horrible decision. > Understandable, but in the end an s.h.d. nonetheless. It would have > been okay to define / and % correctly, in the mathematical sense, > but also provide functions quick_div() and quick_mod() that were > guaranteed to work correctly only when both arguments were positive. > The way they did it is just too error prone, akin to early > optimization. The way they did it was exactly right for the target applications (i.e. - the v6 Unix kernel and system utilities). > It's bitten me before, when I was called on to port > code (which I did not write) from one machine to another. There is no such thing as a portable program - merely ported programs. I've been bitten by the code assuming that ints were two bytes long, and know of cases where people were bitten by code that assumed that chars were 8 bits. The simple fact of the matter is that these things - like the behavior of the low-level div and mod instructions - change from machine to machine. You have to deal with such things when you are writing what is basically assembler. If you were using a real HLL, none of these things would be a problem. > Having standard operators with > under-defined behavior is just inviting trouble: long debugging > sessions, or worse, unexplained failures in the field. Of course you > and I would avoid all the pitfalls at the start. :-) It's no worse than having standard types with loosely defined sizes. That's part of the price for working that close to the machine. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From danperl at rogers.com Thu Feb 17 09:42:42 2005 From: danperl at rogers.com (Dan Perl) Date: Thu, 17 Feb 2005 09:42:42 -0500 Subject: os.walk() References: Message-ID: "rbt" wrote in message news:cv29o3$ror$1 at solaris.cc.vt.edu... > Could someone demonstrate the correct/proper way to use os.walk() to skip > certain files and folders while walking a specified path? I've read the > module docs and googled to no avail and posted here about other os.walk > issues, but I think I need to back up to the basics or find another tool > as this isn't going anywhere fast... I've tried this: > > for root, dirs, files in os.walk(path, topdown=True): > > file_skip_list = ['file1', 'file2'] > dir_skip_list = ['dir1', 'dir2'] > > for f in files: > if f in file_skip_list > files.remove(f) > > for d in dirs: > if d in dir_skip_list: > dirs.remove(d) I think the problem here is that you are removing elements from a list while traversing it. Try to use a copy for the traversal, like this: for f in files[:]: if f in file_skip_list files.remove(f) for d in dirs[:]: if d in dir_skip_list: dirs.remove(d) > And This: > > files = [f for f in files if f not in file_skip_list] > dirs = [d for d in dirs if dir not in dir_skip_list] This is not doing what you want because it just creates new lists and it doesn't modify the existing lists that the os.walk generator is using. From ncoghlan at iinet.net.au Mon Feb 7 08:17:45 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 07 Feb 2005 23:17:45 +1000 Subject: declarations summary In-Reply-To: <1107750862.485179.61980@c13g2000cwb.googlegroups.com> References: <1107750862.485179.61980@c13g2000cwb.googlegroups.com> Message-ID: <42076A79.8090507@iinet.net.au> Michael Tobis wrote: > Also there's the question of typo-driven bugs, where an attempted > rebinding of "epsilon" instead cerated a reference called "epselon". > (The epselon bug) This is the bane of fortran, and after generations it > was generally agreed that optionally one could require all references > to be declared (implicit none). Perl went throgh a similar process and > implemented a "use strict" module. Experienced Pythonistas are oddly > resistant to even contemplating this change, though in the Fortran and > Perl worlds their usage quickly became practically universal. > > I believe that enthusiasm for this construct in other languages is so > strong that it should be prominently addressed in Python introductions > and surveys, and that questions in this regard should be expected from > newbies and patiently addressed. I also don't fully understand the > profound aversion to this idea. > > I myself am going back and forth on all this. I despise the fact that > good fortran90 code often has more declarations than executables. Ed > Ream (LEO's author) pointed out to me the Edward-Tufte-ness of Python. > No wasted ink (except maybe the colons, which I do sometimes find > myself forgetting on long edits...) I don't want Python to look like > f90. What would be the point? *If* the rebinding issue were to be addressed for bare names and the right-most name in a compound name (the only place where it is currently an issue), I imagine it would be by introducing a rebinding augmented assignment operator rather than by introducing variable declarations. Or, more precisely, standard name binding would continue to serve in that role. For Alex: I figured out something resembling a justification for the difference in semantics between a rebinding operator and the rest of the augmented assignment operators: there's no magic method for binding a name, so there is no need for a magic method when simply rebinding one, whereas the other augmented assignment operators combine the name-binding with an operation which normally *can* be overridden, and the augmented assignment magic method is a convenience to allow the rebinding case of that operation to be optimised. Cheers, Nick. Do I really want to add another PEP to the snoozing PEP 338, though? -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From cam.ac.uk at mh391.invalid Fri Feb 11 18:48:30 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 11 Feb 2005 23:48:30 +0000 Subject: pre-check for string-to-number conversion In-Reply-To: <1108163692.700703.183870@o13g2000cwo.googlegroups.com> References: <1108163692.700703.183870@o13g2000cwo.googlegroups.com> Message-ID: 18k11tm001 at sneakemail.com wrote: > I know that I can us exceptions, but they > don't seem like the cleanest and simplest solution to me. Stop worrying and learn to love exceptions. :) -- Michael Hoffman From carribeiro at gmail.com Sat Feb 5 16:35:55 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 5 Feb 2005 19:35:55 -0200 Subject: empty classes as c structs? In-Reply-To: <42053394.6020203@po-box.mcgill.ca> References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <42053394.6020203@po-box.mcgill.ca> Message-ID: <864d37090502051335f71127c@mail.gmail.com> On Sat, 05 Feb 2005 15:59:00 -0500, Brian van den Broek wrote: > (I'm just a hobbyist, so if this suggestion clashes with some well > established use of 'Bag' in CS terminology, well, never mind.) There's already a well know know use for the 'bag' name, including a recipe in Python. A bag is an arbitrary collection of objects. It's similar to a set. The cookbook code is at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259174 -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From duncan.booth at invalid.invalid Fri Feb 18 09:50:04 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Feb 2005 14:50:04 GMT Subject: difference between class methods and instance methods References: <1119g2rre5g610c@corp.supernews.com> <37juh3F5d511mU1@individual.net> <37m8n9F5dkf4kU1@individual.net> Message-ID: Diez B. Roggisch wrote: >> This is badly wrong. John was correct. >> >> Bound methods get created whenever you reference a method of an >> instance. If you are calling the method then the bound method is >> destroyed as soon as the call returns. You can have as many different >> bound methods created from the same unbound method and the same >> instance as you want: > > That did escape me so far - interesting. Why is it that way? I'd > expect that creating a bound method from the class and then storing it > in the objects dictionary is what happens. > If you had a class with 50,000 methods it could take quite a while to create instances, consider Zope as an example where every object acquires large numbers of methods most of which are completely irrelevant. Even outside Zope most objects never have all their methods called: dict, for example, has 38 methods but most of them get little or no use. Creating a bound method is a comparatively cheap operation, its a small object which just has to hold references to the instance and the function. The memory allocation is fast, because Python keeps lists of appropriately sized buckets for small objects. From alan.gauld at btinternet.com Sun Feb 27 04:19:40 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Feb 2005 09:19:40 +0000 (UTC) Subject: lambda strangeness?? References: Message-ID: <544321d0cjhv9925dkopsumiqg7m52em0i@4ax.com> On Sun, 27 Feb 2005 09:07:28 +0000 (UTC), Alan Gauld wrote: > >>> adds = [lambda y: (y + n) for n in range(10)] > >>> adds[0](0) > 9 > >>> for n in range(5): print adds[n](42) > ... > 42 > 43 > the for loop... It seems to somehow be related to the > last value in the range(), am I somehow picking that up as y? Further exploration suggests I'm picking it up as n not y, if that indeed is what's happening... Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From pekka.niiranen at wlanmail.com Thu Feb 10 11:58:50 2005 From: pekka.niiranen at wlanmail.com (pekka niiranen) Date: Thu, 10 Feb 2005 16:58:50 GMT Subject: Is this a bug? BOM decoded with UTF8 Message-ID: Hi there, I have two files "my.utf8" and "my.utf16" which both contain BOM and two "a" characters. Contents of "my.utf8" in HEX: EFBBBF6161 Contents of "my.utf16" in HEX: FEFF6161 For some reason Python2.4 decodes the BOM for UTF8 but not for UTF16. See below: >>> fh = codecs.open("my.uft8", "rb", "utf8") >>> fh.readlines() [u'\ufeffaa'] # BOM is decoded, why >>> fh.close() >>> fh = codecs.open("my.utf16", "rb", "utf16") >>> fh.readlines() [u'\u6161'] # No BOM here >>> fh.close() Is there a trick to read UTF8 encoded file with BOM not decoded? -pekka- From dbickett at gmail.com Thu Feb 3 17:33:53 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Thu, 3 Feb 2005 17:33:53 -0500 Subject: Where are list methods documented? In-Reply-To: References: Message-ID: <1d6cdae3050203143366404788@mail.gmail.com> Simply as a general reply to the OP, I've found that some of the most definitive documentation can be found using help() at the command line: Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> help(list) Help on class list in module __builtin__: [big snip] It goes into good detail about all of the methods, etcetera. -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From jepler at unpythonic.net Mon Feb 14 19:38:10 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 14 Feb 2005 18:38:10 -0600 Subject: How can I tell if my host supports Python? In-Reply-To: References: Message-ID: <20050215003810.GD6339@unpythonic.net> If you have a shell, it's as simple as typing "python" and seeing if the interactive interpreter appears: $ python Python 2.3.3 (#1, May 7 2004, 10:31:40) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> If you've done this, you can find out the path to this Python interpreter: >>> import sys; print sys.executable /usr/bin/python Otherwise, the documentation for the 'cgi' module has a buried suggestion with the simplest Python CGI program. http://docs.python.org/lib/node462.html that program would look something like #!/usr/bin/python import cgi; cgi.test() though you must know the correct path to the Python interpreter for this to work. Your best bet may be to ask your webhost for help---only they know how they've (mis)configured your system. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve at holdenweb.com Thu Feb 3 08:06:19 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Feb 2005 08:06:19 -0500 Subject: global variables In-Reply-To: <1107392092.290042.221600@c13g2000cwb.googlegroups.com> References: <1107385488.822768.317250@l41g2000cwc.googlegroups.com> <1107388493.465599.140480@g14g2000cwa.googlegroups.com> <3YSdnYVEmOCW8pzfRVn-sg@comcast.com> <1107391350.933650.321440@z14g2000cwz.googlegroups.com> <1107392092.290042.221600@c13g2000cwb.googlegroups.com> Message-ID: M.E.Farmer wrote: > Ok it has been a long day, > In my reply to Steven Bethard , Steve should read Steven ;) > > M.E.Farmer > Well, since he signs himself "Steve" too I guess we'll just have to put up with the ambiguities. Or perhaps, given my (lack of) typing skill, I should just start signing myself "Stvev"? regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From jeff at ccvcorp.com Wed Feb 16 12:48:11 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 16 Feb 2005 09:48:11 -0800 Subject: super not working in __del__ ? In-Reply-To: References: Message-ID: <11171oljbbb5cd3@corp.supernews.com> Christopher J. Bottaro wrote: > 2 Questions... > 1) Why does this never happen in C++? Or does it, its just never happened > to me? > 2) I can understand random destruction of instantiated objects, but I find > it weird that class definitions (sorry, bad terminology) are destroyed at > the same time. So __del__ can't safely instantiate any classes if its > being called as a result of interpreter shutdown? Boo... Keep in mind that in Python, everything is a (dynamically created) object, including class objects. My recall of C/C++ memory organization is pretty weak, but IIRC it gives completely different behavior to code, stack objects, and heap objects. Code never needs to be cleaned up. In Python, everything (including functions and classes) is effectively a heap object, and thus functions and classes can (and indeed must) be cleaned up. Refcounting means that they won't ever (normally) be cleaned up while they're still in use, but during program shutdown refcounting necessarily ceases to apply. The closest that would happen in C++, I believe, would manifest itself as memory leaks and/or access of already-freed memory. Jeff Shannon Technician/Programmer Credit International From irmen.NOSPAM at xs4all.nl Mon Feb 14 19:00:09 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 15 Feb 2005 01:00:09 +0100 Subject: is there a safe marshaler? In-Reply-To: <7x3bvyiuin.fsf@ruckus.brouhaha.com> References: <420b6936$0$28982$e4fe514c@news.xs4all.nl> <1108051828.483222.62670@z14g2000cwz.googlegroups.com> <7xmzu6q4cv.fsf@ruckus.brouhaha.com> <4211185b$0$28982$e4fe514c@news.xs4all.nl> <7xbramzt1c.fsf@ruckus.brouhaha.com> <42112b1e$0$28978$e4fe514c@news.xs4all.nl> <7xacq6sqej.fsf@ruckus.brouhaha.com> <421130ae$0$28984$e4fe514c@news.xs4all.nl> <7x3bvyiuin.fsf@ruckus.brouhaha.com> Message-ID: <42113b3b$0$28991$e4fe514c@news.xs4all.nl> Paul Rubin wrote: > Yes, that's what I meant, using hmac to authenticate using a shared secret, > sending the rest in the clear. Note you should also put sequence numbers > in the messages, to stop the attacker from fooling you by selectively > deleting or replaying messages. Thanks for the tip. I'll think about this. >>You should not want to expose a Pyro service to the internet because >>Python doesn't have Java's security model and sandboxing, that are >>used with RMI. Pyro has a few features that are very powerful >>but also require the use of intrinsic insecure Python code (namely, >>pickle, and marshal). > > > Can you say some more about this? Does RMI really rely on sandboxes, > if you don't send code around, but just expose operations on server > side objects? Well, my experience with RMI is very limited (and from a few years ago) but I remember that you are required to set a security manager on your RMI objects. I always used Java's default rmi security manager but I honestly don't know what it actually does :-D Other than that, it would be interesting to know if the RMP or IIOP protocols have any problems with malicious packets? I don't know them well enough to say anything about this. > I don't think marshal is inherently insecure, since the unmarshaller > doesn't itself execute any marshalled code. It apparently has some > bugs that can confuse it if you send it a malformed marshalled string, > but those can be fixed. Pickle is inherently insecure because of how > it calls class constructors. Yep, that's what I now know too from the other replies in this thread. >>Just look at the recent security advisory about the XMLRPC server >>that comes with Python.... it's much more primitive than Pyro is, >>but even that one was insecure. > > > I haven't looked at that bug carefully yet but yes, anything exposed > to the internet has to be done very carefully, and XMLRPC missed something. What I know of it is that you had the possibility to arbitrarily follow attribute paths, including attributes that should rather be kept hidden. >>I wouldn't put a Java RMI server or xyz CORBA server or whatever >>kind of unrestricted API open on the internet anyway. >>Am I rational or paranoid? > > > I haven't used Java enough to advise you on this, but I thought they > were supposed to be ok to expose to the internet. Certainly the whole > idea of .NET is to let you securely provide RPC services (excuse me > for a moment while I try to stop laughing for mentioning security and > Microsoft in the same sentence). And lots of people use things like > SOAP for that. I label things like SOAP and XML-RPC much different than RMI or Pyro, because they (SOAP) are much more "distant" from the actual programming language and environment beneath them. I don't know if this is good thinking or not but the fact that RMI and Pyro expose language features directly, and SOAP not, makes that I reason about them differently. Then again, Pyro allows you to use two forms of XML serialization on the wire (instead of pickle), which may or may not move it much closer to SOAP and the likes. But there are other reasons for not wanting a Pyro server exposed on the internet. Such as the lack of a good security analisys of Pyro. Perhaps it suffers from similar holes as XMLRPC until recently... Furthermore there are practical issues such as having to open a buch of new ports in your firewall. In my experience this is very hard to get done, sadly, in contrast to just exposing a "web-service" (in whatever form) on port 80 HTTP. --Irmen From noreply at python.org Wed Feb 2 22:03:02 2005 From: noreply at python.org (Post Office) Date: Thu, 3 Feb 2005 08:03:02 +0500 Subject: Delivery failed Message-ID: <20050203031528.CEA481E4003@bag.python.org> The original message was received at Thu, 3 Feb 2005 08:03:02 +0500 from [182.255.28.192] ----- The following addresses had permanent fatal errors ----- python-list at python.org ----- Transcript of session follows ----- ... while talking to 72.27.31.20: 550 5.1.2 ... Host unknown (Name server: host not found) From dscottr at bellatlantic.net Wed Feb 9 16:18:19 2005 From: dscottr at bellatlantic.net (Scott Robinson) Date: Wed, 09 Feb 2005 21:18:19 GMT Subject: Big development in the GUI realm References: Message-ID: On Mon, 07 Feb 2005 20:56:44 -0800, Courageous wrote: > >>OK, so according to Linus, the GPL allows .... > >No. Pay attention. Linus has his own revised version, to clarify >this point, and in fact /overruling/ the GPL if the point is >clarified differently by RMS or others. > >That's the right of their community, it's /their/ code. > >>make calls to the kernel, but TrollTech says the GPL doesn't allow a >>proprietary program to make calls to the Qt library. > >That's their prerogative, although TrollTech's authority as an >/interpretational/ entity over the GPL means precisely zero. I >wouldn't push this, though, unless you've got a big litigation >budget. It should also be pointed out that the FSF's interpretation of the GPL with respect to Qt means absolutely zero. If TrollTech publishes an interpretation of the GPL and announces it to any interested in licensing their software, I suspect that the courts will take that into consideration. This won't help that at all if it isn't a legally valid interpretation, but it establishes that you *knew* what their interpretation was when you agreed to the terms to distribute their copyrighted software. > >>It's this double-standard that I find confusing, since both projects >>are said to be based on the same license. > >Linus doesn't use "the" GPL, he uses "his" GPL, version-whatever. > >Anyway, your safe bet: > >Follow the copyright holder's wishes. > >That's fair. After all, it's free, so they're doing you a damn >big favor. > >C// Scott Robinson From skip at pobox.com Thu Feb 10 21:30:34 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 10 Feb 2005 20:30:34 -0600 Subject: Install MySQLdb on Mac OS X (10.3) In-Reply-To: <420bf2f4$0$16553$9b622d9e@news.freenet.de> References: <420bf2f4$0$16553$9b622d9e@news.freenet.de> Message-ID: <16908.6346.779997.277792@montanaro.dyndns.org> TK> I can't install MySQLdb on Mac OS X (Ver. 10.3) properly. Here's my TK> environment: TK> 1. MySQL-python-1.0.0 ... Try a more recent version of mysql-python. I think 1.1.7 is the latest. Skip From michele.simionato at gmail.com Sun Feb 20 04:37:40 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 20 Feb 2005 01:37:40 -0800 Subject: recommended way of generating HTML from Python In-Reply-To: References: <1108889625.068929.88890@z14g2000cwz.googlegroups.com> Message-ID: <1108892260.013164.9000@l41g2000cwc.googlegroups.com> Just to clarify, before people start pointing out their preferred templating language: I am NOT asking for a template system. I am asking for something on the lines of HTMLGen, where you just use pure Python. From jan.dries at dcube-resource.be Sun Feb 20 11:42:37 2005 From: jan.dries at dcube-resource.be (Jan Dries) Date: Sun, 20 Feb 2005 17:42:37 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <42172136$0$27576$9b622d9e@news.freenet.de> <42185b05$0$15460$9b622d9e@news.freenet.de> <42189527$0$6260$9b622d9e@news.freenet.de> Message-ID: <4218BDFD.7070205@dcube-resource.be> Ilias Lazaridis wrote: > > they above 2 questions are coherent, thus answering isolated [as you've > done] makes not much sense. > > " > >> Should I take answers serious? > >> Answer from people which do not respect coherence of writings? > " Except that the quote here above is NOT what was in your original posting. Here is the *real* quote (also note that Python uses """ instead of " for delimiting a multi-line string: """ Should I take answers serious? Answer from people which do not respect coherence of writings? """ If you insert a blank line between two sentences most people in this newsgroup (and in the western world in general) will interprete that as the start of a new paragraph, as an indication that what follows is something different than what precedes the blank line. If you want to obtain "coherence of writing" between two sentences, then maybe you shouldn't type them as different paragraphs. If you would have written: """ Should I take answers serious? Answer from people which do not respect coherence of writings? """ it would have been much more coherent. Regards, Jan From steven.bethard at gmail.com Sun Feb 20 15:04:00 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 20 Feb 2005 13:04:00 -0700 Subject: help please In-Reply-To: <1108921146.274248.11500@g14g2000cwa.googlegroups.com> References: <1108254434.871062.314510@g14g2000cwa.googlegroups.com> <1108260752.791847.180060@l41g2000cwc.googlegroups.com> <1108324679.451793.147890@z14g2000cwz.googlegroups.com> <1108329540.239064.144920@f14g2000cwb.googlegroups.com> <1108334012.336816.221460@g14g2000cwa.googlegroups.com> <1108921146.274248.11500@g14g2000cwa.googlegroups.com> Message-ID: gargonx wrote: > I think there's a problem with the code: > > py> decode_replacements.update([(std[key], key) for key in std]) > py> decode_replacements.update([(ext[key], key) for key in ext]) > > when i run this i get an error: > AttributeError: keys > > I can't get that figured out Can you show the part of your code in which you do this? As you can see from the interactive Python session I posted, I didn't get an AttributeError... STeVe From miki.tebeka at zoran.com Mon Feb 14 02:19:56 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 14 Feb 2005 09:19:56 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: <20050214071934.GK1580@zoran.com> Hello Ilias, > d) Is it really neccessary that I dive into such adventures, to be able > to do the most natural thing like: "developing python extensions with > MinGW"? Writing a setup.py and running python setup.py build_ext --compiler=mingw32 works for me *without* any more work. Things can't get much simpler. Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From gazzar at nospam_email.com Sat Feb 26 07:31:20 2005 From: gazzar at nospam_email.com (Gary Ruben) Date: Sat, 26 Feb 2005 12:31:20 GMT Subject: class factory example needed (long) Message-ID: I have a class factory problem. You could say that my main problem is that I don't understand class factories. My specific problem: I have a class with several methods I've defined. To this class I want to add a number of other class methods where the method names are taken from a list. For each list member, I want to build a method having the list member name so that I can override another method of the same name for objects which are instances of this class. Finally, I want my class factory which creates the method to call the overridden method. I'm sure my description is confusing, so I'll try to illustrate it. import Numeric # The Numeric module contains a whole lot of methods which operate on certain number types class foo: """ this is a number type class """ def __init__(self, value): self.value = float(value) def __str__(self): . . other methods here . import string ufuncs = string.split(""" sqrt arccos arccosh arcsin arcsinh arctan arctanh cos cosh tan tanh log10 sin sinh sqrt absolute fabs floor ceil fmod exp log conjugate """) # these are the methods from Numeric that I want to override/wrap for my number type for u in ufuncs: I need something here which builds methods called sqrt(), arccos(), etc. An illustrative example of the class methods I want to build with some sort of class factory is def sqrt(self): val = Numeric.sqrt(self.value) return foo(Numeric.sqrt(self.value) + 42) def arccos(self): val = Numeric.arccos(self.value) return foo(Numeric.arccos(self.value) + 42) if __name__ == "__main__": a = 9 b = foo(7) print Numeric.sqrt(a) print Numeric.sqrt(b) This would print 3 7 Note that the methods I want to create under program control are all identical in form. In this example they all call the wrapped method with an argument 42 greater than the value of the number. Does anyone have an example where they've done something similar or could help me out with an example? thanks in anticipation, Gary From lbates at syscononline.com Thu Feb 3 16:14:30 2005 From: lbates at syscononline.com (Larry Bates) Date: Thu, 03 Feb 2005 15:14:30 -0600 Subject: remove duplicates from list *preserving order* In-Reply-To: References: Message-ID: <_d-dnbaNjc6uCZ_fRVn-oQ@comcast.com> Take a look at this recipe on ASPN: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297 I think it might help. Larry Bates Steven Bethard wrote: > I'm sorry, I assume this has been discussed somewhere already, but I > found only a few hits in Google Groups... If you know where there's a > good summary, please feel free to direct me there. > > > I have a list[1] of objects from which I need to remove duplicates. I > have to maintain the list order though, so solutions like set(lst), etc. > will not work for me. What are my options? So far, I can see: > > def filterdups(iterable): > result = [] > for item in iterable: > if item not in result: > result.append(item) > return result > > def filterdups(iterable): > result = [] > seen = set() > for item in iterable: > if item not in seen: > result.append(item) > seen.add(item) > return result > > def filterdups(iterable): > seen = set() > for item in iterable: > if item not in seen: > seen.add(item) > yield item > > Does anyone have a better[2] solution? > > STeve > > [1] Well, actually it's an iterable of objects, but I can convert it to > a list if that's helpful. > > [2] Yes I know, "better" is ambiguous. If it helps any, for my > particular situation, speed is probably more important than memory, so > I'm leaning towards the second or third implementation. From thomastnewman at yahoo.com Sat Feb 19 08:36:36 2005 From: thomastnewman at yahoo.com (Thomas Newman) Date: Sat, 19 Feb 2005 14:36:36 +0100 Subject: error in non-existing code? In-Reply-To: References: Message-ID: <421740E4.5030005@yahoo.com> Michael Hoffman wrote: > Thomas Newman wrote: > >> I wanted to look at the code that gives me the error, but there is no >> line 447 in /usr/lib/python2.3/pyclbr.py: > > > Try deleting pyclbr.py[co]. No change there. ttn From peter at engcorp.com Thu Feb 10 14:41:36 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Feb 2005 14:41:36 -0500 Subject: [N00B] What's %? In-Reply-To: <420b9dc1$0$29504$a1866201@visi.com> References: <614c778e.0502100938.6665cb52@posting.google.com> <420b9dc1$0$29504$a1866201@visi.com> Message-ID: Grant Edwards wrote: > It's the modulus operator. It returns the remainder of integer > division. As we used to say in second grade: > > 4 goes into 107 26 times with 3 left over. > > 3 goes into 4 2 times with 1 left over. How long were you stuck in second grade, Grant? -Peter P.S. You're correct, for large values of four.... ;-) From ilias at lazaridis.com Tue Feb 15 16:16:45 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Tue, 15 Feb 2005 23:16:45 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: Tim Peters wrote: [...] - (thorough comments) Thank you very much for your thoroug comments. . -- http://lazaridis.com From cmkleffner at gmx.de Fri Feb 11 09:34:07 2005 From: cmkleffner at gmx.de (cmkl) Date: 11 Feb 2005 06:34:07 -0800 Subject: is there a safe marshaler? References: <420b6936$0$28982$e4fe514c@news.xs4all.nl> <420b6e98$0$23018$626a14ce@news.free.fr> <420b9135$0$28982$e4fe514c@news.xs4all.nl> Message-ID: <3b091a1c.0502110634.5edb1987@posting.google.com> Irmen de Jong wrote in message news:<420b9135$0$28982$e4fe514c at news.xs4all.nl>... > Pierre Barbier de Reuille wrote: > > Irmen de Jong a ?crit : > > > >> Pickle and marshal are not safe. They can do harmful > >> things if fed maliciously constructed data. > >> That is a pity, because marshal is fast. > >> I need a fast and safe (secure) marshaler. > >> Is xdrlib the only option? > >> I would expect that it is fast and safe because > >> it (the xdr spec) has been around for so long. > >> > >> Or are there better options (perhaps 3rd party libraries)? > >> > >> Thanks > >> > >> Irmen. > > > > > > What exactly do you mean by "safe" ? Do you want to ensure your objects > > cannot receive corrupted data ? Do you want to ensure no code will be > > evaluated during the unmarshalling ? > > "safe (secure)" > But to be more precise, let's look at the security warning that > is in the marshal documentation: > "The marshal module is not intended to be secure against erroneous or > maliciously constructed data. Never unmarshal data received from an > untrusted or unauthenticated source." > > So essentially I want the opposite of that ;-) > > I want a marshalar that is okay to use where the data it processes > comes from unknown, external sources (untrusted). It should not crash > on corrupt data and it should not execute arbitrary code when > unmarshaling, so that it is safe against hacking attempts. > > Oh, preferrably, it should be fast :) > Some XML-ish thing may be secure but is likely to be not fast at all. > > Ideally it should be able to transfer user defined Python types, > but if it is like marshal (can only marshal builtin types) that's > okay too. > > --Irmen I'm just curious, but can't effbot's fast cElementree be used for PYROs XML_PICKLE and would it be safe and fast enough? Carl From jack at performancedrivers.com Mon Feb 28 14:05:04 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 28 Feb 2005 14:05:04 -0500 Subject: naming convention for scalars, lists, dictionaries ... In-Reply-To: <3YydnR3xNd4k_r7fRVn-3g@comcast.com> References: <1109613115.760962.292360@z14g2000cwz.googlegroups.com> <3YydnR3xNd4k_r7fRVn-3g@comcast.com> Message-ID: <20050228190504.GV9263@performancedrivers.com> On Mon, Feb 28, 2005 at 11:32:22AM -0700, Steven Bethard wrote: > beliavsky at aol.com wrote: > >Since Python does not have declarations, I wonder if people think it is > >good to name function arguments according to the type of data structure > >expected, with names like "xlist" or "xdict". > > In general, I find that naming collections for their contents is much > more useful than some abbreviated type prefix. However, while I don't > name objects by their type, I do tend to name iterables with plurals > (e.g. "words", "feature_indices", "events", etc.) and I typically suffix > mapping types with "map" (e.g. "word_index_map", "event_relation_map", > "prime_factor_map", etc.) > Ditto for me, plural implies list and singular implies instance, for (contact) in contacts: # do something with contact But I tend to name dictionaries as "key_to_value" as in "email_to_contact" or "ip_to_hostname." for (email) in emails: contact = email_to_contact[email] # do something with contact It may seem verbose but I can type much faster than I can think and it makes reading even forgotten code a breeze. -Jack From mwm at mired.org Tue Feb 15 12:48:27 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 15 Feb 2005 11:48:27 -0600 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: <37bkemF5a7s7vU1@individual.net> Message-ID: <86ll9piuj8.fsf@guru.mired.org> Ilias Lazaridis writes: > MinGW compatibility is not my need. Then why do you waste so much effort whining about it not being given to you? > It is an community need. Based on the evidence at hand, this is a false statement. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From williams13 at llnl.gov Tue Feb 1 05:31:03 2005 From: williams13 at llnl.gov (Dean N. Williams) Date: Tue, 01 Feb 2005 02:31:03 -0800 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 Message-ID: <41FF5A67.3090606@llnl.gov> Dear Python Community, I am trying to build Python with Tcl/Tk under the Cygwin_NT-5.1 OS. Has anyone done this? Do I need to build tcl8.4.9 and tk8.4.9 under the unix directory or the win directory. I found that the Tcl/Tk unix directories compiled just fine and built the libtcl8.4.a and libtk8.4.a libraries for use. But I don't think that Python is looking for this. If you've built Python with Tcl/Tck, is it possible for you to send me instructions on how you did it? Thanks in advance... Best regards, Dean From newsgroups at jhrothjr.com Fri Feb 25 13:14:44 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 25 Feb 2005 12:14:44 -0600 Subject: Unit testing - one test class/method, or test class/class References: <87y8ddywr9.fsf@titan.staselog.com> Message-ID: <111uqqgag7eb253@news.supernews.com> I tend to write one test class per class, but that's just the way I got started. My feeling is that the methods in a test class should tell a story if you read the names in the order they were written, so I'd split the tests for a class into several classes if they had different stories to tell. John Roth "Edvard Majakari" wrote in message news:87y8ddywr9.fsf at titan.staselog.com... > > Hi, > > I just found py.test[1] and converted a large unit test module to py.test > format (which is actually almost-no-format-at-all, but I won't get there > now). Having 348 test cases in the module and huge test classes, I started > to think about splitting classes. Basically you have at least three > obvious > choises, if you are going for consistency in your test modules: > > Choise a: > > Create a single test class for the whole module to be tested, whether it > contains multiple classes or not. > > ...I dont think this method deserves closer inspection. It's probably > rather > poor method to begin with. With py.test where no subclassing is required > (like in Python unittest, where you have to subclass unittest.TestCase) > you'd probably be better off with just writing a test method for each > class > and each class method in the module. > > Choise b: > > Create a test class for each class in the module, plus one class for any > non-class methods defined in the module. > > + Feels clean, because each test class is mapped to one class in the > module > + It is rather easy to find all tests for given class > + Relatively easy to create class skeleton automatically from test module > and the other way round > > - Test classes get huge easily > - Missing test methods are not very easy to find[2] > - A test method may depend on other tests in the same class > > Choise c: > > Create a test class for each non-class method and class method in the > tested > module. > > + Test classes are small, easy to find all tests for given method > + Helps in test isolation - having separate test class for single method > makes tested class less dependent of any other methods/classes > + Relatively easy to create test module from existing class (but then you > are not doing TDD!) but not vice versa > > - Large number of classes results in more overhead; more typing, probably > requires subclassing because of common test class setup methods etc. > > What do you think, any important points I'm missing? > > Footnotes: > [1] In reality, this is a secret plot to advertise py.test, see > http://codespeak.net/py/current/doc/test.html > > [2] However, this problem disappears if you start with writing your tests > first: with TDD, you don't have untested methods, because you start by > writing the tests first, and end up with a module that passes the tests > > > -- > # Edvard Majakari Software Engineer > # PGP PUBLIC KEY available Soli Deo Gloria! > One day, when he was naughty, Mr Bunnsy looked over the hedge into Farmer > Fred's field and it was full of fresh green lettuces. Mr Bunnsy, however, > was > not full of lettuces. This did not seem fair. --Mr Bunnsy has an > adventure From michele.simionato at gmail.com Wed Feb 16 23:32:42 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 16 Feb 2005 20:32:42 -0800 Subject: low-end persistence strategies? In-Reply-To: <7xd5v02l21.fsf@ruckus.brouhaha.com> References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <1108570047.677348.146850@f14g2000cwb.googlegroups.com> <7x7jl8bhii.fsf@ruckus.brouhaha.com> <1108572988.341139.126020@z14g2000cwz.googlegroups.com> <7xd5v02l21.fsf@ruckus.brouhaha.com> Message-ID: <1108614762.026703.323850@l41g2000cwc.googlegroups.com> Paul Rubin: > Oh yow, it looks pretty complicated. Do you have any example code > around that uses the transaction stuff? If not I can try to figure it > out, but it looks like it would take significant effort. This was my impression too :-( The ZODB is way much easier to use so at the end I used just that. Apparently the bsddb stuff is more complicated than needed and the documentation sucks. However, it does satisfy your requirements of being already installed, so I mentioned it. I am looking too for an easy tutorial on how to do concurrency/transactions with it. Michele Simionato From nav+posts at bandersnatch.org Tue Feb 1 14:23:28 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: Tue, 01 Feb 2005 14:23:28 -0500 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> Message-ID: <87u0owaxu7.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> aahz at pythoncraft.com (Aahz) writes: > It's kind of like having a guy who juggles chainsaws wearing body armor > arguing with a guy who juggles rubber chickens wearing a T-shirt about who's > in more danger." --Roy Smith, c.l.py, 2004.05.23 If it's Nethack, the guy in the T-shirt is in more danger. A _lot_ more danger. Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From gmane-schpam at joefrancia.com Tue Feb 15 14:33:52 2005 From: gmane-schpam at joefrancia.com (Joe Francia) Date: Tue, 15 Feb 2005 14:33:52 -0500 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <37bkemF5a7s7vU1@individual.net> <86ll9piuj8.fsf@guru.mired.org> Message-ID: Ilias Lazaridis wrote: > Mike Meyer wrote: > >> Ilias Lazaridis writes: >> >>> MinGW compatibility is not my need. >> >> >> Then why do you waste so much effort whining about it not being given >> to you? >> >>> It is an community need. >> >> >> Based on the evidence at hand, this is a false statement. >> >> > > MinGW compatibility is not [only] my need. > > It is an community need [at least partially] > You keep using that word "community". I do not think it means what you think it means. -- Soraia: http://www.soraia.com From oliver.magno at digitaleyecandy.biz Fri Feb 25 23:46:20 2005 From: oliver.magno at digitaleyecandy.biz (oliverm) Date: Sat, 26 Feb 2005 12:46:20 +0800 Subject: Mask Array Message-ID: <421FFF1C.1010106@digitaleyecandy.biz> hi all, i have read a tutorial about "gemath" and it has a dependency called MA (Mask Array), the problem is i cannot find any link where to download this thing, anyone knows where i could get Mask Array? thanks. -- _____________________________________________________________________ "/No man rises so high as he knows not/ /whither he goes."/ -Oliver Cromwell- http://aps3angel.50megs.com/index.html _____________________________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: oliver.magno.vcf Type: text/x-vcard Size: 169 bytes Desc: not available URL: -------------- next part -------------- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.300 / Virus Database: 266.5.0 - Release Date: 2/25/2005 From fredrik at pythonware.com Mon Feb 7 14:00:46 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 7 Feb 2005 20:00:46 +0100 Subject: Python Binary and Windows References: Message-ID: "peetm" wrote: > I'd like to compile (?) the DiffLib Python code into a binary form that can > be called by other Windows apps - like, I'd like to compile it into a DLL. > > Is this possible? you can link your DLL (or application) against the Python DLL, and use the Python API to pass data from C/C++ to Python, and back again. for details, see the "embedding" sections in http://docs.python.org/api/api.html From steve at holdenweb.com Tue Feb 8 07:12:39 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 08 Feb 2005 07:12:39 -0500 Subject: def __init__ question in a class definition In-Reply-To: <1107828542.466555.27160@o13g2000cwo.googlegroups.com> References: <1107754489.980148.277690@c13g2000cwb.googlegroups.com> <42076939.6020405@holdenweb.com> <1107828542.466555.27160@o13g2000cwo.googlegroups.com> Message-ID: <4208ACB7.3020605@holdenweb.com> M.E.Farmer wrote: > Steve Holden wrote: > >>M.E.Farmer wrote: >> >> >>>>Jeffrey Borkent >>>>Systems Specialist >>>>Information Technology Services >>> >>> >>>With that kind of credentials, and the fact that you claim you are > > a > >>>system specialists.... >>>I don't know you have me worried already. >>>I guess for you I just say RTFM. >>>If you think that is harsh then don't ask a 2nd grade question yet >>>claim/pretend to be some sorta system specialists. >> >>Hey, ease up, this is comp.lang.python, remember. >> >> >>>You tried searching the archives first I am sure. >>>Go here http://www.python.org and *read*, come back when you are >>>really stuck. >>>M.E.Farmer >>>P.S. YES the __ matter, they identify special methods ! __init__ is > > the > >>>class CONSTRUCTOR. >>> >> >>Next time, could we try exchanging the body of the message and the > > PS? > >>That way you could have omitted the PS when you got half way through > > it > >>and realised you were just wasting your time and everyone else's ... >> >>got-out-the-wrong-side-of-bed-ly y'rs - steve >>-- >>Meet the Python developers and your c.l.py favorites March 23-25 >>Come to PyCon DC 2005 http://www.pycon.org/ >>Steve Holden http://www.holdenwewb.com > > P.S. And in an effort to keep on topic...PYCON!! > steve, > I stand by what I said. > Teach a man to fish feed him for a lifetime. > Re-read it, memorize it, and keep it near. > I read comp.lang.py for 3 years before I posted anything, and then i > posted an ANSWER! > I don't go around asking dirt simple questions that would be solved > with a quick read of the docs, usenet archives , Google, books that > have been written about Python,etc.... He should have been *reading* > not *posting*. > I can not understand why you have a problem with me pointing out he > should read the documentation. Why do you think RTFM exist, for people > like that, they are a timesink. He can redeem himself if he just goes > and reads a little and comes back looking like he made some effort. > This guy has a 6 mile sig that says he ought to know better. Had he > come with a different sig *maybe* and a question that did not scream > '''HEY I WANT YOU TO ANSWER EVERYTHING FOR ME BECAUSE I CAN NOT EVEN > READ THE BASIC DOCUMENTATION ON MY OWN'''. > > >>Next time, could we try exchanging the body of the message and the > > PS? > >>That way you could have omitted the PS when you got half way through > > it > >>and realised you were just wasting your time and everyone else's ... > > > I tell him where he is wrong first then I answer the question, sounds > like *YOU* ....Now I have your attention. > What do you think that post was meant to do? Snap him off at the root? > Make him cry? Maybe it was to nudge him to read the docs, so he can > *learn* on his own. > Next time you could just write my post for me! That way I can only > waste as much time as you deem acceptable! Now that I think about it, > if we just answer every question every poster has about any detail of > Python, then we can all sing along and hold hands, who needs to write > documentation or even books about Python look at all the time we will > save... > > >>got-out-the-wrong-side-of-bed-ly y'rs - steve > > Which-side is-the wrong-side-ly yr's - M.E.Farmer > Well, actually my point was that if we just save time by not answering such questions we avoid a reputation for hostility while still encouraging people to use other resources. But anyway, thanks for saying "PyCon"! regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From jstroud at mbi.ucla.edu Sun Feb 27 17:48:14 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 27 Feb 2005 14:48:14 -0800 Subject: TKinter In-Reply-To: <38eb4lF5nldh7U1@individual.net> References: <38eb4lF5nldh7U1@individual.net> Message-ID: <200502271448.15168.jstroud@mbi.ucla.edu> I thought the T was silent. On Sunday 27 February 2005 08:34 am, anthonyberet wrote: > So, is it pronounced 'Tee-Kinter', or 'Tee-Kay-Inter'? > I don't want to appear as a dork down the pub. From antonyliu2002 at yahoo.com Fri Feb 25 23:47:41 2005 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Fri, 25 Feb 2005 20:47:41 -0800 (PST) Subject: Which module is "set " in? Message-ID: <20050226044741.41746.qmail@web54509.mail.yahoo.com> I want to use the set function like mylist = ['a', 'b', 'b', 'd', 'e', 'a'] myset = set (mylist) But I don't know what to import, I tried sys, sets, they don't work. What's the easy way to find out the module that contains a particular function? __________________________________ Do you Yahoo!? Yahoo! Mail - Find what you need with new enhanced search. http://info.mail.yahoo.com/mail_250 From mhartl at post.harvard.edu Wed Feb 16 15:32:37 2005 From: mhartl at post.harvard.edu (Michael Hartl) Date: 16 Feb 2005 12:32:37 -0800 Subject: Test for structure References: <1108566497.848623.45360@c13g2000cwb.googlegroups.com> Message-ID: <1108585957.015878.52530@f14g2000cwb.googlegroups.com> I use a function isListLike in cases such as this one: # def isListLike(L): # """Return True if L is list-like, False otherwise.""" # try: # L + [] # return True # except: # return False Then you can use a standard if-else construct: # if isListLike(myvar): # # else: # Michael -- Michael D. Hartl, Ph.D. Chief Technology Officer http://quarksports.com/ From onurb at xiludom.gro Tue Feb 22 07:49:28 2005 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 22 Feb 2005 13:49:28 +0100 Subject: NOOB coding help.... In-Reply-To: <03f8baafb2634534c398d3ddcc476158@localhost.talkaboutprogramming.com> References: <69012ed09e48920e1e80e311bca1659c@localhost.talkaboutprogramming.com> <03f8baafb2634534c398d3ddcc476158@localhost.talkaboutprogramming.com> Message-ID: <421b2a59$0$14818$636a15ce@news.free.fr> Igorati wrote: > #This program will ask for a user to imput numbers. The numbers will then > be calculated > #to find the statistical mean, mode, and median. Finallly the user will be > asked > #if he would like to print out the answers. > > numbers = [ ] > print 'Enter numbers to add to the list. (Enter 0 to quit.)' so 0 is not a valid value ? Since you only want numbers, any alpha char could be used to exit... > def getint(): > return int(raw_input('Number? ')) What happens if the user type "foo" ? > numbers = sorted(iter(getint, 0)) > > numbers > [2, 3, 5, 7] > def variable_median(x): > > return sorted(x)[len(x)//2] > def variable_mode(x): > > counts = {} > for item in x: > counts[x] = counts.get(x, 0) + 1 > > return sorted(counts, key=counts.__getitem__, reverse=True)[0] > > > > s = variableMean(numbers) > y = variableMedian(numbers) > t = variableMode (numbers) > > import pickle > pickle.dump((s, y, t), file('avg.pickle', 'w')) Take care of removing hard-coded filenames... (this is ok for testing but should not be released like this) > > print 'Thank you! Would you like to see the results after calculating' > print 'The mode, median, and mean? (Please enter Yes or No)' > print 'Please enter Yes or No:' > > > if raw_input == yes: First, raw_input() is a function, you need to use the () operator to *call* (execute) the function. Then, raw_input() returns a string. A string is something between quotes. Yes is a symbol (a variable name, function name or like), not a string. And since this symbol is not defined, you have an exception. What you want to do is to compare the string returned by the raw_input() function to the literral string "Yes". What you're doing in fact is comparing two symbols, one being defined, the other one being undefined... if raw_input() == "Yes": > > f = open("avg.py","r") Same remark as above about hard-coded file names... > avg.py = f.read() Notice that the dot is an operator. Here you trying to access the attribute 'py' of an (actually inexistant) object named 'avg'. What you want is to bind the data returned by f.read() to a variable. data = f.read() > print 'The Mean average is:', mean > print 'The Median is:', meadian > print 'The Mode is:', mode At this time, mean, meadian and mode are undefined symbols. Since you used the pickle module to persist your data, you should use it to unserialize'em too. The pickle module is well documented, so you may want to read the manual. > > I got the error: > > Traceback (most recent call last): > File "C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py", line 9, in ? > numbers = sorted(iter(getint, 0)) > File "C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py", line 7, in > getint > return int(raw_input('Number? ')) > TypeError: 'str' object is not callable Can't tell you since I'm running python 2.3.x here (sorted() is new in 2.4) > and this one for my if statement: > > Traceback (most recent call last): > File "C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py", line 39, in ? > if raw_input == Yes: > NameError: name 'Yes' is not defined See above. > I cannot understand how I can define yes so that when they type yes the > data is printed out. Yes = 'yes' ?-) > Also if they type no how do I make the program do > nothing. Or is that just infered. May I suggest that you : - subscribe to the 'tutor' mailing-list (it's a ml for absolute beginners) - do some tutorials (there's one with the doc, and many others freely available on the net) - use the interactive python shell to test bits of your code ? HTH Bruno -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jfj at freemail.gr Sun Feb 13 06:21:03 2005 From: jfj at freemail.gr (jfj) Date: Sun, 13 Feb 2005 03:21:03 -0800 Subject: Iterate through dictionary of file objects and file names In-Reply-To: References: <420deb18$1_1@news.iprimus.com.au> Message-ID: <420F381F.8080203@freemail.gr> Brian Beck wrote: > print "Closed: %s" % fileName Call me a pedant, but what'd wrong with: print 'closed: ' + filename or print 'closed:', filename ? Modulus operator good but don't over-use it. Otherwise, bad style. jfj From ted.lilley at gmail.com Sat Feb 19 02:42:31 2005 From: ted.lilley at gmail.com (Ted Lilley) Date: 18 Feb 2005 23:42:31 -0800 Subject: lambda closure question Message-ID: <1108798951.128843.79810@f14g2000cwb.googlegroups.com> What I want to do is pre-load functions with arguments by iterating through a list like so: >>>class myclass: ... pass >>>def func(self, arg): ... print arg >>>mylist = ["my", "sample", "list"] >>>for item in mylist: ... setattr(myclass, item, lamdba self: func(self, item)) This attaches a list of functions to the class, making them bound methods when called from a class instance. The functions are all similar except that they know their name through the item argument. The lambda takes the underlying function and preloads it with its name, and since lambdas support closures, it remembers the item variable that was used to create it when it is actually called like so: >>>obj = myclass() >>>obj.list() list That's great, since I can write a generic function that just needs to know its name to make a slight modification to its behavior, then attach it a bunch of times to a class under different names. Unfortunately, it doesn't work. It seems the closure keeps track of the variable fed to it dynamically - if the variable changes after the lambda is created, the lambda still references the _variable_ not the original _value_ and so gets the new value like so: >>>obj.sample() list >>>obj.my() list At least, that's the explanation I'm deducing from this behavior. Assuming that's the way Guido intended it to be (about as dynamic as it can get), I'm at a loss to do what _I_ want it to do. In fact, I don't think there's any way to generate the lambdas properly without coding in the name as a literal string, since any attempt to use a variable reference will always get modified as the loop iterates. Am I missing something? Help. From hgk at et.uni-magdeburg.de Mon Feb 28 07:51:17 2005 From: hgk at et.uni-magdeburg.de (Hans Georg Krauthaeuser) Date: Mon, 28 Feb 2005 13:51:17 +0100 Subject: Text To Speech with pyTTS In-Reply-To: <4221b0b6$0$1998$afc38c87@news.optusnet.com.au> References: <4221b0b6$0$1998$afc38c87@news.optusnet.com.au> Message-ID: Mike P. wrote: > Hi, > I was wondering if anyone has had any luck with the python text to speech > (pyTTS) module available on Sourceforge: > http://sourceforge.net/projects/uncassist > > I have followed the tutorial for pyTTS at: > http://www.cs.unc.edu/~parente/tech/tr02.shtml > > Using the first simple speech example: > > import pyTTS > > tts = pyTTS.Create() > tts.Speak("Hello World!") > > I get the following error on the call to pyTTS.Create() > > C:\Program Files\Python23\Lib\site-packages\pyTTS>python > ActivePython 2.3.2 Build 232 (ActiveState Corp.) based on > Python 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import pyTTS >>>>tts = pyTTS.Create() > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Program Files\Python23\Lib\site-packages\pyTTS\__init__.py", line > 28, in Create > raise ValueError('"%s" not supported' % api) > ValueError: "SAPI" not supported > ... The TTSFast.py file is missing in the 2.3 distribution. I made a copy from the 2.4 dist and everything worked fine for me. Hans Georg From miki.tebeka at zoran.com Tue Feb 8 06:44:18 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 8 Feb 2005 13:44:18 +0200 Subject: email extraction program In-Reply-To: <20050206232317.97390.qmail@web30108.mail.mud.yahoo.com> References: <20050206232317.97390.qmail@web30108.mail.mud.yahoo.com> Message-ID: <20050208114355.GD2156@zoran.com> Hello Paul, > Can you help me create an ebay email extraction program ? > > I have some ebay scripts which worked and extracted emails from > ebay.com but these days don't work. http://www.catb.org/~esr/faqs/smart-questions.html HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From csgcsg39 at hotmail.com Thu Feb 3 10:48:05 2005 From: csgcsg39 at hotmail.com (C Gillespie) Date: Thu, 3 Feb 2005 15:48:05 -0000 Subject: Calling a method using an argument Message-ID: Dear All, I have a simple class class hello: def world(self): return 'hello' def test(self,arg): return self.arg When I want to do is: >hello.test('world') 'hello' i.e. pass the method name as an argument. How should I do this? Thanks Colin From caleb1 at telkomsa.net Thu Feb 3 23:13:14 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Thu, 03 Feb 2005 23:13:14 -0500 Subject: python and visual C++ References: Message-ID: Olivier > But the problem is about modules thats are developped from others with > distutils... Yes, sorry, I reread your original post and now realise that you were referring to other people's modules. And with your comments there, I agree with you -> MSVC as a requirement is unfortunate. thx Caleb From jao at geophile.com Sat Feb 26 19:42:25 2005 From: jao at geophile.com (Jack Orenstein) Date: Sat, 26 Feb 2005 19:42:25 -0500 Subject: Thread scheduling In-Reply-To: <09Kdndga9dgQkrzfRVn-hg@powergate.ca> References: <1109456481.214243.140670@l41g2000cwc.googlegroups.com> <09Kdndga9dgQkrzfRVn-hg@powergate.ca> Message-ID: <42211771.40307@geophile.com> Peter Hansen wrote: > Jack Orenstein wrote: > >> I am using Python 2.2.2 on RH9, and just starting to work with Python >> threads. > > > Is this also the first time you've worked with threads in general, > or do you have much experience with them in other situations? Yes, I've used threading in Java. > You've got two shared global variables, "done" and "counter". > Each of these is modified in a manner that is not thread-safe. > I don't know if "counter" is causing trouble, but it seems > likely that "done" is. I understand that. As I said in my posting, "The counter is incremented without locking -- I expect to see a final count of less than THREADS * COUNT." This is a test case, and I threw out more and more code, including synchronization around counter and done, until it got as simple as possible and still showed the problem. > Basically, the statement "done += 1" is equivalent to the > statement "done = done + 1" which, in Python or most other > languages is not thread-safe. The "done + 1" part is > evaluated separately from the assignment, so it's possible > that two threads will be executing the "done + 1" part > at the same time and that the following assignment of > one thread will be overwritten immediately by the assignment > in the next thread, but with a value that is now one less > than what you really wanted. Understood. I was counting on this being unlikely for my test case. I realize this isn't something to rely on in real software. > If you really want to increment globals from the thread, you > should look into locks. Using the "threading" module (as is > generally recommended, instead of using "thread"), you would > use threading.Lock(). As my note said, I did start with the threading module. And variables updated by different threads were protected by threading.Condition variables. As I analyzed my test cases, and threading.py, I started suspecting thread scheduling. I then wrote the test case in my email, which does not rely on the threading module at all. The point of the test is not to maintain counter -- it's to show that sometimes even after one thread completes, the other thread never is scheduled again. This seems wrong. Try running the code, and let me see if you see this behavior. If you'd like, replace this: counter += 1 by this: time.sleep(0.000001 * id) You should see the same problem. So that removes counter from the picture. And the two increments of done (one by each thread) are still almost certainly not going to coincide and cause a problem. Also, if you look at the output from the code on a hang, you will see that 'thread X: leaving' only prints once. This has nothing to do with what happens with the done variable. Jack From ilias at lazaridis.com Sun Feb 13 13:41:59 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sun, 13 Feb 2005 20:41:59 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler Message-ID: I'm a newcomer to python: [EVALUATION] - E01: The Java Failure - May Python Helps? http://groups-beta.google.com/group/comp.lang.python/msg/75f0c5c35374f553 - I've download (as suggested) the python 2.4 installer for windows. Now I have problems to compile python extension that some packages depend on. I use the MinGW open-source compiler. - My questions: a) Why does the Python Foundation not provide additionally a binary version, compiled with MinGW or another open-source compiler? b) Why does the Python Foundation not ensure, that the python source-code is directly compilable with MinGW? c) Why are the following efforts not _directly_ included in the python source code base? http://jove.prohosting.com/iwave/ipython/pyMinGW.html above link found in this thread: http://groups-beta.google.com/group/comp.lang.python/msg/c9f0444c467de525 d) Is it really neccessary that I dive into such adventures, to be able to do the most natural thing like: "developing python extensions with MinGW"? http://starship.python.net/crew/kernr/mingw32/Notes.html e) Is there any official statement available regarding the msvcr71.dll and other MS licensing issues? [see several threads "[Python-Dev] Is msvcr71.dll re-redistributable?"] http://mail.python.org/pipermail/python-dev/2005-February/thread.html f) Are there any official (Python Foundation) statements / rationales available, which explain why the MinGW compiler is unsupported, although parts of the community obviously like to use it? http://groups-beta.google.com/group/comp.lang.python/msg/dc3474e6c8053336 - I just want to understand. Thankfull for any pointer to official documents / statements. [google is _not_ a fried here. I like to have a stable development environment, which is supported by the official projects, thus it can pass quality-assurance without beeing afraid about every next release.] . -- http://lazaridis.com From bdesth.quelquechose at free.quelquepart.fr Thu Feb 3 04:42:09 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 03 Feb 2005 10:42:09 +0100 Subject: IDLE history, Python IDE, and Interactive Python with Vim In-Reply-To: References: Message-ID: <4201efbe$0$518$636a15ce@news.free.fr> Daniel Bickett a ?crit : > This is certainly a worthy topic. There are several IDEs for Python > (one I like very much being Komodo) that have plenty of fancy > debugging features and advanced operations, however I have yet to > encounter (elsewhere) the convenience that comes with being able to > press F5 and have an interactive interpreter load my code and be ready > for testing. Try emacs + python-mode. From aahz at pythoncraft.com Fri Feb 4 13:37:47 2005 From: aahz at pythoncraft.com (Aahz) Date: 4 Feb 2005 13:37:47 -0500 Subject: Thread in python References: <1107533540.641969.191940@z14g2000cwz.googlegroups.com> <1107534038.823409.89650@l41g2000cwc.googlegroups.com> <4rNMd.103073$Jk5.93452@lakeread01> Message-ID: In article <4rNMd.103073$Jk5.93452 at lakeread01>, Steve Holden wrote: > >http://starship.python.net/crew/aahz/OSCON2001/index.html Thanks! But while that's still good (for the code, if nothing else), it ought to be at least supplemented with http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "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." --GvR From jerf at jerf.org Tue Feb 22 21:29:10 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 22 Feb 2005 21:29:10 -0500 Subject: compatbility of .pyc files References: <421BCED0.2070206@irl.cri.nz> Message-ID: On Wed, 23 Feb 2005 13:31:12 +1300, Blair Hall wrote: > I have a requirement to prevent 'accidental' tampering > with some software written in Python. If I ensure that all > of the modules concerned are compiled into .pyc's, and remove > the .py's to another location, then I should be safe until > the next upgrade of the Python interpretter. Depending on how "scare quote-y" the scare quotes are, if you're really out to avoid accidental tampering, why not just set the *.py files to read-only? Beyond that you get into rapidly diminishing returns; removing the .py files is feasible if you have some semblance of control over the interpreter, beyond that and you're usually better off with a binding legal agreement. From steven.bethard at gmail.com Mon Feb 21 16:37:22 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 21 Feb 2005 14:37:22 -0700 Subject: Tuple index In-Reply-To: <1109021422.351702.296640@o13g2000cwo.googlegroups.com> References: <1108951559.490554.305310@l41g2000cwc.googlegroups.com> <1109021422.351702.296640@o13g2000cwo.googlegroups.com> Message-ID: Michael Hartl wrote: > I actually find it strange that tuples don't have an index function, > since finding the index doesn't involve any mutation. Anyone know why > Python doesn't allow a statement like t.index('foo')? Tuples aren't really intended for this kind of use. See: http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types Tuples are supposed to be operated on as a group. It's even been suggested occasionally on python-dev that in Python 3.0, tuples shouldn't support iteration at all... STeVe From kdahlhaus at yahoo.com Sat Feb 19 14:25:50 2005 From: kdahlhaus at yahoo.com (kdahlhaus at yahoo.com) Date: 19 Feb 2005 11:25:50 -0800 Subject: Chart Director? In-Reply-To: References: <1108739705.870161.36050@z14g2000cwz.googlegroups.com> Message-ID: <1108841150.342993.323160@c13g2000cwb.googlegroups.com> Actually, that's exactly what I did last night. I found it all of the things you said. Consistent api across functions, lots of methods of formatting data labels. A+ on the documentation and examples. It also includes various meters and gauges that I thought might add to the application. I'm comparing it to the charting in Report Lab. I love the fact that Report Lab lets you specify a function to call to translate data points to labels. At this point I will still continue to evaluate it, but so far it probably is not compelling enough to move from Report Labs. I would highly recommend those need a graphics package look at CD though. From rigga at hasnomail.com Sun Feb 27 15:04:29 2005 From: rigga at hasnomail.com (Rigga) Date: Sun, 27 Feb 2005 20:04:29 GMT Subject: Need help running external program References: <38ejcfF5lu11pU1@individual.net> Message-ID: Tim Jarman wrote: > Rigga wrote: > >> Pink wrote: >> >>> Rigga wrote: >>> >>>> Hi, >>>> >>>> I am running the line of code below from a shell script and it works >>>> fine, however I am at a total loss on how i can run it from within a >>>> Python script as every option I have tried fails and it appears to be >>>> down to the escaping of certain characters. >>>> >>>> wget -q www.anywebpage.com -O - | tr '\r' '\n' | tr \' \" | sed -n >>>> 's/.*url="\([^"]*\)".*/\1/p' >>> If your problem is getting a python string without worrying about how to >>> escape the escape sequences, try: >>> >>> r"""wget -q www.anywebpage.com -O - | tr '\r' '\n' | tr \' \" | sed -n >>> 's/.*url="\([^"]*\)".*/\1/p'""" >>> >>> You should be able to pass this directly to a popen() function. >> >> Hi, >> >> Thanks for replying however I have just tried that and it does not seem >> to work, it doesnt return any results (i take it the r was a typo) >> >> Thanks >> >> RiGGa > > No, the r was the point - it's there to tell Python not to do any escaping > on the string. Try it again with the r and see what happens. > Brilliant!!! that works a treat thankyou!!, where on earth did you find out about the 'r' any pointers to documentation appreciated. Thanks RiGGa From mahs at telcopartners.com Wed Feb 16 23:51:55 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Wed, 16 Feb 2005 20:51:55 -0800 Subject: Iterator / Iteratable confusion In-Reply-To: References: <420a5c1e$0$21630$a1866201@visi.com><200502131848.03655.francis.girard@free.fr> <200502131958.27410.francis.girard@free.fr> Message-ID: Terry Reedy wrote: >> "Michael Spencer" wrote in message > > We are both interested in the murky edges at and beyond conventional usage. > ... > I am quite aware that multiple iterators for the same iterable (actual or > conceptual) can be useful (cross products, for example). But I am dubious > that initialized clones of 'iterators' are *more* useful, especially for > Python, than multiple iterators derived from repeated calling of the > callable that produced the first iterator. I'm not sure they are. In the one 'real' example I posted on infinite series, I implemented the approach you advocate here. But I'm keeping copyable iterators in mind. > Here are some related reasons why I think it useful if not essential to > restrict the notion of iterator by restricting iterator.__iter__ to > returning self unmodified. > > Leaving Python aside, one can think of iterable as something that > represents a collection and that can produce an iterator that produces the > items of the collection one at a time. In this general conceptioning, > iterables and iterators seem distinct (if one ignores self-iterables). The separation is appealing, but blurrier in practice, I believe. Neither itertools.cycle nor itertools.tee fits cleanly into this model. Neither do the self-iterables, as you point out. > ... giving iterators an __iter__ method, while quite useful, erases > (confuses) the (seeming) distinction, but giving them a minimal __iter__ > does so minimally, keeping iterators a distinct subcategory of iterable. Iterators that could not be presented to other functions for filtering or whatnot would be pretty limited. Unless every iterator is to be derived from some special-cased object, how could they not have an __iter__ method? I accept your point that keeping the functionality of iterator.__iter__ minimal and predicatable limits the confusion between iterators and iterables. But since that distinction is already blurred in several places, I don't find that argument alone decisive. > ... > > Taking Python as it is, a useful subcategory of iterable is 'reiterable'. > This is distinct from iterator strictly defined. What about itertools.cycle? Not strictly an iterator? This we have iterables > divided into iterators, reiterables, and other. I think this is > didactically useful. Spencerators are reiterables. They may be: they are no more and no less than a thought experiment in which iterator.__iter__ does not return self unmodified. > > Iter(iterator) returning iterator unchanged makes iterator a fixed point of > iter. It ends any chain of objects returned by repeated iter calls. > Spencerators prolong any iter chain, making it infinite instead of finite. > Essential? Repeat the paragraph above with 'a fixed point' substituted for > 'minimal'. > I don't understand this point except in the loosest sense that deviating from the iterator protocol makes it harder to reason about the code. Do you mean something more specific? I have been thinking about iterator.__iter__ rather like object.__new__. Not returning a new instance may be surprising and inadvisable in most cases. But still there are accepted uses for the technique. Do you think these cases are comparable? Do you see the iterator protocol as the vanguard of a new set of python protocols that are more semantically restictive than the "mapping, container, file-like object etc..." interfaces? Defining iterator method semantics strictly seems like a departure from the existing situation. Cheers Michael From quentel.pierre at wanadoo.fr Fri Feb 18 14:49:11 2005 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 18 Feb 2005 11:49:11 -0800 Subject: Probably over my head... Trying to get Font Names References: Message-ID: <3269a8ba.0502181149.275ca26f@posting.google.com> "Samantha" wrote in message news:... > I am attempting to extract the Font Names from the installed windows fonts. > I am having a heck of a time getting these rather than the file names. > Examples can be seen by going to Control Panel > Fonts > > Any help or direction is appreciated. > S Try this : Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from Tkinter import Tk >>> import tkFont >>> root=Tk() >>> print tkFont.families(root) From joakim.storck at home.se Wed Feb 2 12:16:57 2005 From: joakim.storck at home.se (Joakim Storck) Date: 2 Feb 2005 09:16:57 -0800 Subject: Hash of class from instance In-Reply-To: References: <1107363342.531396.238350@g14g2000cwa.googlegroups.com> Message-ID: <1107364617.371795.13740@l41g2000cwc.googlegroups.com> Thanks! Not so strange I think, the hash values of classes will be used as keys in a dictionary that serve as an object pool. Sorry about the double posting, I got a 'server error' message the first time, so I figured it hadn't gone trhough. /Joakim From sjmachin at lexicon.net Mon Feb 28 21:02:18 2005 From: sjmachin at lexicon.net (John Machin) Date: 28 Feb 2005 18:02:18 -0800 Subject: Canonical way of dealing with null-separated lines? In-Reply-To: References: <5aes11d4da95un1n78vtb04m43269hqo4m@4ax.com> Message-ID: <1109642538.040399.60890@z14g2000cwz.googlegroups.com> Douglas Alan wrote: > I wrote: > > > Oops, I just realized that my previously definitive version did not > > handle multi-character newlines. So here is a new definitive > > version. Oog, now my brain hurts: > > I dunno what I was thinking. That version sucked! Here's a version > that's actually comprehensible, a fraction of the size, and works in > all cases. (I think.) > > def fileLineIter(inputFile, newline='\n', leaveNewline=False, readSize=8192): > """Like the normal file iter but you can set what string indicates newline. > > The newline string can be arbitrarily long; it need not be restricted to a > single character. You can also set the read size and control whether or not > the newline string is left on the end of the iterated lines. Setting > newline to '\0' is particularly good for use with an input file created with > something like "os.popen('find -print0')". > """ > outputLineEnd = ("", newline)[leaveNewline] > partialLine = '' > while True: > charsJustRead = inputFile.read(readSize) > if not charsJustRead: break > lines = (partialLine + charsJustRead).split(newline) The above line is prepending a short string to what will typically be a whole buffer full. There's gotta be a better way to do it. Perhaps you might like to refer back to CdV's solution which was prepending the residue to the first element of the split() result. > partialLine = lines.pop() > for line in lines: yield line + outputLineEnd In the case of leaveNewline being false, you are concatenating an empty string. IMHO, to quote Jon Bentley, one should "do nothing gracefully". > if partialLine: yield partialLine > > |>oug From http Thu Feb 17 00:09:12 2005 From: http (Paul Rubin) Date: 16 Feb 2005 21:09:12 -0800 Subject: low-end persistence strategies? References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xoeejlqmf.fsf@ruckus.brouhaha.com> John Lenton writes: > flock(fp, LOCK_EX) # block until can write ... > Of course I'm probably overlooking something, because it really can't > be this easy, can it? Yes, maybe so. I'm just way behind the times and didn't realize flock would block until existing incompatible locks are released. That may solve the whole timeout/retry problem. I should have checked the docs more carefully earlier; I was thinking only in terms of opening with O_EXCL. Thanks! From jicman at cinops.xerox.com Tue Feb 8 19:42:59 2005 From: jicman at cinops.xerox.com (jose isaias cabrera) Date: Tue, 8 Feb 2005 19:42:59 -0500 Subject: Java Integer.ParseInt translation to python References: <008d01c507f4$451d9b30$2820790d@stso.xcdg.xerox.com> <372a762405013116263a4e93b7@mail.gmail.com> Message-ID: <001a01c50e40$4e00ac90$2820790d@stso.xcdg.xerox.com> Ok, so this, >> buffer[0] = (byte)Integer.parseInt(string,16); in java is, partly, this buffer[0] = int(string, 16) in python. But here is my problem. When I call this java subroutine, byte[] decodeKey(String inString) { if (inString == null) return null; System.out.println("StringLength = " + inString.length()); byte[] retBuf = new byte[inString.length()/2]; // The string has two hex characters per byte. for (int index = 0; index < retBuf.length; index++) { System.out.print(inString.substring(2*index, 2*index+2)); System.out.println(" " + Integer.parseInt(inString.substring(2*index, 2*index+2), 16) + " " + (byte)Integer.parseInt(inString.substring(2*index, 2*index+2), 16)); retBuf[index] = (byte)Integer.parseInt(inString.substring(2*index, 2*index+2), 16); } System.out.println(retBuf); return retBuf; } I get this output: StringLength = 40 c1 193 -63 7c 124 124 e1 225 -31 86 134 -122 ab 171 -85 94 148 -108 ee 238 -18 b0 176 -80 de 222 -34 8a 138 -118 e3 227 -29 b5 181 -75 b7 183 -73 51 81 81 a7 167 -89 c4 196 -60 d8 216 -40 e9 233 -23 ed 237 -19 eb 235 -21 [B at 1616c7 But, here is what I have for python, def PrepareHash(HashStr): while len(HashStr) > 0: byte = HashStr[0:2] print byte,int(byte,16),byte(int(byte,16)) # & 0xff HashStr = HashStr[2:] return byte def Main(): HashStr = "c17ce186ab94eeb0de8ae3b5b751a7c4d8e9edeb" HashStr = PrepareHash(HashStr) print "Prepared HashStr :",HashStr Main() and it results to, mulo 19:32:06-> python test.py c1 193 ? 7c 124 | e1 225 ? 86 134 ab 171 ? 94 148 ee 238 ? b0 176 ? de 222 ? 8a 138 e3 227 ? b5 181 ? b7 183 ? 51 81 Q a7 167 ? c4 196 ? d8 216 ? e9 233 ? ed 237 ? eb 235 ? which is not even close, and yes, I know that it's not the same code. So, the question is, how can I make this java (byte) call in python? so that the result would be the right one, "[B at 1616c7" Thanks. jos? From BOOGIEMANPN at YAHOO.COM Sun Feb 13 10:29:56 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Sun, 13 Feb 2005 16:29:56 +0100 Subject: Alternative to raw_input ? References: Message-ID: <1gydyq1m4316i.1z21x6hfdwzk.dlg@40tude.net> On Sun, 13 Feb 2005 12:08:26 +1000, Nick Coghlan wrote: > Try this: > > print "Hit a key!" > cekaj() > print "Nap time!" > time.sleep(15) > print "Hit another key!" > cekaj() > > with the two different implementations, and see what happens if you hit a key > when the 'Nap Time!' prompt appears. I see the difference now, thanks From marmille at gmail.com Sat Feb 5 21:45:28 2005 From: marmille at gmail.com (Martin Miller) Date: 5 Feb 2005 18:45:28 -0800 Subject: "pickle" vs. f.write() References: <41FF70A5.8070806@tx3.com> Message-ID: <1107657928.277563.186760@l41g2000cwc.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > ... > > I write __repr__() methods similar but I think a bit more readable: > > def __repr__(self): > return "%s(%r, %r, %r, %r)" % (self.__class__.__name__, self.name, > self.age, self.friends, self.comment) > > And it's robust against changing the class name. It even works in > subclasses if the signature of the __init__() method stays the same. Yes, that's an excellent suggestion and improvement. Saw the following in a post by Steven Bethard on another thread that I think would be even better (in the sense of being more general/generic) which also ought to work in subclasses. Namely: def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join('%s=%r' % (k, v) for k, v in self.__dict__.items())) Martin From sylvain.thenault at nospam.logilab.fr Tue Feb 1 05:21:24 2005 From: sylvain.thenault at nospam.logilab.fr (Sylvain Thenault) Date: Tue, 01 Feb 2005 11:21:24 +0100 Subject: Next step after pychecker References: <41ff0308$0$6503$636a15ce@news.free.fr> Message-ID: On Tue, 01 Feb 2005 05:18:12 +0100, Philippe Fremy wrote: > Hi, Hi > I would like to develop a tool that goes one step further than pychecker > to ensure python program validity. The idea would be to get close to what > people get on ocaml: a static verification of all types of the program, > without any kind of variable declaration. This would definitely brings a > lot of power to python. > > The idea is to analyse the whole program, identify constraints on function > arguments and check that these constraints are verified by other parts of > the program. Did you take a look at the starkiller [1] and pypy projects [2] ? > What is in your opinion the best tool to achieve this ? I had an > extensive look at pychecker, and it could certainly be extended to do > the job. Things that still concern me are that it works on the bytecode, > which prevents it from working with jython and the new .NET python. > > I am currently reading the documentation on AST and visitor, but I am > not sure that this will be the best tool either. The AST seems quite > deep and I am afraid that it will make the analysis quite slow and > complicated. are you talking about the ast returned by the "parser" module, or the ast from the "compiler" module ? The former is a higher abstraction, using specific class instances in the tree, and most importantly with all the parsing junk removed. See [3]. You may also be interested in pylint [4] which is a pychecker like program built in top of the compiler ast, and so doesn't require actual import of the analyzed code. However it's not yet as advanced as pychecker regarding bug detection. And finally as another poster said you should probably keep an eye open on the python 2.5 ast branch work... Hope that helps ! [1]http://www.python.org/pycon/dc2004/papers/1/paper.pdf) [2]http://codespeak.net/pypy/index.cgi?home [3]http://www.python.org/doc/current/lib/module-compiler.ast.html [4]http://www.logilab.org/projects/pylint -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From francis.girard at free.fr Tue Feb 1 15:13:24 2005 From: francis.girard at free.fr (Francis Girard) Date: Tue, 1 Feb 2005 21:13:24 +0100 Subject: Next step after pychecker In-Reply-To: <369mivF4ubv6mU1@individual.net> References: <41ff0308$0$6503$636a15ce@news.free.fr> <369mivF4ubv6mU1@individual.net> Message-ID: <200502012113.26393.francis.girard@free.fr> Hi, I do not want to discourage Philippe Fremy but I think that this would be very very difficult to do without modifying Python itself. What FP languages rely upon to achieve type inference is a feature named "strong typing". A clear definition of strong typing is : "Every well-formed expression of the language can be assigned a type that can be deduced from the constituents of the expression alone." Bird and Wadler, Introduction to Functional Programming, 1988 This is certainly not the case for Python since one and the same variable can have different types depending upon the execution context. Example : 1- if a is None: 2- b = 1 3- else: 4- b = "Phew" 5- b = b + 1 One cannot statically determine the type of b by examining the line 5- alone. Therefore, Fremy's dream can very well turn to some very complex expert system to make "educated" warning. Being "educated" is a lot harder than to be "brutal". It's funny that what mainly prevents us from easily doing a type inferencer is at this very moment discussed with almost religious flame in the "variable declaration" thread. Anyway, strong typing as defined above would change the Python language in some of its fundamental design. It would certainly be valuable to attempt the experience, and rename the new language (mangoose would be a pretty name). Francis Girard FRANCE Le mardi 1 F?vrier 2005 16:49, Diez B. Roggisch a ?crit?: > > But it can be useful to restrict type variety in certain situations > > e.g. prime number calculation :) And it would probably also be useful > > to check violations of restrictions before running the program in > > normal mode. > > But that's what (oca)ml and the like do - they exactly don't force you to > specify a type, but a variable has an also variable type, that gets > inferned upon the usage and is then fixed. > > -- > Regards, > > Diez B. Roggisch From tchur at optushome.com.au Tue Feb 15 23:32:33 2005 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 16 Feb 2005 15:32:33 +1100 Subject: SHA1 broken Message-ID: <200502160432.j1G4WXLQ018139@mail27.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From grante at visi.com Tue Feb 22 10:45:01 2005 From: grante at visi.com (Grant Edwards) Date: 22 Feb 2005 15:45:01 GMT Subject: imaplib.error: command COPY illegal in state AUTH References: <1109071449.141166.165710@l41g2000cwc.googlegroups.com> Message-ID: <421b537d$0$46552$a1866201@visi.com> On 2005-02-22, Raghul wrote: > I am getting this error while copying n number of messages to the > folder using imaplib.What to do to copy n number of folders in mail > > The error i got is > > imaplib.error: command COPY illegal in state AUTH That means you haven't logged in yet. Will you PLEASE keep your IMAP questions in a single thread? -- Grant Edwards grante Yow! PARDON me, am I at speaking ENGLISH? visi.com From eugene at boardkulture.com Fri Feb 4 13:31:18 2005 From: eugene at boardkulture.com (EuGeNe) Date: Fri, 04 Feb 2005 19:31:18 +0100 Subject: bicyclerepairman python24 windows idle :( Message-ID: Hi there, I am no expert but wanted to give bicyclerepairman 0.9 a go just to see what a refactoring browser is and does. Followed every step of the install, I think, but idle doesn't start with the RepairMan section in config-extensions.def ... is it incompatible with 2.4? Thanks for your help. -- EuGeNe [---- www.boardkulture.com www.actiphot.com www.xsbar.com ----] From dima at trit.invalid Mon Feb 28 17:58:25 2005 From: dima at trit.invalid (Dima Dorfman) Date: 28 Feb 2005 22:58:25 GMT Subject: My C module crashes References: Message-ID: On 2005-02-28, Egil Moeller wrote: > I've written a C-module for Python, and it works as intended, but > obviously does something wrong with its memmory management (refference > counting), as it causes Python to segfault now and then (randomly, > whey :S) Have you tried compiling Python and your module with debugging enabled? It might make the crash less random--or it might not help at all, but it's probably worth a try. Running Python with debugging enabled is a good idea anyway when developing extension modules. From fumanchu at amor.org Mon Feb 7 11:50:05 2005 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 7 Feb 2005 08:50:05 -0800 Subject: Making dynamic data available via ODBC with Python Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339837B@exchange.hqamor.amorhq.net> Erwin S. Andreasen wrote: > I have a Python application server that manages several different data > sets, permits various reports to be run on them and the data to be > downloaded as tab-delimetered files, all via a web interface. > > I'd like to explore the possibilities of making the data directly > available in Windows applications (such as Excel, where it would very > nice to directly do pivot tables from the live data) via ODBC. Hi, Erwin, I give my users Excel documents within a web app. They perform a query to get the subset of data they want to play with, then see that in an HTML table, with a link to "get it in Excel format". [If the dataset is huge, they're prompted to preview only, say, the first 10 rows.] When they request the Excel format, they get the same data (the HTML table!), with a Content-type of "application/vnd.ms-excel" and no frills; both IE and Firefox will use Excel to open it. Works wonderfully. Let me know if you need more details. Robert Brewer MIS Amor Ministries fumanchu at amor.org From francis.girard at free.fr Thu Feb 10 13:28:49 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 10 Feb 2005 19:28:49 +0100 Subject: A great Alan Kay quote In-Reply-To: <420ab9c9$1@nntp0.pdx.net> References: <420a5c1e$0$21630$a1866201@visi.com> <420ab9c9$1@nntp0.pdx.net> Message-ID: <200502101928.50502.francis.girard@free.fr> Thank you. Francis Girard Le jeudi 10 F?vrier 2005 02:48, Scott David Daniels a ?crit?: > Francis Girard wrote: > > ... > > It's also interesting to see GUIs with windows, mouse (etc.), which > > apparently find their origin in is mind, probably comes from the desire > > to introduce computers to children. > > OK, presuming "origin in is mind" was meant to say "origin in his mind," > I'd like to stick up for Doug Engelbart (holds the patent on the mouse) > here. I interviewed with his group at SRI in the ancient past, when > they were working on the "Augmentation Research" project -- machine > augmentation of human intelligence. They, at the time, were working on > input pointing devices and hadn't yet settled. The helmet that read > brain waves was doing astoundingly well (90% correct on up, down, left, > right, don't move), but nowhere near well enough to use for positioning > on edits. This work produced the mouse, despite rumors of Xerox Parc or > Apple inventing the mouse. > > Xerox Parc, did, as far as I understand, do the early development on > interactive graphic display using a mouse for positioning on a > graphics screen. Engelbart's mouse navigated on a standard 80x24 > character screen. > > Augment did real research on what might work, with efforts to measure > ease of use and reliability. They did not simply start with a good > (or great) guess and charge forward. They produced the mouse, and the > earliest "linked" documents that I know of. > > http://sloan.stanford.edu/MouseSite/1968Demo.html > > --Scott David Daniels > Scott.Daniels at Acm.Org From tchur at optushome.com.au Thu Feb 3 21:42:15 2005 From: tchur at optushome.com.au (Tim Churches) Date: Fri, 04 Feb 2005 13:42:15 +1100 Subject: [Fwd: [gnu.org #220719] Re: python and gpl] Message-ID: <200502040242.j142gFUr023786@mail09.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From devries at idolstarastronomer.com Sat Feb 12 22:27:49 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: Sat, 12 Feb 2005 22:27:49 -0500 Subject: SCons build tool speed In-Reply-To: References: Message-ID: <20050213032749.GA15612@miyu.cjas.org> On Sat, Feb 12, 2005 at 07:16:02PM +0000, ted wrote: > How does the speed of the Scons build tool compare with Ant? I would recommend asking this question on users at scons.tigris.org , but my impressions is that most of the time is probably spent in the compiler. If you are working on a java project you could try switching from javac to jikes and that might improve your time, though it has been a while since I used jikes. Chris From das69 at et.byu.edu Wed Feb 2 15:59:12 2005 From: das69 at et.byu.edu (Dan Smyth) Date: Wed, 2 Feb 2005 13:59:12 -0700 Subject: Compilation problems for Python 2.4 on SGI machines Message-ID: <003901c5096a$0c24aa40$6671080a@et.byu.edu> Hey, I'm trying to compile python 2.4 on an SGI machine running IRIX 6.5. The configure program shot back this error and told me to post it to the Python lists. Anyone know what's going on? configure: WARNING: stropts.h: present but cannot be compiled configure: WARNING: stropts.h: check for missing prerequisite headers? configure: WARNING: stropts.h: see the Autoconf documentation configure: WARNING: stropts.h: section "Present But Cannot Be Compiled" configure: WARNING: stropts.h: proceeding with the preprocessor's result configure: WARNING: stropts.h: in the future, the compiler will take precedence configure: WARNING: ## --------------------------------- ## configure: WARNING: ## Report this to the python lists. ## configure: WARNING: ## --------------------------------- ## Dan Smyth Dan Gaidin -- Tai Shar Phoenix "Dovie'andi se tovya sagain" -------------- next part -------------- An HTML attachment was scrubbed... URL: From jerf at jerf.org Wed Feb 9 18:59:17 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 09 Feb 2005 18:59:17 -0500 Subject: A great Alan Kay quote References: <420a5c1e$0$21630$a1866201@visi.com> <1107993430.712644.298500@f14g2000cwb.googlegroups.com> Message-ID: On Wed, 09 Feb 2005 15:57:10 -0800, has wrote: > I'd say Python is somewhere in the middle, though moving slowly towards > 'agglutination' in the last couple years. But it feels really badly about that and promises to kick the habit somewhere around the year 3000. From kentsin at yahoo.com Mon Feb 14 20:07:41 2005 From: kentsin at yahoo.com (kent sin) Date: Mon, 14 Feb 2005 17:07:41 -0800 (PST) Subject: Write Unicode str as utf-8 Message-ID: <20050215010741.54218.qmail@web40521.mail.yahoo.com> Python support unicode, but some library don't. Write is one of them. When writing a csv file, The rows contains numbers and unicode str. It is a little pain to first convert all unicode str to utf-8 before writing the row. Are there anyway I can patch python such that It will convert the unicode string to utf-8 before the write? Where should I start? Best rgs, Kent Sin From deetsNOSPAM at web.de Thu Feb 3 10:56:05 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 03 Feb 2005 16:56:05 +0100 Subject: Calling a method using an argument References: Message-ID: <36evn2F51nullU1@individual.net> def test(self,arg): return getattr(self, arg) -- Regards, Diez B. Roggisch From jkjone2002 at att.net Tue Feb 15 22:33:15 2005 From: jkjone2002 at att.net (john san) Date: Tue, 15 Feb 2005 22:33:15 -0500 Subject: [newbie]How to install python under DOS and is there any Wxpython can be installed under dos? Message-ID: How to install python under DOS and is there any Wxpython-like can be installed under dos? Thanks. From lbates at syscononline.com Wed Feb 2 19:26:35 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 02 Feb 2005 18:26:35 -0600 Subject: global variables In-Reply-To: <1107385488.822768.317250@l41g2000cwc.googlegroups.com> References: <1107385488.822768.317250@l41g2000cwc.googlegroups.com> Message-ID: <47WdnSbgo8ku8pzfRVn-ug@comcast.com> One way to to this is by using keyword args: class a: def __init__(self, arg1, arg2, **kwargs): # # Dictionary kwargs will have keyword, value pairs # that can be used as global space. # self.arg1=arg1 self.arg2=arg2 self.__dict__.update(kwargs) return class b: def __init__(self, arg1, arg2, **kwargs): # # Dictionary kwargs will have keyword, value pairs # that can be used as global space. # self.__dict__.update(kwargs) self.a=a(arg1, arg2, **kwargs) return class c: def __init__(self, arg1, arg2, **kwargs): # # Dictionary kwargs will have keyword, value pairs # that can be used as global space. # self.__dict__.update(kwargs) self.b=b(arg1, arg2, **kwargs) return globals={'global1':1, 'global2':2, 'global3':3, 'global4':4} C=c(1, 2, **globals) you will have global1, global2, global3, and global4 attributs in all classes. If you don't want the attributes, just access to the values, delete the self.__dict__.update(kwargs) lines. Larry Bates alex wrote: > Hi, > > is it possible to create 'global' variables that can be seen in all > other classes? > > Alex > From ilias at lazaridis.com Mon Feb 14 04:53:30 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Mon, 14 Feb 2005 11:53:30 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: Miki Tebeka wrote: > Hello Ilias, > >>d) Is it really neccessary that I dive into such adventures, to be able >>to do the most natural thing like: "developing python extensions with >>MinGW"? > > Writing a setup.py and running > python setup.py build_ext --compiler=mingw32 > works for me *without* any more work. Things can't get much simpler. looks really simple. - but: the central problem still exists: "** For a Python which was built with Cygwin, all should work without any of these following steps. **" source: http://www.python.org/doc/2.2.3/inst/non-ms-compilers.html#SECTION000312000000000000000 - "the problem is that Python binary distributions for MS Windows do not include import libraries for popular gcc based tools: cygwin and mingw32" source: http://www.zope.org/Members/als/tips/win32_mingw_modules - the solutions is possibly (copied from another answer): "The Python Foundation could create an official sub-project to create an automated build target based on the MinGW toolchain. I am sure that many community members would be more than happy to contribute." . -- http://lazaridis.com From lith.usenet at gmail.com Fri Feb 18 02:28:00 2005 From: lith.usenet at gmail.com (Lith) Date: 17 Feb 2005 23:28:00 -0800 Subject: IDLE edit windows ignores tab settings Message-ID: <1108711680.377953.287080@f14g2000cwb.googlegroups.com> [Python/IDLE newbie here] I created a .py file in UltraEdit and saved it. I use (and always will, despite the FAQ's recommendation against it) tabs instead of spaces, set to 4 spaces per tab. When I open the file in IDLE, suddenly the tabs are 8 spaces wide. This is despite the fact that I've gone to Options menu > Configure IDLE... > Fonts/Tabs and set it thusly: Tab key inserts tabs indent width 4 Is this a bug, or am I missing something? I'll now go google to see who to blame for the original 8-space tab. From joele at qalabs.com Thu Feb 3 14:16:59 2005 From: joele at qalabs.com (Joel Eusebio) Date: Thu, 3 Feb 2005 11:16:59 -0800 Subject: errors In-Reply-To: Message-ID: <20050203191700.9483A1E4004@bag.python.org> Tried looking for the misspelled oldmtime on apache.py but can't find it. Joel -----Original Message----- From: python-list-bounces+joele=qalabs.com at python.org [mailto:python-list-bounces+joele=qalabs.com at python.org] On Behalf Of Kartic Sent: Thursday, February 03, 2005 4:00 AM To: python-list at python.org Subject: Re: errors Joel Eusebio said the following on 2/2/2005 4:53 PM: > Can someone help me on this, I don' know where the "testmptest" came from > but the mptest.py is at the /usr/local/apache2/htdocs/test directory and > this error came from apache's error_log > > PythonHandler mod_python.publisher: ImportError: No module named testmptest > > Thanks, > > Joel I found this link from Googling - http://www.modpython.org/pipermail/mod_python/2004-January/014857.html Please read the entire thread and see if it provides your resolutions (the mod_python OP's issue was similar but for a different module). It might also do you some good to join mod_python mailing list if you are going to use it regularly. Thanks, -Kartic -- http://mail.python.org/mailman/listinfo/python-list -- No virus found in this incoming message. Checked by AVG Anti-Virus. Version: 7.0.300 / Virus Database: 265.8.5 - Release Date: 2/3/2005 -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.300 / Virus Database: 265.8.5 - Release Date: 2/3/2005 From wade_stoddard at yahoo.com Tue Feb 22 03:51:43 2005 From: wade_stoddard at yahoo.com (Igorati) Date: Tue, 22 Feb 2005 03:51:43 -0500 Subject: NOOB coding help.... References: <69012ed09e48920e1e80e311bca1659c@localhost.talkaboutprogramming.com> Message-ID: <03f8baafb2634534c398d3ddcc476158@localhost.talkaboutprogramming.com> #This program will ask for a user to imput numbers. The numbers will then be calculated #to find the statistical mean, mode, and median. Finallly the user will be asked #if he would like to print out the answers. numbers = [ ] print 'Enter numbers to add to the list. (Enter 0 to quit.)' def getint(): return int(raw_input('Number? ')) numbers = sorted(iter(getint, 0)) numbers [2, 3, 5, 7] def variable_median(x): return sorted(x)[len(x)//2] def variable_mode(x): counts = {} for item in x: counts[x] = counts.get(x, 0) + 1 return sorted(counts, key=counts.__getitem__, reverse=True)[0] s = variableMean(numbers) y = variableMedian(numbers) t = variableMode (numbers) import pickle pickle.dump((s, y, t), file('avg.pickle', 'w')) print 'Thank you! Would you like to see the results after calculating' print 'The mode, median, and mean? (Please enter Yes or No)' print 'Please enter Yes or No:' if raw_input == yes: f = open("avg.py","r") avg.py = f.read() print 'The Mean average is:', mean print 'The Median is:', meadian print 'The Mode is:', mode I got the error: Traceback (most recent call last): File "C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py", line 9, in ? numbers = sorted(iter(getint, 0)) File "C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py", line 7, in getint return int(raw_input('Number? ')) TypeError: 'str' object is not callable and this one for my if statement: Traceback (most recent call last): File "C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py", line 39, in ? if raw_input == Yes: NameError: name 'Yes' is not defined I cannot understand how I can define yes so that when they type yes the data is printed out. Also if they type no how do I make the program do nothing. Or is that just infered. From mk at interzone.gr Mon Feb 28 02:52:57 2005 From: mk at interzone.gr (Michalis Kabrianis) Date: Mon, 28 Feb 2005 09:52:57 +0200 Subject: wxGrid In-Reply-To: <1109574065.613518.241750@l41g2000cwc.googlegroups.com> References: <1109574065.613518.241750@l41g2000cwc.googlegroups.com> Message-ID: Gensek wrote: > I have a grid. I want to sort it when a column label is clicked. I know > about the EVT_GRID_LABEL_LEFT_DCLICK event, but that is not enough. I > do not merely need to know that a label was clicked. I need to know > which label was clicked. I do not know how to do that. I suspect you > might know. I request that you tell me. > > I also wish to know some other things: how to find out the location of > a mouse pointer in a wxWindow (or at least the frame), and how to > change the color of a single specified pixel in a bitmap. > > I use Python 2.3, wxPython 2.4.2. > Hi, In C++, you can use event.GetColumn() to get that info. Look at wxGridEvent. If I were you, I would try to see if these functions are also available on wxPython Michalis From fredrik at pythonware.com Mon Feb 14 18:25:54 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Feb 2005 00:25:54 +0100 Subject: Inheritance error in python 2.3.4??? References: <1108422852.332215.165790@o13g2000cwo.googlegroups.com> Message-ID: friedmud at gmail.com wrote: > In trying to construct a good object model in a recent project of mine, > I ran across the following peculiarity in python 2.3.4 (haven't tried > any newer versions): > > Say you have a base class that has an attribute and an accessor > function for that attribute (just a simple get). (don't use getters and setters methods in Python; use bare attributes where you can, and properties when you need to add logic) > BUT! If you implement the get function in the derived class it works > fine.... > > This, to me, is completely wrong. it works exactly as documented. > I have worked up the following example to illustrate my point: > > First is the way I want to do it: > ###################################### > bash-2.05b$ cat main.py > class baseClass(object): > __Something = "Dumb!" > > def getSomething( self ): > return self.__Something > > class subClass(baseClass): > def setSomething( self , aSomething ): > self.__Something = aSomething > > anObject = subClass() > anObject.setSomething("Cool!") > print anObject.getSomething() > > bash-2.05b$ python main.py > Dumb! > ################################### > > Note that it prints "Dumb!" instead of "Cool!". members that start with __ (two underscores) are private to the class, so you're in fact working with two different attributes here. see section 9.6 in the tutorial for more on this: http://docs.python.org/tut/node11.html#SECTION0011600000000000000000 to fix your problem, rename the attribute. From snail at objmedia.demon.co.uk Mon Feb 14 09:47:06 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Mon, 14 Feb 2005 14:47:06 +0000 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: Message-ID: In message , Ilias Lazaridis writes >> The answer to most of your questions is, "Because no one has yet >>volunteered their time and effort to get the job done." > >this answer do not fit in most questions. > >please review them again. There you go. Failed the test. He is an AI. A human wouldn't make this mistake. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From EP at zomething.com Fri Feb 4 03:08:52 2005 From: EP at zomething.com (EP) Date: Fri, 4 Feb 2005 00:08:52 -0800 Subject: OT: why are LAMP sites slow? In-Reply-To: <280bd2-1ad.ln1@eskimo.tundraware.com> References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xis59qgaz.fsf@ruckus.brouhaha.com> <280bd2-1ad.ln1@eskimo.tundraware.com> Message-ID: <20050204000852.1247266681.EP@zomething.com> > > The server is slow to respond to requests. Browser rendering is > > independent of the server architecture and "slow to be fetched from > > the server" sounds like it means low network speed. I'm talking > about > > the very familiar experience of clicking a link and then waiting, > > waiting, waiting for the page to load. You rarely see that happen > > with Ebay or Google. It happens all the time with Wikipedia. > > This has a lot to do with the latency and speed of the connecting > network. Sites like Ebay, Google, and Amazon are connected > to internet backbone nodes (for speed) and are cached throughout > the network using things like Akami (to reduce latency)... Akami for services, or better yet, cacheing hardware such as NetCache. Frequently requested data doesn't even have to come from the server disks/database - it's sent from the NetCache. From tim.peters at gmail.com Sat Feb 26 13:05:12 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 26 Feb 2005 13:05:12 -0500 Subject: Whither datetime.date ? In-Reply-To: References: Message-ID: <1f7befae05022610052cd56cb4@mail.gmail.com> [Harald Hanche-Olsen] > I'm confused. I was going to try linkchecker, and it dies with a > traceback ending in > > File "/usr/local/lib/python2.4/calendar.py", line 32, in _localized_month > _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)] > AttributeError: 'module' object has no attribute 'date' > > Sure enough, there is no datetime.date, but there is a datetime.Date: > > Python 2.4 (#2, Feb 19 2005, 20:35:23) > [GCC 3.4.2 [FreeBSD] 20040728] on freebsd5 > Type "help", "copyright", "credits" or "license" for more information. > >>> import datetime > >>> dir(datetime) > ['Date', 'DateTime', ...] > > However, the Library Reference clearly states that datetime.date > should exist. Granted, it's been a while since I used python in > anger, but isn't this what it says? > > http://www.python.org/doc/2.4/lib/node243.html > http://www.python.org/doc/2.4/lib/datetime-date.html > > Moreover, the datetime.date class is supposed to have a strftime() > method. datetime.Date does not. > > I'm beginning to wonder if the FreeBSD python package is at fault. > > Or what is really going on here? As you've deduced, you're certainly not getting Python's builtin datetime module. Therefore you must be getting some other datetime module. Run Python with the "-v" switch to get output telling you how imports are resolved. That will show you where this other datetime module is coming from. Remember that Python searches along sys.path to resolve imports, taking the first thing it finds with the right name. You almost certainly have something _called_ datetime earlier in your PYTHONPATH than where the standard Python libraries appear. From miki.tebeka at Zoran.com Thu Feb 17 03:46:44 2005 From: miki.tebeka at Zoran.com (Miki Tebeka) Date: Thu, 17 Feb 2005 10:46:44 +0200 Subject: Help with C extensions under VC6 / WinXP and Python 2.4 In-Reply-To: <1108619503.324262.282330@c13g2000cwb.googlegroups.com> References: <1108619503.324262.282330@c13g2000cwb.googlegroups.com> Message-ID: <20050217084642.GC4000@zoran.com> Hello Simon, > What's the difference between ctypes, SWIG and SIP? SIG and SIP take C/C++ *sources* and create Python modules. ctypes works directly with the binary dll. Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From rkern at ucsd.edu Tue Feb 1 20:03:25 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 01 Feb 2005 17:03:25 -0800 Subject: Atlas and NumPy Problems In-Reply-To: References: Message-ID: Justin Lemkul wrote: > Hello all, > > I am hoping someone out there will be able to help me. I am trying to install > a program that utilizes NumPy. In installing NumPy, I realized that I was > lacking Atlas. I ran into the following problems installing Atlas and NumPy, > as I realized that NumPy could be installed using the Mac OSX veclib already > built in. If anyone has any ideas on how to fix either of these, I would be > most grateful. > > I am fairly new to Python (I've been learning it myself), so I apologize if > these questions are a bit foolish. I've been fighting these problems for > days, and I'm out of ideas. > > I am running OS X v10.3, gcc v3.3, Python v2.3, ScientificPython v2.4.3, and > am attempting to install NumPy 23.7 Did you try to follow my advice from the other thread? What does your setup.py look like? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From dontwant at spam.com Sun Feb 13 19:04:24 2005 From: dontwant at spam.com (Courageous) Date: Sun, 13 Feb 2005 16:04:24 -0800 Subject: Kill GIL References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <868y5t6sal.fsf@guru.mired.org> <86sm405d38.fsf@guru.mired.org> Message-ID: <0lqv01tvnh23n80qcops33uhnumtbtb9t8@4ax.com> >Actually, this is one of the cases I was talking about. I find it >saner to convert to non-blocking I/O and use select() for >synchronization. That solves the problem, without introducing any of >the headaches related to shared access and locking that come with >threads. Threads aren't always the right entity for dealing with asynchronicity, one might say. C// From miki.tebeka at zoran.com Wed Feb 2 11:30:13 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 2 Feb 2005 18:30:13 +0200 Subject: CONTEST - What is the (best) solution? In-Reply-To: <1107340503.462196.109440@o13g2000cwo.googlegroups.com> References: <1107340503.462196.109440@o13g2000cwo.googlegroups.com> Message-ID: <20050202162949.GI2416@zoran.com> Hello Lad, > In a file there can be several dictionaries like this > {Key11: Value11 > Key12: Value12 > Key13: Value13, > ... > ... > Key1n:Value1n} > {Key21: Value21 > Key22: Value22 > Key23: Value23, > ... > ... > Key2n:Value2n} > {Key31: Value31 > Key32: Value32 > Key33: Value33, > ... > ... > Key3n:Value3n} > .... > .... > .... > {Keyn1: Valuen1 > Keyn2: Valuen2 > Keyn3: Value3, > ... > ... > Keynn:Valuenn} > > Each pair in a dictionary is separated by CRLF and in each dictionary > numbers of pairs can be different. > I need to read only the the first and the last dictionaries.What is a > best solution? ---- d.py --- #!/usr/bin/env python from sys import argv dicts = eval("[" + open(argv[1]).read().replace("}", "},") + "]") print dicts[0], dicts[-1] ---- d.py --- HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From just at xs4all.nl Thu Feb 3 09:37:43 2005 From: just at xs4all.nl (Just) Date: Thu, 03 Feb 2005 15:37:43 +0100 Subject: Hey, get this! References: <4200E5CB.6020508@holdenweb.com> Message-ID: In article , Bernhard Herzog wrote: > Bernhard Herzog writes: > > > Steve Holden writes: > >> if package: > >> module.__path__ = sys.path > > > > You usually should initialize a package's __path__ to an empty list. > > Actually, normally it's a list that contains the name of the package > directory as its only item. I'm not sure what you should do when you do > not import from a file system. If it's a path importer, it could be a cookie, specific to the importer. I think in Steve's case initializing __path__ to ["*db*"] should work. Just From martin at v.loewis.de Fri Feb 11 19:28:10 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 12 Feb 2005 01:28:10 +0100 Subject: sre is broken in SuSE 9.2 In-Reply-To: <1108060527.378911.146240@o13g2000cwo.googlegroups.com> References: <1108060527.378911.146240@o13g2000cwo.googlegroups.com> Message-ID: <420D4D9A.40201@v.loewis.de> Serge Orlov wrote: > To summarize the discussion: either it's a bug in glibc or there is an > option to specify modern POSIX locale. POSIX locale consist of > characters from the portable character set, unicode is certainly > portable. Yes, but U+00E4 is not in the portable character set. The portable character set is defined here: http://www.opengroup.org/onlinepubs/007908799/xbd/charset.html Regards, Martin From mirandacascade at yahoo.com Mon Feb 14 10:52:23 2005 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 14 Feb 2005 07:52:23 -0800 Subject: newbie question - identifying name of method Message-ID: <1108396343.218224.79980@c13g2000cwb.googlegroups.com> Does Python provide some sort of mechanism for answering the question: what method am I in? Example: assume the file example1.py contains the following code: def driver(): print 'hello world' print __name__ print 'the name of this method is %s' % str(???) The output I'd like to see is: hello world example1 driver and I'd like to be able to see it without hardcoding the string 'driver' in the third print statement. Is there anything I can substitute for the ??? that answers the question: what method am I in? From peter at engcorp.com Sun Feb 13 20:51:45 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 13 Feb 2005 20:51:45 -0500 Subject: For American numbers In-Reply-To: References: <420e7376$1@nntp0.pdx.net> Message-ID: <0omdnfYNUY4zmY3fRVn-rA@powergate.ca> Alan Kennedy wrote: > [Peter Hansen] >> For the rest of the computer world, unless I've missed >> a changing of the guard or something, "kilo" is 1024 >> and "mega" is 1024*1024 and so forth... > > Maybe you missed these? > > http://en.wikipedia.org/wiki/Kibibyte > http://en.wikipedia.org/wiki/Mebibyte > http://en.wikipedia.org/wiki/Gibibyte Definitely missed them, in the sense of "didn't see them yet". I must say I'm somewhat astounded that anyone bothered to do this. Don't miss them at all, in the sense of "have no plans to use them and am not stressed in the least over the fact that they are lacking in my life." > kilo-mega-giga-etc-should-be-powers-of-10-ly y'rs, Maybe, but they aren't always... that's just the way it is. I take a descriptive view rather than a prescriptive one. Google for the usage of the above and you'll find the following ratios for the numbers of pages that use the two forms: kibibyte vs. kilobyte: 1:60 (impressively high, I admit) mebibyte vs. megabyte: 1:234 gibibyte vs. gigabyte: 1:2082 I strongly suspect that the vast majority of the former set of pages are of the form "use this instead of kilo!", but perhaps I really have been asleep while much of the computing world converted. I'll be one of the last holdouts, too... it's really not so hard to work in powers of two if you try... -Peter From jerf at jerf.org Tue Feb 8 07:47:02 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 08 Feb 2005 07:47:02 -0500 Subject: turing machine in an LC (was: Xah Lee's stupid question #853,172) References: <1107805151.265680.165380@o13g2000cwo.googlegroups.com> <87mzuf9gu8.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: On Tue, 08 Feb 2005 17:36:19 +0100, Bernhard Herzog wrote: > Nick Vargish writes: > >> "Xah Lee" writes: >> >>> is it possible to write python code without any indentation? >> >> Not if Turing-completeness is something you desire. > > It's possible to implement a turing machine with a single list > comprehension. No indentation needed. I had to think about it, it's an interesting, and I'm going to tentatively disagree, because of the statement/expression dichotomy. "Tentatively" because if somebody can answer these objections than I will happily change my mind :-) I can't figure out how to write a TM in a Python List Comprehension without one of either "variable binding" (so we can store the last symbol list and manipulate it in the next iteration) or "recursive function" (to express the whole tape as a recursive function), both of which require statements. I can figure out how to write a single state transition, but in a single LC I can't figure out how to feed the new state into the next iteration; the previous values generated in the LC are, to my knowledge, not accessible to the LC as it is running. (If they are, I *think* that would indeed be enough.) I'm sure Haskell could do both, being a functional language, and I am satisfied that it is probably possible in that language, as long as you are resigned to creating a wasted list (which may not even matter in Haskell). But I think you're screwed in Python with an LC. However, hack hack hack, I think you could do this in Python 2.4 with a *generator* comprehension and a couple of supporting lines of non-indented code: Python 2.4 (#1, Jan 2 2005, 22:17:50) [GCC 3.4.3 (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> this = sys.modules[__name__] >>> magicGenerator = (getattr(this, "results")[-1] + 1 for x in range(5)) >>> results = [0] # you have to prime the state here >>> results.extend(magicGenerator) >>> results [0, 1, 2, 3, 4, 5] >>> Now you *can* get at the previous state and write a state-transition expression in perfectly legal Python. What do you know, generator comprehensions are Turing Complete and list comprehensions aren't. I wouldn't have expected that. People caught using this technique in real code will be caught and forced to code in Intercal for the rest of their lives. From pink at odahoda.de Sun Feb 27 12:17:30 2005 From: pink at odahoda.de (Pink) Date: Sun, 27 Feb 2005 18:17:30 +0100 Subject: Need help running external program References: Message-ID: Rigga wrote: > Hi, > > I am running the line of code below from a shell script and it works fine, > however I am at a total loss on how i can run it from within a Python > script as every option I have tried fails and it appears to be down to the > escaping of certain characters. > > wget -q www.anywebpage.com -O - | tr '\r' '\n' | tr \' \" | sed -n > 's/.*url="\([^"]*\)".*/\1/p' If your problem is getting a python string without worrying about how to escape the escape sequences, try: r"""wget -q www.anywebpage.com -O - | tr '\r' '\n' | tr \' \" | sed -n 's/.*url="\([^"]*\)".*/\1/p'""" You should be able to pass this directly to a popen() function. From AS at nospam.org Mon Feb 21 14:06:09 2005 From: AS at nospam.org (Alberto Santini) Date: Mon, 21 Feb 2005 20:06:09 +0100 Subject: Real-Time Fluid Dynamics for Games... References: <1108915754.064554.62100@z14g2000cwz.googlegroups.com> Message-ID: You can find some screenshot in the Stam's original paper. I didn't do any serious benchmark. I compared the speed of C version with the Python one. It seems enough good. I advice you to download from Stam's site paper and C code, compile the C code and verify yourself the results. I think the solver of Navier-Stokes equations is a piece of cake(remember, it's patented): one page of code or less. :) I don't like the use of global in the callback functions of OpenGL. -- Regards, Alberto Santini ha scritto nel messaggio news:1108915754.064554.62100 at z14g2000cwz.googlegroups.com... > Your two email addresses bouce emails back, so I post a shortened > version of my comment here. > I haven't installed: > PyOpenGL-2.0.2.01.py2.4-numpy23 > glut-3.7.6 > Therefore at the moment I cannot try your interesting code. > What's the speed of this Python code on your computer? > I'd like to see a screenshoot of the running Python Program... > > Some people are doing in Python some things that require lots of > computations, like: > http://www.joachim-bauch.de/projects/python/pytrace > > Bye, > Bearophile > From cepl at surfbest.net Thu Feb 10 16:46:47 2005 From: cepl at surfbest.net (cepl at surfbest.net) Date: 10 Feb 2005 13:46:47 -0800 Subject: Seekable output from ClientForm? In-Reply-To: References: <35993bcb.0502091338.34591a7@posting.google.com> Message-ID: <1108072007.643781.95100@f14g2000cwb.googlegroups.com> Thanks a lot! Matej From ajikoe at gmail.com Fri Feb 4 11:12:20 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 4 Feb 2005 08:12:20 -0800 Subject: Thread in python Message-ID: <1107533540.641969.191940@z14g2000cwz.googlegroups.com> Hello, is any one knows websites which give a python thread tutorial ? Sincerely Yours, Pujo Aji From pierre.barbier at cirad.fr Wed Feb 9 10:18:06 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Wed, 09 Feb 2005 16:18:06 +0100 Subject: multi threading in multi processor (computer) In-Reply-To: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> Message-ID: <420a2938$0$22987$626a14ce@news.free.fr> ajikoe at gmail.com a ?crit : > Hello, > > Is anyone has experiance in running python code to run multi thread > parallel in multi processor. Is it possible ? > > Can python manage which cpu shoud do every thread? > > Sincerely Yours, > Pujo > There's just no way you can use Python in a multi-processor environment, because the GIL (Global Interpreter Lock) will prevent two threads from running concurrently. When I saw this discussed, the Python developper were more into multi-process systems when it comes to multi-processors. I think I even heard some discussion about efficient inter-process messaging system, but I can't remember where :o) Hope it'll help. Pierre From schulz at sunbroy2.informatik.tu-muenchen.de Wed Feb 16 14:26:49 2005 From: schulz at sunbroy2.informatik.tu-muenchen.de (Stephan Schulz) Date: Wed, 16 Feb 2005 19:26:49 +0000 (UTC) Subject: Imported or executed? References: Message-ID: In article , Fredrik Lundh wrote: >Stephan Schulz wrote: > >> Is there a (portable, standard) way for the program/module to find out >> if it is imported or executed stand-alone? > >if a module is executed, it's name is set to "__main__". see: [...] It works. Thanks! Bye, Stephan -- -------------------------- It can be done! --------------------------------- Please email me as schulz at informatik.tu-muenchen.de (Stephan Schulz) ---------------------------------------------------------------------------- From paddy3118 at netscape.net Sat Feb 19 01:57:06 2005 From: paddy3118 at netscape.net (Paddy) Date: 18 Feb 2005 22:57:06 -0800 Subject: combining several lambda equations References: <2ae25c6b.0502180224.3d6164a7@posting.google.com> Message-ID: <1108796226.581509.148610@o13g2000cwo.googlegroups.com> Steve, Thanks for the info but I do know about that.. What I am doing is taking a set of inputted functions that don't take arguments and programmatically analysing them and combining them to create new functions that are further analysed. During testing I keep the numbers low, and am only dealing with one to two hundred equations, but real life problems could involve maybe thousands of them., (and then I'd ptobably shift to using tuples of ints or tuples of strings as 'handles' or keys to my generated functions, to convey more info on how intermediate functions are generated). Thanks again for the interest, - Paddy. From peter at engcorp.com Wed Feb 9 18:40:27 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Feb 2005 18:40:27 -0500 Subject: newbie question In-Reply-To: <1107992130.921664.68860@z14g2000cwz.googlegroups.com> References: <1107990182.516041.120410@o13g2000cwo.googlegroups.com> <1107992130.921664.68860@z14g2000cwz.googlegroups.com> Message-ID: <2qWdnT0el8ITApffRVn-oA@powergate.ca> doodle4 at gmail.com wrote: > Thanks for the reply. > > I am trying to convert some C code to python and i was not sure what > the equivalent python code would be. > > I want to postdecrement the value in the while loop. Since i cannot use > assignment in while statements is there any other way to do it in > python? Generally in Python you simply put the assignment-based statement in a "while True:" block, and use "break" to exit as required. For example, here is one way to approach it in this case: while True: n = n - 1 if n == -1: break Having written the above, however, I'm uncertain whether this sort of thing is really required in Python. Although I have ported very little C code to Python (so I might be wrong), I definitely have never seen anything resembling the above pattern in Python code that I or others have written. My suspicion is that the code involves operations which are actually better handled in Python by some kind of builtin or standard library operation. For example, often the post-decrementing is part of a pointer operation involving manipulating a string character-by-character. This is effectively never required in Python, and will pretty much always result in a program written at a much lower level than what you should be shooting for in Python. But if you want a direct port, then the above should do... -Peter From ncoghlan at iinet.net.au Sat Feb 5 21:50:53 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 06 Feb 2005 12:50:53 +1000 Subject: empty classes as c structs? In-Reply-To: References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <1gric2n.17myhon1hfrc6gN%aleaxit@yahoo.com> Message-ID: <4205860D.8000908@iinet.net.au> Steven Bethard wrote: > Nick Coghlan wrote: >> I think the idea definitely deserves mention as a possible >> implementation strategy in the generic objects PEP, with the data >> argument made optional: > > > That's basically what the current implementation does (although I use > 'update' instead of '='). The code is complicated because the > implementation also takes all the argument types that dicts take. The main difference I noticed is that by using update, any changes made via the attribute view are not reflected in the original dict. By assigning to __dict__ directly, you can use the attribute view either as it's own dictionary (by not supplying one, or supplying a new one), or as a convenient way to programmatically modify an existing one. For example, you could use it to easily bind globals without needing the 'global' keyword: Py> class attr_view(object): ... def __init__(self, data): ... self.__dict__ = data ... Py> def f(): ... gbls = attr_view(globals()) ... gbls.x = 5 ... Py> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined Py> f() Py> x 5 Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From rkern at ucsd.edu Fri Feb 25 20:57:17 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 25 Feb 2005 17:57:17 -0800 Subject: weird strings question In-Reply-To: References: Message-ID: Lucas Raab wrote: > Is it possible to assign a string a numerical value?? For example, in > the string "test" can I assign a number to each letter as in "t" = 45, > "e" = 89, "s" = 54, and so on and so forth?? Use a dictionary with the strings as keys. string2num = {} string2num['t'] = 45 string2num['e'] = 89 etc. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From grante at visi.com Thu Feb 17 11:49:37 2005 From: grante at visi.com (Grant Edwards) Date: 17 Feb 2005 16:49:37 GMT Subject: newbie question - iterating through dictionary object References: <1108656866.128912.109800@f14g2000cwb.googlegroups.com> Message-ID: <4214cb21$0$44602$a1866201@visi.com> On 2005-02-17, mirandacascade at yahoo.com wrote: > 1) Is there any advantage to use the > > y = a.keys() > for z in y: > > looping technique rather than the > > for x in a: > > looping technique? Not really. > 2) What are the tradeoffs for using each of the techniques? "for x in a" can be more efficient since it allows the dictionary to return key values one at a time instead of creating a list containing all of them. For small dictionaries it won't matter. Here's another choice, that's sometimes handy: >>> d = {1:'one',2:'two',3:'three'} >>> for k,v in d.items(): .... print k,v .... 1 one 2 two 3 three >>> I wouldn't recommend this for large dictionaries. -- Grant Edwards grante Yow! RELATIVES!! at visi.com From bdesth.quelquechose at free.quelquepart.fr Tue Feb 8 16:26:09 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 08 Feb 2005 22:26:09 +0100 Subject: Loop in list. In-Reply-To: <1107874174.445345.41230@c13g2000cwb.googlegroups.com> References: <1107874174.445345.41230@c13g2000cwb.googlegroups.com> Message-ID: <42092c18$0$14115$626a14ce@news.free.fr> Jim a ?crit : > Where did this type of structure come from: > > mat = ['a' for i in range(3)] ? > > This will produce a list of three elements but > I don't see reference for it in any of the books. > Now everyone told you *what* is it, I'll (very very dumbly) answer the question : this syntax comes from Haskell. HTH !-) Bruno From aisaac0 at verizon.net Fri Feb 11 14:04:49 2005 From: aisaac0 at verizon.net (David Isaac) Date: Fri, 11 Feb 2005 19:04:49 GMT Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> <1105549514.563799.307030@z14g2000cwz.googlegroups.com> <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> <41e58244$1@nntp0.pdx.net> Message-ID: "Scott David Daniels" wrote in message news:41e58244$1 at nntp0.pdx.net: > Numarray is the future, Numeric is the "past", This statement is not obviously true. See the recent discussion on the developer lists. (Search for Numeric3.) Alan Isaac From aleaxit at yahoo.com Mon Feb 7 10:54:09 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 7 Feb 2005 16:54:09 +0100 Subject: Confused with methods References: <1grknb0.ygwohl17y6j5yN%aleaxit@yahoo.com> <1grmd4z.1tlm4e61650vedN%aleaxit@yahoo.com> Message-ID: <1grmgxm.11gq1hk2lpcurN%aleaxit@yahoo.com> John Lenton wrote: > I think __new__ being an > exception to this is a (minor) wart, in fact it feels like premature > optimization (how many __new__s do you write, that you can't stick a > @staticmethod in front of them? I personally think it's quite reasonable for Python's infrastructure to consider each special name specially -- that's what the double underscores before and after are FOR, after all. Since __new__ MUST be a staticmethod, and there's no use case for it ever being otherwise, it seems quite sensible for the default metaclass to MAKE it a staticmethod (and otherwise treat it specially, as it needs to be). I don't see what optimization has to do with it (quite apart from the fact that __new__ was introduced before the splatsyntax for decorators, so that rather than sticking anything in front the alternative would have been to demand serious boilerplate, a '__new__ = staticmethod(__new__)' after every definition of such a method). Reducing boilerplate with no ill effects whatsoever seems quite a worthy goal to me, when reachable. Alex From duncan.booth at invalid.invalid Mon Feb 7 03:57:29 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Feb 2005 08:57:29 GMT Subject: def __init__ question in a class definition References: <1107750187.3795.9.camel@batfink.its.adelaide.edu.au> Message-ID: Miki Tebeka wrote: >> IE: is there any special significance to the __ in this case. > http://docs.python.org/tut/tut.html specifically section 9.6 Also Python Reference Manual, section 2.3.2 Reserved classes of identifiers From deetsNOSPAM at web.de Fri Feb 11 16:50:45 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 11 Feb 2005 22:50:45 +0100 Subject: PyQt documentation References: <1108088253.552834.44690@z14g2000cwz.googlegroups.com> <373it0F4uglf9U1@individual.net> <1108131643.216301.92510@o13g2000cwo.googlegroups.com> <373u0qF58g57fU1@individual.net> <1108157806.674018.58490@l41g2000cwc.googlegroups.com> Message-ID: Eric Jardim wrote: > *You* may not need. But think about other people. By the way, I found 9 > "I"s on your last message. Don't be that selfish :) That's right - and it was done to express not my unarguably existing selfishness, but to strech the fact that it was my opinion that not necessarily qualifies as being "the one and only" opinion and didn't want to discourage you too much. Never try to stop volontary workers (at least not in documentation.. :) But I'd still hold the impression that your problems might stem from you wanting to code qt, before done in c++ and just by "accident" in python. All real nasty problems I ran into appeared when I tried to do things that are not complementary between python and qt (like the gui stuff) but in the common subset. My troubles once came from using QThread (made my app totally crash). QText*Stream plays for me in the same league: python itself is perfectly capable of reading and writing data to disk/memory/your wallpaper. So being a pythoneer, it never occured to me to use QText*Streams :) No having said that, I totally agree that such information is surely needed - but I doubt that it really makes sense to create full docs at a api level. It would be hard to be in sync with the qt development itself. Instead a wiki which captures the various pitfalls would be cool. And it appears it exists: http://www.diotavelli.net/PyQtWiki So maybe enhancing that would be an option for you? -- Regards, Diez B. Roggisch From irmen.NOSPAM at xs4all.nl Wed Feb 2 17:27:23 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 02 Feb 2005 23:27:23 +0100 Subject: Getting a module's byte code, how? In-Reply-To: References: <42014e25$0$28975$e4fe514c@news.xs4all.nl> Message-ID: <420153cb$0$28984$e4fe514c@news.xs4all.nl> Mark Nenadov wrote: > On Wed, 02 Feb 2005 23:03:17 +0100, Irmen de Jong wrote: > > >>What would be the best way, if any, to obtain >>the bytecode for a given loaded module? >> >>I can get the source: >>import inspect >>import os >>src = inspect.getsource(os) >> >>but there is no ispect.getbytecode() ;-) >> >>--Irmen > > > The inspect API documentation says that code objects have "co_code", which > is a string of raw compiled bytecode. > > Hope that helps! Not very much, sorry. Because we now changed the problem into: "how to obtain the code object from a module". Perhaps a bit of background is in order. For Pyro, I'm sending module byte codes across the wire if the other side needs it (the mobile code feature). However, this only works for modules that can be loaded from a file on disk (because I'm now reading the .pyc file that belongs to the module). When the receiving end in turn calls another Pyro object, it may have to send the module's bytecode again-- but that is no longer possible because the module has no associated file anymore! (It is considered to be a builtin module) But because it is *loaded*, there must be some way to get to the bytecodes, right? --Irmen From guru.slt at gmail.com Thu Feb 10 13:11:59 2005 From: guru.slt at gmail.com (xiaobin yang) Date: Thu, 10 Feb 2005 13:11:59 -0500 Subject: Python v.s. c++ Message-ID: Hi, if i am already skillful with c++. Is it useful to learn python? thanks! From Scott.Daniels at Acm.Org Thu Feb 24 10:37:52 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 24 Feb 2005 07:37:52 -0800 Subject: Dynamically pass a function arguments from a dict In-Reply-To: References: Message-ID: <421df0aa$1@nntp0.pdx.net> Mark McEahern wrote: > Dan Eloff wrote: >> How can you determine that func2 will only accept >> bar and zoo, but not foo and call the function with >> bar as an argument? > > Let Python answer the question for you: > > ... Please be aware the "normal" way to do this is go ahead and call the function. Many "function wrapping" techniques will fail this test, and often the code that looks into the guts of a call in order to do "something clever" will fail when it is pointed at anything that uses the technique. Not only does curry: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 not show you what args it accepts, but decorators, a Python 2.4 invention, will typically obscure the interface of the decorated function. Since they wrap _any_ function call, they typically take the most general arguments possible in order to accommodate the widest range of functions to wrap. --Scott David Daniels Scott.Daniels at Acm.Org From frans.englich at telia.com Sun Feb 13 20:13:32 2005 From: frans.englich at telia.com (Frans Englich) Date: Mon, 14 Feb 2005 01:13:32 +0000 Subject: Kill GIL In-Reply-To: References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <86sm405d38.fsf@guru.mired.org> Message-ID: <200502140113.32408.frans.englich@telia.com> On Monday 14 February 2005 00:53, Aahz wrote: > In article <86sm405d38.fsf at guru.mired.org>, Mike Meyer wrote: > >aahz at pythoncraft.com (Aahz) writes: > >> In article <868y5t6sal.fsf at guru.mired.org>, Mike Meyer wrote: > >>>Here here. I find that threading typically introduces worse problems > >>>than it purports to solve. > >> > >> Threads are also good for handling blocking I/O. > > > >Actually, this is one of the cases I was talking about. I find > >it saner to convert to non-blocking I/O and use select() for > >synchronization. That solves the problem, without introducing any of > >the headaches related to shared access and locking that come with > >threads. > > It may be saner, but Windows doesn't support select() for file I/O, and > Python's threading mechanisms make this very easy. If one's careful > with application design, there should be no locking problems. (Have you > actually written any threaded applications in Python?) Hehe.. the first thing a google search on "python non-blocking io threading" returns "Threading is Evil". Personally I need a solution which touches this discussion. I need to run multiple processes, which I communicate with via stdin/out, simultaneously, and my plan was to do this with threads. Any favorite document pointers, common traps, or something else which could be good to know? Cheers, Frans From mahs at telcopartners.com Sun Feb 13 18:40:57 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sun, 13 Feb 2005 15:40:57 -0800 Subject: Iterator / Iteratable confusion In-Reply-To: <200502131958.27410.francis.girard@free.fr> References: <420a5c1e$0$21630$a1866201@visi.com> <200502131848.03655.francis.girard@free.fr> <200502131958.27410.francis.girard@free.fr> Message-ID: Francis Girard wrote: > """ > ================================================================================ > Example 8 > ================================================================================ > Running after your tail with itertools.tee > > > The beauty of it is that recursive running after their tail FP algorithms > are quite straightforwardly expressed with this Python idiom. > """ > > def Ex8_Fibonacci(): > print "Entering Ex8_Fibonacci" > def _Ex8_Fibonacci(): > print "Entering _Ex8_Fibonacci" > yield 1 > yield 1 > fibTail.next() # Skip the first one > for n in (head + tail for (head, tail) in izip(fibHead, fibTail)): > yield n > fibHead, fibTail, fibRes = tee(_Ex8_Fibonacci(), 3) > return fibRes > > print > print sEx8Doc > print > print list(islice(Ex8_Fibonacci(), 5)) > Absolutely: ever since you brought up the Hamming sequence I've been interested in this approach. However, if iterators could be extended in place, these solutions would be even more attractive. Here are some examples for infinite series constructed with an extendable iterator. This iterator is returned by an iterable class 'Stream', shown below the examples: def factorial(): """ >>> f = factorial() >>> f.tolist(10) [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] """ factorial = Stream([1]) factorial.extend(factorial * it.count(1)) return factorial def fib(): """Example: >>> f = fib() >>> f.tolist(10) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]""" fib = Stream([1,1]) fib.extend(x+y for x, y in it.izip(fib, fib[1:])) return fib def multimerge(*iterables): """Yields the items in iterables in order, without duplicates""" cache = {} iterators = map(iter,iterables) number = len(iterables) exhausted = 0 while 1: for it in iterators: try: cache.setdefault(it.next(),[]).append(it) except StopIteration: exhausted += 1 if exhausted == number: raise StopIteration val = min(cache) iterators = cache.pop(val) yield val def hamming(): """ Example: >>> h = hamming() >>> list(h[20:40]) [40, 45, 48, 50, 54, 60, 64, 72, 75, 80, 81, 90, 96, 100, 108, 120, 125, 128, 135, 144] >>> h[10000] 288555831593533440L """ hamming = Stream([1]) hamming.extend(i for i in multimerge(2 * hamming, 3 * hamming, 5 * hamming)) return hamming def compounds(): """Extension of Hamming series to compounds of primes(2..13) Example: >>> c = compounds() >>> list(c[20:30]) [24, 25, 26, 27, 28, 30, 32, 33, 35, 36]""" compounds = Stream([1]) compounds.extend(i for i in multimerge(2 * compounds, 3 * compounds, 5 * compounds, 7 * compounds, 9 * compounds, 11 * compounds, 13 * compounds)) return compounds # Stream class for the above examples: import itertools as it import operator as op class Stream(object): """Provides an indepent iterator (using tee) on every iteration request Also implements lazy iterator arithmetic""" def __init__(self, *iterables, **kw): """iterables: tuple of iterables (including iterators). A sequence of iterables will be chained kw: not used in this base class""" self.queue = list(iterables) self.itertee = it.tee(self._chain(self.queue))[0] # We may not need this in every case def extend(self,other): """extend(other: iterable) => None appends iterable to the end of the Stream instance """ self.queue.append(other) def _chain(self, queue): while queue: for i in self.queue.pop(0): self.head = i yield i # Iterator methods: def __iter__(self): """Normal iteration over the iterables in self.queue in turn""" return self.itertee.__copy__() def _binop(self,other,op): """See injected methods - __add__, __mul__ etc..""" if hasattr(other,"__iter__"): return (op(i,j) for i, j in it.izip(self,other)) else: return (op(i,other) for i in self) def __getitem__(self,index): """__getitem__(index: integer | slice) index: integer => element at position index index: slice if slice.stop is given => Stream(it.islice(iter(self), index.start, index.stop, index.step or 1))) else: consumes self up to start then => Stream(iter(self)) Note slice.step is ignored in this case """ if isinstance(index, slice): if index.stop: return (it.islice(iter(self), index.start or 0, index.stop, index.step or 1)) else: iterator = iter(self) for i in range(index.start): iterator.next() return iterator else: return it.islice(iter(self), index,index+1).next() def getattr(self,attrname): """__getattr__/getattr(attrname: string) => Stream(getattr(item,attrname) for item in self) Use the getattr variant if the attrname is shadowed by the Stream class""" return (getattr(item,attrname) for item in self) __getattr__ = getattr # Representational methods def tolist(self, maxlen = 100): return list(it.islice(iter(self),maxlen)) def __repr__(self): return "Stream instance at:%x: %s" % (id(self), repr(self.queue)) # Inject special methods for binary operations: _binopdoc = """%(func)s(other: constant | iterable, op: binary function) other: constant => Stream(op.%(op)s(i,other) for i in self)) other: iterable => Stream(op.%(op)s(i,j) for i, j in it.izip(self,other)) """ [setattr(Stream,attr, func(argspec = "self, other", expr = "self._binop(other, op.%s)" % opfunc, doc=_binopdoc % {"func":attr, "op":opfunc}, name=attr) ) for attr, opfunc in { "__mul__":"mul", "__add__":"add", "__sub__":"sub", "__div__":"div", "__mod__":"mod", "__pow__":"pow", }.items() ] # End inject special methods From bj_666 at gmx.net Wed Feb 2 12:37:03 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 02 Feb 2005 18:37:03 +0100 Subject: "pickle" vs. f.write() References: <41FF70A5.8070806@tx3.com> Message-ID: In <41FF70A5.8070806 at tx3.com>, Martin Miller wrote: > I've found extending this property to your own classes often fairly easy > to implement (and useful). For example: > >> class person: >> def __init__(self, name="", age=0, friends=None, comment=""): >> if friends is None: >> friends = [] >> self.name, self.age, self.friends, self.comment = name, age, friends, comment >> >> def __repr__(self): >> return ("person(" + repr(self.name) + ", " + repr(self.age) + ", " + >> repr(self.friends) + ", " + repr(self.comment) + ")") I write __repr__() methods similar but I think a bit more readable: def __repr__(self): return "%s(%r, %r, %r, %r)" % (self.__class__.__name__, self.name, self.age, self.friends, self.comment) And it's robust against changing the class name. It even works in subclasses if the signature of the __init__() method stays the same. Ciao, Marc 'BlackJack' Rintsch From steven.bethard at gmail.com Fri Feb 4 14:17:24 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 04 Feb 2005 12:17:24 -0700 Subject: empty classes as c structs? In-Reply-To: References: Message-ID: <7rSdne7BcbDeV57fRVn-jg@comcast.com> Christopher J. Bottaro wrote: > I find myself doing the following very often: > > class Struct: > pass > ... > blah = Struct() > blah.some_field = x > blah.other_field = y > ... > > Is there a better way to do this? Yes -- help me rally behind my generic object PEP which proposes a Bunch type (probably to be renamed) for the Python standard lib. =) With this type, you could write your code as: blah = Bunch() blah.some_field = x blah.other_field = y or simply: blah = Bunch(some_field=x, other_field=y) I requested a PEP number on 2 Jan 2005, but haven't heard back yet. However, you can see a recent draft of the PEP at: http://mail.python.org/pipermail/python-list/2005-January/262201.html and you can see the first version of the patch at: http://sourceforge.net/tracker/?func=detail&atid=305470&aid=1094542&group_id=5470 If you'd like to use the Bunch type now (instead of waiting for a future version of Python, assuming it's accepted), the current code for the Bunch class follows. STeVe ---------------------------------------------------------------------- # Copyright (c) 2004 Python Software Foundation. # All rights reserved. # Written by Steven Bethard import operator as _operator class Bunch(object): """Bunch([bunch|dict|seq], **kwds) -> new bunch with specified attributes The new Bunch object's attributes are initialized from (if provided) either another Bunch object's attributes, a dictionary, or a sequence of (name, value) pairs, then from the name=value pairs in the keyword argument list. Example Usage: >>> Bunch(eggs=1, spam=2, ham=3) Bunch(eggs=1, ham=3, spam=2) >>> Bunch({'eggs':1, 'spam':2, 'ham':3}) Bunch(eggs=1, ham=3, spam=2) >>> Bunch([('eggs',1), ('spam',2), ('ham',3)]) Bunch(eggs=1, ham=3, spam=2) >>> Bunch(Bunch(eggs=1, spam=2), ham=3) Bunch(eggs=1, ham=3, spam=2) """ def __init__(*args, **kwds): """Initializes a Bunch instance.""" Bunch.update(*args, **kwds) def __eq__(self, other): """x.__eq__(y) <==> x == y Two Bunch objects are considered equal if they have the same attributes and the same values for each of those attributes. """ return (other.__class__ == self.__class__ and self.__dict__ == other.__dict__) def __repr__(self): """x.__repr__() <==> repr(x) If all attribute values in this bunch (and any nested bunches) are reproducable with eval(repr(x)), then the Bunch object is also reproducable for eval(repr(x)). """ return '%s(%s)' % (self.__class__.__name__, ', '.join('%s=%r' % (k, v) for k, v in self.__dict__.items())) @staticmethod def update(*args, **kwargs): """update(bunch, [bunch|dict|seq,] **kwargs) -> None Updates the first Bunch object's attributes from (if provided) either another Bunch object's attributes, a dictionary, or a sequence of (name, value) pairs, then from the name=value pairs in the keyword argument list. """ if not 1 <= len(args) <= 2: raise TypeError('expected 1 or 2 arguments, got %i' % len(args)) self = args[0] if not isinstance(self, Bunch): raise TypeError('first argument to update should be Bunch, ' 'not %s' % type(self).__name__) if len(args) == 2: other = args[1] if isinstance(other, Bunch): other = other.__dict__ try: self.__dict__.update(other) except (TypeError, ValueError): raise TypeError('cannot update Bunch with %s' % type(other).__name__) self.__dict__.update(kwargs) From bill.mill at gmail.com Fri Feb 4 14:58:46 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 4 Feb 2005 14:58:46 -0500 Subject: string issue In-Reply-To: References: <36QMd.103084$Jk5.36127@lakeread01> Message-ID: <797fe3d40502041158288c8a0a@mail.gmail.com> On Fri, 04 Feb 2005 14:43:30 -0500, rbt wrote: > Steve Holden wrote: > > rbt wrote: > > > >> Either I'm crazy and I'm missing the obvious here or there is > >> something wrong with this code. Element 5 of this list says it doesn't > >> contain the string 255, when that's *ALL* it contains... why would it > >> think that??? > >> > >> import time > >> > >> ips = ['255.255.255.255', '128.173.120.79', '198.82.247.98', > >> '127.0.0.1', '255.0.0.0', '255', '128.173.255.34'] > >> > >> for ip in ips: > >> if '255' in ip: > >> try: > >> print "Removing", ip > >> ips.remove(ip) > >> except Exception, e: > >> print e > >> > >> print ips > >> time.sleep(5) > >> > >> Someone tell me I'm going crazy ;) > > > > > > You are modifying the list as you iterate over it. Instead, iterate over > > a copy by using: > > > > for ip in ips[:]: > > ... > > > > regards > > Steve > > Very neat. That's a trick that everyone should know about. I vote it > goes in Dr. Dobbs newsletter. Once you know it, it's neat, and I use it sometimes. However, it's a little too "magical" for my tastes; I'd rather be more explicit about what's going on. Peace Bill Mill bill.mill at gmail.com > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at myplace.com Mon Feb 21 17:31:17 2005 From: steve at myplace.com (Steve M) Date: Mon, 21 Feb 2005 16:31:17 -0600 Subject: Tuple index References: <1108951559.490554.305310@l41g2000cwc.googlegroups.com> Message-ID: Steven Bethard wrote: > Steve M wrote: >> I'm actually doing this as part of an exercise from a book. What the >> program is supposed to do is be a word guessing game. The program >> automaticly randomly selects a word from a tuple. You then have the >> oportunity to ask for a hint. I created another tuple of hints, where the >> order of the hints correspond to the word order. I was thinking if I >> could get the index position of the randomly selected word, I pass that >> to the hints tuple to display the correct hint from the hints tuple. I'm >> trying to do it this way as the book I'm using has not gotten to lists >> yet. > > I'm guessing it also hasn't gotten to dicts yet either? Perhaps a > somewhat more natural way of doing this would be something like: > > py> hints = dict(word1="here's hint 1!", > ... word2="here's hint 2!", > ... word3="here's hint 3!") > py> words = list(hints) > py> import random > py> selected_word = random.choice(words) > py> selected_word > 'word3' > py> print hints[selected_word] > here's hint 3! > > That said, if you want to find the index of a word in a tuple without > using list methods, here are a couple of possibilities, hopefully one of > which matches the constructs you've seen so far: > > py> t = ("fred", "barney", "foo") > > py> for i, word in enumerate(t): > ... if word == "barney": > ... break > ... > py> i > 1 > > py> for i in range(len(t)): > ... if t[i] == "barney": > ... break > ... > py> i > 1 > > py> i = 0 > py> for word in t: > ... if word == "barney": > ... break > ... i += 1 > ... > py> i > 1 > > HTH, > > STeVe Thanks Steve, I'll see if I can make that solution work for me. Steve From steven.bethard at gmail.com Thu Feb 17 11:50:29 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 17 Feb 2005 09:50:29 -0700 Subject: difference between class methods and instance methods In-Reply-To: <1119eklfad9v292@corp.supernews.com> References: <1119eklfad9v292@corp.supernews.com> Message-ID: John wrote: > Steven Bethard wrote: >> John M. Gabriele wrote: >> class C(object): >> @classmethod >> def f(cls, *args): >> # do stuff > > Sorry -- I'm not as far along as you suspect. :) I've > never yet seen this "@classmethod" syntax. I'm supposing that > it's part of this so-called "new-style" class syntax. This is syntactic sugar in Python 2.4 for: class C(object): def f(cls, *args): # do stuff f = classmethod(f) So if you'd like to check the docs, look in the builtins for classmethod (and staticmethod): http://docs.python.org/lib/built-in-funcs.html > From your reply, I gather that, unless I'm using this special > syntax (@classmethod or @staticmethod), all my def's are supposed > to take 'self' as their first arg. Yup. You're of course welcome to name it whatever you like, but the methods defined in your class (when not wrapped with classmethod, staticmethod, etc.) will all be called with an instance of the class as their first argument. So you need to make sure 'self' or something like it is the first parameter to the function. > So then, are all def's -- that take 'self' as their first -- > argument -- in a class statement, instance methods? Basically, yes. (Again, assuming they're not wrapped with anything.) >> Consider the difference between str.join and ''.join: >> >> py> str.join >> > > > >> py> ', '.join >> > > > > Hmm... weird. Ok, the point here is that str.join and ', '.join are not the same object. The reason is that, when the ', ' instance of str is created, new "bound method" objects are created for each of the instance methods in str. These "bound methods" all know that the first argument to their functions is ', '. >> py> ', '.join(['a', 'b', 'c']) >> 'a, b, c' > > Check. > >> py> str.join(', ', ['a', 'b', 'c']) >> 'a, b, c' > [snip] > What's happening here? str.join is the "unbound method" of the str object. So just like you have to declare 'self' as the first argument of all your instance methods, the writer of the str object methods also declared 'self' as the first argumetn to str.join. So str.join looks something like: class str(object): ... def join(self, sequence): ... So when you access it like str.join(...) you should be passing it an instance and a sequence. On the other hand, the "bound method" created for ', ' has already bound the instance, so it no longer expects the 'self' argument to be passed in. HTH, STeVe From jepler at unpythonic.net Sun Feb 6 15:43:07 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 6 Feb 2005 14:43:07 -0600 Subject: [noob] Questions about mathematical signs... In-Reply-To: <614c778e.0502061226.5f40244c@posting.google.com> References: <614c778e.0502061226.5f40244c@posting.google.com> Message-ID: <20050206204306.GC16104@unpythonic.net> On Sun, Feb 06, 2005 at 12:26:30PM -0800, administrata wrote: > Hi! I'm programming maths programs. > And I got some questions about mathematical signs. > > 1. Inputing suqare like a * a, It's too long when I do time-consuming > things. Can it be simplified? You can write powers with the "**" operator. In this case, a ** 2 > 2. Inputing fractions like (a / b) + (c / d), It's tiring work too. > Can it be simplified? Because of the rules of operator precedence, a / b + c / d has the same meaning as the expression you gave. > 3. How can i input root? Assuming that you've already executed import math Here are some ways to find the square root of a number: math.sqrt(4) 4 ** .5 math.pow(4, .5) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From fredrik at pythonware.com Mon Feb 7 18:34:13 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Feb 2005 00:34:13 +0100 Subject: Modifying the global modules included with the distribution References: Message-ID: Justin Standard wrote: > I'm trying to make some small modifications to the xml.dom.minidom > module. I'm developing on windows (since I have to at work), and I > located the .py files which represent the module in the Python23/Lib > directory, I made my changes to the file: > Python/Lib/xml/dom/minidom.py. However, when I run the interpreter, > my changes aren't reflected. Python23/Lib or Python/Lib ? are you sure you know what you're editing? if you're not 100% sure, import the module, and print its __file__ attribute: >>> import xml.dom.minidom >>> xml.dom.minidom.__file__ '/somewhere/python24/lib/xml/dom/minidom.pyc' edit the corresponding PY file. if the PYC path looks suspicious, remove the PYC file and try again. > Do I need to rebuild python to make these changes take? no. > Or is there some other process to modify global modules. I realize that > I _could_ have extended it, but this _seemed_ easier, and the work is already > done. and will be lost when you update Python, move your script to another platform, etc. From steve at holdenweb.com Wed Feb 2 09:38:03 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 02 Feb 2005 09:38:03 -0500 Subject: Hey, get this! [was: import from database] In-Reply-To: References: Message-ID: <4200E5CB.6020508@holdenweb.com> Steve Holden wrote: > Peter Otten wrote: > >> Steve Holden wrote: >> >> >>> This is even stranger: it makes it if I import the module a second time: >> >> >> >> [second import seems to succeed] >> >> Maybe you are experiencing some version confusion? What you describe >> looks >> much like the normal Python 2.3 behaviour (with no import hook involved) >> whereas you seem to operate on the 2.4 library. >> A partially initialized module object is left behind in sys.modules >> and seen >> by further import attempts. >> > I agree that this is 2.3-like behavior, but Python cannot lie ... > > sholden at dellboy ~/Projects/Python/dbimp > $ python > Python 2.4 (#1, Dec 4 2004, 20:10:33) > [GCC 3.3.3 (cygwin special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>> > Just to make things simpler, and (;-) to appeal to a wider audience, here is a program that doesn't use database at all (it loads the entire standard library into a dict) and still shows the error. What *I* would like to know is: who is allowing the import of bsddb.os, thereby somehow causing the code of the os library module to be run a second time. # # Establish standard library in dict # import os import glob import sys import marshal import new def importpy(dct, path, modname, package): c = compile(file(path).read(), path, "exec") dct[modname] = (marshal.dumps(c), package, path) if package: print "Package", modname, path else: print "Module", modname, path def importall(dct, path, modlist): os.chdir(path) for f in glob.glob("*"): if os.path.isdir(f): fn = os.path.join(path, f, "__init__.py") if os.path.exists(fn): ml = modlist + [f] importpy(dct, fn, ".".join(ml), 1) importall(dct, os.path.join(path, f), ml) elif f.endswith('.py') and '.' not in f[:-3] and f != "__init__.py": importpy(dct, os.path.join(path, f), ".".join(modlist+[f[:-3]]), 0) class dbimporter(object): def __init__(self, item, *args, **kw): ##print "dbimporter: item:", item, "args:", args, "keywords:", kw if item != "*db*": raise ImportError print "Accepted", item def find_module(self, fullname, path=None): print "find_module:", fullname, "from", path if fullname not in impdict: #print "Bailed on", fullname return None else: print "found", fullname, "in db" return self def load_module(self, modname): print "load_module:", modname if modname in sys.modules: return sys.modules[modname] try: row = impdict[modname] except KeyError: #print modname, "not found in db" raise ImportError, "DB module %s not found in modules" code, package, path = row code = marshal.loads(code) module = new.module(modname) sys.modules[modname] = module module.__name__ = modname module.__file__ = path # "db:%s" % modname module.__loader__ = dbimporter if package: module.__path__ = sys.path exec code in module.__dict__ print modname, "loaded:", repr(module), "pkg:", package return module def install(): sys.path_hooks.append(dbimporter) sys.path_importer_cache.clear() # probably not necessary sys.path.insert(0, "*db*") # probably not needed with a metea-path hook? if __name__ == "__main__": impdict = {} for path in sys.argv[1:]: importall(impdict, path, []) install() import bsddb Running this against a copy of the Python 2.4 standard library in C:\Lib gives me [...] Module _strptime C:\Lib\_strptime.py Module _threading_local C:\Lib\_threading_local.py Module __future__ C:\Lib\__future__.py Accepted *db* find_module: bsddb from None found bsddb in db load_module: bsddb find_module: bsddb._bsddb from None find_module: bsddb.sys from None find_module: bsddb.os from None find_module: bsddb.nt from None find_module: bsddb.ntpath from None find_module: bsddb.stat from None Traceback (most recent call last): File "C:\Steve\Projects\Python\dbimp\dictload.py", line 79, in ? import bsddb File "C:\Steve\Projects\Python\dbimp\dictload.py", line 65, in load_module exec code in module.__dict__ File "C:\Lib\bsddb\__init__.py", line 62, in ? import sys, os File "C:\Python24\lib\os.py", line 133, in ? from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep, ImportError: No module named path The 2.3 bsddb library doesn't cause the same problems (and even loads into 2.4 quite nicely). Lots of modules *will* import, and most packages don't seem to cause problems. Anyone give me a pointer here? regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.python.org/pycon/2005/ Steve Holden http://www.holdenweb.com/ From luismgz at gmail.com Mon Feb 7 02:01:10 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 6 Feb 2005 23:01:10 -0800 Subject: WYSIWYG wxPython "IDE"....? In-Reply-To: <1107751731.066796.295170@g14g2000cwa.googlegroups.com> References: <1107560658.584623.303310@o13g2000cwo.googlegroups.com> <4205fcd9@news.highway1.com.au> <1107751731.066796.295170@g14g2000cwa.googlegroups.com> Message-ID: <1107757798.707326.137480@l41g2000cwc.googlegroups.com> Try PythonCard. Very simple, very easy and based on wxPython. From administrata at hotmail.com Sun Feb 6 15:26:30 2005 From: administrata at hotmail.com (administrata) Date: 6 Feb 2005 12:26:30 -0800 Subject: [noob] Questions about mathematical signs... Message-ID: <614c778e.0502061226.5f40244c@posting.google.com> Hi! I'm programming maths programs. And I got some questions about mathematical signs. 1. Inputing suqare like a * a, It's too long when I do time-consuming things. Can it be simplified? 2. Inputing fractions like (a / b) + (c / d), It's tiring work too. Can it be simplified? 3. How can i input root? thx 4 reading :) From jacek.generowicz at cern.ch Tue Feb 1 05:30:26 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 01 Feb 2005 11:30:26 +0100 Subject: Python's idiom for function overloads References: <41ff066c$0$6473$636a15ce@news.free.fr> Message-ID: "F. GEIGER" writes: > As Philippe already said, use objects that support the protocol or decide > what to do with it after having checked its type. I do that, if I have to, > like so: > > 1 def doIt(arg): > 2 if type(arg) == type([]): > 3 map(doIt, arg) > 4 else: > 5 # Do it on a scalar type > 6 # ... > 7 return result Now, consider that line 3 would execute very happily if the type of arg were 1) list, 2) str, 3) tuple, 4) dict, 5) file, 6) any other built-in iterable or sequence, 7) any useer-defined iterable or sequence, 8) a subclass of any of the above, 9) god knows what else ... ... yet in line 2 you have ensured that the whole function will not work properly for any of the listed types other than the first. You could make the code much more general by doing it like this: try: map(doIt, arg) except TypeError: ... The important thing to note is that the actual types of Python objects are usually not very interesting or important at all. What is much more important is what the object is able to do: what messages it understands, what protocols it supports. Hiding some code behind a type-check, in Python, is quite frequently the wrong thing to do. From just at xs4all.nl Sat Feb 26 15:59:40 2005 From: just at xs4all.nl (Just) Date: Sat, 26 Feb 2005 21:59:40 +0100 Subject: any Python equivalent of Math::Polynomial::Solve? References: Message-ID: In article , jgamble at ripco.com (John M. Gamble) wrote: > >> The > >> original source for the algorithm used in the module is > >> from Hiroshi Murakami's Fortran source, and it shouldn't > >> be too difficult to repeat the translation process to python. > > > >Ah ok, I'll try to locate that (following the instruction in Solve.pm > >didn't work for me :( ). > > > > Ouch. I just did a quick search and found that that site has undergone > a few changes, and the code that i reference is missing. A few other > links in the docs are stale too. I need to update the documentation. > > Anyway, doing a search for 'hqr' and Eispack got me a lot of sites. > In particular, this one is pretty friendly: > > > > Look at the source for balanc.f (does the prep-work) and hqr.f > (does the solving). Minor annoyance: the real and imaginary > parts of the roots are in separate arrays. I combined them into > complex types in my perl source, in case you want to make a > comparison. Thanks! I'll check that out. > Of course, all this may be moot if the other suggestions > work out. SciPy indeed appear to contain a solver, but I'm currently stuck in trying to _get_ it for my platform (OSX). I'm definitely not going to install a Fortran compiler just to evaluate it (even though my name is not "Ilias" ;-). Also, SciPy is _huge_, so maybe a Python translation of that Fortran code or your Perl code will turn out to be more attractive after all... Just From xah at xahlee.org Wed Feb 16 04:16:50 2005 From: xah at xahlee.org (Xah Lee) Date: 16 Feb 2005 01:16:50 -0800 Subject: problem: reducing comparison In-Reply-To: <1108471704.220626.27530@g14g2000cwa.googlegroups.com> References: <1108450348.253772.158120@z14g2000cwz.googlegroups.com> <1108471704.220626.27530@g14g2000cwa.googlegroups.com> Message-ID: <1108545410.285927.153320@c13g2000cwb.googlegroups.com> ?someone sent me the following code, which performs identically with the original reduce. (tested for pairings of comb(n) with large n) Superb. ? ?def reduce2( pairings, pair ): ? result={} ? for i,j in pairings.itervalues(): ? if i in pair: i=pair[0] ? if j in pair: j=pair[0] ? if i>j: (i,j) = (j,i) ? if i!=j: result["%d,%d"%(i,j)] = (i,j) ? return result ? ? ?def reduce(pairings, pair): ? ps=pairings.copy(); j=pair; ? ps.pop("%d,%d"%(j[0],j[1]),0) ? for k in pairings.itervalues(): ? if (k[0]==j[0]): ? if (j[1] < k[1]): ? ps.pop("%d,%d"%(j[1],k[1]),0) ? else: ? ps.pop("%d,%d"%(k[1],j[1]),0) ? if (k[1]==j[0]): ? if (k[0] < j[1]): ? ps.pop("%d,%d"%(k[0],j[1]),0) ? else: ? ps.pop("%d,%d"%(j[1],k[0]),0) ? return ps ? ?is reduce2 more efficient? It works entirely differently. I'll have to think about it... besides algorithmic... onto the minute academic diddling, i wonder if it is faster to delete entries in dict or add entries... Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html Xah Lee wrote: > here are the answers: > > Perl code: > > sub reduce ($$) { > my %hh= %{$_[0]}; # e.g. {'1,2'=>[1,2],'5,6'=>[5,6],...} > my ($j1,$j2)=($_[1]->[0],$_[1]->[1]); # e.g. [3,4] > delete $hh{"$j1,$j2"}; > foreach my $k (keys %hh) { > $k=~m/^(\d+),(\d+)$/; > my ($k1,$k2)=($1,$2); > if ($k1==$j1) { > if ($j2 < $k2) { > delete $hh{"$j2,$k2"}; > } > else { > delete $hh{"$k2,$j2"}; > }; > }; > if ($k2==$j1) { > if ($k1 < $j2) { > delete $hh{"$k1,$j2"}; > } > else { > delete $hh{"$j2,$k1"}; > }; > }; > } > return \%hh; > } > > ... > In imperative languages such as Perl and Python and Java, in general it > is not safe to delete elements when looping thru a list-like entity. > (it screws up the iteration) One must make a copy first, and work with > the copy. > > Note also that in Python there's already a function called reduce. (it > is equivalent to Mathematica's Fold.) In Python, looks like user can > over-ride default functions. > > This post is archived at > http://xahlee.org/perl-python/pairing_reduce.html > Possible errata or addenda will appear there. > > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html From faassen at infrae.com Mon Feb 7 10:50:41 2005 From: faassen at infrae.com (Martijn Faassen) Date: Mon, 07 Feb 2005 16:50:41 +0100 Subject: [EVALUATION] - E01: The Java Failure - May Python Helps? In-Reply-To: <1grk4ll.s9ln0u1bpp7huN%aleaxit@yahoo.com> References: <1grk4ll.s9ln0u1bpp7huN%aleaxit@yahoo.com> Message-ID: <42078E51.2010808@infrae.com> Alex Martelli wrote: > Fredrik Lundh wrote: > > >>Markus Wankus wrote: >> >> >>>Google his name - he has been banned from Netbeans and Eclipse (and >>>Hibernate, and others...) for good reason. Can you imagine how much of >>>a Troll you need to be to *actually* get "banned" from the newsgroups of >>>open source projects such as those? >> >>have Pythoneers ever "banned" anyone from a public forum? it's not like >>we haven't seen trolls and crackpots before, you know. > > > I don't see how banning is technically possible in unmoderated groups. > Shunning, or pelting the troll with abuse whenever he shows up, etc, > etc, sure. But, banning? The PSU can do it, by modifying the time stream. This is done by simply readjusting the basic parameter of the From tonino.greco at gmail.com Mon Feb 14 06:51:21 2005 From: tonino.greco at gmail.com (Tonino) Date: 14 Feb 2005 03:51:21 -0800 Subject: gui scripting Message-ID: <1108381881.828494.98340@c13g2000cwb.googlegroups.com> HI, I have a 2 phase question: Phase 1 is I am needing to automate a report generation from a proprietary product. Currently a person sits and input's the data into a GUI frontend and clicks's the appropriate buttons to start the report generation. What I am wanting todo is automate this, but since the GUI is from a proprietary product all I have is the GUI. This is done on a Linux Xfree server. Can anyone please point me in a direction to a pythonic gui scripting module ? Python is the best tool and we use it elsewhere - so it is the best option. Second phase will have this done on a Windows platform... but that is second priority ... Thanks From peter at engcorp.com Wed Feb 9 18:35:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Feb 2005 18:35:11 -0500 Subject: negative integer division In-Reply-To: <420a9c7b$0$21598$a1866201@visi.com> References: <4208039c$0$28559$8fcfb975@news.wanadoo.fr> <42096EAD.879E8A5F@yahoo.com> <86wtti76cp.fsf@guru.mired.org> <420A916C.94F7F175@yahoo.com> <420a9513$0$29477$a1866201@visi.com> <420A98C7.103157A@yahoo.com> <420a9c7b$0$21598$a1866201@visi.com> Message-ID: Grant Edwards wrote: > This is pretty much completely off-topic now. :) No discussion of how lame other languages are is ever completely off-topic in comp.lang.python. After all, these discussions continue to remind us how lucky we all are to be able to program in Python, and that can only be a good thing. ;-) -Peter From ajsiegel at optonline.com Wed Feb 9 20:42:53 2005 From: ajsiegel at optonline.com (Arthur) Date: Wed, 09 Feb 2005 20:42:53 -0500 Subject: Vectors in Visual Python References: <1107944975.498403.225950@f14g2000cwb.googlegroups.com> <1grqqa2.1cnkkbv1l5mrrxN%aleaxit@yahoo.com> Message-ID: On Thu, 10 Feb 2005 00:16:05 +0100, aleaxit at yahoo.com (Alex Martelli) wrote: > Having found out how to >build a lasting killfile, I'd like to see if using it liberally on >people who appear to post here just to provoke flamewars, rather than to >offer and receive help, and participate in interesting discussion, can You are an accomplished provocateur. It is true that I joined the variable declaration discussion without the intent of offering or receiving help. I joined it actually to try to make a point that I thought was community spirited - thinking that the visciousness with wihich you were attacking someone suggesting a proposal for an optional feature - even if an iill adivised proposal for and ill advised optional feature (I frankly don't care much about that part of the discussion one way or another) - was unwarranted, and more importantly *unwise* for someone in a postion of community leadership - considering past, recent, and undoubtedly future issues that have and will arise. What don't *you* understand about that?? We all have are own kinds of stupidities, it seems to me. Art From kent37 at tds.net Mon Feb 14 20:52:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Feb 2005 20:52:03 -0500 Subject: Newbie help In-Reply-To: References: Message-ID: <421152d0$1_1@newspeer2.tds.net> Chad Everett wrote: > Nope, I am trying to learn it on my own. I am using the book by Michael > Dawson. You might be interested in the Python tutor mailing list which is specifically intended for beginners. http://mail.python.org/mailman/listinfo/tutor Kent From steven.bethard at gmail.com Thu Feb 17 11:53:33 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 17 Feb 2005 09:53:33 -0700 Subject: newbie question - iterating through dictionary object In-Reply-To: <1108656866.128912.109800@f14g2000cwb.googlegroups.com> References: <1108656866.128912.109800@f14g2000cwb.googlegroups.com> Message-ID: mirandacascade at yahoo.com wrote: > 1) Is there any advantage to use the > > y = a.keys() > for z in y: > > looping technique rather than the > > for x in a: > > looping technique? > > 2) What are the tradeoffs for using each of the techniques? Calling dict.keys creates a list in memory of the keys to the dict. Using the dict directly in the for-loop (which implicitly calls __iter__) will only load one key into memory at a time. The only time you should call keys is if you *really* need a list. If you're just going to iterate over them in a for-loop, you should definitely use the latter technique. STeVe From tzot at sil-tec.gr Thu Feb 10 17:40:42 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 11 Feb 2005 00:40:42 +0200 Subject: lambda and for that matter goto not forgetting sugar References: Message-ID: <5non019hhm2uu2i2hhic9eu3eh21o2ct8u@4ax.com> On Thu, 10 Feb 2005 15:21:47 +0000, rumours say that Richie Hindle might have written: > >[Philip] >> For that matter I would find implementing the classical algorithms far >> easier if python had 'goto' > >I can't believe it - first a request for COMEFROM and now one for GOTO, >both on the same day. I should have put http://entrian.com/goto/ under a >commercial license. 8-) *Three* requests --check the thread "goto, cls, wait commands". My humourous suggestion of your module came before I read your own replies to the this and the other thread. BTW, my sincere congratulations for what I presume best computer related April's Fool joke of all time; I love double-bluffs. The worst of all is I've often referenced your joke when advocating python... :) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From caleb1 at telkomsa.net Tue Feb 8 23:47:36 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 08 Feb 2005 23:47:36 -0500 Subject: Loop in list. References: <1107874174.445345.41230@c13g2000cwb.googlegroups.com> Message-ID: Stephen You're gonna have to help me here.....what is the effective difference? Thanks Caleb >> '>>> a = [] >> '>>> for b in range(4): >> '>>> for i in range(3): >> '>>> a.append(i*2*b) > > There is a subtle error in this explanation. The equivilence actually > looks like: > > '> a = [] > '> l1 = range(4) > '> l2 = range(3) > '> for b in l1: > '> for i in l2: > '> a.append(i*2*b) > > Stephen From tzot at sil-tec.gr Tue Feb 15 07:36:23 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 15 Feb 2005 14:36:23 +0200 Subject: Variables. References: <614c778e.0502150429.1a2a4d8d@posting.google.com> Message-ID: <4vq3119apgl58g7ghm0hdq1tf5nqceue65@4ax.com> On 15 Feb 2005 04:29:26 -0800, rumours say that administrata at hotmail.com (administrata) might have written: >I wrote this, It's a bit lame though > >I = "Allen" >me = "Allen" >my = "Allen's" > >print \ >""" >%s woke up early in the morning. But, it was unusal by %s. %s pillow >was with %s. %s didn't want to wake up But, %s tried my best and woke up. >it was so amazing!""" % (I,me,my,me,I,I) > >raw_input("\n\\t\t\t- The End -") > >But it looks like this... > >Allen woke up early in the morning. But, it was unusal by Allen. >Allen's pillow >was with Allen. Allen didn't want to wake up But, Allen tried my best and woke up. >it was so amazing > > - The End - It looks exactly how it should, based on what you gave it. Try the following changes: >I = "Allen" >me = "Allen" >my = "Allen's" to xyzzy = "I" footy = "me" spike = "my" and then change the last line of the triple-quoted string: >it was so amazing!""" % (I,me,my,me,I,I) to it was so amazing!""" % (xyzzy,footy,spike,footy,xyzzy,xyzzy) Let us know what you expect to print after these changes. >HELP plz By all means --what's the problem exactly? -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From fredrik at pythonware.com Wed Feb 16 01:54:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Feb 2005 07:54:02 +0100 Subject: Compiler References: <420990CF.7000705@ocf.berkeley.edu> Message-ID: "Roch ...." wrote: > I am begenning to study python programing language and I was > wondering how do I make an executable code with the interpreter > ...like if i have my code in a text file. if you have your code in a text file and you want to run it, just run the "python" interpreter with the name of the text file as the first argument. or, on windows, make sure that filename ends with ".py", and run the file itself. if you want to make an EXE file, see: http://effbot.org/zone/python-compile.htm From duncan.booth at invalid.invalid Thu Feb 17 04:25:34 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Feb 2005 09:25:34 GMT Subject: difference between class methods and instance methods References: Message-ID: John M. Gabriele wrote: > I've done some C++ and Java in the past, and have recently learned > a fair amount of Python. One thing I still really don't get though > is the difference between class methods and instance methods. I > guess I'll try to narrow it down to a few specific questions, but > any further input offered on the subject is greatly appreciated: I'll try not to cover the same ground as Steven did in his reply. > > 1. Are all of my class's methods supposed to take 'self' as their > first arg? consider this: >>> class Demo(object): def foo(self, x): print self, x @classmethod def clsmethod(cls, x): print cls, x @staticmethod def stmethod(x): print x >>> instance = Demo() Calling a bound method, you don't pass an explicit self parameter, but the method receives a self parameter: >>> bound = instance.foo >>> bound(2) <__main__.Demo object at 0x00B436B0> 2 Note that it doesn't matter whether you call instance.foo(2) directly, or bind instance.foo to a variable first. Either will create a *new* bound method object, and the correct instance is used for the call. This is significantly different from languages such as C++ and Javascript which are a real pain if you want to use a method as a callback. Calling an unbound method, you pass a self parameter explicitly (and it must be an instance of the class, *or an instance of a subclass*: >>> unbound = Demo.foo >>> unbound(instance, 2) <__main__.Demo object at 0x00B436B0> 2 Again is doesn't matter whether you do this in one step or two. The usual case for using an unbound method is when you have overridden a method in a derived class and want to pass the call on to a base class. e.g. >>> class Derived(Demo): def foo(self, x): Demo.foo(self, x) A class method is usually called through the class rather than an instance, and it gets as its first parameter the actual class involved in the call: >>> Demo.clsmethod(2) 2 >>> Derived.clsmethod(2) 2 You can call a class method using an instance of the class, or of a subclass, but you still the get class passed as the first parameter rather than the instance: >>> d = Derived >>> d.clsmethod(2) 2 A common use for class methods is to write factory functions. This is because you can ensure that the object created has the same class as the parameter passed in the first argument. Alternatively you can use class methods to control state related to a specific class (e.g. to count the number of instances of that exact class which have been created.) There is no equivalent to a class method in C++. Static methods are like static methods in C++. You can call them through the class or a subclass, or through an instance, but the object used in the call is not passed through to the method: >>> Demo.stmethod(2) 2 >>> instance.stmethod(2) 2 >>> Derived.stmethod(2) 2 >>> d.stmethod(2) 2 >>> > > 2. Am I then supposed to call them with MyClass.foo() or instead: > > bar = MyClass() > bar.foo() > ? If you have an instance then use it. If the class method is a factory then you might want to create a new object of the same type as some existing object (but not a simple copy since you won't get any of the original object's state). Mostly though you know the type of the object you want to create rather than having an existing instance lying around. > > 3. Is "bound method" a synonym for instance method? Close but not quite. It is a (usually transient) object created from an unbound instance method for the purposes of calling the method. > > 4. Is "unbound method" a synonym for class method? Definitely not. > > And if anyone's *really* daring: > Where do the so-called "static methods" fit into all this? > By the name of them, it sounds like the same thing as class > methods... See above. From alefnula at gmail.com Wed Feb 16 18:21:53 2005 From: alefnula at gmail.com (Viktor) Date: 16 Feb 2005 15:21:53 -0800 Subject: Stable GUI + wxPython memory leak In-Reply-To: <1108569376.721830.67370@o13g2000cwo.googlegroups.com> References: <1108564589.069982.71680@o13g2000cwo.googlegroups.com> <1108569376.721830.67370@o13g2000cwo.googlegroups.com> Message-ID: <1108596113.424102.255340@f14g2000cwb.googlegroups.com> I just noticed that wxPython is leaking memory?! Playing with wxPython-demo, I started with 19MB used, and ended whith almost 150MB used?! It's wxPython 2.5.3.1 running on Python 2.4. From ncoghlan at iinet.net.au Thu Feb 10 08:50:09 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 10 Feb 2005 23:50:09 +1000 Subject: deepcopy chokes with TypeError on dynamically assigned instance method In-Reply-To: <698m01djeu9jqpnvvk64vmc488e5c026im@4ax.com> References: <698m01djeu9jqpnvvk64vmc488e5c026im@4ax.com> Message-ID: <420B6691.7090300@iinet.net.au> 5?HH575-UAZWKVVP-7H2H48V3 wrote: > class Foo(list): > "Foo" > > def __init__(self, l=[]): Change this too: def __init__(self, l=None): if l is None: l = [] And see if your problem goes away. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From aleaxit at yahoo.com Sat Feb 5 04:37:10 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 5 Feb 2005 10:37:10 +0100 Subject: changing local namespace of a function References: <1107550212.114358.281200@z14g2000cwz.googlegroups.com> <1107582027.700961.156800@f14g2000cwb.googlegroups.com> Message-ID: <1gri9v3.145y7yo1uzwmprN%aleaxit@yahoo.com> Bo Peng wrote: > M.E.Farmer wrote: > > I really don't see your need. > > Maybe it is just my laziness. It is almost intolerable for me to write > lines and lines of code like > > d['z'] = func(d['x']+d['y']+d['whatever']['as']+d[a][0] ) > > It is ugly, unreadable and error prone. If I have to use this code, I > would write > > _z = func(_x + _y + _whatever['as'] + _a[0]) So, what about having as the real code d.z = func(d.x + d.y + d.whatever['as'] + d.a[0]) Doesn't seem too different from what you would write, would it? To wrap a dictionary into an object whose attributes are mapped to items of the dictionary is not hard: just start your function with d = type('wrapadict', (), {})() d.__dict__ = the_dict_to_wrap and there you are. Affecting *BARE* names is a completely different order of magnitude of complication away from affecting *COMPOUND* names. Barenames are, almost inevitably, handled with deep magic, essentially for the purposes of can't-do-without optimization; compound names are _way_ more malleable... Alex From timothy.grant at gmail.com Thu Feb 10 14:28:27 2005 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 10 Feb 2005 11:28:27 -0800 Subject: Python-libnjb on macosx Message-ID: I was working on some things that use Glenn Strong's excellent libnjb wrapper on my Linux box. I have since bought a PowerBook and have been trying to get everything working correctly under OS/X. This morning I got Python-libnjb to build without errors using the following command: ld -dynamic -dylib -L/sw/lib -L/sw/lib/python2.3/config njb_c_wrap.o -o _njb_c.dylib -lpython2.3 -lnjb -lSystem -framework IOKit -ldylib1.o However, when I try and import NJB.py I get the following: (timothygrant at bastard%) pythonw NJB.py Traceback (most recent call last): File "NJB.py", line 2, in ? import njb_c, sys, os, os.path, stat File "/Users/timothygrant/src/Python-libnjb/njb_c.py", line 5, in ? import _njb_c ImportError: Inappropriate file type for dynamic loading I'm guessing this means that while I got the library to build, I didn't get it to build correctly. However, I'm enough of an OS/X neophyte that I don't know which direction to turn. Any suggestions? -- Stand Fast, tjg. From jjl at pobox.com Sun Feb 6 19:52:14 2005 From: jjl at pobox.com (John J. Lee) Date: 07 Feb 2005 00:52:14 +0000 Subject: Insane import behaviour and regrtest.py: heeelp References: <87sm4aws3v.fsf@pobox.com> <876515ixj0.fsf@pobox.com> <87wttlh2jx.fsf@pobox.com> Message-ID: <87oeexgpj5.fsf@pobox.com> Tim Peters writes: > [John J. Lee] > > I'm still puzzled, though. Reading the -vv output, I see that when [...] > > Lib[0]$ pwd > > /hda/usr/local/buf/python/python/dist/src/Lib > > That doesn't look to be the same thing as the > > /usr/local/src/python/python/dist/src/Lib > > you're asking about, right? [...] Ah: somehow managed to look straight through that, so used am I to the presence of these symlinks: Lib[0]$ ls -l /usr/local/src lrwxrwxrwx 1 root root 19 Sep 4 13:45 /usr/local/src -> /hda/usr/local/src// Lib[0]$ ls -l /hda/usr/local/src/python lrwxr-xr-x 1 john oldjohn 25 Sep 11 13:21 /hda/usr/local/src/python -> /hda/usr/local/buf/python/ The twisty mess of symlinks and owners is down to a couple of OS and hard disk changes. I don't immediately see why at 1am, but I guess that's the problem (that, and trying to understand import details at 1am...). Thanks! John From francis.girard at free.fr Sun Feb 6 17:05:06 2005 From: francis.girard at free.fr (Francis Girard) Date: Sun, 6 Feb 2005 23:05:06 +0100 Subject: After 40 years ... Knuth vol 4 is to be published!! In-Reply-To: <200502051239.j15Cdf6k005835@ratthing-b246.strakt.com> References: <200502051239.j15Cdf6k005835@ratthing-b246.strakt.com> Message-ID: <200502062305.06481.francis.girard@free.fr> I think that Led Zeppelin, Pink Floyd and the Beatles (this time with John Lennon back from the cemetry) also made a come back. Addison-Wesley decided to preprint a photo of the messiah (just for us!) Yippee! Francis Girard Le samedi 5 F?vrier 2005 13:39, Laura Creighton a ?crit?: > "More than forty years in the making, the long-anticipated Volume 4 > of The Art of Computer Programming is about to make its debuta. in > parts. Rather than waiting for the complete book, Dr. Knuth and > Addison-Wesley are publishing it in installments ("fascicles") a la > Charles Dickens. > > See http://www.bookpool.com/.x/xx/ct/163 for an excerpt and more info > on Volume 4. > > And Addison-Wesley is offering Bookpool customers an exclusive sneak > peek -- the first official excerpt from the series." > > (above from the same site) > Yippee! > Laura From theller at python.net Tue Feb 8 13:12:45 2005 From: theller at python.net (Thomas Heller) Date: Tue, 08 Feb 2005 19:12:45 +0100 Subject: Efficient checksum calculating on lagre files References: <5o2nd2-5hl.ln1@pluto.i.infosense.no> Message-ID: Nick Craig-Wood writes: > Ola Natvig wrote: >> Hi all >> >> Does anyone know of a fast way to calculate checksums for a large file. >> I need a way to generate ETag keys for a webserver, the ETag of large >> files are not realy nececary, but it would be nice if I could do it. I'm >> using the python hash function on the dynamic generated strings (like in >> page content) but on things like images I use the shutil's >> copyfileobject function and the hash of a fileobject's hash are it's >> handlers memmory address. >> >> Does anyone know a python utility which is possible to use, perhaps >> something like the md5sum utility on *nix systems. > > Here is an implementation of md5sum in python. Its the same speed > give or take as md5sum itself. This isn't suprising since md5sum is > dominated by CPU usage of the MD5 routine (in C in both cases) and/or > io (also in C). Your code won't work correctly on Windows, since you have to open files with mode 'rb'. But there's a perfect working version in the Python distribution already: tools/Scripts/md5sum.py Thomas From wittempj at hotmail.com Sat Feb 12 19:48:01 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 12 Feb 2005 16:48:01 -0800 Subject: help please In-Reply-To: <1108254434.871062.314510@g14g2000cwa.googlegroups.com> References: <1108254434.871062.314510@g14g2000cwa.googlegroups.com> Message-ID: <1108255681.026407.315710@f14g2000cwb.googlegroups.com> add just below the procedure declaration 'global t2' as you're referring to a global variable ... From robin at reportlab.com Tue Feb 8 11:13:43 2005 From: robin at reportlab.com (Robin Becker) Date: Tue, 08 Feb 2005 16:13:43 +0000 Subject: Efficient checksum calculating on lagre files In-Reply-To: <5o2nd2-5hl.ln1@pluto.i.infosense.no> References: <5o2nd2-5hl.ln1@pluto.i.infosense.no> Message-ID: <4208E537.4070901@chamonix.reportlab.co.uk> Ola Natvig wrote: > Hi all > > Does anyone know of a fast way to calculate checksums for a large file. > I need a way to generate ETag keys for a webserver, the ETag of large > files are not realy nececary, but it would be nice if I could do it. I'm > using the python hash function on the dynamic generated strings (like in > page content) but on things like images I use the shutil's > copyfileobject function and the hash of a fileobject's hash are it's > handlers memmory address. > > Does anyone know a python utility which is possible to use, perhaps > something like the md5sum utility on *nix systems. > > well md5sum is usable on many systems. I run it on win32 and darwin. I tried this in 2.4 with the new subprocess module def md5sum(fn): import subprocess return subprocess.Popen(["md5sum.exe", fn], stdout=subprocess.PIPE).communicate()[0] import time t0 = time.time() print md5sum('test.rml') t1 = time.time() print t1-t0 and got C:\Tmp>md5sum.py b68e4efa5e5dbca37718414f6020f6ff *test.rml 0.0160000324249 Tried with the original C:\Tmp>timethis md5sum.exe test.rml TimeThis : Command Line : md5sum.exe test.rml TimeThis : Start Time : Tue Feb 08 16:12:26 2005 b68e4efa5e5dbca37718414f6020f6ff *test.rml TimeThis : Command Line : md5sum.exe test.rml TimeThis : Start Time : Tue Feb 08 16:12:26 2005 TimeThis : End Time : Tue Feb 08 16:12:26 2005 TimeThis : Elapsed Time : 00:00:00.437 C:\Tmp>ls -l test.rml -rw-rw-rw- 1 user group 996688 Dec 31 09:57 test.rml C:\Tmp> -- Robin Becker From skip at pobox.com Fri Feb 11 13:03:39 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 11 Feb 2005 12:03:39 -0600 Subject: Alternative to raw_input ? In-Reply-To: References: Message-ID: <16908.62331.70813.556420@montanaro.dyndns.org> > Err, why? >> It looks to ugly this way. I want to press >> any key without ENTER to continue How about modifying it to raw_input("Press ENTER to continue ") Skip From mikey666 at 666swampgas.666com Tue Feb 1 17:45:56 2005 From: mikey666 at 666swampgas.666com (The Artist Formerly Known as Kap'n Salty) Date: Tue, 01 Feb 2005 16:45:56 -0600 Subject: web camera or else ? 15-30 fps processing of camera videos. In-Reply-To: <1107295229.657375.318750@o13g2000cwo.googlegroups.com> References: <1107295229.657375.318750@o13g2000cwo.googlegroups.com> Message-ID: <420006a5$0$714$c3e8da3@news.astraweb.com> Newbie wrote: > I am doing some robotics projects but my main area of interest is > trying out several algorithms for the processing of the stream of data > coming from the video. > > I am wondering what type of camera I should invest in. Either I could > buy a web cam and hope I can find a driver I could either modify or > use. i.e. every frame is somehow stored on the computer automagically > or I could buy a camera not unlike the AVRcam > (http://www.jrobot.net/Projects/AVRcam.html) or the CMUcam and try to > do the processing once the data has been streamed to the nearest > computer ? or should I use an expensive video card, some CCTV camera > and a frame grabber to digitize photos so they can be processed > afterwards. I expect my processing algorithms to handle at least 15 > frames per second framerate once they are working ont the final set-up. > > My constraints are that I would like to avoid as much as possible > complex set-ups even if that means buying a more expensive camera > set-up. For the prototyping, I would like to try my algorithms out > using a combination of python and matlab (all very slow) and then > expect the same architecture (image files location and flow) with > speedier set-up like python+psyco or C. All the processing would be > done on a computer dedicated for that. Windows or Linux are possible. > An easy approach to this is to use a wireless camera on your robot, with the receiver attached to a frame grabber on a remote host. This allows you your choice of camera (stand alone video transmitters are widely available), and you are not limited to only processing hardware you can carry on board your robot. You also get full FPS. Frame-grabber cards are inexpensive and widely available for both Windows and Linux. Hope that helps -- tAfkaks -- (Replies: cleanse my address of the Mark of the Beast!) Teleoperate a roving mobile robot from the web: http://www.swampgas.com/robotics/rover.html From steve at myplace.com Mon Feb 21 16:56:55 2005 From: steve at myplace.com (Steve M) Date: Mon, 21 Feb 2005 15:56:55 -0600 Subject: Tuple index References: <1108951559.490554.305310@l41g2000cwc.googlegroups.com> <1109021422.351702.296640@o13g2000cwo.googlegroups.com> Message-ID: Michael Hartl wrote: > I actually find it strange that tuples don't have an index function, > since finding the index doesn't involve any mutation. Anyone know why > Python doesn't allow a statement like t.index('foo')? > > In any case, you can use the index method of list objects if you > convert your tuple to a list first: > >>>> t = ("fred", "barney", "foo") >>>> list(t).index("foo") > 2 >>>> def index(a_tuple, element): > ... return list(a_tuple).index(element) > ... >>>> t[index(t, "foo")] > 'foo' > > (By the way, 'tuple' is a Python built-in type, so it's probably best > to avoid using it as a variable name.) > > > Michael > > -- > Michael D. Hartl, Ph.D. > CTO, Quark Sports LLC > http://quarksports.com/ The book I'm using to learn Python with has not gotten to lists yet, maybe next chapter. I knew tuple is a built in type, I was just trying to be clear, I guess I just muddied the water a bit. Thank you for your help. Steve From sharidas at zeomega.com Wed Feb 16 12:42:02 2005 From: sharidas at zeomega.com (Satchidanand Haridas) Date: Wed, 16 Feb 2005 23:12:02 +0530 Subject: renaming 'references' to functions can give recursive problems In-Reply-To: <1108573114.574794.201470@g14g2000cwa.googlegroups.com> References: <1108565645.179340.70600@o13g2000cwo.googlegroups.com> <1108573114.574794.201470@g14g2000cwa.googlegroups.com> Message-ID: <421385EA.7020702@zeomega.com> peter wrote: >Hello, nice solution: >but it puzzles me :) > >can anyone tell me why >-----------correct solution---------------- >def fA(input): > return input > >def newFA(input, f= fA): > return f(input) > >fA = newFA > >is correct and: > > >>> def fA(input): ... print "inside fA" ... return input ... >>> def newFA(input,f=fA): ... print "inside newFA" ... return f(input) ... >>> fA = newFA >>> fA(2) inside newFA inside fA 2 while: >-------------infinite loop----------------- > >def fA(input): > return input > >def newFA(input): > return fA(input) > >fA = newFA > >gives an infinite recursive loop? > > > >>> def fA(input): ... print "inside fA" ... return input ... >>> def newFA(input): ... print "inside newFA" ... return fA(input) ... >>> fA = newFA >>> fA(2) inside newFA inside newFA inside newFA inside newFA What is happening is that when you call fA (inside newFA) in the second case, you are calling newFA because fA is pointing to newFA (hope that made sense ;-)). So it was recursive. While in the former case you called f, which pointed to fA, but not to newFA. Probably the following will make it clearer: >>> def fA(input): ... print "inside fA" ... return input ... >>> def newFA(input,f=fA): ... print "inside newFA" ... print "f is pointing to: ",f ... return f(input) ... >>> fA = newFA >>> fA(2) inside newFA f is pointing to: inside fA 2 >>> fA >>> newFA Thus f and fA do not point to the same function object when you execute the statement fa(2). This f is called once and terminates. thanks, Satchit From firstname.lastname at iki.fi-spam Wed Feb 2 17:31:47 2005 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 03 Feb 2005 00:31:47 +0200 Subject: Python's idiom for function overloads References: <41ff066c$0$6473$636a15ce@news.free.fr> Message-ID: <87lla6386k.fsf@sme.intra.citec.fi> Philippe Fremy writes: > You can not reproduce the C++ overload idiom but you can get something > close with manual type testing. > > > To in a > > function do an if statement with the type() function? > > I am not aware of any other method. > > def a( arg1 ): > if type(arg1) == types.IntType: return aWithInt(arg1) > if type(arg1) == types.ListType: return aWithList(arg1) > ... Or: def a_overloader (arg1): return my_typed_a_func_dict[type (arg1)] (arg1) Next I'd put my hands in automating the creation of these wrappers and the my_typed_a_func_dict map based on my implementation written so far. Then I'd think of parameterizing on any arbitrary destructuring of arguments like def foo ((a,b), c) and also on classes to which instance methods are bound to. At this point, a preprocessor might be handy to avoid seeing all the internals after which things would probably start looking sick enough to either switch languages or thinking of the right problem first and then come up with a pythonic solution to _that_. br, S From pu.news.001 at gmail.com Sun Feb 27 05:58:58 2005 From: pu.news.001 at gmail.com (Patrick Useldinger) Date: Sun, 27 Feb 2005 11:58:58 +0100 Subject: fdups: calling for beta testers In-Reply-To: <4r8221tlstaq55j9uv7qls8r63jqgr38nu@4ax.com> References: <421f97eb$1@news.vo.lu> <1109380525.262724.275780@g14g2000cwa.googlegroups.com> <422044b9$1@news.vo.lu> <1109451464.546948.174830@z14g2000cwz.googlegroups.com> <4220fdd7$1@news.vo.lu> <4r8221tlstaq55j9uv7qls8r63jqgr38nu@4ax.com> Message-ID: <4221a7f3@news.vo.lu> John Machin wrote: >>I've tested it intensively > "Famous Last Words" :-) ;-) > (1) Manic s/w producing lots of files all the same size: the Borland > C[++] compiler produces a debug symbol file (.tds) that's always > 384KB; I have 144 of these on my HD, rarely more than 1 in the same > directory. Not sure what you want me to do about it. I've decreased the minimum block size once more, to accomodate for more files of the same length without increasing the total amount of memory used. > (2) There appears to be a flaw in your logic such that it will find > duplicates only if they are in the *SAME* directory and only when > there are no other directories with two or more files of the same > size. Ooops... A really stupid mistake on my side. Corrected. > (3) Your fdups-check gadget doesn't work on Windows; the commands > module works only on Unix but is supplied with Python on all > platforms. The results might just confuse a newbie: > Why not use the Python filecmp module? Done. It's also faster AND it works better. Thanks for the suggestion. Please fetch the new version from http://www.homepages.lu/pu/fdups.html. -pu From Felix.Wiemann at gmx.net Thu Feb 17 15:50:27 2005 From: Felix.Wiemann at gmx.net (Felix Wiemann) Date: Thu, 17 Feb 2005 21:50:27 +0100 Subject: sampling items from a nested list References: <7_adnQhRBYDdV47fRVn-sA@comcast.com> Message-ID: <87sm3uc3n0.fsf@news2.ososo.de> Steven Bethard wrote: > py> data = [[('a', 0), > ... ('b', 1), > ... ('c', 2)], > ... > ... [('d', 2), > ... ('e', 0)], > ... > ... [('f', 0), > ... ('g', 2), > ... ('h', 1), > ... ('i', 0), > ... ('j', 0)]] > > I need to count the occurrences of each 'label' (the second item in > each tuple) in all the items of all the sublists, and randomly remove > some items until the number of occurrences of each 'label' is equal. If the tuples are "heavier" than this, you can avoid comparing them using the following algorithm (which probably still leaves some room for optimization, e.g. simpler return_list building [or returning a generator instead of a list], or directly building the sample set instead of converting a random.sample to a set): def resample(data): counts = {} for i in data: for j in i: counts[j[1]] = counts.setdefault(j[1], 0) + 1 min_count = min(counts.itervalues()) # Same keys, so we can reuse the counts dictionary. indices = counts for label, count in counts.iteritems(): indices[label] = set(random.sample(xrange(count), min_count)) # Same thing with a generator expression, building a new dict (dunno # what's faster). #indices = dict(((label, set(random.sample(xrange(count), min_count))) # for label, count in counts.iteritems())) # "done" maps labels to the number of tuples (with that label) which # have been added to return_list. done = {} return_list = [] for i in data: return_list.append([]) for j in i: if done.setdefault(j[1], 0) in indices[j[1]]: return_list[-1].append(j) done[j[1]] += 1 return return_list -- Felix Wiemann -- http://www.ososo.de/ From Peter.Vandersteegen at gmail.com Wed Feb 16 13:05:59 2005 From: Peter.Vandersteegen at gmail.com (peter) Date: 16 Feb 2005 10:05:59 -0800 Subject: renaming 'references' to functions can give recursive problems In-Reply-To: References: <1108565645.179340.70600@o13g2000cwo.googlegroups.com> Message-ID: <1108577159.661733.104710@g14g2000cwa.googlegroups.com> brain reset and understood thx a lot for all your answers Peter From fredrik at pythonware.com Mon Feb 14 18:30:41 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Feb 2005 00:30:41 +0100 Subject: Multidimensional arrays - howto? References: <1108423310.463006.318320@f14g2000cwb.googlegroups.com> Message-ID: wrote: > I am trying to convert some C code into python. Since i am new to > python, i would like to know how to deal with multidimensional arrays? http://www.python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list might be helpful. From fuzzyman at gmail.com Thu Feb 3 07:35:13 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 3 Feb 2005 04:35:13 -0800 Subject: CONTEST - What is the (best) solution? In-Reply-To: <36edbdF51gkl6U1@individual.net> References: <1107340503.462196.109440@o13g2000cwo.googlegroups.com> <36edbdF51gkl6U1@individual.net> Message-ID: <1107434113.798274.320130@f14g2000cwb.googlegroups.com> That's neater than my suggestion. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From dontwant at spam.com Thu Feb 10 00:58:06 2005 From: dontwant at spam.com (Courageous) Date: Wed, 09 Feb 2005 21:58:06 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> Message-ID: >We really need in Python a clear separation of advanced features from >the basic syntax. No more lambda calculus in the basic part. :>) Well I considered writing a pep to move all that stuff to a module called __icky__, you know: from __icky__ import * ... but I didn't think the committee would go for it. C/// From fumanchu at amor.org Wed Feb 9 13:14:22 2005 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 9 Feb 2005 10:14:22 -0800 Subject: Python and version control Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33983C0@exchange.hqamor.amorhq.net> Peter Hansen wrote: > Carl wrote: > > What is the ultimate version control tool for Python if you > > are working in a Windows environment? > > I never liked coupling the two together like that. Instead > I use tools like TortoiseCVS or (now) TortoiseSVN with a > Subversion repository. These things let you access revision > control features from context (right-button) menus right in > Windows Explorer, as you browse the file system. Seconded. Bob From fredrik at pythonware.com Wed Feb 16 03:15:56 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Feb 2005 09:15:56 +0100 Subject: Copying data between file-like objects References: Message-ID: Thomas Lotze wrote: >> if you don't know how large f2 can be, use shutil.copyfileobj: >> >> >>> help(shutil.copyfileobj) >> Help on function copyfileobj in module shutil: >> >> copyfileobj(fsrc, fdst, length=16384) >> copy data from file-like object fsrc to file-like object fdst > > This sounds like what I was looking for. Thanks for the pointer. > However, the following doesn't seem like anything is being copied: > >>>> from StringIO import StringIO >>>> from shutil import copyfileobj >>>> s = StringIO() >>>> s2 = StringIO() >>>> s.write('asdf') >>>> copyfileobj(s, s2) >>>> s2.getvalue() copyfileobj copies from the current location, and write leaves the file pointer at the end of the file. a s.seek(0) before the copy fixes that. >> to copy stringio objects, you can use f1 = StringIO(f2.getvalue()). > > But this should have the same problem as using read(): a string will be > created on the way which contains all the content. getvalue() returns the contents of the f2 file as a string, and f1 will use that string as the buffer. there's no extra copying. > Because I want to manipulate a copy of the data and be able to compare it > to the original afterwards. why not just use a plain string (or a list of strings)? your focus on StringIO sounds like a leftover from some C library you've been using in an earlier life ;-) > Another thing I'd like to do is copy parts of a StringIO object's content > to another object. This doesn't seem possible with any shutil method. Any > idea on that? use a plain string and slicing. (if you insist on using StringIO, use seek and read) > What one can really wonder, I admit, is why the difference between holding > data two or three times in memory matters that much, especially if the > latter is only for a short time. But as I'm going to use the code that > handles the long string as a core component to some application, I'd like > to make it behave as well as possible. use plain strings, so you know what you're doing. From john at grulic.org.ar Fri Feb 18 11:20:51 2005 From: john at grulic.org.ar (John Lenton) Date: Fri, 18 Feb 2005 13:20:51 -0300 Subject: [perl-python] exercise: partition a list by equivalence In-Reply-To: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> Message-ID: <20050218162051.GE17991@grulic.org.ar> On Thu, Feb 17, 2005 at 03:46:20PM -0800, Xah Lee wrote: > here's another interesting algorithmic exercise, again from part of a > larger program in the previous series. > > Here's the original Perl documentation: > > =pod > > merge($pairings) takes a list of pairs, each pair indicates the > sameness > of the two indexes. Returns a partitioned list of same indexes. > > For example, if the input is > merge( [ [1,2], [2,4], [5,6] ] ); > > that means 1 and 2 are the same. 2 and 4 are the same. Therefore > 1==2==4. The result returned is > > [[4,2,1],[6,5]]; > > (ordering of the returned list and sublists are not specified.) > > =cut in Python: def merge(pairings): rev = {} res = [] for pairing in pairings: first, second = pairing has_first = first in rev has_second = second in rev if has_first and has_second: rev[first].extend(rev[second]) rev[second][:] = [] rev[second] = rev[first] elif has_first: rev[first].append(second) rev[second] = rev[first] elif has_second: rev[second].append(first) rev[first] = rev[second] else: copy = [first, second] res.append(copy) rev[first] = rev[second] = copy return filter(None, res) and in Perl: sub merge($) { my %rev = (); my @res = (); my ($pairing, $first, $second, $has_first, $has_second); foreach $pairing (@{$_[0]}) { ($first, $second) = @$pairing; $has_first = exists $rev{$first}; $has_second = exists $rev{$second}; if ($has_first and $has_second) { push @{$rev{$first}}, @{$rev{$second}}; @{$rev{$second}} = (); $rev{$second} = $rev{$first}; } elsif (exists $rev{$first}) { push @{$rev{$first}}, $second; $rev{$second} = $rev{$first}; } elsif (exists $rev{$second}) { push @{$rev{$second}}, $first; $rev{$first} = $rev{$second}; } else { my @copy = ($first, $second); push @res, \@copy; $rev{$first} = $rev{$second} = \@copy; } } return [grep @$_, @res]; } although in Perl you wouldn't define it to take a reference to a list (as you did), but rather a list, and you wouldn't define it to return a reference to a list, but rather a list in list context (and possibly a reference in scalar context). Both versions are (IMHO) pretty clear (when the docstring/pod is included), and O(n) because dict/hash lookup and list appending/pushing is O(1) in both languages. Both versions can probably be tweaked for speed quite a bit, but I don't *think* there's a better-than-O(n) algorithm for this. Note that the Python version assumes that the pairs' elements are hashable; your example used numbers, so I thought it was pretty safe assumption. The Perl version has no such restriction. -- John Lenton (john at grulic.org.ar) -- Random fortune: Noble cosa es, a?n para un anciano, el aprender. -- S?focles. (497-406 a.C.) Fil?sofo griego. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From rgacote at AppropriateSolutions.com Fri Feb 4 18:30:41 2005 From: rgacote at AppropriateSolutions.com (Ray Cote) Date: Fri, 4 Feb 2005 18:30:41 -0500 Subject: advice needed for simple python web app In-Reply-To: <7xis58tgjr.fsf@ruckus.brouhaha.com> References: <5cqdnZX-cZ9ca5_fRVn-3Q@rogers.com> <7xis58reac.fsf@ruckus.brouhaha.com> <7xis58tgjr.fsf@ruckus.brouhaha.com> Message-ID: At 8:51 AM -0800 2/4/05, Paul Rubin wrote: >"Dan Perl" writes: >> This matches pretty much what I've decided to do. I'll start with cgi and >> CGIHTTPServer because I'll learn more from that and then move to a >> framework, quite likely CherryPy, although by that time I may change my >> choice. Philip Greenspun's book looks good and I'll have to go through it. >> Thanks for the advice. > >You might also look at the docs for HTML::Mason (www.masonhq.com) to >get a look at a reasonably mature template system, even if you don't >plan to use it (because it's in Perl and not Python). There's a Python port of HTML::Mason called Myghty. A fairly new project. I've just played around with it a bit Well worth a look: -- Raymond Cote Appropriate Solutions, Inc. PO Box 458 ~ Peterborough, NH 03458-0458 Phone: 603.924.6079 ~ Fax: 603.924.8668 rgacote(at)AppropriateSolutions.com www.AppropriateSolutions.com From jaydonnell at gmail.com Wed Feb 16 17:28:50 2005 From: jaydonnell at gmail.com (jdonnell) Date: 16 Feb 2005 14:28:50 -0800 Subject: web spider and password protected pages In-Reply-To: <_LudnUg0vJIsLI7fRVn-rA@powergate.ca> References: <1108580601.884193.263890@g14g2000cwa.googlegroups.com> <_LudnUg0vJIsLI7fRVn-rA@powergate.ca> Message-ID: <1108592930.373112.90560@c13g2000cwb.googlegroups.com> "I quickly found a page that starts "Here is an explanation about how to handle password protected sites." ... I hope that teaches you a bit about how to fish, rather than just giving you one. ;-) " Actually, I found a much easier solution, but since you know how to fish I don't need to tell you what it is ;) From jeff at ccvcorp.com Tue Feb 8 15:49:36 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 08 Feb 2005 12:49:36 -0800 Subject: Basic file operation questions In-Reply-To: <7q4Od.753$Sd.170775@newshog.newsread.com> References: <1107379669.870799.256030@g14g2000cwa.googlegroups.com> <1107846197.701686.303390@l41g2000cwc.googlegroups.com> <7q4Od.753$Sd.170775@newshog.newsread.com> Message-ID: <110i9cl27fbm27c@corp.supernews.com> Marc Huffnagle wrote: > When you read a file with that method, is there an implied close() call > on the file? I assume there is, but how is that handled? > [...] >>> for line in file(...): >>> # do stuff As I understand it, the disk file will be closed when the file object is garbage collected. In CPython, that will be as soon as there are no active references to the file; i.e., in the above case, it should happen as soon as the for loop finishes. Jython uses Java's garbage collector, which is a bit less predictable, so the file may not be closed immediately. It *will*, however, be closed during program shutdown if it hasn't happened before then. Jeff Shannon Technician/Programmer Credit International From t-meyer at ihug.co.nz Mon Feb 14 18:24:30 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Tue, 15 Feb 2005 12:24:30 +1300 Subject: parsing IMAP responses? In-Reply-To: Message-ID: > Is there a library somewhere that impliments the IMAP protocol > syntax? Twisted has pretty good IMAP support (particularly client), and it's much higher level than imaplib. It probably does what you're after. Of course, the catch is that you have to use twisted <0.5 wink>. =Tony.Meyer From dbickett at gmail.com Wed Feb 2 21:05:23 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Wed, 2 Feb 2005 21:05:23 -0500 Subject: Easy Q: dealing with object type In-Reply-To: <420181b1$1@nntp.zianet.com> References: <420181b1$1@nntp.zianet.com> Message-ID: <1d6cdae3050202180577dea452@mail.gmail.com> On Erik Johnson wrote: > # The following "works", but I don't want to keep a set of instances to > compare against > >>> obj2 = A() > >>> type(obj) == type(obj2) > 1 How about: >>> class A: pass >>> class B: pass >>> objA = A() >>> type( objA ) == type( A() ) True then again.... >>> objB = B() >>> type( objA ) == type( B() ) True they're both of type 'instance'. So how about this: >>> class A: pass >>> class B( object ): pass >>> objA = A() >>> objB = B() >>> type( objA ) >>> type( objB ) >>> type( objB ) == B True I believe that achieves what you were aiming for. -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From fperez.net at gmail.com Tue Feb 8 00:38:53 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Mon, 07 Feb 2005 22:38:53 -0700 Subject: IDLE history, Python IDE, and Interactive Python with Vim References: Message-ID: Ashot wrote: > Sorry, a few more things I forgot to mention having to do with editing > multiline entries in the console: > > Autotab setting doesn't seem to have any effect, I have to type "ctrl-o" > manually I've noticed it doesn't work under win32. It's fine under *nix. There's only so much Gary can do with his readline supplement in a win32 environment, I'm not sure if this is something which he could add, you'd have to contact him directly. This would require support for insertions into the current line, which may not even be possible in a windows terminal, I just don't know. > Is there a setting that treats multiline entries as a single command, as IDLE > does? In otherwords, allowing you to edit the entire entry, going up to > previous lines, and treating as one when cycling through the history? It > seems like ipython recognizes these through the hist command, but not when > editing or cycling. This is impossible in a line-oriented terminal program. What you are asking for requires 2-d cursor control, which can only be provided in a gui environment, or with curses in a terminal (or with custom terminal handling code). Basically, it means writing a complete screen-handling program, which is far more than ipython can do. I keep trying to start an internal ipython cleanup, so it could be embedded into a gui environment. Once that happens, it may be possible to use idle or pycrust but with the ipython engine. Within the design constraints of not taking over the terminal with a curses (or similar) environment, restricted to onlw raw_input() communication with the user, what you are asking is a technical impossibility. > Is it possible to use the "set editing-mode vi" option in ipython since it > uses readline? From reading online, it seems like this should be possible, > however it doesn't work for me. It works in bash, but once I enter either > ipython or just regular python the keybindings don't work anymore. I don't know if this works even under *nix, since I don't know if the python readline library wraps this part of GNU readline. I _do_ know that python only wraps a subset of GNU readline, so I wouldn't be surprised if this wasn't included. It is not something specific to ipython, you'd have to ask the readline developers directly. Best, f From gurpreet.sachdeva at gmail.com Thu Feb 3 00:49:34 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Thu, 3 Feb 2005 11:19:34 +0530 Subject: Two classes problem In-Reply-To: References: Message-ID: The purpose is, I pass a list to a class in a module but I want to use that list out of the scope of that class and that too not in any other class or a function but in the main program... The problem is that when I import that, the statements in the module which are not in the class are executed first and then the variable gets intiallised... I will explain with the example... -global test - -class a: - def __init__(self,test): - global test - print test - -print 'Outside: '+test I want to print that variable test which I am giving to the class as an argument, in the scope of main... I know it is not a good way of programming but my situation is like this... But is this possible or not? If I pass test as 'Garry' can I (by any way) print 'Outside: Garry' with that print statement... (in the main scope) Thanks and Regards, Garry From jerf at jerf.org Sun Feb 6 08:20:29 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 06 Feb 2005 08:20:29 -0500 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1grifns.14san6f1b076mdN%aleaxit@yahoo.com> <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com> <1grj036.r13xcy1d72inbN%aleaxit@yahoo.com> <2qba01d1men2ai48gp4cojo2e28rd5g9ob@4ax.com> <1grjzia.1a4qr9q1t3p77bN%aleaxit@yahoo.com> Message-ID: On Sun, 06 Feb 2005 07:30:33 -0500, Arthur wrote: > What if: > > There was a well conducted market survey conclusive to the effect that > adding optional strict variable declaration would, in the longer run, > increase Python's market share dramatically. > > It just would. > > Why would it? What if, by eating a special mixture of cheddar and marshmallows, you could suddenly fly? It just would. Why would it? (The point, since I don't trust you to get it: The "absurd question" is neither a valid argument technique, nor is it even good rhetoric. You might as well go straight to "What if I'm right and you're wrong? What then, huh?") > My sense of how the real world works is that there is going to be one > anti-Python advocate lying in wait for the first bug he can find that he > can say would have been caught if Python had strict variable declaration, > as he always knew it should. > > He wants to be the PHB someday. The current PHB knows that, and since > being sensitive to these kinds of realities is how he got to be the PHB, > he is too smart to open himself up to this kind of risk. > > The PHB can pretty safely make the use of the option optional. As long as > he is a position to jump down the throat of the programmer who created the > bug. You really aren't very good at this "debate" thing. "Look, I can construct a certain scenario whereby the dangers you propose don't occur (assuming that I'm even right about my scenario in the first place which is highly questionable). How do you respond to *that*? Huh? Huh? Huh? Where's your precious 'overwhelming pattern' now?" It hasn't gone anywhere. > What is the correct language design decision in light of these realities? In light of the above, I question your use of the plural. > But isn't this kind of where Python is at the moment? Only for you. Despite the tone of the rest of this message, I mean that. It's obviously a huge stumbling block for you. It isn't for the rest of us, and once again, I assure you, it's going to take more than spinning implausible isolated entirely theoretical examples to convince us otherwise. Not only do you argue solely from anecdote, even the aforementioned "implausible isolated entirely theoretical" anecdote, it appears to be all you understand. You're going to have to do better than that. Producing a *real* study that shows declaration would be a good thing, instead of an implausible entirely theoretical one, would be a good start. From sean_mcilroy at yahoo.com Tue Feb 22 09:03:14 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 22 Feb 2005 06:03:14 -0800 Subject: 'modal dialogs' with Tkinter Message-ID: I'd like to have a function f such that, when f is invoked, a Tk window w is presented in which a number of variables can be modified, and f returns the values that are indicated by the relevant menus/checkbuttons/etc at the time w gets closed. I've tried various ways of doing this, without success. Any assistance would be greatly appreciated. Peace, Sean McIlroy From timr at probo.com Tue Feb 15 01:18:57 2005 From: timr at probo.com (Tim Roberts) Date: Mon, 14 Feb 2005 22:18:57 -0800 Subject: image fourier transform References: Message-ID: <8u4311tfr8jrh5dv03389p2fhtk9jsl5v9@4ax.com> Johannes Ahl-mann wrote: > >i've been looking all around the net (google is my friend ;-) for a >module to apply fourier transformations on images. the different ones in >numerical python and scientific python seem all to be operating on >sequences and therefore seem to be 1D fourier transform. > >anyone know a library/module to do 2D image FFT in a simple manner. > >or am i just too dumb to see how this is supposed to work with the 1D >fourier transforms?? To do a 2D FFT on a matrix X, you do 1D FFTs on all the rows, producing X', then you do 1D FFTs on all the columns of X'. So, for a 32x32 2D FFT, you'll end up doing 64 1D FFTs. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From cam.ac.uk at mh391.invalid Sun Feb 13 12:12:30 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 13 Feb 2005 17:12:30 +0000 Subject: changing __call__ on demand In-Reply-To: References: Message-ID: Alan McIntyre wrote: > >>>class test(object): > ... def __call1(self): > ... print 1 > ... __call__ = __call1 > Is that what you were looking for? That still only allows him to have one call function per class. -- Michael Hoffman From raghulj at gmail.com Tue Feb 22 23:24:02 2005 From: raghulj at gmail.com (Raghul) Date: 22 Feb 2005 20:24:02 -0800 Subject: reading only new messages in imaplib Message-ID: <1109132642.962280.252070@g14g2000cwa.googlegroups.com> Is it posssible to read only the new messages or unread messages using imaplib in python? If it is possible pls specify the module or give a sample code. Thanks in advance From calvin at ironfroggy.com Sat Feb 26 18:06:16 2005 From: calvin at ironfroggy.com (Calvin Spealman) Date: Sat, 26 Feb 2005 23:06:16 +0000 Subject: PyUnit and multiple test scripts Message-ID: <1233762.Qvm5ykpC2P@ironfroggy.com> I'm trying to find the best way to use PyUnit and organize my test scripts. What I really want is to separate all my tests into 'test' directories within each module of my project. I want all the files there to define a 'suite' callable and to then all all those suites from all those test directories into one big suite and run it all. I'm having trouble with this. My first barrier was just loading the modules. As I had to be able to find them automatically (would be tedious to maintain a manual list of them) I needed to then load the modules from the paths to the files after I found them. This wasn't working, I just couldn't get it to load. I couldn't understand the imp module correctly. 1) Is there a very simple way to just take a file path and name, that I could use to open the source file, and load it as a module object, no strings attached? 2) Is there already a framework around that will do what I need? I've tried py.test, but I really do not like the way it displays results. From cyril.bazin at gmail.com Fri Feb 11 20:57:06 2005 From: cyril.bazin at gmail.com (Cyril BAZIN) Date: Sat, 12 Feb 2005 02:57:06 +0100 Subject: listerator clonage Message-ID: Hello, I want to build a function which return values which appear two or more times in a list: So, I decided to write a little example which doesn't work: #l = [1, 7, 3, 4, 3, 2, 1] #i = iter(l) #for x in i: # j = iter(i) # for y in j: # if x == y: # print x In thinked that the instruction 'j= iter(i)' create a new iterator 'j' based on 'i' (some kind of clone). I wrote this little test which show that 'j = iter(i)' is the same as 'j = i' (that makes me sad): #l = [1, 7, 3, 4, 2] #i = iter(l) #j = iter(i) #k = i #i, j, k (, , ) Just in order to test, I wrote these little test: #l = [1, 7, 3, 4, 2] #i = iter(l) #import pickle #j = pickle.loads(pickle.dumps(i)) Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\pickle.py", line 1386, in dumps Pickler(file, protocol, bin).dump(obj) File "C:\Python24\lib\pickle.py", line 231, in dump self.save(obj) File "C:\Python24\lib\pickle.py", line 313, in save rv = reduce(self.proto) File "C:\Python24\lib\copy_reg.py", line 69, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle listiterator objects #import copy #j = copy.copy(i) Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\copy.py", line 95, in copy return _reconstruct(x, rv, 0) 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: object.__new__(listiterator) is not safe, use listiterator.__new__() So, I would like to know if there is a way to 'clone' a 'listiterator' object. I know that is possible in Java for example... If it is impossible, have you better ideas to find duplicate entries in a list... Thanks, Cyril From eppstein at ics.uci.edu Sun Feb 20 12:59:21 2005 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 20 Feb 2005 09:59:21 -0800 Subject: exercise: partition a list by equivalence References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> <1108814276.680736.264380@l41g2000cwc.googlegroups.com> <37pb5jF5fnfivU1@individual.net> <1108890925.941814.45860@g14g2000cwa.googlegroups.com> <1108895373.013257.192310@l41g2000cwc.googlegroups.com> Message-ID: In article <1108895373.013257.192310 at l41g2000cwc.googlegroups.com>, "John Machin" wrote: > > it would be nice if the two working programs do not use some package. > > This problem shouldn't need to. > > Look at the newsgroup again. By my count there are apparently-working > versions from SIX people: Reinhold, bear.+, Brian Beck, David Eppstein, > yourself, and me. Only David's uses stuff that's not in the Python 2.4 > off-the-shelf distribution. Where "stuff" means a single 62-line file that I linked to in my post. -- David Eppstein Computer Science Dept., Univ. of California, Irvine http://www.ics.uci.edu/~eppstein/ From simoninusa2001 at yahoo.co.uk Thu Feb 17 14:00:16 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 17 Feb 2005 11:00:16 -0800 Subject: Pausing a program - poll/sleep/threads? In-Reply-To: <1119nf8qqj5gfbe@corp.supernews.com> References: <1108625477.222091.34680@l41g2000cwc.googlegroups.com> <1119nf8qqj5gfbe@corp.supernews.com> Message-ID: <1108666816.520517.91390@o13g2000cwo.googlegroups.com> Hmm, yes I had thought of looking around PyQt for a timer, forgot about it though. As far as querying the server every few seconds, it does make sense (you don't miss events) and is the recommended way of doing things with InetCtrl, but I'd prefer to save the bandwidth/server load than have realtime status updates. The status also updates whenever you send a command (like play/pause). I'm really stuck on how to implement this now.... From tom.willis at gmail.com Wed Feb 16 10:00:07 2005 From: tom.willis at gmail.com (Tom Willis) Date: Wed, 16 Feb 2005 10:00:07 -0500 Subject: low-end persistence strategies? In-Reply-To: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> Message-ID: Sounds like you want pickle or cpickle. On Tue, 15 Feb 2005 19:00:31 -0800 (PST), Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > I've started a few threads before on object persistence in medium to > high end server apps. This one is about low end apps, for example, a > simple cgi on a personal web site that might get a dozen hits a day. > The idea is you just want to keep a few pieces of data around that the > cgi can update. > > Immediately, typical strategies like using a MySQL database become too > big a pain. Any kind of compiled and installed 3rd party module (e.g. > Metakit) is also too big a pain. But there still has to be some kind > of concurrency strategy, even if it's something like crude file > locking, or else two people running the cgi simultaneously can wipe > out the data store. But you don't want crashing the app to leave a > lock around if you can help it. > > Anyway, something like dbm or shelve coupled with flock-style file > locking and a version of dbmopen that automatically retries after 1 > second if the file is locked would do the job nicely, plus there could > be a cleanup mechanism for detecting stale locks. > > Is there a standard approach to something like that, or should I just > code it the obvious way? > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Thomas G. Willis http://paperbackmusic.net From mail.python.org at bdash.net.nz Thu Feb 17 18:42:01 2005 From: mail.python.org at bdash.net.nz (Mark Rowe) Date: Fri, 18 Feb 2005 12:42:01 +1300 Subject: msnp, friends list In-Reply-To: <1108679723.100970.322170@c13g2000cwb.googlegroups.com> References: <1108665091.090003.59630@c13g2000cwb.googlegroups.com> <1108679723.100970.322170@c13g2000cwb.googlegroups.com> Message-ID: <5c88935652ad34ddd6b057a0014d39d0@bdash.net.nz> On Feb 18, 2005, at 11:35 AM, jr wrote: > Sorry, I guess what I meant to ask was the status of the friends in the > friends list begin updated. Right now we have a friends list which is > being populated with the correct users, but their status (online, > offline) is never getting set. For some reason the events aren't being > fired?? Ok, I've seen this problem before. Basically, the MSN servers do not send state changes for your buddies if you change your status from offline -> online before you have retrieved your entire buddy list. There doesn't appear to be a way around that with msnp as it always changes your state after sign-in, and it fails to group the buddy list state into a single transaction so that you can tell when the entire list has been retrieved... It should be relatively simple to adapt the code to fix the problem. Regards, Mark Rowe From deetsNOSPAM at web.de Wed Feb 16 08:48:40 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 16 Feb 2005 14:48:40 +0100 Subject: low-end persistence strategies? References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> Message-ID: <37h194F50j4pkU1@individual.net> Maybe ZODB helps. -- Regards, Diez B. Roggisch From jeremy+plusnews at jeremysanders.net Wed Feb 16 08:56:16 2005 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Wed, 16 Feb 2005 13:56:16 +0000 Subject: supress creation of .pyc files References: Message-ID: On Wed, 16 Feb 2005 14:53:22 +0100, Thomas Guettler wrote: > The imported file is a config file, not a script. You could use execfile() to read the file, and not import. Jeremy From vibroverb at hotmail.com Wed Feb 23 09:19:43 2005 From: vibroverb at hotmail.com (Deltones) Date: 23 Feb 2005 06:19:43 -0800 Subject: Sizers VS window size References: Message-ID: Brian Victor wrote in message news:... > Deltones wrote: > > However, if I add this part from the tutorial, I get a much smaller > > window. Why is there an interference with the result I want when > > adding the sizer code? > [snip] > > self.sizer.Fit(self) > > As noted in the the docs for Fit(): "Tell the sizer to resize the window > to match the sizer's minimal size." Take this call out and the size > should be as you expect. Thanks Brian, that was it. I admit I'm having quite a lot of fun learning the Python/wxPython combo, but man is there a lot of concepts to grasp! Denis From smitty_one_each at bigfoot.com Wed Feb 2 06:43:08 2005 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Wed, 02 Feb 2005 06:43:08 -0500 Subject: [perl-python] string pattern matching References: <1107290707.549792.199860@c13g2000cwb.googlegroups.com> <2uWdnWyp5M1Fip3fRVn-sQ@rogers.com> Message-ID: >>>>> Stephen Thorne writes: > On Tue, 01 Feb 2005 21:19:34 -0500, Chris Smith > wrote: >> Falls into the 'cure worse than the disease' category. It's >> really just a prompt to explore the corners of Gnus, and >> determine how to give X.L. the thorough ignoring he deserves. > *headdesk* > I'm using gmail, and I can set up the filter trivially > (from:xah at xahlee.org -> delete), but I just wasn't thinking > clearly. I was cursing not having the ability to use a procmail > filter while the solution was right in front of me. > Regards, Stephen. There, there, friend; we've all reached for the Big, Fancy Hammer (BFH) when there was a lazier way to do it. ;) Best, Chris From franz.steinhaeusler at utanet.at Thu Feb 24 08:17:31 2005 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Thu, 24 Feb 2005 14:17:31 +0100 Subject: wanted: C++ parser written in Python Message-ID: Hello NG, has anyone written such a thing in python? Where could I look for? (I need it for an editor written in wxPython to display function names, include, global variables, classes, ... in a sidepanel). kind regards, -- Franz Steinhaeusler From tjreedy at udel.edu Fri Feb 25 12:47:18 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Feb 2005 12:47:18 -0500 Subject: accessor/mutator functions References: <1109315698.002207.245690@g14g2000cwa.googlegroups.com> Message-ID: wrote in message news:1109315698.002207.245690 at g14g2000cwa.googlegroups.com... > When I look at how classes are set up in other languages (e.g. C++), I > often observe the following patterns: > 1) for each data member, the class will have an accessor member > function (a Get function) > 2) for each data member, the class will have a mutator member function > (a Set function) > 3) data members are never referenced directly; they are always > referenced with the accessor and mutator functions > > My questions are: > a) Are the three things above considered pythonic? As others have said, 'no', as in 'unnecessary because we have a better way to accomplish the same purpose without doubling the attribute namespace'. The purpose of the pattern is to hide the specific implementation of a class (which attributes are static and which dynamic) and to allow that implementation to change without changing programs that use the class. Consider a complex class with interdependent .real, .imag, .rad, and .theta attributes and the possible behind-the-scene implementations for what is kept static and how they are kept synchronized. The need for get/set to accomplish this in C++ arises from the fact that attribute names are resolved at compile time, so that x.a syntax can only be used for simple static attributes and access. Python, on the other hand, has means to 'magically' map what looks like direct attribute access into a function call. First there was __get/setattr__ (which is awkward for multiple dynamic attributes) and now properties with get/set/del for individual dynamic attributes. > b) What are the tradeoffs of using getattr() and setattr() rather than > creating accessor and mutator functions for each data member? > > -- > http://mail.python.org/mailman/listinfo/python-list > From mike at maibaum.org Fri Feb 25 09:39:00 2005 From: mike at maibaum.org (Michael Maibaum) Date: Fri, 25 Feb 2005 14:39:00 +0000 Subject: split a directory string into a list In-Reply-To: <4D97153E7D88F44FB6B534C661EE42900300A89C@medexch1.medplus.com> References: <4D97153E7D88F44FB6B534C661EE42900300A89C@medexch1.medplus.com> Message-ID: On 25 Feb 2005, at 14:09, Harper, Gina wrote: > I would start with something like this: > somestring = '/foo/bar/beer/sex/cigarettes/drugs/alcohol/' > somelist = somestring.split('/') > print somelist However - this will not work on Windows. It'd work on all the OS I usually use though ;) Michael From steve at holdenweb.com Mon Feb 28 12:40:18 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 28 Feb 2005 11:40:18 -0600 Subject: bsddb for k, v in db.items(): do order the numbers ? In-Reply-To: References: <1109608259.047662.256140@z14g2000cwz.googlegroups.com> Message-ID: Christopher De Vries wrote: > On Mon, Feb 28, 2005 at 08:30:59AM -0800, martijn at gamecreators.nl wrote: > >>WHen I use the code below and printing all the results i get this: >>------ >>0 1 10 >>11 2 3 >>4 5 6 >>7 8 9 >>------ >>But I want >>------ >>0 1 2 >>3 4 5 >>6 7 8 >>9 10 11 >>------ > > > If you want your key, value pairs in a certain order you have to sort them > yourself. Dictionaries and bsddb keys are unsorted. > Remember, also, that the keys are strings, so you'll need to convert them to numbers if you want them to sort numerically - otherwise "11" will come before "2". regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From crankycoder at gmail.com Fri Feb 25 09:46:08 2005 From: crankycoder at gmail.com (Victor Ng) Date: Fri, 25 Feb 2005 09:46:08 -0500 Subject: Is there way to determine which class a method is bound to? Message-ID: I'm doing some evil things in Python and I would find it useful to determine which class a method is bound to when I'm given a method pointer. For example: class Foo(object): def somemeth(self): return 42 class Bar(Foo): def othermethod(self): return 42 Is there some way I can have something like : findClass(Bar.somemeth) that would return the 'Foo' class, and findClass(Bar.othermethod) would return the 'Bar' class? vic From sandeep.sandy at gmail.com Wed Feb 9 08:07:52 2005 From: sandeep.sandy at gmail.com (sandy) Date: 9 Feb 2005 05:07:52 -0800 Subject: Performance Issues of MySQL with Python Message-ID: <1107954472.246556.258030@g14g2000cwa.googlegroups.com> Hi All, I am a newbie to MySQL and Python. At the first place, I would like to know what are the general performance issues (if any) of using MySQL with Python. By performance, I wanted to know how will the speed be, what is the memory overhead involved, etc during database specific operations (retrieval, update, insert, etc) when MySQL is used with Python. Any solutions to overcome these issues (again, if any)? Thanks and Regards, Sandeep From tzot at sil-tec.gr Fri Feb 25 03:54:27 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 25 Feb 2005 10:54:27 +0200 Subject: duplicate file finder References: <3vvr11dvtbu030065pj9ptmj1i2eelodq8@4ax.com> Message-ID: On Thu, 24 Feb 2005 15:32:03 -0800, rumours say that Lowell Kirsh might have written: >It looks pretty good, but I'll have to take a better look later. Out of >curiosity, why did you convert the first spaces to pipes rather than add >the code as an attachment? (As you probably noticed, the pipes ended up as dots in the final version, but I forgot to change the text.) I considered the code to be small enough to leave it in the message. And using some non-space character at the start of every line (usually dots) is common use lately in the group. Even if one doesn't use vi for editing, it's easiest with Idle to remove the dot at the start of every line. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From fuzzyman at gmail.com Fri Feb 11 04:58:51 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 11 Feb 2005 01:58:51 -0800 Subject: PyINI : Cross-Platform INI parser In-Reply-To: <3f_Od.26957$QG6.468964@twister2.libero.it> References: <3f_Od.26957$QG6.468964@twister2.libero.it> Message-ID: <1108115931.429635.101290@f14g2000cwb.googlegroups.com> Giovanni Bajo wrote: > SeSe wrote: > > > hi, every one, > > > > I started a opensource project PyINI for corss-platform *.ini parsing > > at http://sourceforge.net/projects/pyini/ > > > > I have released a simple alpha version, which can read *.ini, with > > some extended features such as "key=value1,value2,value3". I also > > made a c++ binding to PyINI with elmer toolkit. > > > The most useful feature would be to be able to write INI files back without > affecting their formatting, without removing user commands, etc. This is what > Windows APIs do, and it is what I am missing from most INI parsing libraries > out there. > -- > Giovanni Bajo ConfigObj easily writes back, files but doesn't *yet* support the full 'ini' file spec (empty values and split lines it doesn't yet support). These are targetted for next release. What aspects of formatting do you want to keep, and I'll try and include them ? http://www.voidspace.org.uk/python/configobj.html Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From gdamjan at gmail.com Mon Feb 7 16:18:22 2005 From: gdamjan at gmail.com (Damjan) Date: Mon, 07 Feb 2005 22:18:22 +0100 Subject: Big development in the GUI realm References: <1107795145.049239.73450@l41g2000cwc.googlegroups.com> Message-ID: <36q48uF55o5c6U1@individual.net> > For all you GUI developers, things just got a little more interesting. > Trolltech will soon be offering the QT GUI toolkit for Windows under > the GPL license. That means that PyQt may become a much more popular > option in the near future. This applies to QT-4 only. I wonder how much of PyQT is ready for QT4? Anyway its time for a PyQT based VB-killer [ a GPL one :) ]. -- damjan From tim.peters at gmail.com Tue Feb 15 14:39:53 2005 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 15 Feb 2005 14:39:53 -0500 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: <1f7befae050215113977b1506a@mail.gmail.com> [Tim Peters] >> Well, I'm a Director of the Python Software Foundation, and my view is >> "the more platforms the merrier". [Ilias Lazaridis] > I extract: "you are intrested, that the source-code-base compiles > directly with MinGW (and other compilers)". Sure, I'm in favor of that. I'm also in favor of world peace, for that matter . > Thus you should be intrested, that existent patches are incorporated > into the source-code-base. That one doesn't follow. It follows that I'd like to see existing patches _reviewed_, but not necessarily that I'd be in favor of incorporating them if I had time to review them myself. > The suggested process ist: use of #defines whenever possible, to avoid > influence on the existent behaviour of the code. Patches are reviewed on technical merit, balancing the tradeoffs; #defines are actually discouraged when it's possible to do a thing without introducing platform-specific #ifdefs. A problem is that a patch won't get reviewed unless a volunteer does a review, and we've got an increasing backlog of unreviewed patches because of that. The most effective way for a person P to get their patch reviewed now is for P to volunteer to review 5 other patches first. There are a few Python developers who have promised, in return, to review P's patch then. >> But I'm not paid to work on Python, and I don't have time to volunteer to help >> MinGW along, so I don't anticipate that I'll do anything here beyond writing >> this reply. > You have done already very much. > > But should should take some time to evaluate community needs. I don't know what that means, but plausible meanings sound futile. No matter what I think "the community" needs, it's not going to happen unless somebody else does the work: I can't tell anyone else what to do. Heck, I don't even want to. It sounds like you might want development driven by some kind of marketing study. Nothing wrong with that, if so, but it's not how open source works. An entity like the Python Business Forum would presumably be more open to that tack (although I doubt the PBF would have a natural interest in MinGW). "Minority platforms" generally don't get far unless a truly dedicated volunteer shows up. For example, Jason Tishler does an excellent job on Python's Cygwin port, as does Andrew MacIntyre on OS/2 EMX, and they've both done so for years. Nobody asked them to do this (AFAIK), it's more that nobody could _stop_ them from doing it. They're motivated by love of the platforms they take care of. In the absence of anyone willing to pay someone else here, that's what's truly needed. > ... > This effort could be driven by the intrested community members (which > obviously exist). Then maybe they need to be better organized, and/or more assertive in pushing their interests. If someone is getting left behind here, they should speak up on the python-dev list. ... > Now, can you please tell me the process I have to follow to suggest the > following (to the PSF or to the programmers or to the decision takers), > possibly to get at least a vote on it: No such thing will happen -- forget that. For MinGW to be supported forever, it's necessary and sufficient that a specific person volunteer to support MinGW forever. If that person goes away, so does the support they provided; it's the same story for Cygwin, and even for Linux and native Windows. A difference is that Linux and native Windows attract more than enough volunteers so that ongoing support seems statistically certain. But, e.g., if Andrew MacIntyre went away, I wouldn't bet on OS/2 EMX support continuing. > "Please ensure that the source-code-base compliles directly with MinGW. > The suggested process is to: > > * provide the infrastructure > (e.g. mailinglist, issue- tracking-category,... ) > > * Notify the community about this subproject to channelise efforts > > * include existing MinGW specific patches > > * ensure future verificatioin of changes, > * optimal: due to an automated build-system > * or simpler: due to community-feedback > " If a specific person or group wants to volunteer to do all that, year after year, they can start doing it today. The PSF won't do any of it (although the PSF will fund and arrange to run the Python website, and one way or another supply a bug tracker, source-control system, and other infrastructure for keeping the Python project as a whole running). From harlinseritt at yahoo.com Sat Feb 26 03:48:43 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 26 Feb 2005 00:48:43 -0800 Subject: Yet another logo design... In-Reply-To: References: <6c9897c2.0502251551.2b8feb@posting.google.com> Message-ID: <1109407723.289500.118050@o13g2000cwo.googlegroups.com> I like the type logo (on the right of the image). The black snake-like image can be cropped though. :-) Harlin From irmen.NOSPAM at xs4all.nl Sat Feb 12 14:55:44 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sat, 12 Feb 2005 20:55:44 +0100 Subject: ANN: pyMinGW support for Python 2.3.5 (final) is available In-Reply-To: <1108237204.920670.213190@f14g2000cwb.googlegroups.com> References: <1108189500.707806.316520@g14g2000cwa.googlegroups.com> <1108237204.920670.213190@f14g2000cwb.googlegroups.com> Message-ID: <420e5ef3$0$28979$e4fe514c@news.xs4all.nl> Simon John wrote: > Maybe I'll fork out the 100usd for Visual Studio .NET 2003 after all.... $100? Where? Last time I looked it was closer to $800. --Irmen From __peter__ at web.de Fri Feb 18 12:36:10 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Feb 2005 18:36:10 +0100 Subject: Newbie CGI problem References: Message-ID: Rory Campbell-Lange wrote: > #!/usr/bin/python > import cgi > print "Content-type: text/html\n\n" > print "hi" > > Gives me the following in my browser: > > ''' > hi > Content-type: text/html > > > hi > ''' > > Why are there two 'hi's? You have chosen a bad name for your script: cgi.py. It is now self-importing. Rename it to something that doesn't clash with the standard library, and all should be OK. Peter From __peter__ at web.de Thu Feb 3 06:32:00 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Feb 2005 12:32:00 +0100 Subject: SUCCESS! References: <41f6c3f7$1@nntp.zianet.com> <41f85dd8@nntp.zianet.com> <41f97058$1@nntp.zianet.com> <41faee43$1@nntp.zianet.com> Message-ID: Erik Johnson wrote: > I installed readline-devel. (Thank you for re-asking that question.) I had that hunch :-) > Interestingly, configure *still* says... > ej at sand:~/Python-2.3.4> ./configure | grep readline > checking for rl_pre_input_hook in -lreadline... no > checking for rl_completion_matches in -lreadline... no I get similar messages for Python 2.4 on Suse 9.1, but the history *does* work by default. Maybe if you start with a newly unzipped copy and do ./configure it will work for you, too? Pardon me for not digging deeper into the gory details... > Thanks again for your help! :) You're welcome. Peter From VBoycheva at jea.net Mon Feb 7 09:27:26 2005 From: VBoycheva at jea.net (Valentina Boycheva) Date: Mon, 7 Feb 2005 09:27:26 -0500 Subject: executing VBScript from Python and vice versa Message-ID: <51B182D9911B914EA2243227834E86C005CB0760@jeamail.jea.net> Thanks to Michel Claveau and Paul Paterson for providing examples on how to use ScriptControl to embed VBScript in Python script. I've only tried this once before on another occasion and it was fascinating to see how a function generates another function! Valentina From tjreedy at udel.edu Fri Feb 25 13:26:58 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Feb 2005 13:26:58 -0500 Subject: strange SyntaxError References: <20050225133355.GI20239@csola.ugyvitelszolgaltato.hu> Message-ID: "Attila Szabo" wrote in message news:20050225133355.GI20239 at csola.ugyvitelszolgaltato.hu... > Hi, > > I wrote this sample piece of code: > > def main(): > lambda x: 'ABC%s' % str(x) > for k in range(2): exec('print %s' % k) > > main() > > With the lambda line, I get this: > SyntaxError: unqualified exec is not allowed in function 'main' > it contains a nested function with free variables The lambda expression is the nested function, the free variable is 'str'. Since this general situation *could* be a problem, as Scott explained, the compiler quits, since it cannot do the analysis needed to determine whether the specific situation *is* a problem. Terry J. Reedy From jaydonnell at gmail.com Wed Feb 16 14:03:21 2005 From: jaydonnell at gmail.com (jdonnell) Date: 16 Feb 2005 11:03:21 -0800 Subject: web spider and password protected pages Message-ID: <1108580601.884193.263890@g14g2000cwa.googlegroups.com> I've been writing a simple web spider for fun, and I've run into a problem I can't figure out. The spider hangs (waits for username and pass) when I hit a page that requires .htaccess authentication. self.f = urllib.urlopen('http://blogbloc.com/~jay/test/') #nothing below here gets executed print self.f.info() ... It hangs as soon as I call urllib.urlopen(). I was going to try to read the info and break for pages that require authentication, but it hangs before I can call self.f.info() Any ideas? From sjmachin at lexicon.net Sun Feb 20 03:52:46 2005 From: sjmachin at lexicon.net (John Machin) Date: 20 Feb 2005 00:52:46 -0800 Subject: newbie question - exception processing References: <1108883612.511033.154920@o13g2000cwo.googlegroups.com> Message-ID: <1108889566.821032.155660@f14g2000cwb.googlegroups.com> mirandacascade at yahoo.com wrote: > O/S: Windows XP Service Pack 2 > Python version: 2.4 > > Unable to understand how to build a class to handle an exception. > > Contents of sample01.py: > import exceptions > class SampleMain: > try: > def __init__(self): > print 'in SampleMain constructor' > > def Allowed(self): > print 'in allowed' > > def NotYetAllowed(self): > UCError = UnderConstructionError('not yet ready') > raise UCError > > except UnderConstructionError, e: > print e.msg > > class Error(exceptions.Exception): > def __init__(self): > print 'in base class constructor' > > class UnderConstructionError(Error): > def __init__(self, message): > print 'in UnderConstructionError constructor' > self.msg = message ! def __str__(self): ! return self.msg > > Copy/paste of interactive window: > PythonWin 2.4 (#60, Nov 30 2004, 09:34:21) [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 sample01 > >>> x = sample01.SampleMain() > in SampleMain constructor > >>> x.NotYetAllowed() > in UnderConstructionError constructor > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\sample01.py", line 12, in NotYetAllowed > raise UCError > UnderConstructionError: > >>> > > My questions are: > 1) What is causing the error described in the Traceback? The text was printed because there was no mechanism to print the error object. > 2) Given that what I want to happen when the NotYetAllowed() method is > called is: > a) an exception to be raised Happening already. > b) the exception results in a message getting printed; the message > should come from the place where the exception was raised, and it > should be passed to the exception class as a string object; so in this > case the message that should be printed is 'not yet ready' Insert __str__ method as per above. > c) the exception gets handled with the try/except within the > SampleMain class > Now that would be difficult. That 'try' statement is executed when the class is *loaded*. Put a print statement just before the try statement and you'll see what I mean. It's not a declaration that encompasses all calls to methods of instances of the class. Let's take a step back: Why do you think you need to catch and *handle* such exceptions? You have some methods that aren't fit to be seen in public yet? Don't tell anyone about them. Don't put your code in a callable place. Alternatively, put "raise NotImplementedError" -- that's a standard built-in exception -- as the first line of each method. A bit of explanation from you might be useful so that the help can be tailored. And if all you really want to do is just print a message, that's what happens by default e.g. >>> raise NotImplementedError, 'come back after lunch' Traceback (most recent call last): File "", line 1, in ? NotImplementedError: come back after lunch >>> class Mistake(Exception): ... pass ... >>> def foo(): ... raise Mistake, 'somebody goofed' ... >>> foo() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in foo __main__.Mistake: somebody goofed >>> HTH, John From sandip at lug-delhi.org Sat Feb 12 05:16:58 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Sat, 12 Feb 2005 15:16:58 +0500 Subject: Unittesting for web applications Message-ID: Can someone suggest me some good resources for learning how to use unittests for web applications? Do we always have to cook up our own webpage scrapers to test the code? - Sandip -- Sandip Bhattacharya * Puroga Technologies * sandip at puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From akineko at pacbell.net Wed Feb 16 13:51:27 2005 From: akineko at pacbell.net (Aki Niimura) Date: 16 Feb 2005 10:51:27 -0800 Subject: Pmw.Balloon under Windows Message-ID: <1108579886.983146.56130@z14g2000cwz.googlegroups.com> Hello everyone, I'm encountering a weird problem and couldn't find any Internet postings that are relevant to my problem and it seems coming from the Pmw Balloon widget inside. I have developed a Tkinter software using Pmw. The software is being developed under Solaris but is targeting all platforms including Windows. The software is working fine under Solaris 9. However, when I tried it under Windows, it worked also fine but it spit out the following error message when exiting. (from cygwin terminal) % c:/Python23/python my_app.py This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. (the same error message is observed when I run the program directly in Windows XP environment.) // First, I thought I screwed up something because it was working fine before with my older software version. After painful investigation, I found Pmw.Balloon was causing this problem (because the problem went away if I commented out all balloon statements). Then I compared my usages and Pmw Balloon example because the example didn't cause this. (http://pmw.sourceforge.net/doc/Balloon.html) But I didn't see any problem in my coding. // Then I found two clues: (1) The problem won't occur if I quit the program by clicking 'X' of the Window decoration. (not from Quit in the Menu) (2) The Pmw Balloon example has the exact same problem *if* I change the program to quit using widget quit() method. self.suicide = Tkinter.Button(frame, text='Kill me soon!', command = parent.quit) # this causes the problem # command = self.killButton) # The original one Of course, the problem is occurring only under Windows. (Windows XP/Cygwin) // My questions are: (1) Why my program is complaining and is there any workaround? (2) What is the difference between using widget quit() method and using Windows 'X' button. - I know clicking Windows 'X' button generates an event but I thought - ultimately it reached to the same routine to terminate the program. (3) Is it possible to fake clicking 'X' button? I see a widget has event_generate() method. // Any feedbacks, comments are highly appreciated. It would be nice if you can send your reply to . Thank you for your attention. Best regards, Aki Niimura From ilias at lazaridis.com Fri Feb 18 14:29:44 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Fri, 18 Feb 2005 21:29:44 +0200 Subject: - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <1108398011.213872.321390@o13g2000cwo.googlegroups.com> <1108411893.940158.270090@c13g2000cwb.googlegroups.com> <42163065.8070708@lazaridis.com> Message-ID: Josef Meile wrote: > It looks like here the only worth words are yours. Didn't > you close this thread? yes, but when reviewing again I found this lack [created by myself due to private conversation]. > I will refresh your mind with your own unpolite way: I find this very polite [to notify conversation partners instead of letting them wait for an answer]. > """ > Ilias Lazaridis wrote: > [...] > > closing thread > http://groups-beta.google.com/group/comp.lang.python/msg/f2ae9cdbe16676d1 > """ > > Anyway, I will add some comments: [...] The first step is to make a pyMinGW project. If one is intrested, he has possibly more luck [than I had] to convince the author of pyMinGW. Good luck. . -- http://lazaridis.com From fitzgeraldsteele at gmail.com Wed Feb 23 08:09:30 2005 From: fitzgeraldsteele at gmail.com (Fitzgerald Steele) Date: 23 Feb 2005 05:09:30 -0800 Subject: File/Directory hacks - is there a better way to do this? Message-ID: <1109164170.566047.206390@z14g2000cwz.googlegroups.com> I had a software package screw up a directory tree by placing all the files in a directory of the same name. So I wound up with: Root file1.txt (dir) file1.txt (file) file2.txt (dir) file2.txt (file) Annoying. So I wrote the following script, which fixed the problem by renaming and copying the file up to the root directory, removing the intermediate directory, and finally restoring the orginal file name. Is there a better (faster, or fewer lines of code, or more 'python-esque') way to do? In particular, I know the latest versions of python includes iterators, generators, and decorators...but I haven't had a chance to really read about them, or understand how to use them properly. So I'd love to hear if the new tools could've solved this simpler/faster. Thanks! ------------------------------------------------------ #!/user/bin/env python import os, os.path, shutil top = 'c:\$user' class fixdirectories: def __init__(self, top): self.top = top def walk(self): for root, dirs, files in os.walk(self.top, topdown=False): rootdir, roottail = os.path.split(root) for name in files: if name.lower() == roottail: oldname = os.path.join(root, name) tmpname = os.path.join(rootdir, "PRE-" + name) newname = os.path.join(rootdir, name) shutil.move(oldname, tmpname) try: os.rmdir(root) print "removing: " + rootdir shutil.move(tmpname, newname) except: print "Could not remove: " + root if __name__ == "__main__": f = fixdirectories(top) f.walk() From ilias at lazaridis.com Mon Feb 14 14:14:14 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Mon, 14 Feb 2005 21:14:14 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: <4210c5c3$0$41647$a1866201@visi.com> References: <4210c5c3$0$41647$a1866201@visi.com> Message-ID: Grant Edwards wrote: > On 2005-02-14, Ilias Lazaridis wrote: > >>Fredrik Lundh wrote: >> >>>Ilias Lazaridis wrote >>> >>>>The idea that the Python Foundation cares about user needs would affect that. >>> >>>please let the users speak for themselves. >> >>I have. >> >>I've review several threads,publications, actions etc., that show that >>the users have this need. > > This is open source. You don't just order somebody else to do > what you want. You _do_ it and donate it to the community. I analyze the current situation. The is the fundamentall step before doing anything. But the reaction of this community raises some questions and my curiosity. >>please review the initial thread with care, i've pointed to >>some documents/thread. > > So what? You want it, you do it. I like to synchronize any efforts with the existing ones. That's why I ask some questions. nothing special. . -- http://lazaridis.com From apardon at forel.vub.ac.be Mon Feb 7 09:53:49 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Feb 2005 14:53:49 GMT Subject: Confused with methods References: <1grknb0.ygwohl17y6j5yN%aleaxit@yahoo.com> <1grmd4z.1tlm4e61650vedN%aleaxit@yahoo.com> Message-ID: Op 2005-02-07, Alex Martelli schreef : > Antoon Pardon wrote: > >> Op 2005-02-06, Alex Martelli schreef : >> > >> >> Isn't that inconsistent? >> > >> > That Python has many callable types, not all of which are descriptors? >> > I don't see any inconsistency there. Sure, a more generalized currying >> > (argument-prebinding) capability would be more powerful, but not more >> > consistent (there's a PEP about that, I believe). >> >> I think python is a bit inconsistent here, by using 'def' for >> two different things. > > It doesn't. > >> I think it would have been more consistent >> if def always produces a function > > It does. > > def g(self): pass > class A(object): > f = g > > class B(object): > def f(self): pass > > class C(object): pass > C.f = g > > class D(object): > f = B.f > > These four classes are essentially equivalent. def always produces a > function object and binds it to the name coming after keyword 'def'. > Any such function object, no matter how produced and how bound hither > and thither, always behaves in exactly the same way. > > You're free to like or dislike this arrangement, but calling it > "inconsistent" is a madman's folly, as it is TOTALLY consistent. Yes it is inconsistent with the rest of python. That you found a subset in which it is consistent doesn't change that. And what if you do: c = C() c.f = g The fact that a function in a class performs a lot of magic if it is called through an instance, that isn't performed otherwise, makes python inconsistent here. You may like the arrangement (and it isn't such a big deal IMO) but that doesn't make it consistent. -- Antoon Pardon From export at hope.cz Sat Feb 26 02:36:59 2005 From: export at hope.cz (export at hope.cz) Date: 25 Feb 2005 23:36:59 -0800 Subject: Watermark on images Message-ID: <1109403419.904324.115860@f14g2000cwb.googlegroups.com> Is there a way how to put a watermark on images by using Python? Lad. From ncoghlan at iinet.net.au Thu Feb 24 06:15:09 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 24 Feb 2005 21:15:09 +1000 Subject: Compile time evaluation (aka eliminating default argument hacks) Message-ID: <421DB73D.30407@iinet.net.au> Time for another random syntax idea. . . So, I was tinkering in the interactive interpreter, and came up with the following one-size-fits-most default argument hack: Py> x = 1 Py> def _build_used(): ... y = x + 1 ... return x, y ... Py> def f(_used = _build_used()): ... x, y = _used ... print x, y ... Py> f() 1 2 Py> x = 3 Py> f() 1 2 Works pretty well in terms of getting early binding, compile-time evaluation of expensive values and psuedo-constants, initialising a local with a shadowed value from an outer scope, sharing mutable values between invocations, and well, really, anything that default argument hacks are used for. It has the benefit of allowing use of a full suite at compile time, instead of the expressions one is usually limited to in default arguments hacks. It also slightly improves the argspec pollution situation by only using one argument instead of several. However, it's still ugly as sin, still pollutes the functions argspec, the lists of names in the assignment statement and the return statement have to be kept in sync manually, and you're now polluting the outer namespace as well. Not to mention the fact that the contents of the compile-time functions are miles away from where the results are used. But consider a syntax like the following: def f(): use x, y from: y = x + 1 # [1] print x, y [1] I'll grant that the binding of x from the outer scope here is more than a little obscure. However, I could see 'use x from: pass' becoming an idiom for early binding, in which case the example 'use' block could be written: use y from: y = x + 1 use x from: pass Then mixing early binding with early evaluation in the same 'use' block might simply be considered bad style, and discouraged (although not prevented). Essentially, the function is compiled as usual, and emits code at the location of the 'use' statement equivalent to that for "x, y = ". The relevant entry in co_consts is populated by executing the body of the 'use' statement with an implicit "return x, y" at the end. The environment for that execution is the same as that for any function defined at the same level as the containing scope of the 'use' statement (e.g. module level in the example). Multiple 'use' blocks would be allowed in a scope. A 'use' block at module level would simply mean that the result of calling the block gets marshalled into the compiled module file, rather than the block itself. You could get performance improvements on *any* function, simply by moving code which doesn't depend on the functions arguments inside a 'use' block. For modules, data structures initialised inside a using block could simply be unmarshalled rather than built anew. Cheers, Nick. P.S. I didn't search the archive, because I couldn't figure out any search terms for the topic that weren't swamped by irrelevant hits. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steven at lczmsoft.com Mon Feb 28 19:50:18 2005 From: steven at lczmsoft.com (steven at lczmsoft.com) Date: 28 Feb 2005 16:50:18 -0800 Subject: Hey, How Do I Distribute my New Completed Python Project? In-Reply-To: <1109598508.839761.278740@f14g2000cwb.googlegroups.com> References: <1109579904.014493.222540@o13g2000cwo.googlegroups.com> <1109598508.839761.278740@f14g2000cwb.googlegroups.com> Message-ID: <1109638218.905448.159500@f14g2000cwb.googlegroups.com> Thank You All From ville at spammers.com Thu Feb 10 06:55:51 2005 From: ville at spammers.com (Ville Vainio) Date: 10 Feb 2005 13:55:51 +0200 Subject: That horrible regexp idiom References: Message-ID: >>>>> "Stephen" == Stephen Thorne writes: Stephen> We've all seen it before. Its a horrible idiom that you Stephen> would achieve in another language by doing: Stephen> if (m = foo_pattern.search(subject)) Stephen> { } Stephen> else Stephen> { } Stephen> but it occured to me today, that it is possible to do it in python Stephen> without the extra line. Stephen> ' Stephen> '>>> def xsearch(pattern, subject): Stephen> '>>> yield pattern.search(subject) Stephen> '>>> for m in xsearch(foo_pattern, subject): Stephen> '>>> pass Stephen> '>>> else: Stephen> '>>> pass Stephen> simple, concise, requires no new syntax, and is only a Stephen> little confusing[1]! I'm always confused by for-else (lack of practice), but isn't the else clause going to be always executed when there is no break in the for suite? -- Ville Vainio http://tinyurl.com/2prnb From fredrik at pythonware.com Mon Feb 14 11:58:19 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Feb 2005 17:58:19 +0100 Subject: Probel with socket "recv" function on Win2000 References: <8C22373EA650AF40928EEA0C188D62D201810286@xmb-ams-338.emea.cisco.com> Message-ID: Guy Machlev wrote: > I have a problem with the socket recv() function while using it on > win-2000, the problem accrue while receiving data from socket in a > constant format (e.g. 1Byte then 4Bytes and then number of bytes > according to the previous 4Bytes number), this receiving action "fail" > after a bout ~120Kbytes of data the, actually the phenomena that accrue > after reading this amount of data is a kind of data skipping which mean > that the next recv is reading data start from ~121Kbytes I am losing > data between the 120 and 121, this phenomena is consistently happened > exactly at the same data point. I have tried to run the same script on > Linux and there it went perfect. > > anyone has any idea way it happened ? TCP or UDP? are you checking the length of the buffers you get back from recv? are you sure it's skipping and not just getting out of sync? does replacing the recv() with read() on a socket stream (use makefile() to create the stream) help? From eric_brunel at despammed.com Mon Feb 14 06:35:03 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 14 Feb 2005 12:35:03 +0100 Subject: Tkinter option_add for menu radiobutton References: Message-ID: On Sun, 13 Feb 2005 15:31:18 -0700, Bob Greschke wrote: [snip] > Root.option_add("*Radiobutton*selectColor", "black") > > also works fine for regular radiobuttons. What I can't > do is get the selectColor of the radiobutton's in the > menu to be black...the x.add_radiobutton() ones. > > Root.option_add("*Menu.Radiobutton*selectColor", "black")...nope > Root.option_add("*Menu*selectColor", "black")...no change Strange... The last one works for me (as it should - see http://www.tcl.tk/man/tcl8.4/TkCmd/menu.htm). What platform are you on and what is your tcl/tk version? - Eric Brunel - From raghulj at gmail.com Mon Feb 21 22:49:11 2005 From: raghulj at gmail.com (Raghul) Date: 21 Feb 2005 19:49:11 -0800 Subject: copying or moving the mail message using imaplib Message-ID: <1109044151.869953.187270@c13g2000cwb.googlegroups.com> Hi Friends, I am doing project in python.I am new to this. My problem is I want to move the mail message to other folder in the mail using imaplib (E.g) I want to move a message from the inbox to the Draft folder in my account using python code. Can any one help me by giving a sample code to do this? Thanks in advance From peter at engcorp.com Thu Feb 24 20:59:10 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 24 Feb 2005 20:59:10 -0500 Subject: user interface for python In-Reply-To: <86mztvf543.fsf@guru.mired.org> References: <1109131790.140672.209730@l41g2000cwc.googlegroups.com> <421c9031$1@nntp0.pdx.net> <86mztvf543.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > "There are no portable programs, only ported programs." > > -- John Gilmore (?) This doesn't really ring true, unless one insists on defining "portable" to include the idea of "universally". I've got dozens of Python utilities that run equally well on my Linux machines and my Windows machines. I didn't "port" them, I just wrote them in Python and put them in both places. Maybe I'm missing the point of Gilmore's comment... -Peter From sjmachin at lexicon.net Sat Feb 26 15:57:44 2005 From: sjmachin at lexicon.net (John Machin) Date: 26 Feb 2005 12:57:44 -0800 Subject: fdups: calling for beta testers In-Reply-To: <422044b9$1@news.vo.lu> References: <421f97eb$1@news.vo.lu> <1109380525.262724.275780@g14g2000cwa.googlegroups.com> <422044b9$1@news.vo.lu> Message-ID: <1109451464.546948.174830@z14g2000cwz.googlegroups.com> Patrick Useldinger wrote: > John Machin wrote: > > > (1) It's actually .bz2, not .bz (2) Why annoy people with the > > not-widely-known bzip2 format just to save a few % of a 12KB file?? (3) > > Typing that on Windows command line doesn't produce a useful result (4) > > Haven't you heard of distutils? > > (1) Typo, thanks for pointing it out > (2)(3) In the Linux world, it is really popular. I suppose you are a > Windows user, and I haven't given that much thought. The point was not > to save space, just to use the "standard" format. What would it be for > Windows - zip? Yes. Moreover, "WinZip", the most popular archive-handler, doesn't grok bzip2. > > (6) You are keeping open handles for all files of a given size -- have > > you actually considered the possibility of an exception like this: > > IOError: [Errno 24] Too many open files: 'foo509' > > (6) Not much I can do about this. In the beginning, all files of equal > size are potentially identical. I first need to read a chunk of each, > and if I want to avoid opening & closing files all the time, I need them > open together. > What would you suggest? Test, like I did, to see how many open handles you can get away with. I was not joking, 20 was the max on MS-DOS at one stage and I vaguely recall: (a) some low limits on various flavours of *x (b) the "ulimit" command can be used to vary the per-process limit but (c) there is a system-wide limit also. You should consider a fall-back method to be used in this case and in the case of too many files for your 1Mb (default) buffer pool. BTW 1Mb seems tiny; desktop PCs come with 512MB standard these days, and Bill does leave a bit more than 1MB available for applications. > > And what is "chown" -- any relation of Perl's "chomp"? > > chown is a Unix command to change the owner or the group of a file. It > has to do with controlling access to the file. It is not relevant on > Windows. No relation to Perl's chomp. The question was rhetorical. Your irony detector must be on the fritz. :-) > Did you actually run it on your > Windows box? Yes, with trepidation, after carefully reading the source. It detected some highly plausible duplicates, which I haven't verified yet. Cheers, John From peter at somewhere.com Tue Feb 15 14:22:28 2005 From: peter at somewhere.com (Peter Maas) Date: Tue, 15 Feb 2005 20:22:28 +0100 Subject: replacing ASP/VBScript with Python In-Reply-To: References: Message-ID: Robert Brewer schrieb: >>I'm now confident that it is doable and keen on finding out. The usual >>question: what is the one and best way to do it? ;) > > > Python ASP (pywin32), but put as little code as possible into the > ASP--make it just a stub to call the real Python app. That app will be > running persistently in the background, which should obviate most of the > need for session support. That's been my experience, anyway. Sounds reasonable. How do ASP-Python and IIS work together? Is the Python- Interpreter loaded each time a Python-ASP is called? > Here's an example (from > http://www.aminus.org/rbre/cation/html/admin/ASP.html): > > <%@Language=Python%> > <% > from cation.html.uiasp import UserInterfaceASP > from cation import catapp > > ui = UserInterfaceASP(catapp) > ui.request(Request, Response) > %> That's interesting, thanks for the URL and your advice. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From dalcolmo at vh-s.de Fri Feb 11 07:57:47 2005 From: dalcolmo at vh-s.de (Josef Dalcolmo) Date: 11 Feb 2005 13:57:47 +0100 Subject: Big development in the GUI realm References: <1107795145.049239.73450@l41g2000cwc.googlegroups.com> <5ocf01hmspufk3iusvm35p6hj4mes5heke@4ax.com> <4207c8db$0$21623$a1866201@visi.com> <36sip2F56jjmaU1@individual.net> Message-ID: You can distribute GPL'ed code in binary form, you just have to make the sources available as well. And, yes I would use this as a test: if your program needs gpl-ed code for some of it's functionality, you have to licence your program according to the GPL - unless you distribute the GPL'ed parts separately and your program is still basically functioning without the GPL'ed code. Now, if you are unsure about these questions and are serious about writing a program using GPL'ed code, the FSF is probably willing to help you with your questions. Besides this, why not putting your code under the GPL? - Josef From martin at v.loewis.de Fri Feb 18 15:16:01 2005 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 18 Feb 2005 21:16:01 +0100 Subject: unicode encoding usablilty problem In-Reply-To: References: Message-ID: <42164d01$0$4676$9b622d9e@news.freenet.de> aurora wrote: > The Java > has a much more usable model with unicode used internally and > encoding/decoding decision only need twice when dealing with input and > output. In addition to Fredrik's comment (that you should use the same model in Python) and Walter's comment (that you can enforce it by setting the default encoding to "undefined"), I'd like to point out the historical reason: Python predates Unicode, so the byte string type has many convenience operations that you would only expect of a character string. We have come up with a transition strategy, allowing existing libraries to widen their support from byte strings to character strings. This isn't a simple task, so many libraries still expect and return byte strings, when they should process character strings. Instead of breaking the libraries right away, we have defined a transitional mechanism, which allows to add Unicode support to libraries as the need arises. This transition is still in progress. Eventually, the primary string type should be the Unicode string. If you are curious how far we are still off that goal, just try running your program with the -U option. Regards, Martin From ilias at lazaridis.com Sun Feb 20 06:29:02 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sun, 20 Feb 2005 13:29:02 +0200 Subject: - E02 - Support for MinGW Open Source Compiler In-Reply-To: <1108841089.636568.292320@c13g2000cwb.googlegroups.com> References: <42172136$0$27576$9b622d9e@news.freenet.de> <1108841089.636568.292320@c13g2000cwb.googlegroups.com> Message-ID: A.B., Khalid wrote: [...] - (comments) I've just overflown your comments for a few seconds. And I got my confirmations. Thank you for your time. > -- > pyMinGW: > http://jove.prohosting.com/iwave/ipython/pyMinGW.html . -- http://lazaridis.com From kid at kendermedia.com Wed Feb 2 20:17:16 2005 From: kid at kendermedia.com (Kevin Dangoor) Date: Wed, 02 Feb 2005 20:17:16 -0500 Subject: XML with Unicode: what am I doing wrong? Message-ID: <42017B9C.1080601@kendermedia.com> In article news.t-online.com>, "Diez B. Roggisch" web.de> wrote: > you confuse unicode with utf8. Expat can parse the latter - the former is > internal to python. And passing it to something that needs a string will > result in a conversion - which fails because of the ascii encoding. Ahh... that makes sense. I kept thinking that if I'm working with unicode strings, I should be passing around unicode objects. What you say makes sense, though, that the PyExpat understands UTF-8 encoded strings. Working with unicode objects in Python is so transparent, it's easy to forget about what a C extension would likely want. Thanks Diez and Just for the quick responses! Kevin From fumanchu at amor.org Fri Feb 4 11:35:54 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 4 Feb 2005 08:35:54 -0800 Subject: Converting a string to a function pointer Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339835A@exchange.hqamor.amorhq.net> H?kan Persson wrote: > I am trying to "convert" a string into a function pointer. > Suppose I have the following: > > from a import a > from b import b > from c import c > > funcString = GetFunctionAsString() > > and funcString is a string that contains either "a", "b" or "c". > How can I simply call the correct function? > I have tried using getattr() but I don't know what the first (object) > argument should be in this case. If you want to avoid typing all of the "import" statements, use something like my public-domain xray module (http://www.aminus.org/rbre/python/xray.py) and then write: import xray funcString = GetFunctionAsString() func = xray.functions(funcString) func() Dotted-package names work with that module, by the way. The benefit is that you can then import any function in any module. The curse is that you can then import any function in any module. ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org From gargonx at gmail.com Sun Feb 20 12:39:06 2005 From: gargonx at gmail.com (gargonx) Date: 20 Feb 2005 09:39:06 -0800 Subject: help please References: <1108254434.871062.314510@g14g2000cwa.googlegroups.com> <1108260752.791847.180060@l41g2000cwc.googlegroups.com> <1108324679.451793.147890@z14g2000cwz.googlegroups.com> <1108329540.239064.144920@f14g2000cwb.googlegroups.com> <1108334012.336816.221460@g14g2000cwa.googlegroups.com> Message-ID: <1108921146.274248.11500@g14g2000cwa.googlegroups.com> I think there's a problem with the code: py> decode_replacements.update([(std[key], key) for key in std]) py> decode_replacements.update([(ext[key], key) for key in ext]) when i run this i get an error: AttributeError: keys I can't get that figured out From strombrg at dcs.nac.uci.edu Wed Feb 2 21:15:29 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Thu, 03 Feb 2005 02:15:29 GMT Subject: mounting a filesystem? Message-ID: Is there a python module that can mount a filesystem? More specifically, a loopback filesystem with a particular offset, under linux? Thanks! From francis.girard at free.fr Mon Feb 7 15:11:50 2005 From: francis.girard at free.fr (Francis Girard) Date: Mon, 7 Feb 2005 21:11:50 +0100 Subject: "Collapsing" a list into a list of changes In-Reply-To: References: Message-ID: <200502072111.50781.francis.girard@free.fr> Le lundi 7 F?vrier 2005 20:30, Steven Bethard a ?crit?: > Francis Girard wrote: > > Is there someone on this list using this tool and happy with it ? Or is > > my mind too much targeted on FP paradigm and most of you really think > > that all the functions that apply another function to each and every > > elements of a list are bad (like "reduce", "map", "filter") ? > > I know there are definitely proponents for map and filter, especially > for simple cases like: > > map(int, lst) > filter(str.strip, lst) > > Note that, unlike reduce, map and filter aren't really going to increase > the number of function calls. Consider the equivalent list comprehensions: > > [int(x) for x in lst] > [x for x in lst if str.strip(x)] [1] > > The list comprehensions also require the same number of function calls > in these cases. Of course, in cases where a function does not already > exist, map and filter will require more function calls. Compare: > > map(lambda x: x**2 + 1, lst) > > with > > [x**2 + 1 for x in lst] > > Where the LC allows you to essentially "inline" the function. (You can > dis.dis these to see the difference if you like.) > I see. > > As far as my personal preferences go, while the simple cases of map and > filter (the ones using existing functions) are certainly easy enough for > me to read, for more complicated cases, I find things like: > > [x**2 + 1 for x in lst] > [x for x in lst if (x**2 + 1) % 3 == 1] > > much more readable than the corresponding: > > map(lambda x: x**2 + 1, lst) > filter(lambda x: (x**2 + 1) % 3 == 1, lst) > I agree. > especially since I avoid lambda usage, and would have to write these as: Why avoid "lambda" usage ? You find them too difficult to read (I mean in general) ? > > def f1(x): > return x**2 + 1 > map(f1, lst) > > def f2(x): > return (x**2 + 1) % 3 == 1 > map(f2, lst) > > (I actually find the non-lambda code clearer, but still more complicated > than the list comprehensions.) > > Given that I use list comprehensions for the complicated cases, I find > it to be more consistent if I use list comprehensions in all cases, so I > even tend to avoid the simple map and filter cases. > > > As far as reduce goes, I've never seen code that I thought was clearer > using reduce than using a for-loop. I have some experience with FP, and > I can certainly figure out what a given reduce call is doing given > enough time, but I can always understand the for-loop version much more > quickly. > I think it's a question of habits. But I agree that we should always go with code we find easy to read and that we think others find the same. I think I will stop using that function in Python if Python practionners find it difficult to read in general. There is no point in being cool just for being cool. Thank you Francis Girard > > Of course, YMMV. > > STeVe > > > [1] While it's not technically equivalent, this would almost certainly > be written as: > [x for x in lst if x.strip()] > which in fact takes better advantage of Python's duck-typing -- it will > work for unicode objects too. From mahs at telcopartners.com Fri Feb 4 23:08:06 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 04 Feb 2005 20:08:06 -0800 Subject: returning True, False or None In-Reply-To: References: <6Z6dnVfTmdUDopnfRVn-1A@rcn.net> Message-ID: Fahri Basegmez wrote: > "Michael Spencer" wrote in message > news:mailman.1946.1107575241.22381.python-list at python.org... > >>Fahri Basegmez wrote: >> >>>reduce(lambda x, y: x or y, lst) >>> >>>works but when I tried >>> >>>import operator >>>reduce(operator.or_, lst) >>> >>>this did not work. It pukes >>> >>>Traceback (most recent call last): >>> File "", line 1, in ? >>>TypeError: unsupported operand type(s) for |: 'NoneType' and 'bool' >>> >>>Any comments? >>> >>>Fahri >>> >>> >> >>TypeError: unsupported operand type(s) for |: 'NoneType' and 'bool' >> >>operator.or_ is "|" i.e., bitwise, not logical or >> >>Michael >> > > > That explains it. Is there a logical or we can use with reduce? > > Fahri > > Yes, but it's not quite the same as the 'or' operator >>> bool.__or__(True, False) True >>> bool.__or__(False, False) False >>> bool.__or__(False, None) NotImplemented >>> this may not be intentional... Michael From irmen.NOSPAM at xs4all.nl Wed Feb 16 14:02:05 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 16 Feb 2005 20:02:05 +0100 Subject: SHA1 broken In-Reply-To: References: Message-ID: <421398ad$0$28984$e4fe514c@news.xs4all.nl> Tim Churches wrote: > Also, the new findings only apply to hash collisions, not to the invertibility of SHA1 > hashes - thus, as Schneier points out, uses of keyed hashes (such as HMAC) are not > compromised by this. What about HMAC-MD5? --Irmen From dbickett at gmail.com Wed Feb 2 22:43:52 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Wed, 2 Feb 2005 22:43:52 -0500 Subject: IDLE history, Python IDE, and Interactive Python with Vim In-Reply-To: References: Message-ID: <1d6cdae305020219434e814e86@mail.gmail.com> This is certainly a worthy topic. There are several IDEs for Python (one I like very much being Komodo) that have plenty of fancy debugging features and advanced operations, however I have yet to encounter (elsewhere) the convenience that comes with being able to press F5 and have an interactive interpreter load my code and be ready for testing. That said, that is my only reason for my ever using IDLE. Without it I would probably forget that IDLE exists, were it not for the obnoxious context menu entry. ;) -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From steve at holdenweb.com Sun Feb 6 15:41:58 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 06 Feb 2005 15:41:58 -0500 Subject: OT: why are LAMP sites slow? In-Reply-To: References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xhdktt36q.fsf@ruckus.brouhaha.com> <7xacqkc0uq.fsf@ruckus.brouhaha.com> Message-ID: Lee Harr wrote: > On 2005-02-06, Brian Beck wrote: > >>>Refactoring a database on a live system is a giant pain in the ass, >>>simpler file-based approaches make incremental updates easier. >>> > > >>As much as I hate working with relational databases, I think you're >>forgetting the reliability even the most poorly-designed database >>provides. Continuing with the words example: assuming all words would >>otherwise be stored in a table, consider the process of updating the >>database schema--all entries are guaranteed to conform to the new >>schema. > > > > Not only that, but with a well-design RDBMS you can put your > schema changes inside of a transaction and make sure everything > is right before committing. > Bear in mind, however, that *most* common RDBMS will treat each DDL statement as implicitly committing, so transactional change abilities *don't* extend to schema changes. > Isn't there a saying like ... those who create file-based > databases are destined to re-create a relational database > management system poorly? ;o) regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From bpeng at rice.edu Sat Feb 5 00:24:08 2005 From: bpeng at rice.edu (Bo Peng) Date: Fri, 04 Feb 2005 23:24:08 -0600 Subject: changing local namespace of a function In-Reply-To: References: <4204400C.5060608@iinet.net.au> Message-ID: Thank all for your suggestions. I have tried all methods and compared their performance. >>> import profile >>> a = {'x':1, 'y':2} >>> N = 100000 >>> # solution one: use dictionary directly ... def fun1(d): ... for i in xrange(0,N): ... d['z'] = d['x'] + d['y'] ... >>> # solution two: use exec ... def fun2(d): ... for i in xrange(0,N): ... exec 'z = x + y' in globals(), d ... >>> # solution three: update local dictionary ... # Note that locals() is *not* d after update() so ... # z = x + y ... # does not set z in d ... def fun3(d): ... exec "locals().update(d)" ... for i in xrange(0,N): ... d['z'] = x + y ... >>> # solution four: use dict wrapper ... # this makes code easier to write and read ... class wrapdict(object): ... """Lazy attribute access to dictionary keys. Will not access ... keys that are not valid attribute names!""" ... def __init__(self, mydict): ... object.__setattr__(self, "mydict",mydict) ... def __getattr__(self, attrname): ... return self.mydict[attrname] ... def __setattr__(self, attrname, value): ... self.mydict[attrname] = value ... >>> # use wrapper ... def fun4(d): ... wd = wrapdict(d) ... for i in xrange(0,N): ... wd.z = wd.x + wd.y ... >>> profile.run('fun1(a)') 3 function calls in 0.070 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.060 0.060 :1(?) 1 0.010 0.010 0.070 0.070 profile:0(fun1(a)) 0 0.000 0.000 profile:0(profiler) 1 0.060 0.060 0.060 0.060 python-4645vcY.py:2(fun1) >>> profile.run('fun2(a)') 100003 function calls (3 primitive calls) in 5.890 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 100001/1 0.440 0.000 5.890 5.890 :1(?) 1 0.000 0.000 5.890 5.890 profile:0(fun2(a)) 0 0.000 0.000 profile:0(profiler) 1 5.450 5.450 5.890 5.890 python-46458me.py:2(fun2) >>> profile.run('fun3(a)') 4 function calls (3 primitive calls) in 0.060 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 2/1 0.000 0.000 0.060 0.060 :1(?) 1 0.000 0.000 0.060 0.060 profile:0(fun3(a)) 0 0.000 0.000 profile:0(profiler) 1 0.060 0.060 0.060 0.060 python-4645Jxk.py:5(fun3) >>> profile.run('fun4(a)') 300004 function calls in 3.910 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 3.910 3.910 :1(?) 1 0.000 0.000 3.910 3.910 profile:0(fun4(a)) 0 0.000 0.000 profile:0(profiler) 100000 0.530 0.000 0.530 0.000 python-4645W7q.py:10(__setattr__) 1 0.000 0.000 0.000 0.000 python-4645W7q.py:6(__init__) 200000 0.960 0.000 0.960 0.000 python-4645W7q.py:8(__getattr__) 1 2.420 2.420 3.910 3.910 python-4645jFx.py:1(fun4) Exec is slow since compiling the string and calls to globals() use a lot of time. The last one is most elegant but __getattr__ and __setattr__ are costly. The 'evil hack' solution is good since accessing x and y takes no additional time. I guess I will go with solution 3. It is evil but it is most close to my original intention. It leads to most readable code (except for the first line to do the magic and the last line to return result) and fastest performance. Thank again for everyone's help. I have learned a lot from the posts, especially the wrapdict class. Bo From just at xs4all.nl Sat Feb 26 14:46:21 2005 From: just at xs4all.nl (Just) Date: Sat, 26 Feb 2005 20:46:21 +0100 Subject: any Python equivalent of Math::Polynomial::Solve? References: Message-ID: In article , jgamble at ripco.com (John M. Gamble) wrote: > In article , > Just wrote: > >While googling for a non-linear equation solver, I found > >Math::Polynomial::Solve in CPAN. It seems a great little module, except > > Thank you. > > >it's not Python... > > Sorry about that. Heh, how big are the odds you find the author of an arbitrary Perl module on c.l.py... > > I'm especially looking for its poly_root() > >functionality (which solves arbitrary polynomials). Does anyone know of > >a Python module/package that implements that? > > Are you looking for that particular algorithm, or for any > source that will find the roots of the polynomial? Any will do. As I wrote in another post, I'm currently only looking for a quintic equation solver, which your module does very nicely. > The > original source for the algorithm used in the module is > from Hiroshi Murakami's Fortran source, and it shouldn't > be too difficult to repeat the translation process to python. Ah ok, I'll try to locate that (following the instruction in Solve.pm didn't work for me :( ). Just From ray at rgibbon.freeserve.co.uk Sat Feb 12 22:06:44 2005 From: ray at rgibbon.freeserve.co.uk (Ray Gibbon) Date: Sun, 13 Feb 2005 03:06:44 -0000 Subject: Testing conditions. References: Message-ID: > Testing conditions. > All replies - Spot on! Much appreciated, apology for delay. Ray. From noahspurrier at gmail.com Tue Feb 22 20:11:49 2005 From: noahspurrier at gmail.com (Noah) Date: 22 Feb 2005 17:11:49 -0800 Subject: Comm. between Python and PHP In-Reply-To: References: Message-ID: <1109121109.176070.84810@l41g2000cwc.googlegroups.com> It wasn't quite clear, but I assume that you want a PHP script that can call on the Python daemon and not have the daemon make calls to a PHP script. You could use xml-rpc which is built into Python as of version 2.2: http://docs.python.org/lib/module-xmlrpclib.html On the PHP side xmlrpc is still experimental. You have to enable this when you build PHP: http://us3.php.net/manual/en/ref.xmlrpc.php You could also just add a simple HTTP interface to your daemon. It's pretty easy to add an HTTP interface to your daemon. Look at SimpleHTTPServer the docs: http://docs.python.org/lib/module-SimpleHTTPServer.html You will also need to read the source for SimpleHTTPServer.py to figure out how it works (I don't know why they don't just put the example in the docs instead of putting the example in the source). Yours, Noah From sean_mcilroy at yahoo.com Mon Feb 28 22:44:41 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 28 Feb 2005 19:44:41 -0800 Subject: String Replace Problem... References: <8KqdnUR88Z-4Gr7fRVn-2A@comcast.com> Message-ID: Alright, now it's too much. It's not enough that you're eliminating it from the language, you have to stigmatize the lambda as well. You should take some time to reflect that not everybody thinks the same way. Those of us who are mathematically inclined like the lambda because it fits in well with the way we already think. And besides, it amounts to an explicit declaration that the function in question has no side effects. And besides, it adds flexibility to the language. Go ahead and throw it away, but you're making python less accessible for those of us whose central concern is something other than programming. ("Single line" indeed!) From donn at u.washington.edu Fri Feb 25 13:24:43 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 25 Feb 2005 10:24:43 -0800 Subject: Threading and consuming output from processes References: <1109278779.955986.193860@z14g2000cwz.googlegroups.com> <1109283053.971905.27670@z14g2000cwz.googlegroups.com> <1109295016.597170.21350@o13g2000cwo.googlegroups.com> Message-ID: In article , Jack Orenstein wrote: > I am developing a Python program that submits a command to each node > of a cluster and consumes the stdout and stderr from each. I want all > the processes to run in parallel, so I start a thread for each > node. There could be a lot of output from a node, so I have a thread > reading each stream, for a total of three threads per node. (I could > probably reduce to two threads per node by having the process thread > handle stdout or stderr.) > > I've developed some code and have run into problems using the > threading module, and have questions at various levels of detail. > > 1) How should I solve this problem? I'm an experienced Java programmer > but new to Python, so my solution looks very Java-like (hence the use of > the threading module). Any advice on the right way to approach the > problem in Python would be useful. > > 2) How many active Python threads is it reasonable to have at one > time? Our clusters have up to 50 nodes -- is 100-150 threads known to > work? (I'm using Python 2.2.2 on RedHat 9.) > > 3) I've run into a number of problems with the threading module. My > program seems to work about 90% of the time. The remaining 10%, it > looks like notify or notifyAll don't wake up waiting threads; or I > find some other problem that makes me wonder about the stability of > the threading module. I can post details on the problems I'm seeing, > but I thought it would be good to get general feedback > first. (Googling doesn't turn up any signs of trouble.) One of my colleagues here wrote a sort of similar application in Python, used threads, and had plenty of troubles with it. I don't recall the details. Some of the problems could be specific to Python. For example, there are some extra signal handling issues - but this is not to say that there are no signal handling issues with a multithreaded C application. For my money, you just don't get robust applications when you solve problems like multiple I/O sources by throwing threads at them. As I see another followup has already mentioned, the classic "pre threads" solution to multiple I/O sources is the select(2) function, which allows a single thread to serially process multiple file descriptors as data becomes available on them. When using select(), you should read from the file descriptor, using os.read(fd, size), socketobject.recv(size) etc., to avoid reading into local buffers as would happen with a file object. Donn Cave, donn at u.washington.edu From peter at engcorp.com Fri Feb 11 21:58:21 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Feb 2005 21:58:21 -0500 Subject: check if object is number In-Reply-To: <374t0mF4te5vbU1@individual.net> References: <374t0mF4te5vbU1@individual.net> Message-ID: <7tOdnYs6NtrV7JDfRVn-vQ@powergate.ca> marco wrote: > Steven Bethard wrote: >> Is there a good way to determine if an object is a numeric type? > > Maybe this can help? > > def isnumber(x): > try: > return(x == x-0) > except: > return False Not exactly foolproof: >>> def isnumber(x): ... try: return (x == x-0) ... except: return False ... >>> import numarray >>> a = numarray.arange(1.1, 5.5) >>> a array([ 1.1, 2.1, 3.1, 4.1, 5.1]) >>> print '%s:\t' % a, isnumber(a) [ 1.1 2.1 3.1 4.1 5.1]: [1 1 1 1 1] The result is actually this: >>> a == a-0 array([1, 1, 1, 1, 1], type=Bool) And if you try to call bool() on it (as perhaps your isnumber() routine already should have, rather than relying on == to return a boolean): >>> bool(a == (a-0)) Traceback (most recent call last): File "", line 1, in ? File "C:\a\python24\Lib\site-packages\numarray\generic.py", line 477, in __nonzero__ raise RuntimeError("An array doesn't make sense as a truth value. Use sometrue(a) or alltrue(a).") RuntimeError: An array doesn't make sense as a truth value. Use sometrue(a) or alltrue(a). Yuck. Of course, most of the other definitions of "is a number" that have been posted may likewise fail (defined as not doing what the OP would have wanted, in this case) with a numarray arange. Or maybe not. (Pretty much all of them will call an arange a number... would the OP's function work properly with that?) -Peter From fredrik at pythonware.com Tue Feb 8 11:26:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Feb 2005 17:26:07 +0100 Subject: Efficient checksum calculating on lagre files References: <5o2nd2-5hl.ln1@pluto.i.infosense.no> <4208E537.4070901@chamonix.reportlab.co.uk> Message-ID: Robin Becker wrote: >> Does anyone know of a fast way to calculate checksums for a large file. I need a way to generate >> ETag keys for a webserver, the ETag of large files are not realy nececary, but it would be nice >> if I could do it. I'm using the python hash function on the dynamic generated strings (like in >> page content) but on things like images I use the shutil's copyfileobject function and the hash >> of a fileobject's hash are it's handlers memmory address. >> >> Does anyone know a python utility which is possible to use, perhaps something like the md5sum >> utility on *nix systems. >> > well md5sum is usable on many systems. I run it on win32 and darwin. > > I tried this in 2.4 with the new subprocess module on my machine, Python's md5+mmap is a little bit faster than subprocess+md5sum: import os, md5, mmap file = open(fn, "r+") size = os.path.getsize(fn) hash = md5.md5(mmap.mmap(file.fileno(), size)).hexdigest() (I suspect that md5sum also uses mmap, so the difference is probably just the subprocess overhead) From greg at invalid.invalid Sun Feb 6 13:54:03 2005 From: greg at invalid.invalid (Greg Krohn) Date: Sun, 06 Feb 2005 18:54:03 GMT Subject: pygame.mixer.music not playing In-Reply-To: <36mb0iF54udklU1@individual.net> References: <36mb0iF54udklU1@individual.net> Message-ID: Marian Aldenh?vel wrote: > Hi, > > I am trying to make pygame play music on windows. This simple program: > > import pygame,time > pygame.init() > print "Mixer settings", pygame.mixer.get_init() > print "Mixer channels", pygame.mixer.get_num_channels() > pygame.mixer.music.set_volume(1.0) > pygame.mixer.music.load('file1.mp3) > print "Play" > pygame.mixer.music.play() > > while pygame.mixer.music.get_busy(): > print "Playing", pygame.mixer.music.get_pos() > time.sleep(1) > > print "Done" I tried this exact same code (except the mp3 filename, of course) on my machine and it worked fine. ActivePython 2.3.4 and Pygame 1.6. Could it be a hardware problem? -greg From tjreedy at udel.edu Sat Feb 26 21:16:47 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Feb 2005 21:16:47 -0500 Subject: string methods (warning, newbie) References: <38co9sF5lgss3U1@individual.net> Message-ID: "anthonyberet" wrote in message news:38co9sF5lgss3U1 at individual.net... > Is there a string mething to return only the alpha characters of a > string? > eg 'The Beatles - help - 03 - Ticket to ride', would be > 'TheBeatlesTickettoride' I believe you can do this with string.translate (string module, not str()) tjr From lee at example.com Thu Feb 3 17:57:52 2005 From: lee at example.com (Lee Harr) Date: Thu, 03 Feb 2005 22:57:52 GMT Subject: Popularizing SimpleHTTPServer and CGIHTTPServer References: <1107412654.121488.157070@c13g2000cwb.googlegroups.com> Message-ID: > Does anyone know how to use SimpleHTTPServer to: > > 1. Support virtual hosts? > > 2. Support SSL? > > I'd like to use SimpleHTTPServer to create some simple reporting utilities, > but can't get past these two points. Is there a NotSoSimpleHTTPServer? I think I would point to twisted for that. It is another dependency, but it has all you will ever need and more. From jtp11 at att.net Thu Feb 10 08:38:12 2005 From: jtp11 at att.net (Jim) Date: 10 Feb 2005 05:38:12 -0800 Subject: Loop in list. In-Reply-To: <1108036633.269008.194370@l41g2000cwc.googlegroups.com> References: <1107874174.445345.41230@c13g2000cwb.googlegroups.com> <3e8ca5c805020813074e975a4d@mail.gmail.com> <1108003131.605166.309350@c13g2000cwb.googlegroups.com> <1108036633.269008.194370@l41g2000cwc.googlegroups.com> Message-ID: <1108042692.085985.153940@z14g2000cwz.googlegroups.com> I assume this is one of the addons for Python. I know that there is a great deal of stuff out there available for Python that does some of the stuff that I am looking at, but I am interested in learning to use Python. When I want to get faster and more general, I will get some of this stuff or use a different language. Thanks for the help. Jim From fuzzyman at gmail.com Mon Feb 14 03:41:31 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 14 Feb 2005 00:41:31 -0800 Subject: - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: <1108370491.792820.142200@z14g2000cwz.googlegroups.com> Ilias Lazaridis wrote: > I'm a newcomer to python: > > [EVALUATION] - E01: The Java Failure - May Python Helps? > http://groups-beta.google.com/group/comp.lang.python/msg/75f0c5c35374f553 > > - > > I've download (as suggested) the python 2.4 installer for windows. > > Now I have problems to compile python extension that some packages > depend on. > > I use the MinGW open-source compiler. > > - > > My questions: > > a) Why does the Python Foundation not provide additionally a binary > version, compiled with MinGW or another open-source compiler? > It's not necessary. > b) Why does the Python Foundation not ensure, that the python > source-code is directly compilable with MinGW? > Are you sure it isn't ? > c) Why are the following efforts not _directly_ included in the python > source code base? > > http://jove.prohosting.com/iwave/ipython/pyMinGW.html > > above link found in this thread: > > http://groups-beta.google.com/group/comp.lang.python/msg/c9f0444c467de525 > > d) Is it really neccessary that I dive into such adventures, to be able > to do the most natural thing like: "developing python extensions with > MinGW"? > > http://starship.python.net/crew/kernr/mingw32/Notes.html > Not very difficult. The mingw compiler *is* supported through distutils. distutils can straightforwardly be configured to build extensions with mingw. The relevent lib files need converting, which is also simple. I did it for Python 2.3. For Python 2.4 I use the free MS optimimizing compiler. That does need a bit of hacking into distutils, but gain - not very difficult. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > e) Is there any official statement available regarding the msvcr71.dll > and other MS licensing issues? > > [see several threads "[Python-Dev] Is msvcr71.dll re-redistributable?"] > > http://mail.python.org/pipermail/python-dev/2005-February/thread.html > > f) Are there any official (Python Foundation) statements / rationales > available, which explain why the MinGW compiler is unsupported, although > parts of the community obviously like to use it? > > http://groups-beta.google.com/group/comp.lang.python/msg/dc3474e6c8053336 > > - > > I just want to understand. > > Thankfull for any pointer to official documents / statements. > > [google is _not_ a fried here. I like to have a stable development > environment, which is supported by the official projects, thus it can > pass quality-assurance without beeing afraid about every next release.] > > . > > -- > http://lazaridis.com From aahz at pythoncraft.com Thu Feb 3 19:42:09 2005 From: aahz at pythoncraft.com (Aahz) Date: 3 Feb 2005 19:42:09 -0500 Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> Message-ID: In article <7x8y65kwfl.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >I've only worked on one serious site of this type and it was "SAJO" >(Solaris Apache Java Oracle) rather than LAMP, but the concepts are >the same. I just feel like something bogus has to be going on. I >think even sites like Slashdot handle fewer TPS than a 1960's airline >reservation that ran on hardware with a fraction of the power of one >of today's laptops. Something I saw recently was that XML has inherently horrid performance for searching precisely because it isn't fixed-length records. Yes, the old platforms handled more TPS, but they also handled much less data of a form much more amenable to indexing. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "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." --GvR From peter at engcorp.com Wed Feb 9 13:13:01 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 09 Feb 2005 13:13:01 -0500 Subject: Python and version control In-Reply-To: References: Message-ID: Carl wrote: > What is the ultimate version control tool for Python if you are working in a > Windows environment? > > What is the most common adopted approach among Python developers working in > a Windows environment? I never liked coupling the two together like that. Instead I use tools like TortoiseCVS or (now) TortoiseSVN with a Subversion repository. These things let you access revision control features from context (right-button) menus right in Windows Explorer, as you browse the file system. The best part is that they work regardless of which editor or other tool you have to work with, and you aren't at the mercy of a greedy corporation that decides it's time for you to upgrade so you can give them more money. You can also use the command line tools when appropriate, of course. -- BTW, as a general caution: while Visual Source Safe may be "easy", it's also dangerous and has been known to corrupt many a code base, mine included. I wouldn't touch the product with a virtual ten-foot pole, and I strongly recommend to anyone who is stuck using it -- *especially in a multi-programmer environment* -- that they immediately abandon it in favour of something more stable. (Google can fill in background detail for anyone interested.) -Peter From steven.bethard at gmail.com Wed Feb 2 15:27:24 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 02 Feb 2005 13:27:24 -0700 Subject: Two classes problem In-Reply-To: References: Message-ID: Caleb Hattingh wrote: > ===file: a.py=== > # module a.py > test = 'first' > class aclass: > def __init__(self, mod, value): > mod.test = value # Is there another way to refer > to the module this class sits in? > ===end: a.py=== You can usually import the current module with: __import__(__name__) so you could write the code like: test = 'first' class aclass: def __init__(self, value): mod = __import__(__name__) mod.test = value or you could use globals() like: test = 'first' class aclass: def __init__(self, value): globals()['test'] = value > ===file: b.py=== > # file b.py > import a > x = a.aclass(a,'monkey') > print a.test > ===end: b.py=== If you used one of the solutions above, this code would be rewritten as: import a x = a.aclass('monkey') print a.test To the OP: In general, this seems like a bad organization strategy for your code. What is your actual use case? Steve From nytimes at swiftdsl.com.au Thu Feb 17 03:07:40 2005 From: nytimes at swiftdsl.com.au (news.sydney.pipenetworks.com) Date: Thu, 17 Feb 2005 19:07:40 +1100 Subject: Why doesn't join() call str() on its arguments? In-Reply-To: <873bvw9nqh.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> References: <37hippF4gcimiU1@individual.net> <37hqlrF59l2b2U1@individual.net> <873bvw9nqh.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <421450CC.9080504@swiftdsl.com.au> Nick Vargish wrote: > Leo Breebaart writes: > > >>That suggests >>to me an "obvious default" of the kind that exists elsewhere in >>Python as well. > > > I feel pretty much the opposite... If a non-string-type has managed to > get into my list-of-strings, then something has gone wrong and I would > like to know about this potential problem. > > If you want to do force a conversion before the join, you can use a > list comp: > > ', '.join([str(x) for x in l]) > > > Nick "Explicit is better than Implicit" > Really ? Then why are you using python. Python or most dynamic languages are are so great because of their common sense towards the "implicit". You must have heard of "never say never" but "never say always" (as in "always better") is more appropriate here. There are many cases of python's implicitness. What about a = "string" b = 2 c = "%s%s" % (a, b) There is an implicit str(b) here. ''.join(["string", 2]) to me is no different then the example above. Huy From ncoghlan at iinet.net.au Fri Feb 25 21:04:38 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 26 Feb 2005 12:04:38 +1000 Subject: Code evaluation at function definition execution time (was Re: Compile time evaluation (aka eliminating default argument hacks)) In-Reply-To: <421FD226.2060006@iinet.net.au> References: <421FD226.2060006@iinet.net.au> Message-ID: <421FD936.6090007@iinet.net.au> Nick Coghlan wrote: > Basically, yeah. Although I later realised I got the name of the feature > I want wrong - default arguments are evaluated when the def statement is > executed, not when the code is compiled. So it's a matter of being able > to execute some code in the functions local namespace at compile time. D'oh - "definition execution time", not compile time. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jmeile at hotmail.com Mon Feb 28 05:53:40 2005 From: jmeile at hotmail.com (Josef Meile) Date: Mon, 28 Feb 2005 11:53:40 +0100 Subject: split a directory string into a list In-Reply-To: References: Message-ID: <4222F834.30403@hotmail.com> > The most obvious case where it wouldn't work would be for a UNC path name. > Using the string split method gives two empty strings: > > >>>>os.path.normpath(r'\\machine\share').split(os.path.sep) > > ['', '', 'machine', 'share'] > > > > whereas the splitpath function I proposed gives you: > > >>>>splitpath(r'\\machine\share') > > ['\\\\', 'machine', 'share'] > > So to find out the type of path (relative, absolute, unc), you only have to > consider the first element with my function but you have to look at the > first two elements if you just naively split the string. Thanks for the explanation. I forgot that you could do thinks like that on windows. > > Also a relative windows path with a drive letter doesn't get fully split: > > >>>>os.path.normpath(r'c:dir\file').split(os.path.sep) > > ['c:dir', 'file'] > >>>>splitpath(r'c:dir\file') > > ['c:', 'dir', 'file'] Again, I forgot it. > If you really are worried about speed (and are sure you aren't optimising > prematurely), then you could combine some special case processing near the > start of the string with a simple split of the remainder. No, I'm not worried about speed. Actually, the original post wasn't mine. I was just curious about your answer. Regards, Josef From willems.john at gmail.com Wed Feb 23 16:26:10 2005 From: willems.john at gmail.com (John Willems) Date: 23 Feb 2005 13:26:10 -0800 Subject: Python and "Ajax technology collaboration" Message-ID: <1109193970.029421.213490@l41g2000cwc.googlegroups.com> Interesting GUI developments, it seems. Anyone developed a "Ajax" application using Python? Very curious.... thx (Ajax stands for: XHTML and CSS; dynamic display and interaction using the Document Object Model; data interchange and manipulation using XML and XSLT; asynchronous data retrieval using XMLHttpRequest; and JavaScript binding everything together ie Google has used these technologies to build Gmail, Google Maps etc. more info: http://www.adaptivepath.com/publications/essays/archives/000385.php) From tjprojects_usenet at yahoo.com Tue Feb 15 22:06:50 2005 From: tjprojects_usenet at yahoo.com (TJ's Projects) Date: 15 Feb 2005 19:06:50 -0800 Subject: Loading functions from a file during run-time References: <1108091598.055004.24890@g14g2000cwa.googlegroups.com> Message-ID: Answer below... "Bryant Huang" <735115 at gmail.com> wrote in message news:<1108091598.055004.24890 at g14g2000cwa.googlegroups.com>... > Hello! > > I would like to read in files, during run-time, which contain plain > Python function definitions, and then call those functions by their > string name. In other words, I'd like to read in arbitrary files with > function definitions, using a typical 'open()' call, but then have > those functions available for use. > > > ===== [bar.txt] ===== > > def negate(x): > return -x > > def square(x): > return x*x > > > ===== [foo.py] ===== > > # open functions file > foo_file = open("bar.txt") > foo_lines = foo_file.readlines() > foo_file.close() > foo_str = "".join(foo_lines) > > # compile code > foo_code = compile(foo_str, "", "exec") > foo_ns = {} > exec(foo_code) in foo_ns > > # use functions > k = 5 > print foo_ns["negate"](k) // outputs -5 > print foo_ns["square"](k) // outputs 25 > > > I'm not sure exactly what happens below the surface, but I'm guessing > the 'compile()' and 'exec()' commands load in 'negate()' and 'square()' > as functions in the global scope of 'foo.py'. I find that when I run > 'compile()' and 'exec()' from within a function, say 'f()', the > functions I read in from 'bar.txt' are no longer accessible since they > are in global scope, and not in the scope of 'f()'. > > Any pointers would be very welcome. > > Thanks! > Bryant You're actually very close here. The problem you are having is that you are creating a local namespace (foo_ns) and executing that code within that namespace. To "import" the functions into the global namespace, exec them as: exec foo_code in globals() You will then be able to call the methods as if they had been declared locally, ie. 'negate(5)' rather than 'foo_ns["negate"](5)'. I've written a simple line editor intended to be used within the Python interactive interpreter, based on the old DOS 'edlin' command. This is how I enable the user to "import" the entered functions into their local namespace. The actual "execution" of the code is actually pretty simple, and not much more involved than what you see here. You may be able to get some more ideas, however. For more info (or comments, suggestions, or pointers), check out http://pyedlin.sourceforge.net). Here's a simple example that shows a "good" input loop: ====== Start exec example ====== if __name__ == '__main__': funcdata = ['def func():\n', "\tprint 'Hello, world!'\n", '\n'] codeline = '' for line in funcdata: codeline += line execline = codeline if execline.endswith('\n'): execline = execline[:-1] try: obj = compile(execline, '', 'exec') except SyntaxError: pass else: exec obj in globals() codeline = '' func() ====== End exec sample ====== Executing this code will print 'Hello, world!' to the console. Hope this helps! T.J. From steven.bethard at gmail.com Sat Feb 5 14:05:13 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 05 Feb 2005 12:05:13 -0700 Subject: empty classes as c structs? In-Reply-To: References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> Message-ID: Nick Coghlan wrote: > Steven Bethard wrote: > >> Yes -- help me rally behind my generic object PEP which proposes a >> Bunch type (probably to be renamed) for the Python standard lib. =) > > Did you see the suggestion of 'namespace' as a name? Yup, it's in the current PEP draft. See the "Open Issues" section: PEP: XXX Title: Generic Object Data Type Version: $Revision: 1.0 $ Last-Modified: $Date: 2004/11/29 16:00:00 $ Author: Steven Bethard Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 29-Nov-2004 Python-Version: 2.5 Post-History: 29-Nov-2004 Abstract ======== This PEP proposes a standard library addition to support the simple creation of 'generic' objects which can be given named attributes without the need to declare a class. Such attribute-value mappings are intended to complement the name-value mappings provided by Python's builtin dict objects. Motivation ========== Python's dict objects provide a simple way of creating anonymous name-value mappings. These mappings use the __getitem__ protocol to access the value associated with a name, so that code generally appears like:: mapping['name'] Occasionally, a programmer may decide that dotted-attribute style access is more appropriate to the domain than __getitem__ style access, and that their mapping should be accessed like:: mapping.name Currently, if a Python programmer makes this design decision, they are forced to declare a new class, and then build instances of this class. When no methods are to be associated with the attribute-value mappings, declaring a new class can be overkill. This PEP proposes adding a simple type to the collections module of the standard library that can be used to build such attribute-value mappings. Providing such a type allows the Python programmer to determine which type of mapping is most appropriate to their domain and apply this choice with minimal effort. Some of the suggested uses include: Returning Named Results ----------------------- It is often appropriate for a function that returns multiple items to give names to the different items returned. The type suggested in this PEP provides a simple means of doing this that allows the returned values to be accessed in the usual attribute-style access:: >>> def f(x): ... return Bunch(double=2*x, squared=x**2) ... >>> y = f(10) >>> y.double 20 >>> y.squared 100 Representing Hierarchical Data ------------------------------ The type suggested in this PEP also allows a simple means of representing hierarchical data that allows attribute-style access:: >>> x = Bunch(spam=Bunch(rabbit=1, badger=[2, 3, 4]), ham='neewom') >>> x.spam.badger [2, 3, 4] >>> x.ham 'neewom' Rationale ========= As Bunch objects are intended primarily to replace simple, data-only classes, simple Bunch construction was a primary concern. As such, the Bunch constructor supports creation from keyword arguments, dicts, and sequences of (attribute, value) pairs:: >>> Bunch(eggs=1, spam=2, ham=3) Bunch(eggs=1, ham=3, spam=2) >>> Bunch({'eggs':1, 'spam':2, 'ham':3}) Bunch(eggs=1, ham=3, spam=2) >>> Bunch([('eggs',1), ('spam',2), ('ham',3)]) Bunch(eggs=1, ham=3, spam=2) To allow attribute-value mappings to be easily combined, the Bunch type provides a update staticmethod that supports similar arguments:: >>> bunch = Bunch(eggs=1) >>> Bunch.update(bunch, [('spam', 2)], ham=3) >>> bunch Bunch(eggs=1, ham=3, spam=2) Note that update is available through the class, not through the instances, to avoid the confusion that might arise if an 'update' attribute added to a Bunch instance hid the update method. If Bunch objects are used to represent hierarchical data, comparison of such objects becomes a concern. For this reason, Bunch objects support object equality which compares Bunch objects by attributes recursively:: >>> x = Bunch(parrot=Bunch(lumberjack=True, spam=42), peng='shrub') >>> y = Bunch(peng='shrub', parrot=Bunch(spam=42, lumberjack=True)) >>> z = Bunch(parrot=Bunch(lumberjack=True), peng='shrub') >>> x == y True >>> x == z False Note that support for the various mapping methods, e.g. __(get|set|del)item__, __len__, __iter__, __contains__, items, keys, values, etc. was intentionally omitted as these methods did not seem to be necessary for the core uses of an attribute-value mapping. If such methods are truly necessary for a given use case, this may suggest that a dict object is a more appropriate type for that use. Examples ========= Converting an XML DOM tree into a tree of nested Bunch objects:: >>> import xml.dom.minidom >>> def getbunch(element): ... result = Bunch() ... if element.attributes: ... Bunch.update(result, element.attributes.items()) ... children = {} ... for child in element.childNodes: ... if child.nodeType == xml.dom.minidom.Node.TEXT_NODE: ... children.setdefault('text', []).append( ... child.nodeValue) ... else: ... children.setdefault(child.nodeName, []).append( ... getbunch(child)) ... Bunch.update(result, children) ... return result ... >>> doc = xml.dom.minidom.parseString("""\ ... ... ... a text 1 ... ... b text ... a text 2 ... ... c text ... """) >>> b = getbunch(doc.documentElement) >>> b.a[0].b[1] Bunch(attr_b=u'3', text=[u' b text ']) Reference Implementation ======================== The code is available as SourceForge patch 1094542 [1]_. Open Issues =========== What should the type be named? Some suggestions include 'Bunch', 'Record', 'Struct' and 'Namespace'. Where should the type be placed? The current suggestion is the collections module. References ========== .. [1] http://sourceforge.net/tracker/index.php?func=detail&aid=1094542&group_id=5470&atid=305470 .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From benn at cenix-bioscience.com Mon Feb 14 10:20:10 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Mon, 14 Feb 2005 16:20:10 +0100 Subject: For American numbers In-Reply-To: <420e7376$1@nntp0.pdx.net> References: <420e7376$1@nntp0.pdx.net> Message-ID: <4210C1AA.9020104@cenix-bioscience.com> Scott David Daniels wrote: > Kind of fun exercise (no good for British English). > > what's American about it? If anything, it's more French than American ;-) N -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From onurb at xiludom.gro Mon Feb 14 08:12:57 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 14 Feb 2005 14:12:57 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: <4210a3d9$0$23451$626a14ce@news.free.fr> Simon Brunning wrote: > On Mon, 14 Feb 2005 14:23:08 +0200, Ilias Lazaridis wrote: > > (snip) > > >>But if those answers above were of official nature, I must seriously >>rethink if I can rely on _any_ system which is based on python, as the >>foundation and the community do not care about essential needs and >>requirements. > > > I couldn't agree more. You need to find a community that *does* care > about essential needs. Might I recommend Perl or Ruby? > Why do you hate Perl and Ruby community that much ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From steven.bethard at gmail.com Fri Feb 18 12:26:38 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 18 Feb 2005 10:26:38 -0700 Subject: combining several lambda equations In-Reply-To: <2ae25c6b.0502180224.3d6164a7@posting.google.com> References: <2ae25c6b.0502180224.3d6164a7@posting.google.com> Message-ID: Paddy McCarthy wrote: > x=lambda : A < B > y=lambda : C+6 >= 7 > [snip] > > Z=lambda : (A=7) See "Inappropriate use of Lambda" in http://www.python.org/moin/DubiousPython Perhaps your real example is different, but notice that = lambda : is equivalent to def (): return except that the latter will give your function a useful name. No reason to use the *anonymous* function construct to create a *named* function. STeVe From http Fri Feb 4 21:05:32 2005 From: http (Paul Rubin) Date: 04 Feb 2005 18:05:32 -0800 Subject: EDI x12 --> XML References: Message-ID: <7xy8e3kbgz.fsf@ruckus.brouhaha.com> Greg Lindstrom writes: > I am working on automating a system accepting input data in EDI x12 > format and would like to convert it to XML. Before I start, I thought > I'd ask if anyone has worked on such a beast. I have seen work by > Chris Cioffi on parsing EDI records. Is anything else out there > before I either write one or use one that I have written in Perl? I wrote a thing like that a long time ago. As a pure coding task, it's not that hard. The main hassle is having the appropriate segment and element dictionaries for the docs you're trying to parse (comparable to XML DTD's). Maybe they're online someplace now. The main thing needing special code was the HL segment, which has a recursive structure, but even that's such a big deal. I don't know why you want to do this, but if you have a use for it, go for it. From the.ech0 at gmail.com Sun Feb 13 20:44:47 2005 From: the.ech0 at gmail.com (ech0) Date: 13 Feb 2005 17:44:47 -0800 Subject: Second posting - Howto connect to MsSQL In-Reply-To: References: Message-ID: <1108345487.094034.168860@o13g2000cwo.googlegroups.com> You can also use pymssql. I've used it before on a little project. It looks like it works on linux too. http://pymssql.sourceforge.net/ From dev at huelix-remove.com Sat Feb 26 11:34:27 2005 From: dev at huelix-remove.com (Sarat Venugopal) Date: Sun, 27 Feb 2005 00:34:27 +0800 Subject: getting at raw POST data? References: <421fbaf9$1@nntp.zianet.com> Message-ID: <4220a510$1@news.starhub.net.sg> Erik Johnson wrote: > I am trying to work with a program that is trying make an HTTP POST > of text data without any named form parameter. (I don't know - is > that a normal thing to do?) Often, people do require abnormal things. > I need to write a CGI program that > accepts and processes that data. I'm not seeing how to get at data > that's not a named form parameter. As far as CGI is concerned, the POST data resides in stdin. So accessing it is as simple as reading sys.stdin within the CGI script. Of course, it is up to you to interpret the data, though you can just read everything as a string. The POST data could just as well be binary - such as a file upload. To dump the strings to a file to your webserver, try the following script: import sys print 'Content-type: text/plain\r\n\r\n' dumped = open('test.txt', 'wb') for line in sys.stdin.readline(): dumped.write(line) HTH, Sarat Venugopal www.huelix.com From a at a.invalid Tue Feb 8 15:11:14 2005 From: a at a.invalid (Timo Virkkala) Date: Tue, 08 Feb 2005 20:11:14 GMT Subject: python code with indention In-Reply-To: <1107805151.265680.165380@o13g2000cwo.googlegroups.com> References: <1107805151.265680.165380@o13g2000cwo.googlegroups.com> Message-ID: Xah Lee wrote: > is it possible to write python code without any indentation? 1) Why in the name of Xah Lee would you even want to? 2) If you need to ask questions this simple, are you sure you are the right person to write tutorials? 3) Do you even read the replies you get? -- Timo Virkkala From timothy.williams at nvl.army.mil Fri Feb 25 10:21:41 2005 From: timothy.williams at nvl.army.mil (timothy.williams at nvl.army.mil) Date: 25 Feb 2005 07:21:41 -0800 Subject: problem installing wxPython 2.5.3, wxWidgets installed ok Message-ID: <1109344901.877838.71280@o13g2000cwo.googlegroups.com> I'm trying to install wxPython 2.5.3.1 using Python 2.3.2 on a Fedora 2 machine. I have python in a non-standard place, but I'm using --prefix with the configure script to point to where I have everything. The make install in $WXDIR seemed to go fine. I have the libxw* libraries in my lib/ directory libwx_base-2.5.so@ libwx_gtk_adv-2.5.so.3.0.0* libwx_base-2.5.so.3@ libwx_gtk_core-2.5.so@ libwx_base-2.5.so.3.0.0* libwx_gtk_core-2.5.so.3@ libwx_base_net-2.5.so@ libwx_gtk_core-2.5.so.3.0.0* libwx_base_net-2.5.so.3@ libwx_gtk_gl-2.4.so@ libwx_base_net-2.5.so.3.0.0* libwx_gtk_gl-2.4.so.0@ libwx_base_xml-2.5.so@ libwx_gtk_gl-2.4.so.0.1.1* libwx_base_xml-2.5.so.3@ libwx_gtk_html-2.5.so@ libwx_base_xml-2.5.so.3.0.0* libwx_gtk_html-2.5.so.3@ libwx_gtk-2.4.so@ libwx_gtk_html-2.5.so.3.0.0* libwx_gtk-2.4.so.0@ libwx_gtk_xrc-2.5.so@ libwx_gtk-2.4.so.0.1.1* libwx_gtk_xrc-2.5.so.3@ libwx_gtk_adv-2.5.so@ libwx_gtk_xrc-2.5.so.3.0.0* libwx_gtk_adv-2.5.so.3@ I also have a wx/ directory under my lib. directory. The problem is when I try to do a 'python setup.py install' in the ./wxPython directory. I get a message about not finding a config file for wx-config and then several errors during gcc compiles. > python setup.py build Found wx-config: /project/c4i/Users_Share/williams/Linux/bin/wx-config Using flags: --toolkit=gtk2 --unicode=no --version=2.5 Warning: No config found to match: /project/c4i/Users_Share/williams/Linux/bin/wx-config --toolkit=gtk2 --unicode=no --version=2.5 --cxxflags in /project/c4i/Users_Share/williams/Linux/lib/wx/config If you require this configuration, please install the desired library build. If this is part of an automated configuration test and no other errors occur, you may safely ignore it. You may use wx-config --list to see all configs available in the default prefix. ... Preparing OGL... Preparing STC... Preparing GIZMOS... running build running build_py copying wx/__version__.py -> build-gtk2/lib.linux-i686-2.3/wx running build_ext building '_core_' extension creating build-gtk2/temp.linux-i686-2.3 creating build-gtk2/temp.linux-i686-2.3/src creating build-gtk2/temp.linux-i686-2.3/src/gtk gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DSWIG_GLOBAL -DHAVE_CONFIG_H -DWXP_USE_THREAD=1 -UNDEBUG -DXTHREADS -D_REENTRANT -DXUSE_MTSAFE_API -Iinclude -Isrc -I/usr/include/gtk-2.0 -I/usr/lib/gtk-2.0/include -I/usr/X11R6/include -I/usr/include/atk-1.0 -I/usr/include/pango-1.0 -I/usr/include/freetype2 -I/usr/include/freetype2/config -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/project/c4i/Users_Share/williams/Linux/include/python2.3 -c src/libpy.c -o build-gtk2/temp.linux-i686-2.3/src/libpy.o -O3 gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DSWIG_GLOBAL -DHAVE_CONFIG_H -DWXP_USE_THREAD=1 -UNDEBUG -DXTHREADS -D_REENTRANT -DXUSE_MTSAFE_API -Iinclude -Isrc -I/usr/include/gtk-2.0 -I/usr/lib/gtk-2.0/include -I/usr/X11R6/include -I/usr/include/atk-1.0 -I/usr/include/pango-1.0 -I/usr/include/freetype2 -I/usr/include/freetype2/config -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/project/c4i/Users_Share/williams/Linux/include/python2.3 -c src/gtk/_core_wrap.cpp -o build-gtk2/temp.linux-i686-2.3/src/gtk/_core_wrap.o -O3 cc1plus: warning: command line option "-Wstrict-prototypes" is valid for Ada/C/ObjC but not for C++ In file included from src/gtk/_core_wrap.cpp:400: include/wx/wxPython/wxPython_int.h:19:19: wx/wx.h: No such file or directory include/wx/wxPython/wxPython_int.h:21:25: wx/busyinfo.h: No such file or directory include/wx/wxPython/wxPython_int.h:22:22: wx/caret.h: No such file or directory include/wx/wxPython/wxPython_int.h:23:25: wx/choicebk.h: No such file or directory include/wx/wxPython/wxPython_int.h:24:24: wx/clipbrd.h: No such file or directory include/wx/wxPython/wxPython_int.h:25:25: wx/colordlg.h: No such file or directory include/wx/wxPython/wxPython_int.h:26:23: wx/config.h: No such file or directory include/wx/wxPython/wxPython_int.h:27:23: wx/cshelp.h: No such file or directory include/wx/wxPython/wxPython_int.h:28:25: wx/dcmirror.h: No such file or directory include/wx/wxPython/wxPython_int.h:29:21: wx/dcps.h: No such file or directory include/wx/wxPython/wxPython_int.h:30:24: wx/dirctrl.h: No such file or directory include/wx/wxPython/wxPython_int.h:31:23: wx/dirdlg.h: No such file or directory include/wx/wxPython/wxPython_int.h:32:20: wx/dnd.h: No such file or directory include/wx/wxPython/wxPython_int.h:33:24: wx/docview.h: No such file or directory include/wx/wxPython/wxPython_int.h:34:24: wx/encconv.h: No such file or directory include/wx/wxPython/wxPython_int.h:35:25: wx/fdrepdlg.h: No such file or direct ... Why isn't there a -I../include switch on the compile line, and how do I reconfigure it so it does? Thanks for any help. From alefnula at gmail.com Wed Feb 16 09:19:27 2005 From: alefnula at gmail.com (Viktor) Date: 16 Feb 2005 06:19:27 -0800 Subject: Stable GUI Message-ID: Which GUI is the most stable one? I don't need any fancy looking widgets (look and feel doesn't realy matter to me), I "just" need it to be rock stable and fast... From harlinseritt at yahoo.com Sun Feb 27 10:07:11 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 27 Feb 2005 07:07:11 -0800 Subject: Googlewhacker In-Reply-To: <4221b704$0$8752$db0fefd9@news.zen.co.uk> References: <4221b671$0$8752$db0fefd9@news.zen.co.uk> <4221b704$0$8752$db0fefd9@news.zen.co.uk> Message-ID: <1109516831.755068.208910@l41g2000cwc.googlegroups.com> They actually won't ban your IP for this. They only limit your number of searches per day. I discovered this once when I used http://www.google.com as a test metric for my network monitoring program. I do like your script though. Regards, Harlin From steve at holdenweb.com Tue Feb 8 16:32:38 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 08 Feb 2005 16:32:38 -0500 Subject: python code with indention In-Reply-To: References: <1107805151.265680.165380@o13g2000cwo.googlegroups.com> Message-ID: <42092FF6.7040204@holdenweb.com> Timo Virkkala wrote: > Xah Lee wrote: > >> is it possible to write python code without any indentation? > > > 1) Why in the name of Xah Lee would you even want to? > 2) If you need to ask questions this simple, are you sure you are the > right person to write tutorials? > 3) Do you even read the replies you get? > Surely by now it's obvious that Xah Lee is an output-only device. Please do not feed the troll. regards Steve From robin at reportlab.com Fri Feb 25 11:04:12 2005 From: robin at reportlab.com (Robin Becker) Date: Fri, 25 Feb 2005 16:04:12 +0000 Subject: Is there way to determine which class a method is bound to? In-Reply-To: References: Message-ID: <421F4C7C.6040204@chamonix.reportlab.co.uk> Victor Ng wrote: > I'm doing some evil things in Python and I would find it useful to > determine which class a method is bound to when I'm given a method > pointer. > > For example: > > class Foo(object): > def somemeth(self): > return 42 > > class Bar(Foo): > def othermethod(self): > return 42 > > > Is there some way I can have something like : > > findClass(Bar.somemeth) > > that would return the 'Foo' class, and > > findClass(Bar.othermethod) > > would return the 'Bar' class? > > vic I think you can use the mro function >>> class Foo(object): ... def somemeth(self): ... pass ... >>> class Bar(Foo): ... def othermeth(self): ... pass ... >>> def findClass(meth): ... for x in meth.im_class.mro(): ... if meth.im_func in x.__dict__.values(): return x ... >>> findClass(Bar.somemeth) >>> findClass(Bar.othermeth) >>> -- Robin Becker From belred at gmail.com Mon Feb 21 11:51:31 2005 From: belred at gmail.com (Bryan) Date: Mon, 21 Feb 2005 08:51:31 -0800 Subject: python2.4 generator expression > python2.3 list expression In-Reply-To: <0ioj11dsgqhatqc3d7ldeb35rta6d9fk69@4ax.com> References: <0ioj11dsgqhatqc3d7ldeb35rta6d9fk69@4ax.com> Message-ID: Christos TZOTZIOY Georgiou wrote: > On 21 Feb 2005 06:48:19 -0500, rumours say that Dan Sommers > might have written: > > [snip: snacktime posts code to count bits] > > >>>Seems to work, is there a better way to do this? > > > [Dan] > >>for c in range( 128 ): >> even_odd = 0 >> print '%3d' % c, >> while c: >> c &= c - 1 >> even_odd = not even_odd >> print int( even_odd ) > > > Just for the sake of people who haven't messed with bit manipulation in C or > assembly, the effect of > > c &= c - 1 > > is to reset the rightmost (less significant) '1' bit of a number (ie change it > to '0'). i tried c &= c - 1 but i'm not getting the least significant or rightmost bit reset to zero. am i misunderstanding something? >>> 2 & 1 # 2 = 0x10; reset right most would be 0x10 0 >>> 10 & 9 # 10 = 0x1010; reset right most would be 0x1010 8 bryan From xah at xahlee.org Mon Feb 7 14:39:11 2005 From: xah at xahlee.org (Xah Lee) Date: 7 Feb 2005 11:39:11 -0800 Subject: python code with indention Message-ID: <1107805151.265680.165380@o13g2000cwo.googlegroups.com> is it possible to write python code without any indentation? Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From mefjr75 at hotmail.com Sat Feb 5 00:40:27 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 4 Feb 2005 21:40:27 -0800 Subject: changing local namespace of a function In-Reply-To: References: <1107550212.114358.281200@z14g2000cwz.googlegroups.com> Message-ID: <1107582027.700961.156800@f14g2000cwb.googlegroups.com> I quote myself : > Also try this stuff out in an interpreter session it is easy and fast > to get your own answers. Sorry I guess I should have added a nudge and a <.5 wink> at the end. Sometimes misinformation is just what we need to get our own answers! The absurdity of what you are doing led me to give you that piece of advice. It seems if I had just told you to RTF you would not have learned as much. I have been out so did not respond earlier, but I see others have given you other useful information. There is no reason to make these local epecially if they are large , leave them in the dictionary they come in and acess the members as needed. I really don't see your need. M.E.Farmer From fredrik at pythonware.com Mon Feb 14 13:44:53 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Feb 2005 19:44:53 +0100 Subject: nested lists as arrays References: <1108405326.819090.219970@l41g2000cwc.googlegroups.com> Message-ID: benjamin.cordes at blawrc.de wrote: > Allright. What difference in runtime and space would it make using > dictionaries instead? is this for an interactive game? if so, the answer is "none at all". (on my machine, you can make about 6000000 dict[x,y] accesses per second, compared to 7500000 list[x][y] accesses... assuming that your algorithm needs to check each cell on the board 10 times per move, and you want the moves to appear "instantly", the slower solution should be fast enough for a 250x250 board, compared to a 270x270 board for the faster solution...). From sunriselee2002 at yahoo.com Sun Feb 27 00:59:14 2005 From: sunriselee2002 at yahoo.com (sunriselee) Date: Sun, 27 Feb 2005 00:59:14 -0500 Subject: parse lines to name value pairs Message-ID: <94c18f5a4bd6cad273a40299b1b137e8@localhost.talkaboutprogramming.com> Hi all, I want to parse some string lines into name value pairs, where the value will be a list. Here are some sample lines: line1 = """path {{data/tom} C:/user/john}""" line2 = """books{{book music red} {book {math 1} blue} {book {tom's book} green}}""" For line1, the name is "path", the name-value should be the following forms: ["path", ["data/tom", "C:/user/john"]] For line 2, the name is "books", and the value should be a list in either one of the following forms (either one is ok): ["books", [["book","music","red"],["book","math 1","blue"],["book", "tom's book", "green"]]] or ["books", ["book","music","red","book","math 1","blue","book", "tom's book", "green"]] Any ideas? Many thanks! From yyusenet at yahoo.com Thu Feb 10 21:15:18 2005 From: yyusenet at yahoo.com (YYUsenet) Date: Thu, 10 Feb 2005 19:15:18 -0700 Subject: [perl-python] combinatorics fun In-Reply-To: <1108075884.250995.62520@g14g2000cwa.googlegroups.com> References: <1108075884.250995.62520@g14g2000cwa.googlegroups.com> Message-ID: Xah Lee wrote: > a year ago i wrote this perl program as part of a larger program. > > as a exercise of fun, let's do a python version. I'll post my version > later today. [code snipped] > > This is Perl-Python a-day. To subscribe, see > http://xahlee.org/perl-python/python.html > > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html > Why are you posting this to comp.lang.python? This obviously has nothing to do with python at all. If you are trying to teach people python, claiming that "...let's do a python version. I'll post my version later today." Isn't really the proper way to do it. An even better method would be to set up a website dedicated to nothing but it, and stop posting here with garbage code that no one wants to read, and that helps no one. Please, consider others a little bit when you go off on your wild hope that you might be able to teach other people what you obviously know nothing about, teaching people from a language that you know nothing about. *PLEASE STOP POSTING*!! *NOBODY WANTS YOU TO POST*!! -- yyusenet (at) xmission (dot) com From BOOGIEMANPN at YAHOO.COM Sat Feb 12 16:16:53 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Sat, 12 Feb 2005 22:16:53 +0100 Subject: Alternative to raw_input ? References: Message-ID: On Fri, 11 Feb 2005 21:38:47 -0500, Peter Hansen wrote: > print prompt > while msvcrt.kbhit(): > msvcrt.getch() > msvcrt.getch() Thanks, it works but without line "print prompt" and also I'm not sure if I should put this function : def cekaj(): while msvcrt.kbhit(): msvcrt.getch() msvcrt.getch() #Or this one, which sounds more logical according to help #kbhit() - Return true if a keypress is waiting to be read. def cekaj(): msvcrt.getch() while msvcrt.kbhit(): msvcrt.getch() It works both ways, not sure which one is right From bill.mill at gmail.com Fri Feb 4 15:36:49 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 4 Feb 2005 15:36:49 -0500 Subject: string issue In-Reply-To: References: <36QMd.103084$Jk5.36127@lakeread01> <87lla4w0av.fsf@pobox.com> Message-ID: <797fe3d405020412362a30500e@mail.gmail.com> On Fri, 04 Feb 2005 15:25:04 -0500, rbt wrote: > John J. Lee wrote: > > Steve Holden writes: > > [...] > > > >>You are modifying the list as you iterate over it. Instead, iterate > >>over a copy by using: > >> > >>for ip in ips[:]: > >> ... > > > > > > Just to help popularise the alternative idiom, which IMO is > > significantly less cryptic (sane constructors of mutable objects > > almost always make a copy, and list is no exception: it's guaranteed > > to do so): > > > > for ip in list(ips): > > ... > > > > > > Works back to at least Python 1.5.2. > > > > > > John > > I don't know that that approach is less cryptic. ips is already a > list... it looks cryptic to make it a list again, doesn't it? IMO, the > two are equally cryptic. The epitome of clarity would be copy(ips)... > now *that* makes sense, of course, ips[:] or list(ips) work equally well > to the programmer who has learned them. Howsabout: >>> from copy import copy >>> ips = ['255.255.255.255', '128.173.120.79', '198.82.247.98', ... '127.0.0.1', '255.0.0.0', '255', '128.173.255.34'] >>> for ip in copy(ips): ... if '255' in ip: ... ips.remove(ip) ... >>> ips ['128.173.120.79', '198.82.247.98', '127.0.0.1'] But I still think that the list comprehension is the best. Peace Bill Mill bill.mill at gmail.com > -- > http://mail.python.org/mailman/listinfo/python-list > From donnal at donnal.net Mon Feb 7 09:39:18 2005 From: donnal at donnal.net (Donnal Walter) Date: Mon, 07 Feb 2005 08:39:18 -0600 Subject: AsciiDoc 6.0.0 In-Reply-To: <4204241E.6010504@methods.co.nz> References: <4204241E.6010504@methods.co.nz> Message-ID: Stuart Rackham wrote: > AsciiDoc > -------- > AsciiDoc is an uncomplicated text document format for writing short > documents, articles, books and UNIX man pages. > > AsciiDoc files can be translated to HTML (with or without > stylesheets), DocBook (articles, books and refentry documents) > and LinuxDoc using the asciidoc(1) command. Lately I've been thinking about using reStructuredText for creating simple web pages. Should I consider AsciiDoc as an alternative, and if so, what are its advantages by comparison? Thanks. Donnal Walter From BOOGIEMANPN at YAHOO.COM Fri Feb 11 15:36:38 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Fri, 11 Feb 2005 21:36:38 +0100 Subject: Alternative to raw_input ? References: Message-ID: On Fri, 11 Feb 2005 18:00:08 +0100, den wrote: > Did you try this: > > import msvcrt > msvcrt.getch() Yes, that's what I need. Thank you. BTW, sometimes program continues without me pressing any button, why ? From fuzzyman at gmail.com Mon Feb 28 09:07:46 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 28 Feb 2005 06:07:46 -0800 Subject: How do you control _all_ items added to a list? In-Reply-To: <1109599026.828317.297700@z14g2000cwz.googlegroups.com> References: <1109599026.828317.297700@z14g2000cwz.googlegroups.com> Message-ID: <1109599666.643466.239700@l41g2000cwc.googlegroups.com> Xif wrote: > Hi > > I want to have control over all items added to a list. > > The first attempt was to subclass list and override its .append() > method. > > Problem is, there are plenty of other ways the list can have items > added to it - e.g. extend, insert - and theyr'e not at all affected by > the changes I made to append. > > Is there some "base" item-adding method that all other item-adding > methods use, so I can override it and have the changes affect all > item-adding functions? > If you subclass list then you will need to override all methods that can set items. This is because the built in methods work directly with the internal structure and are implemented in C. It's a bit of a pain... but not that much. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > Thanks, > Xif From jerf at jerf.org Wed Feb 2 16:29:04 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 02 Feb 2005 16:29:04 -0500 Subject: Integrated Testing - Peppable? References: <1107373949.960435.212020@z14g2000cwz.googlegroups.com> Message-ID: On Wed, 02 Feb 2005 11:52:29 -0800, carl.manaster at gmail.com wrote: > So... Should I turn this into a PEP? I would think a much more productive step one would be to put together the proposed functionality with unittest and the trace module, and use the output of your tool to drive some sort of simple output showing what you are talking about. (Putting together a Tk app to show coverage would be pretty simple as long as you don't try to get too fancy.) I'm not too optimistic about ever seeing this in the language, but without an implementation, I think it's about 0 likelihood. But remember, that's just my opinion. You need the experience you'll get from the implementation to write a PEP that has a prayer of acceptance. At least with a tool, worst case scenario, your PEP is rejected and you put together a module to do it anyways. If you get enough people to use it, you might at least get the module into the standard lib, though that is also another big step. No prose can compare to a live, functional demonstration. I, for instance, am not *certain* this would be useful, but I think it is the sort of thing that if I got a taste of it I might fall in love with. (Coverage is, of course, not a sufficient condition to know your testing is complete, but it is a necessary one, and a graphical readout with uncovered lines colored bright red could be quite interesting and useful, even if it isn't initially integrated into anything.) From fredrik at pythonware.com Tue Feb 8 07:35:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Feb 2005 13:35:57 +0100 Subject: Choosing the right parser for parsing C headers References: <1107861023.254610.14310@g14g2000cwa.googlegroups.com> <1107865641.937691.282930@g14g2000cwa.googlegroups.com> Message-ID: Jean de Largentaye wrote: > GCC-XML looks like a very interesting alternative, as Python includes > tools to parse XML. > The mini-C compiler looks like a step in the right direction for me. > I'm going to look into that. > I'm not comfortable with C++ yet, and am not sure how I'd use Pyste. to clarify, Pyste is a Python tool that uses GCCXML to generate bindings; it might not be something that you can use out of the box for your project, but it's definitely something you should study, and perhaps borrow implementation ideas from. From ulrich.schaefer at dfki.de Thu Feb 24 03:18:24 2005 From: ulrich.schaefer at dfki.de (Ulrich Schaefer) Date: Thu, 24 Feb 2005 09:18:24 +0100 Subject: Communication between JAVA and python In-Reply-To: <421d137e$1_1@newspeer2.tds.net> References: <421ce234$0$12950$626a14ce@news.free.fr> <421d137e$1_1@newspeer2.tds.net> Message-ID: Jacques Daussy wrote: >> Hello >> How can I transfert information between a JAVA application and a >> python script application. I can't use jython because, I must use >> python interpreter.I think to socket or semaphore, but can I use it >> on Windows plateform ? > Try XML-RPC (a simple implementation of remote procedure call via HTTP sockets). It's built-in in Python since 2.2 (http://www.python.org/doc/2.4/lib/module-xmlrpclib.html), in Java use e.g. Apache XML-RPC (http://ws.apache.org/xmlrpc/). Ulrich From caleb1 at telkomsa.net Wed Feb 9 23:46:59 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Wed, 09 Feb 2005 23:46:59 -0500 Subject: Python versus Perl ? References: <1107695949.247611.272800@g14g2000cwa.googlegroups.com> <1107930486.318280.251010@l41g2000cwc.googlegroups.com> Message-ID: Joe, thanks Yes, I am on the P4D mailing list :) What you didn't say was that the "python for delphi" extensions are *awesome*. full two-way communication, and you get it all by drag&dropping a little component widget onto your form in the IDE. Amazing. However... Dll's can be used by things other than python, which is the main reason why we would go that route. However, with all the .NET hoopla, maybe IronPython and a .NET dll would be the way to go in the future. I'm still a little uneasy about adopting .NET as a standard just yet... I should give it some more thought anyways. Thanks again Caleb On Wed, 09 Feb 2005 12:38:37 -0500, Joe Francia wrote: > Caleb Hattingh wrote: >> As you might imagine, I think about this constantly. However, there >> are many other issues that make it complicated, such as having to work >> in a team where the average guy knows pascal well (we're just a bunch >> of chemical engineers), but has never even heard of python. Plus, were >> I to go this type of route, I would almost definitely code the binary >> modules in Delphi or FreePascal, make a DLL and use ctypes to call it. >> I do not know C and have no desire to learn now :) On the other >> hand, I know pascal quite well. >> keep well >> Caleb >> > > You could always code Python extensions directly in Delphi: > > http://membres.lycos.fr/marat/delphi/python.htm > http://www.atug.com/andypatterns/PythonDelphiLatest.htm > > Demo09 (look in demodll.dpr & module.pas) in the download tells you how. > > Peace, > Joe > From snail at objmedia.demon.co.uk Mon Feb 14 14:51:44 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Mon, 14 Feb 2005 19:51:44 +0000 Subject: - E02 - Support for MinGW Open Source Compiler References: <1108398011.213872.321390@o13g2000cwo.googlegroups.com> <1108407625.250592.104280@c13g2000cwb.googlegroups.com> <1108409476.874751.16600@l41g2000cwc.googlegroups.com> Message-ID: In message <1108409476.874751.16600 at l41g2000cwc.googlegroups.com>, Pat writes >if I have both versions of Python installed - 2.3.5 and 2.4? Is there >an easy way to detect this and switch between the two dlls? Easy? Depends what you call easy. a) You just need to detect if pythonNN.dll is implicitly linked to msvcrt.dll or msvcrXX.dll (where XX indicates a VS studio number, currently XX can only be 71, but if Python is done for Visual Studio 2005 (8.0) then XX may also have a value of 80). b) GetModuleHandle(name of DLL from a) to get the DLL handle. c) GetProcAddress on the respective to get the C runtime function you want to call (for example, fopen). d) call the function. You either need (a) or all of (a)...(d) depending on what you are doing. Those embedding Python but no idea of the Python version in advance will do the latter. >If I'm asking questions already answered elsewhere, I'd love a link to >that resource, if you have it. I'm probably not the best person to answer such a question. I'm mainly a C/C++ (with Java under protest) person dabbling in Python/Ruby. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From fredrik at pythonware.com Mon Feb 14 06:02:54 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Feb 2005 12:02:54 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: Message-ID: Ilias Lazaridis wrote > The idea that the Python Foundation cares about user needs would affect that. please let the users speak for themselves. From michele.simionato at gmail.com Sun Feb 20 03:53:45 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 20 Feb 2005 00:53:45 -0800 Subject: recommended way of generating HTML from Python Message-ID: <1108889625.068929.88890@z14g2000cwz.googlegroups.com> What is the recommended way of generating HTML from Python? I know of HTMLGen and of few recipes in the Cookbook, but is there something which is more or less standard? Also, are there plans to include a module for HTML generation in the standard library? I really would like to see some standardization in this area. Michele Simionato From steve at holdenweb.com Thu Feb 3 07:36:11 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Feb 2005 07:36:11 -0500 Subject: IDLE history, Python IDE, and Interactive Python with Vim In-Reply-To: References: <1d6cdae305020219434e814e86@mail.gmail.com> Message-ID: <9_oMd.102683$Jk5.16356@lakeread01> Ashot wrote: > WingIDE looks nice though, and it seems that the interactive shell is > built in from the screenshots. Can you run a program to a certain > point break point and use the shell? > Indeed you can - there's an interpreter available that executes in the context of the current stack frame when you reach a breakpoint. It's a great way to find out what's going on. [But don't I remember that IDLE can do that too? ...] regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From cam.ac.uk at mh391.invalid Mon Feb 14 05:43:09 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 14 Feb 2005 10:43:09 +0000 Subject: changing __call__ on demand In-Reply-To: References: Message-ID: Stefan Behnel wrote: > > Thanks for the quick answer. I didn't know they were class-level > methods. Too bad. Guess I'll stick with indirection then. Here is one way of doing that indirection I just thought of--have the class __call__ attribute call on the instance __call__ attribute: >>> class MyClass(object): ... def __init__(self, func): ... self.__call__ = func ... def __call__(self, *args, **keywds): ... return self.__call__(*args, **keywds) ... >>> def f1(): return "foo" ... >>> def f2(x, y): return x+y ... >>> MyClass(f1)() 'foo' >>> MyClass(f2)(30, 12) 42 I still can't figure out whether this is elegant, or opaque and to be avoided. -- Michael Hoffman From gabriel.cooper at mediapulse.com Fri Feb 11 14:23:17 2005 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Fri, 11 Feb 2005 14:23:17 -0500 Subject: Python UPS / FedEx Shipping Module Message-ID: <420D0625.2020408@mediapulse.com> I've made UPS and FedEx shipping rate request modules in python using XML. Is there an interest in putting this on the web? From ncoghlan at iinet.net.au Sat Feb 26 23:14:55 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 27 Feb 2005 14:14:55 +1000 Subject: string methods (warning, newbie) In-Reply-To: References: Message-ID: <4221493F.5060602@iinet.net.au> Jimmy Retzlaff wrote: > The approach you are considering may be easier than you think: > > >>>>filter(str.isalpha, 'The Beatles - help - 03 - Ticket to ride') > > 'TheBeatleshelpTickettoride' Hmm, I think this is a case where filter is significantly clearer than the equivalent list comprehension: Py> "".join([c for c in 'The Beatles - help - 03 - Ticket to ride' if c.isalpha( )]) 'TheBeatleshelpTickettoride' Py> Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From greg at cosc.canterbury.ac.nz Fri Feb 11 00:21:27 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 11 Feb 2005 18:21:27 +1300 Subject: :-) In-Reply-To: References: <1107805151.265680.165380@o13g2000cwo.googlegroups.com> <36vm80F554hv7U1@individual.net> Message-ID: <372tn2F5998g4U1@individual.net> Sion Arrowsmith wrote: > Greg Ewing wrote: > >>As a fellow named Church once pointed out, lambdas are really >>*all* you need in a language... > > > ... where as others argue that it is impractical not to have > some form of runtime data storage, thereby giving rise to the > separation of Church and state. > -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bvande at po-box.mcgill.ca Fri Feb 4 13:31:15 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 04 Feb 2005 13:31:15 -0500 Subject: returning True, False or None In-Reply-To: <1grh3fe.1km48v56sadeyN%aleaxit@yahoo.com> References: <1grh3fe.1km48v56sadeyN%aleaxit@yahoo.com> Message-ID: <4203BF73.80507@po-box.mcgill.ca> Alex Martelli said unto the world upon 2005-02-04 13:02: > Steven Bethard wrote: > > >>I have lists containing values that are all either True, False or None, >>e.g.: >> >> [True, None, None, False] >> [None, False, False, None ] >> [False, True, True, True ] >> etc. >> >>For a given list: >>* If all values are None, the function should return None. >>* If at least one value is True, the function should return True. >>* Otherwise, the function should return False. >> >>Right now, my code looks like: >>This has a light code smell for me though -- can anyone see a simpler >>way of writing this? > > > What about...: > > for val in lst: > if val is not None: > return val > return None > > or the somewhat fancy/clever: > > for val in (x for x in lst if x is not None): > return val > return None > > > Alex These don't do what the OP desired. .>>> test_case = [False, True, True, True ] .>>> def alexs_funct(lst): . for val in lst: . if val is not None: . return val . return None >>> alexs_funct(test_case) False But, by the 'spec', it ought return True. Best, Brian vdB A mere newbie, quite pleased with himself for finding a problem with 'bot code -- next scheduled to occur mid 2011 :-) From fuzzyman at gmail.com Mon Feb 14 04:44:34 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 14 Feb 2005 01:44:34 -0800 Subject: - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: <1108374274.207311.155780@l41g2000cwc.googlegroups.com> Ilias Lazaridis wrote: [snip..] > >> b) Why does the Python Foundation not ensure, that the python > >> source-code is directly compilable with MinGW? > > > > Why should they? It already runs on Windows with a freely available > > compiler. > > Obvious: Courtesy [against the userbase needs] > > Obvious: Consistency [same code-base across different compiler] > Are you aware that the MSVC compiler they use produces tighter code than gcc ? [1] *Most* users would rather have a faster python than a python built with an open source compiler. Particularly as distutils (read Python) can *easily* be configured to use mingw to build extensions from source - which seems to be your real requirement. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shmtl [snip..] > -- > http://lazaridis.com [1] Not knocking gcc - it's just optimsied for portability rather than speed. If you want to see *a* benchmark, there is a link to one in my 'upgrading python' article. (In the article section at http://www.voidspace.org.uk/python/index.shmtl ) From timothy.grant at gmail.com Thu Feb 24 16:11:33 2005 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 24 Feb 2005 13:11:33 -0800 Subject: More newbie macosx user questions Message-ID: I think I'm mis-understanding something about how PYTHONPATH works (at least on OSX I didn't have this trouble on Linux). I have a directory where I store libraries that I'm playing around with. However, for some reason python can't find the library. Since I'm using PyQt, I use pythonw, but the results are identical with python. It doesn't look like my PYTHONPATH is getting prepended to the library path. Can anyone tell me what I'm doing wrong? (timothygrant at bastard%) echo $PYTHONPATH /Users/timothygrant/code/lib (timothygrant at bastard%) ls $PYTHONPATH NJB.py NJB.pyc _njb_c.so njb_c.py njb_c.pyc (timothygrant at bastard%) pythonw Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import NJB Traceback (most recent call last): File "", line 1, in ? ImportError: No module named NJB >>> import sys >>> for p in sys.path: ... print p ... /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python23.zip /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3 /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-darwin /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac/lib-scriptpackages /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-tk /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-dynload /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages From cam.ac.uk at mh391.invalid Sun Feb 13 12:11:50 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 13 Feb 2005 17:11:50 +0000 Subject: changing __call__ on demand In-Reply-To: References: Message-ID: Stefan Behnel wrote: > Is there a way to change __call__ after class creation? __call__, like __getitem__, and __getattr__ is called on the class object, not the instance object. So, no, not as far as I am aware, without using metaclass trickery. The simplest option IMO is to use another level of indirection as you suggest. -- Michael Hoffman From martin at v.loewis.de Sun Feb 13 14:44:38 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Feb 2005 20:44:38 +0100 Subject: sre is broken in SuSE 9.2 In-Reply-To: References: <1108060527.378911.146240@o13g2000cwo.googlegroups.com> <420D4D9A.40201@v.loewis.de> Message-ID: <420FAE26.6020700@v.loewis.de> Serge Orlov wrote: > Emphasis is mine. So how many libc implementations with > non-unicode wide-character codes do we have in 2005? Solaris has supported 2-byte wchar_t implementations for many years, and so I believe did HP-UX and AIX. ISO C99 defines a constant __STDC_ISO_10646__ which an implementation can use to indicate that wchar_t uses Unicode (aka ISO 10646) in all locales. Very few implementations define this constant at this time, though. Regards, Martin From python at hope.cz Wed Feb 16 04:46:39 2005 From: python at hope.cz (Lad) Date: 16 Feb 2005 01:46:39 -0800 Subject: MYSQL - how to install ? Message-ID: <1108547199.260223.211450@f14g2000cwb.googlegroups.com> I use XP windows and Python 2.3. How can I install MYSQL on my computer? I could not find any installer for MYSQL and Python 2.3 Thanks for help Lad. From mlescault91967 at aol.com Mon Feb 28 11:29:39 2005 From: mlescault91967 at aol.com (mike) Date: Mon, 28 Feb 2005 11:29:39 -0500 Subject: NEED MONEY FOR FAMILY MATTERS Message-ID: HI I WAS A MARINE MECHANIC working boat engines for 20 years and now I have started making money for the rest of my life after i got into my own business but I wish I had started many years ago, check it out for yourself you'll be HAPPY you did. This site changed my life and my families and it will change yours. COPY AND PAST THIS SITE http://www.mach90.com/pre.asp?username=mad4701 From neutrinman at myrealbox.com Thu Feb 24 11:34:09 2005 From: neutrinman at myrealbox.com (neutrinman at myrealbox.com) Date: 24 Feb 2005 08:34:09 -0800 Subject: what is wrong? Message-ID: <1109262849.733430.13020@f14g2000cwb.googlegroups.com> I cannot find out why the following code generates the error: Traceback (most recent call last): File "D:/a/Utilities/python/ptyhon22/test.py", line 97, in ? main() File "D:/a/Utilities/python/ptyhon22/test.py", line 60, in main crit = Critter(crit_name) File "D:/a/Utilities/python/ptyhon22/test.py", line 8, in __init__ self.feed = feed # I wrote this AttributeError: can't set attribute I add some codes to a program on a book. The lines that have "I wrote this" comment is the added codes. Could anyone tell me what is worng here? -------------- ## class Critter(object): """A virtual pet""" def __init__(self, name, hunger = 0, boredom = 0, feed = 0): self.name = name self.hunger = hunger self.boredom = boredom self.feed = feed # I wrote this def __pass_time(self): self.hunger += 1 self.boredom += 1 def __feed_time(self): # I worte this self.feed += 1 # I wote this def __get_feed(self): # I wrote this return self.feed # I worte this feed = property(__get_feed) # I wrote this def __get_mood(self): unhappiness = self.hunger + self.boredom if unhappiness < 5: mood = "happy" elif 5 <= unhappiness <= 10: mood = "okay" elif 11 <= unhappiness <= 15: mood = "frustrated" else: mood = "mad" return mood mood = property(__get_mood) def talk(self): print "I'm", self.name, "and I feel", self.mood, "now.\n" self.__pass_time() def eat(self, food = 4): print "Brruppp. Thank you." self.hunger -= food self.__feed_time() # I wrote this print self.feed # I wrote this if self.hunger < 0: self.hunger = 0 self.__pass_time() def play(self, fun = 4): print "Wheee!" self.boredom -= fun if self.boredom < 0: self.boredom = 0 self.__pass_time() ## def main(): crit_name = raw_input("What do you want to name your critter?: ") crit = Critter(crit_name) choice = None while choice != "0": print \ """ Critter Caretaker 0 - Quit 1 - Listen to your critter 2 - Feed your critter 3 - Play with your critter """ choice = raw_input("Choice: ") print # exit if choice == "0": print "Good-bye." # listen to your critter elif choice == "1": crit.talk() # feed your critter elif choice == "2": crit.eat() # play with your critter elif choice == "3": crit.play() # some unknown choice else: print "\nSorry, but", choice, "isn't a valid choice." main() ("\n\nPress the enter key to exit.") From sjmachin at lexicon.net Thu Feb 24 15:56:49 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 25 Feb 2005 07:56:49 +1100 Subject: Canonical way of dealing with null-separated lines? References: Message-ID: <5aes11d4da95un1n78vtb04m43269hqo4m@4ax.com> On Thu, 24 Feb 2005 11:53:32 -0500, Christopher De Vries wrote: >On Wed, Feb 23, 2005 at 10:54:50PM -0500, Douglas Alan wrote: >> Is there a canonical way of iterating over the lines of a file that >> are null-separated rather than newline-separated? > >I'm not sure if there is a canonical method, but I would recommending using a >generator to get something like this, where 'f' is a file object: > >def readnullsep(f): > # Need a place to put potential pieces of a null separated string > # across buffer boundaries > retain = [] > > while True: > instr = f.read(2048) > if len(instr)==0: > # End of file > break > > # Split over nulls > splitstr = instr.split('\0') > > # Combine with anything left over from previous read > retain.append(splitstr[0]) > splitstr[0] = ''.join(retain) > > # Keep last piece for next loop and yield the rest > retain = [splitstr[-1]] > for element in splitstr[:-1]: (1) Inefficient (copies all but the last element of splitstr) > yield element > > # yield anything left over > yield retain[0] (2) Dies when the input file is empty. (3) As noted by the OP, can return a spurious empty line at the end. Try this: !def readweird(f, line_end='\0', bufsiz=8192): ! retain = '' ! while True: ! instr = f.read(bufsiz) ! if not instr: ! # End of file ! break ! splitstr = instr.split(line_end) ! if splitstr[-1]: ! # last piece not terminated ! if retain: ! splitstr[0] = retain + splitstr[0] ! retain = splitstr.pop() ! else: ! if retain: ! splitstr[0] = retain + splitstr[0] ! retain = '' ! del splitstr[-1] ! for element in splitstr: ! yield element ! if retain: ! yield retain Cheers, John From caleb1 at telkomsa.net Tue Feb 8 23:55:28 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 08 Feb 2005 23:55:28 -0500 Subject: variable declaration References: <110i8st7n7n084a@corp.supernews.com> Message-ID: Jeff I fully agree. As I stated in a message to alexander, it is quick and easy even to write a simple project-specific tool for checking that only allowed variable names exist in all the project files. Compared to having to work with tons of effectively useless variable declarations forever (perhaps even only in other peoples code who decided to use the "option"), it is not much to ask (I work in pascal a lot - I know all about tons and tons of declarations). thx Caleb > You can also get all places where said variable exists by using grep, or > your editor's search feature. I don't see how a var declaration gains > you anything over 'grep PowerOfGenerator *.py' ... > > Jeff Shannon > Technician/Programmer > Credit International > > From unlearned at gmail.com Tue Feb 1 21:36:35 2005 From: unlearned at gmail.com (Daniel Fackrell) Date: Tue, 1 Feb 2005 19:36:35 -0700 Subject: [perl-python] string pattern matching References: <1107290707.549792.199860@c13g2000cwb.googlegroups.com><2uWdnWyp5M1Fip3fRVn-sQ@rogers.com> Message-ID: - Henry Wadsworth Longfellow "Erik Max Francis" wrote in message news:fbydnQJ8DNSthJ3fRVn-pw at speakeasy.net... > Dan Perl wrote: > > > Perhaps someone will write a program to automatically follow up on every > > [perl-python] posting? The follow-up could just contain a statement like > > the one Daniel mentions. Obviously the program would be written in python. > > ;-) > > I'm not really sure that such a disclaimer is explicitly necessary. > Anyone looking at Xah Lee's posts will also see the threads they > generate, which involve people pointing out all their errors. Granted > this won't happen with every single post, but since he's posting this > stuff once a day, I don't think the chances of someone finding his posts > and not seeing the related discussion and refutations is a big risk. > > For the rest of us, we can just killfile the threads easily enough. It seems to me that application of one of these solutions reduces the effectiveness of the other. If enough persons killfile the threads, who warns the newbies? And so those who don't killfile the threads to ensure that somebody is still guarding against misleading information to newbies continue dealing with it manually. Daniel Fackrell From irmen.NOSPAM at xs4all.nl Sat Feb 12 18:29:12 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 13 Feb 2005 00:29:12 +0100 Subject: Text files read multiple files into single file, and then recreate the multiple files In-Reply-To: <1108250252.479092.298670@z14g2000cwz.googlegroups.com> References: <1108250252.479092.298670@z14g2000cwz.googlegroups.com> Message-ID: <420e90fb$0$28978$e4fe514c@news.xs4all.nl> googlinggoogler at hotmail.com wrote: > Hiya, > > The title says it all really, but im a newbie to python sort of. I can > read in files and write files no probs. > > But what I want to do is read in a couple of files and output them to > one single file, but then be able to take this one single file and > recreate the files I put into it. A ZIP archive perhaps? See the zipfile module. > Im really at a loss as to how I go about recovering the files? > obviously if i scan for a string that specifys the start and end of > each file, theres the chance that the file might contain this term to > which would split the files into unwanted chucks of file, which wouldnt > be wanted. ZIP archives are binary compressed files. Is this okay or do you require the file to be a text file? --Irmen From ajsiegel at optonline.com Sat Feb 5 16:03:09 2005 From: ajsiegel at optonline.com (Arthur) Date: Sat, 05 Feb 2005 16:03:09 -0500 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1grifns.14san6f1b076mdN%aleaxit@yahoo.com> <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com> <1grj036.r13xcy1d72inbN%aleaxit@yahoo.com> Message-ID: <2qba01d1men2ai48gp4cojo2e28rd5g9ob@4ax.com> On Sat, 5 Feb 2005 20:02:44 +0100, aleaxit at yahoo.com (Alex Martelli) wrote: >Arthur wrote: > >> On Sat, 5 Feb 2005 17:00:15 +0100, aleaxit at yahoo.com (Alex Martelli) >> wrote: >> > >> >I consider this one of the worst ideas to have been proposed on this >> >newsgroup over the years, which _IS_ saying something. \ >> >> I would disagree, but only to the extent that nothing that is only a >> request for an option toggle should qualify for this award. For >> anyone not interested in it's effects, it's business as usual. > >You must have lead a charmed life, I think, unusually and blissfully >free from pointy-haired bosses (PHBs). In the sublunar world that most >of us inhabit, ``optional'' idiocies of this kind soon become absolutely >mandatory -- thanks to micromanagement by PHBs. It seems to me that you would be more accurate (and calmer) if you generalized from your own experience, rather than in direct contradiction to it. That the firms that advocate the use of Python are the one's least likely to be dominated by PHB's who DKTAFTE (who don't know their ass from their elbows). Unless I am misintepreting you. Do the STUPID firms use Python as well. Why? Clearly there are stupider choices. I prefer to use VB when doing certain kinds of stupid things. It's the right tool in those cases. Really. Perhaps the answer here has more to do with backing off efforts to make Python ubiquitous. Why shouldn't the community stay a bit elitist? Or else maybe that's where you started on this thread, in fact - and in your own way. If so, I agree - within reason. One doesn't toggle between VB and Python, perhaps is the point. They are of different species. Art From bh at intevation.de Tue Feb 8 14:47:06 2005 From: bh at intevation.de (Bernhard Herzog) Date: Tue, 08 Feb 2005 20:47:06 +0100 Subject: turing machine in an LC References: <1107805151.265680.165380@o13g2000cwo.googlegroups.com> <87mzuf9gu8.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Jeremy Bowers writes: > On Tue, 08 Feb 2005 17:36:19 +0100, Bernhard Herzog wrote: >> Nick Vargish writes: >>> "Xah Lee" writes: >>>> is it possible to write python code without any indentation? >>> Not if Turing-completeness is something you desire. >> >> It's possible to implement a turing machine with a single list >> comprehension. No indentation needed. > > I had to think about it, it's an interesting, and I'm going to tentatively > disagree, because of the statement/expression dichotomy. "Tentatively" > because if somebody can answer these objections than I will happily change > my mind :-) Here's an implementation of a turing machine simulator I hacked up a while ago. For readability's sake, it's a function definition with a doc-string, but the heart of it is a single list comprehension which could be written without indentation: def listcomp_turing(M, T, initial_state = 0): """Run the turing machine M on the tape T. The tape T should be a dictionary mapping head positions to the value on the tape at that position. Valid values on the tape are 0 and 1. Empty positions have the value 0. The initial head position is 0. The turing machine M should be a sequence of state pairs. The state of the machine is used as an index into that sequence and thus should be in range(len(M)). Each state pair is a pair of (write_symbol, head_direction, next_state) triples, one for each of the possible values on the tape at the current head position. The initial state is given by the optional parameter initial_state. If the next state is None, the machine stops. The direction may be either -1 or 1 meaning left and right respectively. The function does not enforce this limitation but with other values the machine is not a turing machine anymore. The return value is T. """ [x for L in [[[initial_state, 0]]] for state, pos in L if state is not None and (L.append([M[state][T.get(pos, 0)][2], pos + M[state][T.get(pos, 0)][1]]) or T.__setitem__(pos, M[state][T.get(pos, 0)][0]))] return T For an example, lets take the one from wikipedia's article on turing machines: The following Turing machine has an alphabet {'0', '1'}, with 0 being the blank symbol. It expects a series of 1's on the tape, with the head initially on the leftmost 1, and doubles the 1's with a 0 in between, i.e., "111" becomes "1110111". The set of states is {s1, s2, s3, s4, s5} and the start state is s1. The action table is as follows. Old Read Wr. New Old Read Wr. New St. Sym. Sym. Mv. St. St. Sym. Sym. Mv. St. - - - - - - - - - - - - - - - - - - - - - - - - s1 1 -> 0 R s2 s4 1 -> 1 L s4 s2 1 -> 1 R s2 s4 0 -> 0 L s5 s2 0 -> 0 R s3 s5 1 -> 1 L s5 s3 0 -> 1 L s4 s5 0 -> 1 R s1 s3 1 -> 1 R s3 The listcomp_turing call with a tape containing "11" would be listcomp_turing([((0, +1, None), (0, +1, 1)), ((0, +1, 2), (1, +1, 1)), ((1, -1, 3), (1, +1, 2)), ((0, -1, 4), (1, -1, 3)), ((1, +1, 0), (1, -1, 4))], {0:1, 1:1}) which produces a result tape of {0: 1, 1: 1, 2: 0, 3: 1, 4: 1} Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ From FBatista at uniFON.com.ar Wed Feb 16 12:55:03 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 16 Feb 2005 14:55:03 -0300 Subject: renaming 'references' to functions can give recursive problem s Message-ID: [Fredrik Lundh] #- you're confused. resetting your brain and reading the documentation #- again might help: #- #- http://docs.python.org/ref/objects.html #- http://docs.python.org/ref/naming.html This article will also help him a lot: http://starship.python.net/crew/mwh/hacks/objectthink.html . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jerf at jerf.org Thu Feb 3 14:20:26 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 03 Feb 2005 14:20:26 -0500 Subject: Apache & Python 500 Error References: <36bkqfF4sjt0oU1@individual.net> <36el9jF4oj223U1@individual.net> Message-ID: On Thu, 03 Feb 2005 13:55:13 +0100, Christian wrote: > from mod_python import apache > ^ > SyntaxError: invalid syntax > > ---- > My test script: > #!/usr/bin/python > > print 'Content-Type: text/plain\r' > print '\r' > import os > print os.getcwd() For the quote of the error message, I've taken the liberty of stripping off the apache-added stuff off the front so you can read it better. You should now be able to easily see that the error message and your shown program don't mesh. That error appears to be from an earlier run. Even so, I can tell you one thing: The error resulted from indenting your "from mod_python import apache" call that you no longer have. Python uses whitespace for structure, and just as you must indent the body of loops, you must *not* extraneously indent other things (line continuations don't count). You'll need to post the correct error message after configuring Apache for CGI as Peter showed, unless of course you figure out the problem. From fredrik at pythonware.com Thu Feb 17 03:02:53 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Feb 2005 09:02:53 +0100 Subject: Derived class and deepcopy References: Message-ID: Philip Smith wrote: > In the given example I want to apply deepcopy() to the Matrix instance (on initialisation) to > ensure that the list part is not affected by subsequent changes to the initialising list or Matrix > but this gives me a string of errors (some of which imply I'm trying to copy the class rather than > the instance). > > Anyone got any thoughts on this???? where's the example? what errors do you get? From aleaxit at yahoo.com Sun Feb 6 02:27:32 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 6 Feb 2005 08:27:32 +0100 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1grifns.14san6f1b076mdN%aleaxit@yahoo.com> <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com> <1grixdp.1ttyiwh1m4ydsiN%aleaxit@yahoo.com> Message-ID: <1grjzax.1ibjw8e1iktxyvN%aleaxit@yahoo.com> Nick Coghlan wrote: ... > > _temp = x.y > > x.y = type(temp).__irebind__(temp, z) ... > I was thinking of something simpler: > > x.y > x.y = z > > That is, before the assignment attempt, x.y has to resolve to *something*, but > the interpreter isn't particularly fussy about what that something is. OK, I guess this makes sense. I just feel a tad apprehensive at thinking that the semantics differ so drastically from that of every other augmented assignment, I guess. But probably it's preferable to NOT let a type override what this one augmented assignment means; that looks like an "attractive nuisance" tempting people to be too clever. Still, if you write a PEP, I would mention the possible alternative and why it's being rejected in favor of this simpler one. Alex From roy at panix.com Sun Feb 6 17:40:56 2005 From: roy at panix.com (Roy Smith) Date: Sun, 06 Feb 2005 17:40:56 -0500 Subject: Python versus Perl ? References: <1107695949.247611.272800@g14g2000cwa.googlegroups.com> Message-ID: "EP" wrote: > There are very very few cases where anyone is going to require > you to use Python Conversely, it pays to understand when you are likely to be permitted to use it (or any new technology), and when you are likely to be forbidden. Companies are generally the most conservative about "customer-facing" projects. Something that's going to be shipped to a customer, or used directly by a customer, is not a good candidate to try and the the PHB to approve using something new. The next step down the line is something which is going to be used by many people within your own organization. If you write a tool in language X and want it to get adopted as a tool that everybody uses, don't be too surprised if the answer is, "Yeah, but who's going to maintain it, nobody but you knows X". The easiest way to sneak a new technology in the door is on a project where nobody else has to use the technology directly, in other words, a tool you write to help you get your own work done. When the boss notices that you're getting your stuff done in half the time most of the other group spends doing it, and you tell him it's because you're using X and everybody else is using Y, it's like waving dollar signs in front of his face. From mart.franklin at gmail.com Wed Feb 23 01:36:46 2005 From: mart.franklin at gmail.com (Martin Franklin) Date: Wed, 23 Feb 2005 06:36:46 +0000 Subject: basic tkinter/Windows question In-Reply-To: <7xwtt0ysuo.fsf@ruckus.brouhaha.com> References: <421BCED0.2070206@irl.cri.nz> <7xwtt0ysuo.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I find myself having to write some code on Windows :-(. To alleviate > the pain, at least I get to use Python for some of it. > > I'm trying to write a simple application, say "eggs.py". It pops a > tkinter gui and lets the user do some stuff. The system has Python > installed so I don't care about wrapping it in a .exe file or anything > like that. But I'd like to make a desktop icon for eggs.py and let the > user double-click it and run the app without also getting a DOS box on > the screen. > > Is there a simple way to do that? I didn't see anything in the Python > docs about it. I suspect that this is really a dumb Windows question, > but I avoid Windows whenever I can, so most anything I can ask about it > is probably dumb. > > Thanks much. renaming the eggs.py to eggs.pyw will tell windows to use pythonw.exe to start this python file (and will not open a console) You can then create a shortcut in the normal way Martin From unknownsoldier93 at yahoo.com Thu Feb 24 23:22:32 2005 From: unknownsoldier93 at yahoo.com (gf gf) Date: Thu, 24 Feb 2005 20:22:32 -0800 (PST) Subject: Trace exceptions Message-ID: <20050225042232.68519.qmail@web20708.mail.yahoo.com> Is there anyway to do something like this: try: ... except Exception: print the Exception message (and maybe other info) __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From bearophileHUGS at lycos.com Sun Feb 13 17:52:32 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 13 Feb 2005 14:52:32 -0800 Subject: builtin functions for and and or? In-Reply-To: <37a2i0F58gsbsU1@individual.net> References: <37a2i0F58gsbsU1@individual.net> Message-ID: <1108335152.338013.45530@z14g2000cwz.googlegroups.com> In Python there are so many ways to do things... This looks like another one, I haven't tested it: not False in imap(pred, iterable) As usual tests are required to measure the faster one. I agree with Roose, there are are some "primitive" operations (like this, and flatten, partition, mass removal of keys from a dictionary, and few others) that can be added to the language (but I'm still not capabable of doing it myself, and Python is free, so it's not right to ask people to work for free for us). Bear hugs, Bearophile From pipedreamergrey at gmail.com Tue Feb 22 15:36:40 2005 From: pipedreamergrey at gmail.com (PipedreamerGrey) Date: 22 Feb 2005 12:36:40 -0800 Subject: PythonCard and Py2Exe Message-ID: <1109104600.289868.118190@f14g2000cwb.googlegroups.com> I'm trying to create a standalone version (.exe) of PythonCard's Custdb sample using Py2Exe version 0.5.0. Everytime I attempt to compile the program, I get an error during compilation. This is the exact code I'm using in the setup file: from distutils.core import setup import py2exe setup( name = "custdb", console = ["custdb.py"], data_files = [ (".", ["custdb.ini", "custdb.de.rsrc.py", "custdb.rsrc.py", "customerdata.csv"]) ] ) This is the error message I get when I run custdb.exe: Traceback (most recent call last): File "custdb.py", line 202, in ? app = model.Application(CustDbStack) File "PythonCard\model.pyc", line 337, in __init__ File "PythonCard\resource.pyc", line 48, in getResource File "PythonCard\resource.pyc", line 86, in __init__ File "PythonCard\resource.pyc", line 91, in __init__ File "PythonCard\resource.pyc", line 91, in __init__ File "PythonCard\resource.pyc", line 96, in __init__ File "PythonCard\resource.pyc", line 139, in enforceSpec File "PythonCard\resource.pyc", line 30, in loadComponentModule ImportError: cannot import module 'radiogroup When I add "radiogroup" to the imports at the top of custdb.py, I get this error message: Traceback (most recent call last): File "custdb.py", line 18, in ? ImportError: cannot import name radiogroup This is line 18 in Custdb.py: from PythonCard import dialog, model, radiogroup From johnpote at blueyonder.co.uk Thu Feb 10 19:04:21 2005 From: johnpote at blueyonder.co.uk (John Pote) Date: Fri, 11 Feb 2005 00:04:21 GMT Subject: tkinter menu bar problem References: Message-ID: <9ESOd.40955$68.917@fe1.news.blueyonder.co.uk> Thanks for the reply. I now have radio buttons (with a nice tick!) on my menu that can be greyed out when disabled. I can also change the background colour of the individual buttons as you suggest. What I cannot do is change the background colour of the menu bar itself. The following code is accepted but the menu bar background stays resolutely light grey rather than light blue. rootWin = Tk() menuBar = MenuBar(rootWin, background='light blue') menuBar.insert_cascade(MenuBar.CONFIG, label='Config', menu=configMenu, background='light blue') The background options are being ignored and the window retains its standard windows colour scheme which I assume is overriding the background colour option. I guess my normal windows colour scheme (classic windows!) is not so bad and life is too short to tinker with this any more. Thanks again John Pote "Eric Brunel" wrote in message news:opslxnemnrrqur0o at eb.pragmadev... > On Wed, 09 Feb 2005 11:35:40 GMT, John Pote > wrote: > >> I have a menu bar in a top level window as follows > [snip code] >> >> Q1 Cannot find a way of changing the menu bars background colour. When >> colour options are accepted they seem to be ignored. Is this a native >> look >> and feel characteristic of write once run anywhere, not yet implemented >> or >> possibly a bug. > > Even if the tk man pages [1] don't mention it, it would not be surprising > if the background option for menu items did not work on Windows, since > many things seem to be "hardcoded" on this platform. I tested the > following code on Linux; it works without problem and has the expected > behaviour: > >>>> from Tkinter import * >>>> root = Tk() >>>> mb = Menu(root) >>>> root.configure(menu=mb) >>>> m = Menu(mb) >>>> mb.add_cascade(label='Menu', menu=m) >>>> m.add_command(label='Quit', command=root.quit, background='red') > > If it is what you did and if it doesn't work on Windows, it is likely that > the background option for menu items is not supported for this platform... > >> Q2 Some of the menu options in the config menu will not always be >> available >> depending on program state. How can individual items in such a menu be >> turned to faint gey to indicate their unavailability. Also a tick mark >> against an item would be useful to show the currently selected option. Is >> this possible? > > To "grey out" a menu item: > > parentMenu.entryconfigure(itemIndex, state=DISABLED) > > To have menu items with a check-mark, use the add_checkbutton or > add_radiobutton methods on the parent menu. Their use is similar to the > Checkbutton and Radiobutton classes. See [1] for all available options. > > [1] http://www.tcl.tk/man/tcl8.4/TkCmd/menu.htm > - Eric Brunel - From secun at yahoo.com Fri Feb 25 10:20:04 2005 From: secun at yahoo.com (Chris) Date: Fri, 25 Feb 2005 15:20:04 GMT Subject: Nevow examples References: Message-ID: Does anyone know of a site(s) that shows examples of what you can do with Nevow? I'm not necessarily referring to code, but what it can do over the web. (Something I can show my boss if needed.) In article , oliphant at ee.byu.edu says... > > There was a request for nevow examples. Nevow is a fantastic > web-development framework for Python. > > I used nevow to create http://www.scipy.org/livedocs/ > > This site uses nevow and self introspection to produce (live) > documentation for scipy based on the internal docstrings. It would be > nice to add the capability for users to update the documentation through > the web-site. But, that functionality is not complete. > > The code itself is available in the util directory of scipy which can be > checked out of CVS (or browsed). Go to http://www.scipy.org for mor > details. > > -Travis Oliphant > > From bearophileHUGS at lycos.com Fri Feb 11 05:53:30 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 11 Feb 2005 02:53:30 -0800 Subject: lambda and for that matter goto not forgetting sugar In-Reply-To: References: Message-ID: <1108119209.965796.246160@z14g2000cwz.googlegroups.com> Nick Coghlan wrote: > Anyway, check out AlternateLambdaSyntax on the python.org Wiki It's an interesting page: http://www.python.org/moin/AlternateLambdaSyntax Some days ago I suggested something different: maybe def can become a function, then it can work as lambda (and still as the old def) too. Something like: original : lambda a, b, c:f(a) + o(b) - o(c) lambda x: x * x lambda : x lambda *a, **k: x.bar(*a, **k) ==> def(a, b, c): return f(a) + o(b) - o(c) fun1 = def(x): return x * x def(): return x def(*a, **k): return x.bar(*a, **k) Such def can be used as the lambda inside expressions too. fun1 = def(a, b, c): return f(a) + o(b) - o(c) This is the same as the old: def fun1(a, b, c): return f(a) + o(b) - o(c) (That use of "return" in the middle is a little verbose to use it for functions inside expressions.) That Ruby syntax at the end of page is cute. {a,b,c | return f(a) + o(b) - o(c)} {a,b,c | f(a) + o(b) - o(c)} def(a, b, c | f(a) + o(b) - o(c) ) fun(a, b, c | f(a) + o(b) - o(c) ) (etc. there are lots of other possibilities). If def becomes a function like that, then beside this syntax: fun1 = def(a, b, c): return f(a) + o(b) - o(c) This other one can be interesting for expressions only: def(a, b, c | f(a) + o(b) - o(c) ) (Both can be acceptable at the same time). Bye, Bearophile From grante at visi.com Tue Feb 8 16:39:22 2005 From: grante at visi.com (Grant Edwards) Date: 08 Feb 2005 21:39:22 GMT Subject: Basic file operation questions References: <1107379669.870799.256030@g14g2000cwa.googlegroups.com> <1107846197.701686.303390@l41g2000cwc.googlegroups.com> <7q4Od.753$Sd.170775@newshog.newsread.com> Message-ID: <4209318a$0$21621$a1866201@visi.com> On 2005-02-08, Marc Huffnagle wrote: >>>for line in file(...): >>> # do stuff > When you read a file with that method, is there an implied close() call > on the file? I assume there is, but how is that handled? The file will be closed when the the file object is deleted by the garbage collection algorithm. That will happen sometime after the for loop exits and before the program exits. In normal C-Python I believe it happens immediately after the for loop exits. However, that behavior is not guaranteed by the language spec. -- Grant Edwards grante Yow! Now that I have my at "APPLE", I comprehend COST visi.com ACCOUNTING!! From carribeiro at gmail.com Fri Feb 4 18:09:46 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 4 Feb 2005 21:09:46 -0200 Subject: Persistence design [was: RE: OT: why are LAMP sites slow?] In-Reply-To: <20050204224644.GG1607@performancedrivers.com> References: <3A81C87DC164034AA4E2DDFE11D258E3398367@exchange.hqamor.amorhq.net> <20050204224644.GG1607@performancedrivers.com> Message-ID: <864d370905020415095e876649@mail.gmail.com> On Fri, 4 Feb 2005 17:46:44 -0500, Jack Diederich wrote: > On Fri, Feb 04, 2005 at 10:31:19AM -0800, Robert Brewer wrote: > > Jack Diederich wrote: > > > If there is interest I'll follow up with some details on my own LAMP > > > software which does live reports on gigs of data and - you > > > guessed it - > > > I regret it is database backed. That story also involves why > > > I started > > > using Python (the prototype was in PHP). > > > > I'd be interested, if only selfishly to hear more potential use cases > > for *my* projects. ;) > > It would be long so I'll spin it into a blog piece. They seem to be > all the rage these days *0.5 wink* A blog piece of yours truly :-) (call it a blatant plug if you want) http://pythonnotes.blogspot.com/2004/11/alternative-database-systems.html """ There was a time when a database meant a flat file, fixed record repository. Indexes were added later, bringing better performance for several tasks. During the sixties, hierarchical database systems were developed, allowing to model complex real-life structures better. Even today, old-style mainframe systems (such as IBM's IMS) are still in production, managing huge databases. SQL was only invented in the seventies, based on a mathematical formalization of high-level data manipulation algorithms. Batch processing systems read and process data in a sequential fashion, and normally do not need such abstractions. But the new generation interactive systems really needed them. And when PC-based client-server computing exploded in the 90's, SQL kingdom was started. """ ... """ In the middle of this, there is a unforeseen trend in the use of the file system as a storage medium. Yes, the file system. Guess what? Forget the FAT, please. Current file systems are much more stable and efficient than older ones. Modern filesystems are hierarchical, and can store arbitrary objects. Support for journaling, and better metadata management means that the filesystem is now a better choice for many situations. Several web publishing engines (blogs, wikis, and even full-fledged content management systems) support filesystem-based storage for text notes and documents, which were previously stored (in a hackish and haphazardous way) into DB blobs. The full filename is now a primary key, and flexible relationships between entities can be expressed as hiperlinks. """ I'm (slowly) designing a personal CMS that is intended to use Subversion as its backend, for both blog & wiki style entries. It's filesystem based, fast (the website can use the working copy for nearly everything) and allows for versioning - something that its difficult to implement properly with low-end RDBMSs. It looks promising :-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From alanmk at hotmail.com Tue Feb 15 05:22:41 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 15 Feb 2005 10:22:41 +0000 Subject: How to implement a file lock ?? In-Reply-To: References: Message-ID: [ionel] > is there a cross-platform library or module for file locking? > or at least a win32 implementation. > > i'm trying to get a lock on some file in a cgi script. ( i got my data > erased a few times :P ) portalocker - Cross-platform (posix/nt) API for flock-style file locking. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 HTH, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From ilias at lazaridis.com Sun Feb 6 08:10:51 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sun, 06 Feb 2005 15:10:51 +0200 Subject: [EVALUATION] - E01: The Java Failure - May Python Helps? In-Reply-To: References: Message-ID: Stephen Kellett wrote: > In message , Ilias Lazaridis > writes > >> Can one please point me to a downloadable version of the 2 reference >> manuals (did not found them)? > > Well, there is an obvious website address to visit and you can see the > word "documentation" on that website without scrolling. which leads to: http://python.org/doc/ which leads to: http://docs.python.org/download.html The conviently downloadable documentation-pack contains 4 "reference" type manuals. I assume the mentioned "2 reference manuals" were contained therein. > Use Google or a different search engine to find the obvious website. Thank you. I prefere interaction with the community. . -- http://lazaridis.com From nytimes at swiftdsl.com.au Thu Feb 17 22:14:55 2005 From: nytimes at swiftdsl.com.au (news.sydney.pipenetworks.com) Date: Fri, 18 Feb 2005 14:14:55 +1100 Subject: Why doesn't join() call str() on its arguments? In-Reply-To: References: <37hippF4gcimiU1@individual.net> <37hqlrF59l2b2U1@individual.net> <873bvw9nqh.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <421450CC.9080504@swiftdsl.com.au> <87psyz8h9o.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <4214A800.4010509@swiftdsl.com.au> Message-ID: <42155DAF.4010806@swiftdsl.com.au> Jeremy Bowers wrote: > On Fri, 18 Feb 2005 01:19:44 +1100, news.sydney.pipenetworks.com wrote: > >>Thanks for the pointer. Let's see how many zen points are for the OP's >>idea vs against > > > Along with the fact that I agree with Nick that you've seriously > miscounted (most of your "fors" are simply irrelevant and I think you > added them to bolster your point, at least I *hope* you don't think they > are all relevant... for instance if you really think "Flat is better than > nested" applies here, you don't understand what that one is saying...), You're right there. It's my own interpretation :-) > I'd point out that the Zen that can be comprehended by checking off items > in a list is not the true Zen. Well I didn't create or bring up the list of items originally. I was "zenning" it out until someone pointed me to the "Python" commandments. I always wished computer science was more engineering then philosophy. That way there'd always be an obvious answer. Regards, Huy From mhartl at post.harvard.edu Sat Feb 26 01:58:16 2005 From: mhartl at post.harvard.edu (Michael Hartl) Date: 25 Feb 2005 22:58:16 -0800 Subject: Which module is "set " in? References: Message-ID: <1109401096.625038.51050@l41g2000cwc.googlegroups.com> It's good that you're using Python 2.3, which does have sets available, as a previous poster mentioned. Users of Python 2.2 or earlier can get most of the Set functionality using the following class (from Peter Norvig's utils.py file): # class Set: # """This implements the Set class from PEP 218, except it does not # overload the infix operators. # Ex: s = Set([1,2,3]); 1 in s ==> True; 4 in s ==> False # s.add(4); 4 in s ==> True; len(s) ==> 4 # s.discard(999); s.remove(4); 4 in s ==> False # s2 = Set([3,4,5]); s.union(s2) ==> Set([1,2,3,4,5]) # s.intersection(s2) ==> Set([3]) # Set([1,2,3]) ==> Set([3,2,1]); repr(s) ==> '{1, 2, 3}' # for e in s: pass""" # # def __init__(self, elements=[]): # self.dict = {} # for e in elements: # self.dict[e] = 1 # # def __contains__(self, element): # return element in self.dict # # def __getitem__(self, i): # return self.dict.items()[i] # # def add(self, element): # self.dict[element] = 1 # # def remove(self, element): # del self.dict[element] # # def discard(self, element): # if element in self.dict: # del self.dict[element] # # def pop(self): # key, val = self.dict.popitem() # return key # # def clear(self): # self.dict.clear() # # def union(self, other): # return Set(self).union_update(other) # # def intersection(self, other): # return Set(self).intersection_update(other) # # def union_update(self, other): # for e in other: # self.add(e) # return self # # def intersection_update(self, other): # for e in self.dict.keys(): # if e not in other: # self.remove(e) # return self # # def issubset(self, other): # for e in self.dict.keys(): # if e not in other: # return False # return True # # def __iter__(self): # for e in self.dict: # yield e # # def __len__(self): # return len(self.dict) # # def __cmp__(self, other): # if self is other: return False # if not isinstance(other, Set): return id(self) - id(other) # return cmp(self.dict, other.dict) # # def __repr__(self): # return "{%s}" % ", ".join([str(e) for e in self.dict.keys()]) Michael -- Michael D. Hartl, Ph.D. CTO, Quark Sports LLC http://quarksports.com/ From onurb at xiludom.gro Wed Feb 9 04:47:34 2005 From: onurb at xiludom.gro (bruno modulix) Date: Wed, 09 Feb 2005 10:47:34 +0100 Subject: Lambda In-Reply-To: <9VdOd.110$0b3.4668@news.uswest.net> References: <9VdOd.110$0b3.4668@news.uswest.net> Message-ID: <4209dc38$0$29400$626a14ce@news.free.fr> e wrote: > Question: WHAT IS LAMBDA? No need to scream, we here you quite well. > I can't figure out what it does from any > documentation i've found anywhere. Then I doubt you really did search. http://www.google.com/search?q=Python+%2B+lambda > i doubt i need it Why ? > but i still want to > know what the heck it is/does/fixes/whatever! lambda is a keyword that is used to create anonymous functions. This is pretty handy for simple callbacks. -- bruno desthuilliers ruby -e "print 'onurb at xiludom.gro'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@')" -- From mdane at h2001.net Thu Feb 3 09:19:14 2005 From: mdane at h2001.net (Mabon Dane) Date: 3 Feb 2005 06:19:14 -0800 Subject: Is there a market for python developers? Message-ID: <1107440354.317628.221090@g14g2000cwa.googlegroups.com> I am new to python and took my first attempts at working with this language today. Is there a market for people who work with Python? Mabon Dane From eric_brunel at despammed.com Thu Feb 17 04:27:30 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 17 Feb 2005 10:27:30 +0100 Subject: Pmw.Balloon under Windows References: <1108579886.983146.56130@z14g2000cwz.googlegroups.com> Message-ID: On 16 Feb 2005 10:51:27 -0800, Aki Niimura wrote: [snip] > The software is working fine under Solaris 9. > However, when I tried it under Windows, it worked also fine but it spit > out > the following error message when exiting. > > (from cygwin terminal) > > % c:/Python23/python my_app.py > > This application has requested the Runtime to terminate it in an > unusual way. > Please contact the application's support team for more information. > > (the same error message is observed when I run the program directly in > Windows XP environment.) > // [snip] > After painful investigation, I found Pmw.Balloon was causing this > problem > (because the problem went away if I commented out all balloon > statements). > > Then I compared my usages and Pmw Balloon example because the example > didn't > cause this. (http://pmw.sourceforge.net/doc/Balloon.html) I used the Pmw.Balloon quite a lot and never see any problem. One question: what Python do you use? Is it a regular Windows Python distribution or the Python delivered with Cygwin? I know by experience that the Python in Cygwin has quite a lot of problems (mine crashes *very* often). If you don't already use a "regular" Windows distro, I think using one may solve your problem. > My questions are: > (1) Why my program is complaining and is there any workaround? > > (2) What is the difference between using widget quit() method > and using Windows 'X' button. > - I know clicking Windows 'X' button generates an event but I thought > - ultimately it reached to the same routine to terminate the program. I think the default binding for the 'X' button is to call destroy, not quit. Calling destroy on the main window is almost equivalent to calling quit, so maybe it can be a solution? > (3) Is it possible to fake clicking 'X' button? > I see a widget has event_generate() method. Not that I know of. The event_generate method won't help here, because the 'X' button is handled by the window manager, and not by the application. It's a bit more complicated on Windows (as usual...) since there is no "real" window manager, but from the tk/Tkinter point of view, the result is the same: you can't "fake" a window manager event using event_generate. BTW, what are the versions of Python, tk and Pmw you're using? HTH a little... - Eric Brunel - From theller at python.net Thu Feb 17 13:24:00 2005 From: theller at python.net (Thomas Heller) Date: Thu, 17 Feb 2005 19:24:00 +0100 Subject: [newbie]How to install python under DOS and is there any Wxpython can be installed under dos? References: <1108557065.547230.254540@z14g2000cwz.googlegroups.com> <11172sa1sg2svc8@corp.supernews.com> <4K6dneoBWMc4KInfRVn-rA@rogers.com> <37jsdgF5e56jeU1@individual.net> Message-ID: <4qgbt58f.fsf@python.net> "Diez B. Roggisch" writes: > Maybe somehow the pygame sdl wrapper can be used for gui-stuff. SDL has had > a DOS mode. But it is discontinued. What exactly is discontinued? pygame? SDL? Thomas From aurora00 at gmail.com Wed Feb 2 14:54:18 2005 From: aurora00 at gmail.com (aurora) Date: Wed, 02 Feb 2005 11:54:18 -0800 Subject: hotspot profiler experience and accuracy? References: <42011f05$0$28983$e4fe514c@news.xs4all.nl> Message-ID: Thanks for pointing me to your analysis. Now I know it wasn't me doing something wrong. hotspot did lead me to knock down a major performance bottleneck one time. I found that zipfile.ZipFile() basically read the entire zip file in instantiation time, even though you may only need one file from it subsequencely. In anycase the number of function call seems to make sense and it should give some insight to the runtime behaviour. The CPU time is just so misleading. > aurora wrote: > >> But the numbers look skeptical. Hotspot claim 71.166 CPU seconds but >> the actual elapsed time is only 54s. When measuring elapsed time >> instead of CPU time the performance gain is only 13% with the profiler >> running and down to 10% when not using the profiler. >> Is there something I misunderstood in reading the numbers? > > Well, I'm confused too. Look at my post from a few months ago: > http://tinyurl.com/6awzj > (note that my code contained a few errors and that you need > to use the fixed code that I posted a few replies later). > > Perhaps somebody can explain a bit more about this this time? :-) > > At the moment, frankly, hotspot seems rather useless. > > --Irmen From cappy2112 at gmail.com Thu Feb 10 17:56:11 2005 From: cappy2112 at gmail.com (Cappy2112) Date: 10 Feb 2005 14:56:11 -0800 Subject: convert list of tuples into several lists References: <36uihlF58p63iU1@individual.net> <1107998078.610891.111510@z14g2000cwz.googlegroups.com> Message-ID: <1108076171.929529.280860@z14g2000cwz.googlegroups.com> Thanks I dont remember reading anything about this. What is this feature called? Steven Bethard wrote: > Cappy2112 wrote: > > What does the leading * do? > > Tells Python to use the following iterable as the (remainder of the) > argument list: > > From fuzzyman at gmail.com Tue Feb 1 05:40:18 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 1 Feb 2005 02:40:18 -0800 Subject: Forcing interactive interpreter without (-i) In-Reply-To: References: Message-ID: <1107254418.446746.59270@f14g2000cwb.googlegroups.com> In Movable Python I use IPython and code.InteractiveConsole to provide interactive sessions. See the file 'movpy.py' in the source distribution to see the code. Note that to get IPython working with py2exe you must effectively do an explicit `import site`. >def interactive(localvars=None): > """A very simple function to embed an interactive interpreter into movpy.""" # could have the banner passed in as an optional argument, plus maybe the IPython config file location > IPShellEmbed = None > try: > from IPython.Shell import IPShellEmbed > except ImportError: > pass > if not IPShellEmbed or IPOFF: > if localvars == None: > localvars = sys._getframe(0).f_back.f_locals # extract locals from the calling frame - taken from IPython > from code import InteractiveConsole > con = InteractiveConsole(localvars) > con.interact() > else: > banner = 'Movable Python\nIPython Interactive Shell. See the manual for a list of features and tips.\nCtrl-D to exit.' > argv = ['-ipythondir', libdir] # where to find the ipython config file > ipshell = IPShellEmbed(argv, banner=banner) > ipshell() http://sourceforge.net/projects/movpy Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From peter at engcorp.com Sat Feb 19 15:00:19 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 19 Feb 2005 15:00:19 -0500 Subject: PyGTA next meeting: Tuesday February 22, 7-9pm at offices of Frogware (not our usual location!) Message-ID: We're announcing here in case anyone who doesn't subscribe to our announcement mailing list was thinking of attending: NOTE the change in location from where we've been meeting for the last 12 months!! The next meeting of PyGTA, the Toronto-area Python user group, will be held at the offices of Frogware (http://www.frogware.com/) at: 477 Richmond Street West, Suite 210, Toronto, Ontario on Tuesday, February 22nd, 2005, 7pm to 9pm. Here's a link using the Google Maps Beta: http://maps.google.com/maps?q=477%20Richmond%20Street%20West%2C%20Toronto Note also that as of this moment, we have no official speaker. If you would like to reserve time to talk about your own Python-related project, please let us know! -Ian and Peter, meeting organizers P.S.: We'd also like to take this opportunity to publicly thank Givex (http://web.givex.com/) and D'Arcy Cain for generously hosting our meetings for the last year. From lfdl at hotmail.com Mon Feb 21 19:14:40 2005 From: lfdl at hotmail.com (GuyBrush Treepwood) Date: Tue, 22 Feb 2005 01:14:40 +0100 Subject: wxPython Message-ID: I just compiled and installed wxWidgets and wxPython. When I want to test this libraries, I get: Python 2.4 (#1, Feb 19 2005, 19:24:31) [GCC 3.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from wxPython.wx import * Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.4/site-packages/wx-2.5.3-gtk2-ansi/wxPython/__init__.py", line 10, in ? import _wx File "/usr/local/lib/python2.4/site-packages/wx-2.5.3-gtk2-ansi/wxPython/_wx.py", line 3, in ? from _core import * File "/usr/local/lib/python2.4/site-packages/wx-2.5.3-gtk2-ansi/wxPython/_core.py", line 15, in ? import wx._core File "/usr/local/lib/python2.4/site-packages/wx-2.5.3-gtk2-ansi/wx/__init__.py", line 42, in ? from wx._core import * File "/usr/local/lib/python2.4/site-packages/wx-2.5.3-gtk2-ansi/wx/_core.py", line 4, in ? import _core_ ImportError: libwx_gtk2_xrc-2.5.so.3: cannot open shared object file: No such file or directory I installed wxWidgets in /opt/wx/2.5 as described in http://www.wxpython.org/BUILD.html. $ls /opt/wx/2.5/lib | grep wx libwx_baseud-2.5.so@ libwx_baseud-2.5.so.3@ libwx_baseud-2.5.so.3.0.0* libwx_baseud_net-2.5.so@ libwx_baseud_net-2.5.so.3@ libwx_baseud_net-2.5.so.3.0.0* libwx_baseud_xml-2.5.so@ libwx_baseud_xml-2.5.so.3@ libwx_baseud_xml-2.5.so.3.0.0* libwx_gtk2ud_adv-2.5.so@ libwx_gtk2ud_adv-2.5.so.3@ libwx_gtk2ud_adv-2.5.so.3.0.0* libwx_gtk2ud_core-2.5.so@ libwx_gtk2ud_core-2.5.so.3@ libwx_gtk2ud_core-2.5.so.3.0.0* libwx_gtk2ud_gizmos-2.5.so@ libwx_gtk2ud_gizmos-2.5.so.3@ libwx_gtk2ud_gizmos-2.5.so.3.0.0* libwx_gtk2ud_gl-2.5.so@ libwx_gtk2ud_gl-2.5.so.3@ libwx_gtk2ud_gl-2.5.so.3.0.0* libwx_gtk2ud_html-2.5.so@ libwx_gtk2ud_html-2.5.so.3@ libwx_gtk2ud_html-2.5.so.3.0.0* libwx_gtk2ud_ogl-2.5.so@ libwx_gtk2ud_ogl-2.5.so.3@ libwx_gtk2ud_ogl-2.5.so.3.0.0* libwx_gtk2ud_stc-2.5.so@ libwx_gtk2ud_stc-2.5.so.3@ libwx_gtk2ud_stc-2.5.so.3.0.0* libwx_gtk2ud_xrc-2.5.so@ libwx_gtk2ud_xrc-2.5.so.3@ libwx_gtk2ud_xrc-2.5.so.3.0.0* wx/ I seem to have the necessary libraries installed, but with a *ud* pattern in their name. Any advice here? From adam at cognitcorp.com Tue Feb 15 19:54:02 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Tue, 15 Feb 2005 19:54:02 -0500 Subject: Iterator / Iteratable confusion In-Reply-To: References: <420a5c1e$0$21630$a1866201@visi.com> <200502131848.03655.francis.girard@free.fr> <200502131958.27410.francis.girard@free.fr> Message-ID: <1108515242.4371.9.camel@localhost.localdomain> On Tue, 2005-02-15 at 19:25, Terry Reedy wrote: > "Michael Spencer" wrote in message > news:cuthdk$dnq$1 at sea.gmane.org... > > > Terry, thanks for responding in depth. > We are both interested in the murky edges at and beyond conventional usage. > > Terry wrote > >> 2. "It is not essential to not do something wasteful as long as it is >> > >> otherwise inconsequential." > > Not that "iter(iterator) is iterator" is somehow wasteful (actually it > > > seems conservative), but rather that alternative behavior is readily > > implmented. > What I was pointing to as wasteful is the application of your alternative > behavior where an object is replaced by a copy and then effectively tossed. > > However, I suggest that there may be cases where > > "iter(iterator) is not iterator" is useful behavior. > I am quite aware that multiple iterators for the same iterable (actual or > conceptual) can be useful (cross products, for example). But I am dubious > that initialized clones of 'iterators' are *more* useful, especially for > Python, than multiple iterators derived from repeated calling of the > callable that produced the first iterator. It might be different if Python > were a prototype/clone language rather than a typeclass/instance language. > It is also possible that we have slightly different ideas of 'useful' in > the Python context. > In your example, as I pointed out, A.__iter__ and AnIterator.__iter__ have > the same code, so I could not see any advantage to getting a copy through > calling the latter instead of the former. For the disadvantage, see below. > > What to call such an object is another matter. > spencerator ;-? > Here are some related reasons why I think it useful if not essential to > restrict the notion of iterator by restricting iterator.__iter__ to > returning self unmodified. > Leaving Python aside, one can think of iterable as something that > represents a collection and that can produce an iterator that produces the > items of the collection one at a time. In this general conceptioning, > iterables and iterators seem distinct (if one ignores self-iterables). In > Python, giving iterators an __iter__ method, while quite useful, erases > (confuses) the (seeming) distinction, but giving them a minimal __iter__ > does so minimally, keeping iterators a distinct subcategory of iterable. > Spencerators confuse the distinction more than minimally and define a > vaguer subcategory. > Essential? For something defined as minimal, it is essential that it be > minimal. But you point seems to be that it is not essential that iterator > be so defined. Ok. > (Aside: an iterator can be thought of as representing the sequence of > future .next() returns. From this viewpoint, making iterators a > subcategory of iterable is more than just a convenience.) > Taking Python as it is, a useful subcategory of iterable is 'reiterable'. > This is distinct from iterator strictly defined. This we have iterables > divided into iterators, reiterables, and other. I think this is > didactically useful. Spencerators are reiterables. > Iter(iterator) returning iterator unchanged makes iterator a fixed point of > iter. It ends any chain of objects returned by repeated iter calls. > Spencerators prolong any iter chain, making it infinite instead of finite. > Essential? Repeat the paragraph above with 'a fixed point' substituted for > 'minimal'. How is spencerator different than itertools.tee? Adam DePrince From farcepest at gmail.com Thu Feb 17 22:10:23 2005 From: farcepest at gmail.com (Andy Dustman) Date: 17 Feb 2005 19:10:23 -0800 Subject: Why doesn't join() call str() on its arguments? In-Reply-To: References: <4214fea9$0$20394$636a15ce@news.free.fr> <1108686001.198554.21520@g14g2000cwa.googlegroups.com> Message-ID: <1108696223.190228.325840@z14g2000cwz.googlegroups.com> Looking at the code, it seems that if it finds a unicode object on the first pass (the sizing pass), it punts and returns PyUnicode_Join(self, seq), which is the sequence from above and not necessarily the original object (orig), and starts over. In the worst-case scenario, you have a long sequence of strings with one unicode string at the end... Actually, I guess I'm a little surprised that str.join(arg) doesn't require arg to be an iterator that returns str instances. unicode.join(arg) can afford to be a little more flexible. I wonder how common it is to pass a mixture of str and unicode to str.join(). From mwm at mired.org Thu Feb 17 20:05:09 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 17 Feb 2005 19:05:09 -0600 Subject: [Fwd: Re: [Uuu-devel] languages] <-- Why Python References: <1108678805.542584.171930@z14g2000cwz.googlegroups.com> Message-ID: <864qgaisoq.fsf@guru.mired.org> Arich Chanachai writes: > These last two points kind of diverge from the point, no? What I mean > is that we want to present the argument of why Python is the best > choice as THE built-in programming language for the revolutionary uuu > operating system. A new operating system shouldn't be picking "THE" built-in programming language. It should instead be providing mechanisms to allow arbitrary programming languages to be used wherever they are required. Tying the users of the OS - or of some application - down to a specific language is a disservice to the developers and users of that OS or application. While Python is an excellent language, and has a nice implementation for embedding/extending applications, it's not necessarily the best choice for all problems. You're be doing much better for your users to allow them to choose the right language for the problem than to dictate the language that has to be used. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From luismgz at gmail.com Tue Feb 8 22:21:24 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 8 Feb 2005 19:21:24 -0800 Subject: Learning Python - resources and ideas In-Reply-To: References: <1107855763.533466.254380@c13g2000cwb.googlegroups.com> Message-ID: <1107919284.128799.316600@g14g2000cwa.googlegroups.com> Regarding rec.photo.equipment.35mm... this is not his fault. Yesterday I tried posting to comp.lang.python and, for some strange reason, it was posted momentarily to this group. Regarding Cody's question: If you are an absolute newby, try Josh Cogliati's python tutorial for non-programmers (google this). I learned the basics with it. Then you can try any of the other resources listed in www.python.org. If you're willing to buy a book, try "Learning Python 2nd.Ed" by Mark Lutz or "Core Python" by Wesley Chun. Regards, Luis From irmen.NOSPAM at xs4all.nl Fri Feb 11 12:45:45 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 11 Feb 2005 18:45:45 +0100 Subject: is there a safe marshaler? In-Reply-To: <3b091a1c.0502110634.5edb1987@posting.google.com> References: <420b6936$0$28982$e4fe514c@news.xs4all.nl> <420b6e98$0$23018$626a14ce@news.free.fr> <420b9135$0$28982$e4fe514c@news.xs4all.nl> <3b091a1c.0502110634.5edb1987@posting.google.com> Message-ID: <420cef48$0$28977$e4fe514c@news.xs4all.nl> cmkl wrote: > but can't effbot's fast cElementree be used for PYROs XML_PICKLE > and would it be safe and fast enough? ElementTree's not a marshaler. Or has it object (de)serialization included? --Irmen From michele.simionato at gmail.com Tue Feb 22 05:15:37 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 22 Feb 2005 02:15:37 -0800 Subject: pydoc documentation In-Reply-To: References: Message-ID: <1109067337.009677.32380@c13g2000cwb.googlegroups.com> $ pydoc -g M.S. From alan.mcintyre at esrgtech.com Sat Feb 5 09:12:42 2005 From: alan.mcintyre at esrgtech.com (Alan McIntyre) Date: Sat, 05 Feb 2005 09:12:42 -0500 Subject: Trouble converting hex to decimal? In-Reply-To: References: Message-ID: Earl, Try this: >>> ord('\x00') 0 or: >>> import struct >>> struct.unpack('b', '\x00') (0,) If you're needing to pull values out of multiple bytes (shorts, longs, floats, etc.), have a look at the struct module. Here's an example: >>> struct.unpack('f', '\x00\x00(B') (42.0,) Hope this helps, Alan Earl Eiland wrote: > I'm trying to process the IP packet length field, as recorded by pcap > (Ethereal) and recovered using pcapy. When I slice out those bytes, I > get a value that shows in '\x00' format, rather than '0x00'. Neither > int() nor eval() are working. How do I handle this? > > Earl Eiland > From bpeng at rice.edu Sun Feb 27 15:03:26 2005 From: bpeng at rice.edu (Bo Peng) Date: Sun, 27 Feb 2005 14:03:26 -0600 Subject: default value for list access? In-Reply-To: References: Message-ID: To clearify the problem: The data is the count of something, for example a[90]=10. a may be a dictionary if the range is huge and a list when the range is reasonably small. In the dictionary case, I can use a.setdefault(80, 0) if key 80 does not exist. In the list case, I have to check the length of list before I access it (or use exception). This becomes troublesome when I need to do the following a lot. b = a[80][1] + a[80][2] + a[80][3] If I use the getItem function in my previous email, it will look like b = getItem(getItem(a, 80, []), 1, 0) + getItem(getItem(a, 80, []), 2, 0) + getItem(getItem(a, 80, []), 3, 0) What would be the best solution to handle this? Something like b = df( a[80][1], 0) + df( a[80][2], 0) + df( a[80][3], 0) would be reasonable but df can not be easily defined since the exception will be raised before function df is called. Something like b = df( a, [80, 1], 0) + df( a, [80,2], 0) + df( a, [80, 3], 0) would work if df is defined as def df(a, idx, default): try: for i in range(0, idx): a = a[ idx[i] ] return a except: return 0 but I am afraid that a for loop would bring serious performance problem. Thanks. Bo From cjw at sympatico.ca Wed Feb 16 12:56:12 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 16 Feb 2005 12:56:12 -0500 Subject: Multidimensional arrays - howto? In-Reply-To: <1108423310.463006.318320@f14g2000cwb.googlegroups.com> References: <1108423310.463006.318320@f14g2000cwb.googlegroups.com> Message-ID: <4213893C.3050204@sympatico.ca> doodle4 at gmail.com wrote: > Hello all, > > I am trying to convert some C code into python. Since i am new to > python, i would like to know how to deal with multidimensional arrays? > > Thanks, > -Joe > > Here's a snippet of what i am trying to convert: > > # define table0 15 > # define table1 20 > > unsigned int Table[table0][table1] > > if(Table[table0][table1] != 0) > { > Table[table0][table1]-- > } > You might consider numarray. This is a package which is downloadable from Source Forge and intended for numeric and other arrays. Colin W. From morphex at gmail.com Fri Feb 18 10:18:06 2005 From: morphex at gmail.com (morphex) Date: 18 Feb 2005 07:18:06 -0800 Subject: Platform independent adduser script? Message-ID: <1108739886.550370.231620@g14g2000cwa.googlegroups.com> Hi there, does anyone here know of a script that enables adding of users on UNIX platforms via python? Thanks, Morten From adam at cognitcorp.com Sun Feb 6 02:20:34 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Sun, 06 Feb 2005 02:20:34 -0500 Subject: pickle/marshal internal format 'life expectancy'/backward compatibility In-Reply-To: <1f7befae05020514046ab10822@mail.gmail.com> References: <1107640264.7097.5.camel@localhost> <1f7befae05020514046ab10822@mail.gmail.com> Message-ID: <1107674434.3948.19.camel@localhost.localdomain> On Sat, 2005-02-05 at 17:04, Tim Peters wrote: > [Philippe C. Martin] > > I am looking into using the pickle format to store object/complex data > > structures into a smart card as it would make the design of the embedded > > application very simple. > > > > Yet the card might have to stay in the pocket of the customer for a few > > years, during which the back office application responsible for > > retrieving the information from the card might evolve as well as the > > python release it relies upon. > > > > Is there a commitment for python releases to be able to interpret > > 'older' pickle/marshal internal formats ? > > Pickle and marshal have nothing in common, and there's no > cross-release guarantee about marshal behavior. Pickles are safe in > this respect; indeed, each Python released to date has been able to > load pickles created by all earlier Python releases. Of course a > pickle produced by a later Python may not be loadable by an earlier > Python, although even in that direction you can get cross-release > portability by forcing the newer Python to restrict itself to produce > obsolete pickle formats. Reading Lib/pickletools.py in a current > release will explain all this. How complicated is your data structure? Might you just store: repr( ) and eval it later? Trust is an issue; you are vulnerable to malicious code, but no more so than with pickle or marshal. One quick and dirty way to be a little safer is to "sign" the data you store. # To save your data import sha import cPickle mysecret = "abc" mydata = {"what":"my data structure"} f = open( "/tmp/myfile.txt", "w+" ) mydata = cPickle.dumps( mydata, protocol=0 ) # I'm assuming this is a flash device ... lets be safe and not assume # that write is buffered ... f.write( sha.new( mysecret + mydata ).digest() + mydata) # To load your data import sha import cPickle mysecret = "abc f = open( "/tmp/myfile.txt", "w+" ) hash = f.read( sha.digest_size ) mydata = f.read() if sha.new( mysecret + mydata ).digest() != hash: raise "Somebody is tring to hack you!" mydata = cPickle.loads( mydata ) Of course, the security of this scheme is dependent on a lot, including the strength of sha, your ability to keep your secret key secret, the correctness of what I'm saying, etc etc etc. Adam DePrince From bpeng at rice.edu Sun Feb 27 16:39:04 2005 From: bpeng at rice.edu (Bo Peng) Date: Sun, 27 Feb 2005 15:39:04 -0600 Subject: default value for list access? In-Reply-To: References: Message-ID: > Sounds to me like the best solution is to simplify the implementation > and dispense with the list alternative. Why use a list if a dictionary > is suitable? Don't say performance: that's premature optimization. > Dictionaries already have what you need, apparently, with setdefault(), > so just use them and keep the code simple. You are right that if I use all dictionaries, I can use a.setdefault(4,{}).setdefault(2,0) to access a[4][2]. Not too bad compared to the getItem function. However, this is an scientific application. Data are stored internally in C format and exposed to Python as python array (arraymodule). I guess the best way is to modify the arraymodule interface and stop it from raising an exception when index is out of range. (similar to Ruslan's solution). But this means too much trouble for now. I will use the df(a, idx, default) method and see if its performance is acceptable. Thanks. Bo From sylvain.thenault at logilab.fr Fri Feb 4 05:59:22 2005 From: sylvain.thenault at logilab.fr (Sylvain Thenault) Date: Fri, 04 Feb 2005 11:59:22 +0100 Subject: making symlinks with distutils References: <1107513934.428944.257820@z14g2000cwz.googlegroups.com> Message-ID: On Fri, 04 Feb 2005 02:45:34 -0800, Michele Simionato wrote: > I want to distribute a pure Python package with this structure: > >> mypackage >> __init__.py >> module1.py >> module2.py >> ... >> myexecutable.py > > In particular, myexecutable.py is a script which is intended to be used > from the command line via the shebang trick. I want to distribute on > Unices. > and I want a symlink > > /usr/bin/myexecutable -> /mypackage/myexecutable.py > > to be made at installation time, when the user runs "python setup.py > install". > > What is the recommanded way to do that? Do I need a postinstallation > script or something like that? > > I could do that in various way, but I don't see the obvious one, maybe > because I am not a Dutch ;) i'm not sure there is a standard way to do so with distutils. My current way to handle executable scripts is to have a run() function in the myexecutable.py module, and then to have a very simple myexecutable script with the following content: #!/usr/bin/python from mypackage import myexecutable myexecutable.run() And then register this script using distutils'"scripts" keyword argument. This has the advantage that I can also create a very simple .bat file for windows users without code duplication. -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From groleo at gmail.com Tue Feb 22 03:12:49 2005 From: groleo at gmail.com (Groleo Marius) Date: Tue, 22 Feb 2005 10:12:49 +0200 Subject: Execute a list Message-ID: Hi. How can i execute a string in python? For example if I have the variable s, defined below s = '"print "hello"' How can I execute the code that "s" keeps inside, considering that the code is correct? From erikbethke at gmail.com Wed Feb 9 09:31:33 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 9 Feb 2005 06:31:33 -0800 Subject: Trouble with the encoding of os.getcwd() in Korean Windows In-Reply-To: <1107959130.925848.91910@l41g2000cwc.googlegroups.com> References: <1107953764.478501.176650@c13g2000cwb.googlegroups.com> <1107956992.350460.12720@f14g2000cwb.googlegroups.com> <1107958914.583017.79190@l41g2000cwc.googlegroups.com> <1107959130.925848.91910@l41g2000cwc.googlegroups.com> Message-ID: <1107959493.948056.211700@c13g2000cwb.googlegroups.com> Wow, even more information. When I set my default browser to IE, it launches fine... so it is something about FireFox being more picky than IE... Where would I hunt down this sort of problem? Sounds rare, should I contact Mozilla, or can you guys spot something silly I am doing? Thank you, -Erik From exogen at gmail.com Wed Feb 16 17:15:42 2005 From: exogen at gmail.com (Brian Beck) Date: Wed, 16 Feb 2005 17:15:42 -0500 Subject: Getting milliseconds in Python In-Reply-To: References: <1108565135.167562.196830@z14g2000cwz.googlegroups.com><37h5epF5ck38lU2@individual.net><1108571009.698970.152020@z14g2000cwz.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Brian Beck wrote: > > >>That IS what you want. >> >>seconds * 100 = milliseconds > > > are you sure you know what a millisecond is? > > (duck) Touch?. But it was a typo. -- Brian Beck Adventurer of the First Order From calvin at ironfroggy.com Mon Feb 28 14:28:00 2005 From: calvin at ironfroggy.com (Calvin Spealman) Date: Mon, 28 Feb 2005 19:28:00 +0000 Subject: Scoping issue with import References: <200502281556.39680.jstroud@mbi.ucla.edu> Message-ID: <2119925.1gXpuWuGCO@ironfroggy.com> Each module is only 'aware' of the built-ins and the modules it itself imports. So, all you need to do is add this line to my_imported_mod: from my_main_mod import myfun This is a fully intentional feature. Modules stand on their own. James Stroud wrote: > Say I have a module, we'll call it "my_imported_mod". It contains a > function in it that calls another function, "myfun". The "myfun" function > is in the module "my_main_mod", that imports "my_imported_mod". > > The code of "my_main_mod" might look like this: > ============== > from my_imported_mod import * > > def myfun(): > print "stuff" > ============== > > the code of "my_imported_mod" might look like this: > ============== > def somefun(): > myfun() > ============== > > When trying to execute the function somefun(), I get a > NameError: global name 'myfun' is not defined > > How to rectify this with minimal code change? How to let imported modules > know about the namespace they are getting imported into? I do not want to > restructure my code right now. > > Thanks in advance for help. > > James -- From fredrik at pythonware.com Sun Feb 20 07:09:47 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Feb 2005 13:09:47 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: <42172136$0$27576$9b622d9e@news.freenet.de> Message-ID: Ilias Lazaridis wrote: >>>Should a professional developer take python serious? >> >> yes. > > Should I take answers serious? yes. > Answer from people which do not respect coherence of writings? coherence of writings? From martin at v.loewis.de Sat Feb 19 06:21:26 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 19 Feb 2005 12:21:26 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: <42172136$0$27576$9b622d9e@news.freenet.de> Ilias Lazaridis wrote: > My questions: It appears that nobody has answered the questions, yet. > a) Why does the Python Foundation not provide additionally a binary > version, compiled with MinGW or another open-source compiler? We don't have the resources to do that. > b) Why does the Python Foundation not ensure, that the python > source-code is directly compilable with MinGW? In the past, we did not do that because we did not know how to do it. With Python 2.4.1, we now had a contribution that should allow direct compilation of extensions using MingW. > c) Why are the following efforts not _directly_ included in the python > source code base? > > http://jove.prohosting.com/iwave/ipython/pyMinGW.html I believe this was because it was never contributed to Python. > d) Is it really neccessary that I dive into such adventures, to be able > to do the most natural thing like: "developing python extensions with > MinGW"? > > http://starship.python.net/crew/kernr/mingw32/Notes.html No. These instructions are outdated. > e) Is there any official statement available regarding the msvcr71.dll > and other MS licensing issues? > > [see several threads "[Python-Dev] Is msvcr71.dll re-redistributable?"] > > http://mail.python.org/pipermail/python-dev/2005-February/thread.html No, there isn't. > f) Are there any official (Python Foundation) statements / rationales > available, which explain why the MinGW compiler is unsupported, although > parts of the community obviously like to use it? > > http://groups-beta.google.com/group/comp.lang.python/msg/dc3474e6c8053336 The official statement is that the MingW compiler is supported, indeed. Regards, Martin From http Thu Feb 3 23:42:26 2005 From: http (Paul Rubin) Date: 03 Feb 2005 20:42:26 -0800 Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xis59qgaz.fsf@ruckus.brouhaha.com> Message-ID: <7xvf99ndfx.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > It's more than a bit unfair to compare Wikipedia with Ebay or > Google. Even though Wikipedia may be running on high-performance > hardware, it's unlikely that they have anything like the underlying > network structure (replication, connection speed, etc), total number > of cpus or monetary resources to throw at the problem that both Ebay > and Google have. I suspect money trumps LAMP every time. I certainly agree about the money and hardware resource comparison, which is why I thought the comparison with 1960's mainframes was possibly more interesting. You could not get anywhere near the performance of today's servers back then, no matter how much money you spent. Re connectivity, I wonder what kind of network speed is available to sites like Ebay that's not available to Jane Webmaster with a colo rack at some random big ISP. Also, you and Tim Danieliuk both mentioned caching in the network (e.g. Akamai). I'd be interested to know exactly how that works and how much difference it makes. But the problems I'm thinking of are really obviously with the server itself. This is clear when you try to load a page and your browser immediately get the static text on the page, followed by a pause while the server waits for the dynamic stuff to come back from the database. Serving a Slashdotting-level load of pure static pages on a small box with Apache isn't too terrible ("Slashdotting" = the spike in hits that a web site gets when Slashdot's front page links to it). Doing that with dynamic pages seems to be much harder. Something is just bugging me about this. SQL servers provide a lot of capability (ACID for complicated queries and transactions, etc). that most web sites don't really need. They pay the price in performance anyway. > We also know Google has thousands of CPUs (I heard 5,000 at one point and > that was a couple years ago). It's at least 100,000 and probably several times that ;-). I've heard every that search query does billions of cpu operations and crunches through 100's of megabytes of data (search on "apple banana" and there are hundreds of millions of pages with each word, so two lists of that size must be intersected). 100,000 was the published number of servers several years ago, and there were reasons to believe that they were purposely understating the real number. From steve at holdenweb.com Wed Feb 2 18:02:39 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 02 Feb 2005 18:02:39 -0500 Subject: Getting a module's byte code, how? In-Reply-To: <42015854$0$28986$e4fe514c@news.xs4all.nl> References: <42014e25$0$28975$e4fe514c@news.xs4all.nl> <42015854$0$28986$e4fe514c@news.xs4all.nl> Message-ID: <42015C0F.7040803@holdenweb.com> Irmen de Jong wrote: > Steve Holden wrote: > >> Having said which, if the module was loaded from a .pyc file then the >> bytecode is available from that - take everything but the first eight >> bytes and use marshal.loads() to turn it back into a code object: > > > Yup. As I explained in the other message, this is basically > what I'm doing at the moment (with a few twists; it reads the .py > file if no .pyc is available). > But I also want the bytecode of modules that don't have a .pyc file, > possibly because they have already been 'dynamically' loaded from > another bytecode string ;-) > Aah, right, I suspect in these cases (which *are* pretty far from the ordinary run of things) you'd sometimes be up the creek without a paddle. > Now, I could ofcourse store the bytecode string that I started > with *inside* the module itself, in a special attribute or so. > This just occurred to me and I think it's a possible solution. > But the bytecodes must be stored by Python itself somewhere > already... because Python is able to execute my module... right? Not necessarily. I've just been playing with importing modules from a database. Here's the relevant extract from my load_module() function: code, package, path = row # ... from the database code = marshal.loads(code) module = DBmodule(modname) # subclass of moduleType sys.modules[modname] = module module.__name__ = modname module.__file__ = path # "db:%s" % modname module.__loader__ = dbimporter if package: module.__path__ = ["*db*"] exec code in module.__dict__ #print modname, "loaded:", module, "pkg:", package return module Note well that the module is essentially imported by executing its bytecode in the context of the module's directory. From that point on the module doesn't need access to its code - all its functions and classes have been created, and the functions and methods reachable from the module's __dict__ now have appropriate snippets of the byte code as their own code objects. > I want them! :-) > Well I'm afraid there's no guarantee that they haven't already been garbage collected, and stamping your foot isn't going to do any good :-) >> Note that the ugly details *might* change, and that byte codes are >> version-dependent. > > > I know, but this fact was not yet mentioned in the Pyro manual. > Thanks for reminding me, I'll add it. > > --Irmen A pleasure. Thanks for Pyro! (and thanks for reminding me indirectly that I need to guard that execution of hte module's code against exceptions). regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.python.org/pycon/2005/ Steve Holden http://www.holdenweb.com/ From sjmachin at lexicon.net Mon Feb 28 16:12:20 2005 From: sjmachin at lexicon.net (John Machin) Date: 28 Feb 2005 13:12:20 -0800 Subject: cannot open file in write mode, no such file or directory In-Reply-To: <1109620212.056771.77930@o13g2000cwo.googlegroups.com> References: <1109618906.347448.218700@o13g2000cwo.googlegroups.com> <1109619707.033450.227120@f14g2000cwb.googlegroups.com> <1109620212.056771.77930@o13g2000cwo.googlegroups.com> Message-ID: <1109625140.228067.156390@o13g2000cwo.googlegroups.com> haynesc at gmail.com wrote: > Kartic wrote: > > > I'm having a problem where when trying to open a file in write > mode, > > I > > > get an IOError stating no such file or directory. I'm calling an > > > external program which takes an input file and produces an output > > file > > > repeatedly, simulating the input file separately for each > replicate. > > > The error occurs when trying to open the input file to write out > the > > > new data. The problem is difficult to reproduce since it only > shows > > up > > > once every few thousand replicates. I've tried using both > os.system > > > > I am afraid you need to give more information that just IOError, > > calling an external program. > > > > Please post the exact message including the input filename at the > time > > the program went down. If you don't print the filename, please modify > > your program to do so. > > > > A shot in the dark solution to your problem might be that you are > > dynamically generating a filename and that filename probably > contains > > characters not allowed by the local file system OR you generate a > path > > that does not exist. For open() to work with the 'w' flag, the path > > where the file you say should be created should exist. > > > > Thanks, > > -Kartic > > Sorry, here is the exact error: > > Traceback (most recent call last): > File "hapSim.py", line 415, in ? > run(REPLICATES, dsSelection, permuteStatus, sigThreshold > File "hapSim.py", line 354, in run > createInput(dt) > File "hapSim.py", line 178, in createInput > inF = open(IN_FNAME, "w") > IOError: [Errno 2] No such file or directory: 'prog.input' > > I am using the same file name repeatedly, it works fine the first few > thousand times, but eventually gives this error. 1. Exactly how many is "few thousand"? Is it the same number each time? Does the problem still happen if you don't run the external program, but just create the input file a few thousand times? 2. Which version of Windows are you using, and what type of filesystem? When it dies, how many files exist in the directory where you are trying to create "prog.input"? Reason for asking: I vaguely recall problems with FAT-type filesystems where there was a rather low limit on the number of files that could be recorded in a directory, PLUS a rather misleading "errno" being returned when one hit the limit. From john_sips_teaz at yahooz.com Tue Feb 8 11:46:36 2005 From: john_sips_teaz at yahooz.com (John M. Gabriele) Date: Tue, 08 Feb 2005 11:46:36 -0500 Subject: Is Python as capable as Perl for sysadmin work? In-Reply-To: <87r7jr9gxv.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> References: <87r7jr9gxv.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <110hr73rl7g8ec@corp.supernews.com> Nick Vargish wrote: > "John M. Gabriele" writes: > > >>At some point during some dingy job in the back boiler room >>of Unix, would you find yourself saying, "geez, I'd wish I >>started this with Perl -- Python just isn't cutting it." ? > > > Sometimes I have to write a quick script in Perl because Python isn't > ubiquitous enough around here, and I often find myself thinking I > the opposite... "Perl just isn't cutting it." > > And I spent several years putting food on the table with Perl, so it's > not like I'm a noob with Perl. > > Nick > Thanks Nick (and everyone else) for the replies. Much appreciated. -- --- remove zees if replying via email --- From drobinow at gmail.com Thu Feb 24 08:13:41 2005 From: drobinow at gmail.com (drobinow at gmail.com) Date: 24 Feb 2005 05:13:41 -0800 Subject: PyEphem on Win32 -- 2nd try In-Reply-To: References: Message-ID: <1109250821.444086.99070@g14g2000cwa.googlegroups.com> Flory at fdu.edu wrote: > Has anyone run the PyEphem ephemeris application under WinXP? > http://rhodesmill.org/brandon/projects/pyephem.html > I have compiled it with Visual Studio 6 and it crashes Python with a > simple > > >>> import ephem > >>> ephem.date('1994/7/16') > > Identical code works fine under Linux. I suspect that the problem has > to do with a parser built into the c shell for the c code that the > app wraps around. However, I am not good enough at c to spot the > error. I had the same problem with Python 2.4. Dates appear to need a trailing space. ephem.date('1994/7/16 ') works for me. I believe the following code in ephem.c is responsible: if (conversions == -1 || !conversions || (conversions == 1 && s[dchars] != '\0') || (conversions == 2 && s[tchars] != '\0')) { PyErr_SetString(PyExc_ValueError, "your date string does not seem to have " "year/month/day followed optionally by " "hours:minutes:seconds"); This may be a VC versus gcc issue. It would be interesting to see if a Mingw compile would help here. From ilias at lazaridis.com Mon Feb 14 05:58:10 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Mon, 14 Feb 2005 12:58:10 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: Robert Kern wrote: > Ilias Lazaridis wrote: >> David Fraser wrote: >>> Ilias Lazaridis wrote: [...] >>I do not "just complain". >> >> I've spend already hours with writing down the questionaire [which you >> have successfully ignored]. > > Why don't you spend hours writing code and submitting working patches, > instead? That's what I did years ago in the original effort to get mingw > to compile Python extensions (one of the, woefully out-dated, web-pages > you cite is mine. I have now edited it to clarify the situation so > others do not come away from it as you did). "This page is extremely out-of-date. Not much applies anymore. This page only remains because too many people still point to it. PExports may also still be useful to some people; I don't know. I do not use this platform any longer." http://starship.python.net/crew/kernr/mingw32/Notes.html very gentle. up-to-date information is important, especially to avoid confusing newcomers. [you see: even if I just complain, one positive change has already happen] > Just writing "questionnaires" *is* actually "just complaining." of course not. > The answer to most of your questions is, "Because no one has yet > volunteered their time and effort to get the job done." this answer do not fit in most questions. please review them again. > If this is important to you, you need to step up yourself and get it > done and not expect other people to volunteer their unpaid time to > satisfy your whims. > > The open source Python community is driven by volunteerism, not a sense > of entitlement. If this does not appeal to you, then perhaps the Python > community is not the right one for you. I ask some questions and suggest some things. Voluntarlily and without beeing paid. There are many commercial systems around python. So please stop this volunteerism-stuff. - If you like to help me and other newcomers, please give me simple some answers on the initial questions. . -- http://lazaridis.com From jzgoda at gazeta.usun.pl Wed Feb 23 15:06:52 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 23 Feb 2005 21:06:52 +0100 Subject: Problem with minidom and special chars in HTML In-Reply-To: <421c541c$1@news.uni-klu.ac.at> References: <421b5b8c$1@news.uni-klu.ac.at> <421c541c$1@news.uni-klu.ac.at> Message-ID: Horst Gutmann napisa?(a): >> Don't use minidom or convert HTML4 to XHTML and change declaration of >> doctype. >> > This was just a bad example :-) I get the same problem with XHTML in the > doctype. The funny thing here IMO is, that the special chars are simply > removed. No warning, no nothing :-( As Fredrik pointed out, it's minidom that cann't fetch DTD from remote location. Download this DTD file to your local machine (it lies at exactly this URI), try changing PUBLIC identifier to SYSTEM and give local path to this file. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From reinhold-birkenfeld-nospam at wolke7.net Tue Feb 8 15:12:39 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 08 Feb 2005 21:12:39 +0100 Subject: string issue In-Reply-To: <1grmsu7.voqhco123pqaoN%aleaxit@yahoo.com> References: <36QMd.103084$Jk5.36127@lakeread01> <1grl717.1o4ofg7arp8c2N%aleaxit@yahoo.com> <36plr5F551pg8U1@individual.net> <1grmr97.9o27yo1xzwzd7N%aleaxit@yahoo.com> <36pv1dF55bt9jU1@individual.net> <1grmsu7.voqhco123pqaoN%aleaxit@yahoo.com> Message-ID: <36skpnF53c5feU1@individual.net> Alex Martelli wrote: > Reinhold Birkenfeld wrote: > >> Alex Martelli wrote: >> >> > So, *WHAT ON EARTH* could possibly >> > make this weird 'x[:]' form preferable to 'x*1'?! It's MUCH more >> > obvious that the second one returns an independent, separate object >> > initially equal to x >> >> .>> x = 2 >> .>> y = x*1 >> .>> x is y >> True >> .>> >> >> just-kidding-ly yours, > > You're just snipping a crucial side-observation which I had put in > exactly to avert such irrelevant diversions: > >> whenever it >> matters -- i.e., whenever x is mutable. > > Immutable types are allowed to collapse any two equal but "distinct" > objects into one identity -- that's always the case, I acknowledged that > in my sentence which I just quoted and which you had failed to quote > again, and I don't see what's funny in this procedure and the time it's > wasting, for me and for every reader of this group, now and in the > future from archives. Well, I overread your side-observation (can happen if you don't have too much time and are not accustomed to flying over English text) and, though I sensed that it was bad, posted my little joke. > I'm sure that by selectively quoting just some of your words and > artfully omitting others I could ``make" you say, not just slightly > imprecise things, but utter and total idiocies. So? What's the point > of this "kidding"? Next time, why don't you just omit, for example, a > "not", when you quote me, so as to make it appear that I was saying > exactly the reverse of what I was obviously saying? Well, snipping single paragraphs is different from snipping words out of them. Sorry. Didn't mean to drive you insane -- your posts are of use, so clpy (include me) need you in the future. > I guess it must be time for me to go away from this group again, if my > time on it is to me spent repeating over and over all sorts of asides > which people "just kidding" carefully avoid quoting from my posts, > apparently in order to make believe they caught me in anything less than > perfect accuracy. Cheez -- I HAVE been guilty of less than perfect > accuracy in the past (even of outright errors), but not THIS time (if > one has the common decency to look at ALL the words I posted, rather > than a careful selection thereof), so I completely fail to see how you > thought this "kidding" could be fun. This is the hot Italian temper, I suppose ;) Of course you were right, and I'm glad to see your posts of today. > OK, I'm off. Have a nice life. Thanks, I'll do. Reinhold From fredrik at pythonware.com Fri Feb 4 02:40:18 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 4 Feb 2005 08:40:18 +0100 Subject: [EVALUATION] - E01: The Java Failure - May Python Helps? References: Message-ID: Markus Wankus wrote: > Google his name - he has been banned from Netbeans and Eclipse (and Hibernate, and others...) for > good reason. Can you imagine how much of a Troll you need to be to *actually* get "banned" from > the newsgroups of open source projects such as those? have Pythoneers ever "banned" anyone from a public forum? it's not like we haven't seen trolls and crackpots before, you know. From "ben-fuzzybear" at yahoo.com Wed Feb 23 15:25:29 2005 From: "ben-fuzzybear" at yahoo.com ("ben-fuzzybear" at yahoo.com) Date: Wed, 23 Feb 2005 12:25:29 -0800 (PST) Subject: Yahoo! Auto Response Message-ID: <20050223202531.164141E4005@bag.python.org> Hi - This is the "vacation" program; I'm working for my owner, Ben. The account to which you have sent your mail is going to be discontinued at at the end of July (Yahoo's mail service has deteriorated well past "abysmal" into "nightmarishly bad", and the trend shows no sign of stopping). Please update your information for Ben; his new email address is at the "callahans.org" domain under the username of "ben" (it is not shown as a complete address in order to foil stupid spambots; use it as "username at domain".) Sorry about any inconvenience, and have a nice day. -------------------- Original Message: X-YahooFilteredBulk: 61.1.74.98 Authentication-Results: mta106.mail.mud.yahoo.com from=python.org; domainkeys=neutral (no sig) X-Originating-IP: [61.1.74.98] Return-Path: Received: from 61.1.74.98 (EHLO yahoo.com) (61.1.74.98) by mta106.mail.mud.yahoo.com with SMTP; Wed, 23 Feb 2005 12:25:29 -0800 From: python-list at python.org To: ben-fuzzybear at yahoo.com Subject: Re: Message Error Date: Thu, 24 Feb 2005 01:55:13 +0530 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_0016----=_NextPart_000_0016" X-Priority: 3 X-MSMail-Priority: Normal This is a multi-part message in MIME format. ------=_NextPart_000_0016----=_NextPart_000_0016 Content-Type: text/plain; charset="Windows-1252" Content-Transfer-Encoding: 7bit For further details see the attachment. +++ Attachment: No Virus found +++ Kaspersky AntiVi _________________________________________________________ DO YOU YAHOO!? Get your free @yahoo.com address at http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Thu Feb 24 21:34:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 25 Feb 2005 02:34:42 +0000 (UTC) Subject: Flushing print() References: Message-ID: gf gf wrote: : Is there any way to make Python's print() flush : automatically, similar to...mmm...that other : language's $|=1 ? Hello gf gf, Yes; you can use the '-u' command line option to Python, which will turn off stdout/stderr buffering. : If not, how can I flush it manually? sys.stdout.flush() didn't : seem to work. Hmmmm, that's odd. sys.stdout.flush() should do it. How are you testing that stdout isn't flushing as you expect? Best of wishes to you! From sjmachin at lexicon.net Fri Feb 18 18:21:10 2005 From: sjmachin at lexicon.net (John Machin) Date: 18 Feb 2005 15:21:10 -0800 Subject: exercise: partition a list by equivalence In-Reply-To: References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> Message-ID: <1108768870.455974.244590@c13g2000cwb.googlegroups.com> John Lenton wrote: > On Thu, Feb 17, 2005 at 03:46:20PM -0800, Xah Lee wrote: > > here's another interesting algorithmic exercise, again from part of a > > larger program in the previous series. > > > > Here's the original Perl documentation: > > > > =pod > > > > merge($pairings) takes a list of pairs, each pair indicates the > > sameness > > of the two indexes. Returns a partitioned list of same indexes. > > > > For example, if the input is > > merge( [ [1,2], [2,4], [5,6] ] ); > > > > that means 1 and 2 are the same. 2 and 4 are the same. Therefore > > 1==2==4. The result returned is > > > > [[4,2,1],[6,5]]; > > > > (ordering of the returned list and sublists are not specified.) > > > > =cut > > in Python: > > def merge(pairings): > rev = {} > res = [] > for pairing in pairings: > first, second = pairing > has_first = first in rev > has_second = second in rev Not robust in the face of input like: [[1,1]] or [[1,2], [1,2]] or [[1,2], [2,1]] or [[1,2], [2,3], [3,1]] needs "if first == second: continue" here > if has_first and has_second: needs "if rev[first] == rev[second]: continue" here > rev[first].extend(rev[second]) > rev[second][:] = [] > rev[second] = rev[first] > elif has_first: > rev[first].append(second) > rev[second] = rev[first] > elif has_second: > rev[second].append(first) > rev[first] = rev[second] > else: > copy = [first, second] > res.append(copy) My reaction to the "magic" by which res grows was "omigod that's the most horrible thing I've seen for quite a while" but there was worse to come :-) > rev[first] = rev[second] = copy > return filter(None, res) > > and in Perl: > [snip] > > Both versions are (IMHO) pretty clear (when the docstring/pod is > included), and O(n) because dict/hash lookup and list > appending/pushing is O(1) in both languages. Both versions can > probably be tweaked for speed quite a bit, but I don't *think* there's > a better-than-O(n) algorithm for this. List appending is O(1) only in the amortised sense. Extending is not O(1) in any sense. Neither is the list comparison that is necessary for robustness (using your data structure, that is). You don't need to think. This problem has been extensively picked over by folk who are a lot smarter than us, starting from 30 years ago. Google for "disjoint set" and "union-find". One gets the impression that the best possible algorithm would be slightly *worse* than O(n). > > Note that the Python version assumes that the pairs' elements are > hashable; your example used numbers, so I thought it was pretty safe > assumption. The Perl version has no such restriction. In the real world, the objects under comparison (images, fingerprints, customer records, etc) may not themselves be hashable and comparison for equality may be expensive but a unique identifier would be assigned to each object and that ID would of course be cheaply hashable and comparable. From ray at rgibbon.freeserve.co.uk Thu Feb 10 00:38:54 2005 From: ray at rgibbon.freeserve.co.uk (Ray Gibbon) Date: Thu, 10 Feb 2005 05:38:54 -0000 Subject: Testing conditions. Message-ID: Testing conditions. Common scenario. Old programmer, new to Python, love it, but still hankering after some of my old ways. Of all of it's 'new to me' features, I appear to be enjoying 'no declarations' and mixing types with abandon. In particular I find myself writing functions which return whatever might be useful in whatever type seems appropriate, I'm really attracted to this, it works like magic. BUT, every time the result of a fuction hits a 'while' or 'if' the magic stops. If I want the result and I want to test it I have to do an assignment and test separately. It grates every time I come across this, and it seems obvious what I'm hankering for. I *know* this has been gone over and over and over... This is NOT another request for statements to be accepted as expressions for two reasons:- 1. I've seen enough arguments on the subject where I've found myself firmly on the anti change side. 2. I now realise that it might scratch the itch, but it would not cure it. e.g. 1 | while new_data = get_more_data(source): | process_data(new_data) is obviously the sort of thing I'm missing, but it is not a general solution because :- e.g. 2 | while new_data, environment = get_more_data(source): | process_data(new_data, environment) is something I'm equally likely to want to do, but I can't express it's meaning. Before I resign myself to the inevitable, 'that's the way it is - get used to it', I'd just like to scratch it once. But, before I try walking on very thin ice, I want to ask whether there are expectations of some future changes which address these issues? I note PEP 3000 is silent on this matter, and PEP 315, though related, is not relevant. Ray. From fredrik at pythonware.com Thu Feb 17 02:45:00 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Feb 2005 08:45:00 +0100 Subject: Font size References: <42126822@news.comindico.com.au><42129ea1@news.comindico.com.au> <4213e033$1@news.comindico.com.au> Message-ID: "Adam" wrote: > So we came up with the idea of using a random number generator to > generate numbers from 0 to 36 and display them in large figures on my > laptop. This is for the benefit of those people who are hard of hearing. > They like to see what is happening. here's one way to do this: from Tkinter import * from random import randint from time import sleep def update(event=None): for i in range(10): label.config(text=str(randint(0,36))) label.update() sleep(0.05) # create a maximized window root = Tk() root.wm_state("zoomed") root.title("my roulette wheel") # 80% of the screen height height = int(root.winfo_screenheight() * 0.8) # create label (use negative font size for size in pixels) label = Label(root, font="Arial " + str(-height), bg="gold") label.pack(fill=BOTH, expand=1) # click anywhere in window to pick a new number root.bind("", update) update() # display first number mainloop() (tweak as necessary) From caleb1 at telkomsa.net Sun Feb 6 23:10:21 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Sun, 06 Feb 2005 23:10:21 -0500 Subject: Multiple constructors References: <6SjNd.38337$K7.21639@fe2.news.blueyonder.co.uk> Message-ID: Hi Philip > C++ to Python is a steep 'unlearning' curve... That's worthy of QOTW. I decided not to reply to this thread earlier, but you just convinced me otherwise :) I work in Delphi a lot, which is in a lot of respects very similar to C. I have come to the conclusion that function overloading was introduced to allow the same calling syntax and even functionality to be applied to different *types*. This is a consequence of the fact that in Delphi and C, for example, typing is static. In a dynamic language like python, however, overloading isn't necessary. Not only can the *type* of a function argument be determined at run-time, the *number* of arguments can as well. Though Alex indicated differently earlier, I intend to always use an "if" statment inside one constructor to initialise any class in the situation where the arguments may be different in number and type. I don't have the years of experience that Alex has, however, so I may end up regretting it but right now, it seems to me to be the clearest approach in this situation. thx Caleb From newsgroups at jhrothjr.com Wed Feb 23 13:48:54 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 23 Feb 2005 12:48:54 -0600 Subject: PyEphem on Win32 -- 2nd try References: Message-ID: <111pk2f31bcln61@news.supernews.com> A quick look at the site, and following the link to the XEphem site reveals that the Windows port of XEphem uses Cygwin. AFAIK, that's not compatible with the usual CPython implementation. Again, AFAIK, you'll either have to use a Python port compiled under Cygwin, or you'll have to find a Windows port compiled with VS 6 or higher. Someone who knows more about those issues will have to take it from here. John Roth wrote in message news:mailman.2972.1109178865.22381.python-list at python.org... > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > A second request for help... > > Has anyone run the PyEphem ephemeris application under WinXP? > http://rhodesmill.org/brandon/projects/pyephem.html > I have compiled it with Visual Studio 6 and it crashes Python with a > simple > >>>> import ephem >>>> ephem.date('1994/7/16') > > Identical code works fine under Linux. I suspect that the problem has > to do with a parser built into the c shell for the c code that the > app wraps around. However, I am not good enough at c to spot the > error. > > I am running ActivePython 2.3.5 Build 236 on a WinXP SP2 system with > Visual Studio 6 patched to sp6. > > I would appreciate either help from a c guru who knows how to wrap > python around c or a pointer to another list where experts might > reside. > - ------------------------------------------- > Cheers, David Flory > > -----BEGIN PGP SIGNATURE----- > Version: PGP 8.1 > > iQA/AwUBQhy551e2/rcN3lp8EQIu2gCfRyDmSCtiP4uB2qKMtIvjcOOsNUkAn1FD > rir+BKqfDqZ0P+lKcwfgdQPu > =5+at > -----END PGP SIGNATURE----- > From eurleif at ecritters.biz Thu Feb 17 07:46:00 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 17 Feb 2005 07:46:00 -0500 Subject: Why doesn't join() call str() on its arguments? In-Reply-To: <37hippF4gcimiU1@individual.net> References: <37hippF4gcimiU1@individual.net> Message-ID: <37jht7F5emcioU1@individual.net> Leo Breebaart wrote: > What I can't find an explanation for is why str.join() doesn't > automatically call str() on its arguments I don't really like that idea for the reasons others have stated. But a related and (IMHO) more Pythonic idea would be to allow arbitrary objects to be str.join()ed if they use __radd__ to allow concatenation with strings. This would be consistent with how the + operator behaves: Python 2.4 (#2, Jan 8 2005, 20:18:03) [GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(object): ... def __radd__(self, other): ... if isinstance(other, basestring): ... return other + str(self) ... def __str__(self): ... return 'Foo()' ... >>> 'foo:' + Foo() 'foo:Foo()' >>> ''.join(['foo', Foo()]) Traceback (most recent call last): File "", line 1, in ? TypeError: sequence item 1: expected string, Foo found From noreply at python.org Tue Feb 22 07:48:38 2005 From: noreply at python.org (The Post Office) Date: Tue, 22 Feb 2005 15:48:38 +0300 Subject: Delivery reports about your e-mail Message-ID: <20050222105637.5921C1E4003@bag.python.org> Your message was undeliverable due to the following reason: Your message was not delivered because the destination server was not reachable within the allowed queue period. The amount of time a message is queued before it is returned depends on local configura- tion parameters. Most likely there is a network problem that prevented delivery, but it is also possible that the computer is turned off, or does not have a mail system running right now. Your message was not delivered within 8 days: Host 138.95.127.173 is not responding. The following recipients could not receive this message: Please reply to postmaster at python.org if you feel this message to be in error. From deetsNOSPAM at web.de Sun Feb 20 16:30:50 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 20 Feb 2005 22:30:50 +0100 Subject: Moving to Python from PHP - 3 questions References: Message-ID: > Thank you. My impression of Zope in the past has been that it does what > I need, along with 10,000 other things I don't (built in WebDAV > server?!), but clearly I owe it another chance. I've been initially The apache has a built in webdav server too - is that a reason _not_ to use it? If you don't want a feature, don't use it. You can turn them off, btw. But what you might not be aware of is that zope does not store its templates, scripts and files in general in the filesystem as php does, but as objects in the zodb database. So webdav and ftp are other views to that objects that allow you to load and save these files using "normal" editors and tools, not only the web-interface of zope. The advantage of this approach is that versioning of content - regardless of it's type - is built-in. Can be a life-saver sometimes :) > attracted to mod_python because of its raw simplicity and its apparent > similarity to mod_php and mod_perl, which I am familiar with. It certainly is the most simple way to create dynamic content. But there is a big difference between python and php: php started as a web-developers tool, and it's features are a direct consequence of that. python oth is a general purpose programming language - it is certainly suited for web development, but not limited to. There are people who also want to use php as general purpose programming language - but nevertheless, its design has been influenced by its main purpose. So you e.g. get session state handling "for free" - as more or less _all_ web-apps today need them. -- Regards, Diez B. Roggisch From jalemkul at vt.edu Tue Feb 1 17:51:14 2005 From: jalemkul at vt.edu (Justin Lemkul) Date: Tue, 1 Feb 2005 17:51:14 -0500 Subject: Atlas and NumPy Problems Message-ID: <421E79FA@zathras> Hello all, I am hoping someone out there will be able to help me. I am trying to install a program that utilizes NumPy. In installing NumPy, I realized that I was lacking Atlas. I ran into the following problems installing Atlas and NumPy, as I realized that NumPy could be installed using the Mac OSX veclib already built in. If anyone has any ideas on how to fix either of these, I would be most grateful. I am fairly new to Python (I've been learning it myself), so I apologize if these questions are a bit foolish. I've been fighting these problems for days, and I'm out of ideas. I am running OS X v10.3, gcc v3.3, Python v2.3, ScientificPython v2.4.3, and am attempting to install NumPy 23.7 Thank you! -Justin ATLAS install problem: n file included from /Users/jalemkul/Desktop/ATLAS/include/ atlas_prefetch.h:8, from ../ATL_col2blk.c:33:/Users/jalemkul/Desktop/ATLAS/ include/atlas_altivec.h:6:27: altivec.h: No such file or directory../ATL_col2blk.c: In function `ATL_dcol2blk_aX':../ATL_col2blk.c:79: error: `vector' undeclared (first use in this function)../ATL_col2blk.c:79: error: (Each undeclared identifier is reported only once../ ATL_col2blk.c:79: error: for each function it appears in.)../ATL_col2blk.c:79: error: parse error before "float"../ATL_col2blk.c:80: error: parse error before "float"make[7]: *** [ATL_dcol2blk_aX.o] Error 1make[7]: *** Waiting for unfinished jobs....make[6]: *** [dlib] Error 2make[5]: *** [dmmlib] Error 2make[4]: *** [res/atlas_cacheedge.h] Error2make[3]: *** [dinstall] Error 2make[2]: *** [MMinstall] Error 2 STAGE2-1-2: CacheEdge DETECTIONmake -f Makefile INSTALL_LOG/atlas_cacheedge.h pre=d 2>&1 | ./xatlas_tee INSTALL_LOG/dMMCACHEEDGE.LOGcd /Users/jalemkul/Desktop/ATLAS/tune/blas/gemm/ OSX_UNKNOWNAltiVec_2 ; make res/atlas_cacheedge.h pre=dmake dRunFindCEcd /Users/ jalemkul/Desktop/ATLAS/src/blas/gemm/OSX_UNKNOWNAltiVec_2 ; make dlibmake auxillib dcleanuplib dusergemmcd /Users/jalemkul/Desktop/ATLAS/src/auxil/ OSX_UNKNOWNAltiVec_2 ; make libmake[7]: Nothing to be done for `lib'.cd KERNEL ; make -f dMakefile dlibmake[7]: Nothing to be done for `dlib'.cd /Users/jalemkul/Desktop/ATLAS/ src/blas/gemm/OSX_UNKNOWNAltiVec_2 ; make dusermmmake[7]: `dusermm' is up to date.make -j 2 dlib.grd/usr/bin//gcc -o ATL_dcol2blk_aX.o -c -DL2SIZE=4194304 -I/Users/ jalemkul/Desktop/ATLAS/include -I/Users/jalemkul/Desktop/ATLAS/include/ OSX_UNKNOWNAltiVec_2 -I/Users/jalemkul/Desktop/ATLAS/include/contrib -DATL_OS_OSX -DATL_AltiVec -DATL_AVgcc -DATL_AS_OSX_PPC -DATL_NCPU=2 -O -maltivec -mabi=altivec -DDREAL -DALPHAX ../ATL_col2blk.c /usr/bin//gcc -o ATL_drow2blkT_aX.o -c -DL2SIZE=4194304 -I/Users/jalemkul/Desktop/ ATLAS/include -I/Users/jalemkul/Desktop/ATLAS/include/OSX_UNKNOWNAltiVec_2 -I/Users/ jalemkul/Desktop/ATLAS/include/contrib -DATL_OS_OSX -DATL_AltiVec -DATL_AVgcc -DATL_AS_OSX_PPC -DATL_NCPU=2 -O -maltivec -mabi=altivec -DDREAL -DALPHAX ../ ATL_row2blkT.c In file included from /Users/jalemkul/Desktop/ATLAS/include/atlas_prefetch.h:8, from ../ATL_row2blkT.c:32: /Users/jalemkul/Desktop/ATLAS/include/atlas_altivec.h:6:27: altivec.h: No such file or directory ../ATL_row2blkT.c: In function `ATL_drow2blkT_NB_aX': ../ATL_row2blkT.c:64: error: `vector' undeclared (first use in this function) ../ATL_row2blkT.c:64: error: (Each undeclared identifier is reported only once ../ATL_row2blkT.c:64: error: for each function it appears in.) ../ATL_row2blkT.c:64: error: parse error before "float" ../ATL_row2blkT.c:65: error: parse error before "float" ../ATL_row2blkT.c:74: error: parse error before "float" ../ATL_row2blkT.c:75: error: parse error before "float" In file included from /Users/jalemkul/Desktop/ATLAS/include/atlas_prefetch.h:8, from ../ATL_col2blk.c:33: /Users/jalemkul/Desktop/ATLAS/include/atlas_altivec.h:6:27: altivec.h: No such file or directory ../ATL_col2blk.c: In function `ATL_dcol2blk_aX': ../ATL_col2blk.c:79: error: `vector' undeclared (first use in this function) make[6]: *** [ATL_drow2blkT_aX.o] Error 1 make[6]: *** Waiting for unfinished jobs.... ../ATL_col2blk.c:79: error: (Each undeclared identifier is reported only once ../ATL_col2blk.c:79: error: for each function it appears in.) ../ATL_col2blk.c:79: error: parse error before "float" ../ATL_col2blk.c:80: error: parse error before "float" make[6]: *** [ATL_dcol2blk_aX.o] Error 1 make[5]: *** [dlib] Error 2 make[4]: *** [dmmlib] Error 2 make[3]: *** [res/atlas_cacheedge.h] Error 2 make[2]: *** [/Users/jalemkul/Desktop/ATLAS/tune/blas/gemm/OSX_UNKNOWNAltiVec_2/ res/atlas_cachedge.h] Error 2 ERROR 572 DURING CACHE EDGE DETECTION!!. cd ../.. ; make error_report arch=OSX_UNKNOWNAltiVec_2 make -f Make.top error_report arch=OSX_UNKNOWNAltiVec_2 uname -a 2>&1 >> bin/OSX_UNKNOWNAltiVec_2/INSTALL_LOG/ERROR.LOG /usr/bin//gcc -v 2>&1 >> bin/OSX_UNKNOWNAltiVec_2/INSTALL_LOG/ERROR.LOG Reading specs from /usr/libexec/gcc/darwin/ppc/3.3/specs Thread model: posix gcc version 3.3 20030304 (Apple Computer, Inc. build 1495) /usr/bin//gcc -V 2>&1 >> bin/OSX_UNKNOWNAltiVec_2/INSTALL_LOG/ERROR.LOG gcc: `-V' option must have argument make[4]: [error_report] Error 1 (ignored) /usr/bin//gcc --version 2>&1 >> bin/OSX_UNKNOWNAltiVec_2/INSTALL_LOG/ERROR.LOG /usr/bin//tar cf error_OSX_UNKNOWNAltiVec_2.tar Make.OSX_UNKNOWNAltiVec_2 bin/ OSX_UNKNOWNAltiVec_2/INSTALL_LOG/* /usr/bin//gzip --best error_OSX_UNKNOWNAltiVec_2.tar mv error_OSX_UNKNOWNAltiVec_2.tar.gz error_OSX_UNKNOWNAltiVec_2.tgz Error report error_.tgz has been created in your top-level ATLAS directory. Be sure to include this file in any help request. First, make sure this error is not covered in the ATLAS errata file, http://math-atlas.sourceforge.net/errata.html All known errors, and most common mistakes/system problems are documented in this file, so it will save everyone hassle in the long run if you take the time to scope it out before sending e-mail to the help list. If this does not have the solution to your problem, and you can't figure out what went wrong, submit a support request to the ATLAS support tracker, as discussed here: http://math-atlas.sourceforge.net/faq.html#help In the above examples, should be replaced with your architecture string, such as "Linux_PIII" or "FreeBSD_21264". make[1]: *** [install] Error 255 make: *** [install] Error 2 NumPy install problem: warning: no library file corresponding to '/System/Library' found (skipping) gcc -Wl,-F. -Wl,-F. -bundle -framework Python build/temp.darwin-7.7.0-Power_Macintosh -2.3/Packages/dotblas/dotblas/_dotblas.o -L/System/Library -o build/lib.darwin-7.7.0- Power_Macintosh-2.3/_dotblas.so ld: Undefined symbols: _cblas_caxpy _cblas_cdotc_sub _cblas_cdotu_sub _cblas_cgemm _cblas_cgemv _cblas_daxpy _cblas_ddot _cblas_dgemm _cblas_dgemv _cblas_saxpy _cblas_sdot _cblas_sgemm _cblas_sgemv _cblas_zaxpy _cblas_zdotc_sub _cblas_zdotu_sub _cblas_zgemm _cblas_zgemv error: command 'gcc' failed with exit status 1 From jao at geophile.com Thu Feb 24 22:18:37 2005 From: jao at geophile.com (Jack Orenstein) Date: Thu, 24 Feb 2005 22:18:37 -0500 Subject: Threading and consuming output from processes In-Reply-To: References: <1109278779.955986.193860@z14g2000cwz.googlegroups.com> <1109283053.971905.27670@z14g2000cwz.googlegroups.com> <1109295016.597170.21350@o13g2000cwo.googlegroups.com> Message-ID: <421E990D.9070608@geophile.com> I am developing a Python program that submits a command to each node of a cluster and consumes the stdout and stderr from each. I want all the processes to run in parallel, so I start a thread for each node. There could be a lot of output from a node, so I have a thread reading each stream, for a total of three threads per node. (I could probably reduce to two threads per node by having the process thread handle stdout or stderr.) I've developed some code and have run into problems using the threading module, and have questions at various levels of detail. 1) How should I solve this problem? I'm an experienced Java programmer but new to Python, so my solution looks very Java-like (hence the use of the threading module). Any advice on the right way to approach the problem in Python would be useful. 2) How many active Python threads is it reasonable to have at one time? Our clusters have up to 50 nodes -- is 100-150 threads known to work? (I'm using Python 2.2.2 on RedHat 9.) 3) I've run into a number of problems with the threading module. My program seems to work about 90% of the time. The remaining 10%, it looks like notify or notifyAll don't wake up waiting threads; or I find some other problem that makes me wonder about the stability of the threading module. I can post details on the problems I'm seeing, but I thought it would be good to get general feedback first. (Googling doesn't turn up any signs of trouble.) Thanks. Jack Orenstein From tom at dtsam.com Wed Feb 9 10:14:13 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Wed, 9 Feb 2005 09:14:13 -0600 Subject: Performance Issues of MySQL with Python References: <1107954472.246556.258030@g14g2000cwa.googlegroups.com> Message-ID: <6dSdnTh0iusJtZffRVn-gQ@telcove.net> "sandy" wrote in message news:1107954472.246556.258030 at g14g2000cwa.googlegroups.com... > Hi All, > > I am a newbie to MySQL and Python. At the first place, I would like to > know what are the general performance issues (if any) of using MySQL > with Python. > > By performance, I wanted to know how will the speed be, what is the > memory overhead involved, etc during database specific operations > (retrieval, update, insert, etc) when MySQL is used with Python. > > Any solutions to overcome these issues (again, if any)? There are no "general performance issues" with respect to "using MySQL with Python". The use of Python as a programming front end does not impact the performance of whatever database server you might select. The choice of MySQL as your database server does not impact the effectiveness of whatever front end programming language you select. The 2 functions, database server and programming language, do not interact in ways that raise unique performance issues. You can choose each one without worrying about the other. They two quite separate design choices. Thomas Bartkus From kent37 at tds.net Fri Feb 11 08:44:19 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 11 Feb 2005 08:44:19 -0500 Subject: Is this a bug? BOM decoded with UTF8 In-Reply-To: <373p8vF57039vU1@individual.net> References: <420bc317$0$4925$9b622d9e@news.freenet.de> <373p8vF57039vU1@individual.net> Message-ID: <420cb3d6$1_2@newspeer2.tds.net> Diez B. Roggisch wrote: >>I know its easy (string.replace()) but why does UTF-16 do >>it on its own then? Is that according to Unicode standard or just >>Python convention? > > > BOM is microsoft-proprietary crap. Uh, no. BOM is part of the Unicode standard. The intent is to allow consumers of Unicode text files to disambiguate UTF-8, big-endian UTF-16 and little-endian UTF-16. See http://www.unicode.org/faq/utf_bom.html#BOM Kent From shoot at the.moon Wed Feb 9 18:30:13 2005 From: shoot at the.moon (Steve Horsley) Date: Wed, 09 Feb 2005 23:30:13 +0000 Subject: Is Python as capable as Perl for sysadmin work? In-Reply-To: References: Message-ID: Jeff Epler wrote: > If I want to beg my computer to run programs, I know > where to find Intercal with its "PLEASE" and "DO PLEASE" constructions. > Was it INTERCAL that had the COMEFROM statement instead of GOTO? I REALLY like the idea of a COMEFROM statement. I think python should have a COMEFROM statement, but since perl revels in being impenetrable, I suppose perl is likely to get it first. Shame. Steve From bvdeenen at access-four-all.nl.invalid Mon Feb 21 05:38:23 2005 From: bvdeenen at access-four-all.nl.invalid (Bart) Date: Mon, 21 Feb 2005 11:38:23 +0100 Subject: Don't understand global variables between modules Message-ID: <4219ba1f$0$162$e4fe514c@dreader14.news.xs4all.nl> Hi all I don't understand globals between multiple modules in a python program. I really don't. I've narrowed it down to the following two very simple programs a.py and b.py. When I run a.py I get the following output: inc: 2 A: 2 inc: 3 B: 3 C: 1 I don't understand the last line at all. Why is my x variable 1 after having been incremented twice? Is there more than one global space? Is this backreference to the original a.py not allowed? I could use some help. Thanks Bart van Deenen a.py: --------------------------------- import b x=1 def inc(): global x x+=1 print "inc: ",x if __name__=="__main__": b.test() print "C: ",x b.py: --------------------------------- def test(): import a a.inc() print "A: ",a.x a.inc() print "B: ",a.x From simoninusa2001 at yahoo.co.uk Sat Feb 19 14:04:24 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 19 Feb 2005 11:04:24 -0800 Subject: Pausing a program - poll/sleep/threads? References: <1108625477.222091.34680@l41g2000cwc.googlegroups.com> <1119nf8qqj5gfbe@corp.supernews.com> <1108666816.520517.91390@o13g2000cwo.googlegroups.com> <1119v7o1h4k8be5@corp.supernews.com> <1108699641.787642.310960@f14g2000cwb.googlegroups.com> Message-ID: <1108839864.101293.184050@o13g2000cwo.googlegroups.com> OK, I've implemented the 2sec threaded update, but I'm having some problems with it. Basically the thread will have to just run constantly, never exiting (just sleeping for 2secs), which seems to work OK except when I try to get the thread to do anything with the main program's window. As the thread doesn't end, it doesn't return a result, so on every pass of the thread's while loop, I write the current track info to the mainWindow directly, however this causes the program to hang. Here is a snippet of the current method: class ThreadedInfo(Thread): """overloads init and defines run""" def __init__(self): Thread.__init__(self) def run(self): # runs the whole time while 1: self.info() time.sleep(2) def info(self): """referencing window kills linux here""" # get track info, returned as dictionary self.info_dict = backend.getInfo(config.server, config.port) I was thinking of getting the thread to just run once, then getting the main program to write the result (using join() ) to the mainWindow. That method would be something like this, but it's almost totally pointless using a thread then, as the while loop will singletask the program: while 1: # start thread self.infothread.start() # when thread ends, get result self.result = self.infothread.join() # write result to window window.mainTextarea.setText(self.result) # pause for 2secs before starting again sleep(2) I made sure that I built PyQt using threads, so that's not the issue. Any other ideas? From dave.opstad at monotypeimaging.com Tue Feb 1 18:35:18 2005 From: dave.opstad at monotypeimaging.com (Dave Opstad) Date: Tue, 01 Feb 2005 15:35:18 -0800 Subject: Awkwardness of C API for making tuples References: <1107289261.185768.116790@f14g2000cwb.googlegroups.com> Message-ID: In article <1107289261.185768.116790 at f14g2000cwb.googlegroups.com>, "John Machin" wrote: > What is the purpose of this first loop? Error handling. If I can't successfully create all the PyInts then I can dispose the ones I've made and not bother making the tuple at all. > > In what variable-length storage are you storing these (Python) integers > during this first loop? Something you created with (a) PyMem_Malloc (b) > malloc (c) alloca (d) your_own_malloc? (b) malloc. The sequence here is: 1) malloc; 2) check for malloc success; 3) loop to create PyInts (if failure, Py_DECREF those made so far and free the malloc'ed buffer); 4) create new tuple (error checks again); and 5) PyTuple_SET_ITEM (no error checks needed) > 1. Determine the length of the required tuple; this may need a loop, > but only to _count_ the number of C longs that you have. > 2. Use PyTuple_New. > 3. Loop to fill the tuple, using PyInt_FromLong and PyTuple_SetItem. This would certainly be simpler, although I'm not sure I'm as clear as to what happens if, say, in the middle of this loop a PyInt_FromLong fails. I know that PyTuple_SetItem steals the reference; does that mean I could just Py_DECREF the tuple and all the pieces will be automagically freed? If so, I'll take your recommendation and rework the logic this way. Thanks! Dave From christopher_culver at yahoo.com Mon Feb 14 00:52:47 2005 From: christopher_culver at yahoo.com (Christopher Culver) Date: 13 Feb 2005 21:52:47 -0800 Subject: FS: O'Reilly Python Pocket Reference Message-ID: <1108360367.579794.122150@g14g2000cwa.googlegroups.com> I am offering for sale a copy of O'Reilly's _Python Pocket Reference_. It is the second edition, covering Python 2. It is in fine condition, with no broken spine or dog-earned pages. One might even believe it just came out of the bookstore. Asking price is US$4 plus shipping (USPS Media Mail within the US, airmail internationally), payable by check or money order in the US, or Paypal elsewhere. Christopher Culver christopher_culver at yahoo.com From franz.steinhaeusler at utanet.at Sat Feb 19 11:05:41 2005 From: franz.steinhaeusler at utanet.at (Franz Steinhäusler) Date: Sat, 19 Feb 2005 17:05:41 +0100 Subject: [ANN] Python 2.4 Quick Reference available References: Message-ID: <0roe11d8engklsoto03jh2171k60g43vo7@4ax.com> On Sat, 19 Feb 2005 13:00:59 +0100, "Richard Gruet" wrote: >Hi Pythoners, > >An updated version of the Python Quick Reference is available for Python 2.4 >at http://rgruet.free.fr/#QuickRef. >It is a single looonnng html page (30 printed A4 pages) with a choice of 4 >different CSS styles; also available in PDF. > >Richard > Hello Richard, many thanks! Such a coincidence, because I wanted to ask these days, wheter a newer one exist (I have a printed reference for Python 1.5.1) -- Franz Steinh?usler DrPython (Project Developer) http://mitglied.lycos.de/drpython/ From simoninusa2001 at yahoo.co.uk Thu Feb 17 00:51:43 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 16 Feb 2005 21:51:43 -0800 Subject: Help with C extensions under VC6 / WinXP and Python 2.4 In-Reply-To: References: Message-ID: <1108619503.324262.282330@c13g2000cwb.googlegroups.com> What's the difference between ctypes, SWIG and SIP? I've used SWIG to "convert" C source to Python (as I believe SIP does?), so does ctypes wrap functions from binaries (e.g. DLL's)? From pltrry at yahoo.com Sun Feb 6 18:23:17 2005 From: pltrry at yahoo.com (Paul Terry) Date: Sun, 6 Feb 2005 15:23:17 -0800 (PST) Subject: email extraction program Message-ID: <20050206232317.97390.qmail@web30108.mail.mud.yahoo.com> Good day, Can you help me create an ebay email extraction program ? I have some ebay scripts which worked and extracted emails from ebay.com but these days don't work. Regards. --------------------------------- Do you Yahoo!? Yahoo! Search presents - Jib Jab's 'Second Term' -------------- next part -------------- An HTML attachment was scrubbed... URL: From abuse at solumslekt.org Thu Feb 17 04:13:26 2005 From: abuse at solumslekt.org (Leif B. Kristensen) Date: Thu, 17 Feb 2005 10:13:26 +0100 Subject: [newbie]How to install python under DOS and is there any Wxpython can be installed under dos? References: Message-ID: john san skrev: > pure DOS, old pc, used for teaching . want show some "windows" under > DOS (under Python). curses is a text-based interface that will let you build windowed applications like you could with the crt unit in Turbo Pascal of those golden days. I've no idea if anyone's compiled it for the 16-bits DOS platform, though. -- Leif Biberg Kristensen From pipedreamergrey at gmail.com Tue Feb 22 16:43:48 2005 From: pipedreamergrey at gmail.com (PipedreamerGrey) Date: 22 Feb 2005 13:43:48 -0800 Subject: PythonCard and Py2Exe Message-ID: <1109108628.859879.121020@g14g2000cwa.googlegroups.com> I'm trying to create a standalone version (.exe) of PythonCard's Custdb sample using Py2Exe version 0.5.0. Everytime I attempt to compile the program, I get an error during compilation. This is the exact code I'm using in the setup file: from distutils.core import setup import py2exe setup( name = "custdb", console = ["custdb.py"], data_files = [ (".", ["custdb.ini", "custdb.de.rsrc.py", "custdb.rsrc.py", "customerdata.csv"]) ] ) This is the error message I get when I run custdb.exe: Traceback (most recent call last): File "custdb.py", line 202, in ? app = model.Application(CustDbStack) File "PythonCard\model.pyc", line 337, in __init__ File "PythonCard\resource.pyc", line 48, in getResource File "PythonCard\resource.pyc", line 86, in __init__ File "PythonCard\resource.pyc", line 91, in __init__ File "PythonCard\resource.pyc", line 91, in __init__ File "PythonCard\resource.pyc", line 96, in __init__ File "PythonCard\resource.pyc", line 139, in enforceSpec File "PythonCard\resource.pyc", line 30, in loadComponentModule ImportError: cannot import module 'radiogroup When I add "radiogroup" to the imports at the top of custdb.py, I get this error message: Traceback (most recent call last): File "custdb.py", line 18, in ? ImportError: cannot import name radiogroup This is line 18 in Custdb.py: from PythonCard import dialog, model, radiogroup From ajsiegel at optonline.com Tue Feb 1 08:06:52 2005 From: ajsiegel at optonline.com (Arthur) Date: Tue, 01 Feb 2005 08:06:52 -0500 Subject: Go visit Xah Lee's home page References: Message-ID: On Mon, 31 Jan 2005 16:07:41 -0800, aurora wrote: >Let's stop discussing about the perl-python non-sense. It is so boring. > >For a break, just visit Mr Xah Lee's personal page >(http://xahlee.org/PageTwo_dir/Personal_dir/xah.html). You'll find lot of >funny information and quotes from this queer personality. Thankfully no >perl-python stuff there. > >Don't miss Mr. Xah Lee's recent pictures at > > http://xahlee.org/PageTwo_dir/Personal_dir/mi_pixra.html > >My favor is the last picture. Long haired Xah Lee sitting contemplatively >in the living room. The caption says "my beautiful hair, fails to resolve >the problems of humanity. And, it is falling apart by age." And of each of us contributed something 50% as worthwhile as well executed as his geometry pages to the Web, the Web would begin to deliver 10% of its promise. POST GET this ;) Art From duncan.booth at invalid.invalid Tue Feb 8 04:43:02 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Feb 2005 09:43:02 GMT Subject: variable declaration References: <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com> Message-ID: Brian van den Broek wrote: > Can it then be further (truly :-) ) said that > > if False: > # thousands of lines of code here > > would effect the structure of the function object's bytecode, but not > its behaviour when run? Or, at most, would cause a performance effect > due to the bytecode being bloated by thousands of line's worth of code > that would never get executed? > Yes, but that purely an implementation detail. if 0: # thousands of lines of code here has no effect at all on the bytecode, it it optimised out entirely. 'if False:' is not optimised out in Python 2.4 or earlier, but might be in later versions. Now, to really get your brain hurting, see what this one does: def hurts_my_brain(v): if 0: # unlike Steve's eg, ensuring that the global x # nested block is never hit at runtime x = v I'll give you a clue, it's not the same as your: def hurts_my_brain(v): if False: # unlike Steve's eg, ensuring that the global x # nested block is never hit at runtime x = v So the global statement is a wart which isn't executed at runtime, but behaves differently when the bytecode it doesn't generate is optimised out. From deetsNOSPAM at web.de Fri Feb 18 16:05:49 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 18 Feb 2005 22:05:49 +0100 Subject: re.compile and very specific searches References: <1108759781.084277.64990@f14g2000cwb.googlegroups.com> Message-ID: > > This approach would actually work without the need for subsequent > validation, if implemented properly. Not only as you noted does it let > "259" through, but also it doesn't cover 2-digit numbers starting with > 2. Assuming excess leading zeroes are illegal, the components required > are: Damn. Certainly not my glory regular expression day. -- Regards, Diez B. Roggisch From apardon at forel.vub.ac.be Mon Feb 28 05:19:46 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Feb 2005 10:19:46 GMT Subject: Why do descriptors (and thus properties) only work on attributes. References: <7xoee5kpiv.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-02-28, Daniel Dittmar schreef : > Antoon Pardon wrote: >>>>Can anyone explain why descriptors only work when they are an attribute >>>>to an object or class. I think a lot of interesting things one can >>>>do with descriptors would be just as interesting if the object stood >>>>on itself instead of being an attribute to an other object. >>> >>>How would that work? >> >> >> Well AFAIU a descriptor is an object with at least one method out of >> __get__, __set__ or __del__. I don see why implicitly calling one >> of these methods would be any more difficult when they are autonomous >> objects than when they are attributes. > > I guess properties are really a feature of the class, not of the > attribute. Certain operations on objects of the class (getattr, setattr, > delattr) have to be intercepted. If you want to have this for general > variable access, you 'd have to intercept all accesses to local and > module name spaces. This slows things down a lot. OK, I can understand this. > And many think that > overloading assignment is a bad idea. But not bad enough to allow it in some cases? > You probably find some dicussions > when searching for "overloading assignment" in the newsgroup archive. I'll take a look. > >>>to an object or class. I think a lot of interesting things one can > > As in the chinese curse "May you live in interisting times"? Well I think python partly makes the time interesting. So in that respect we are all cursed. -- Antoon Pardon From steve at holdenweb.com Wed Feb 2 08:03:49 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 02 Feb 2005 08:03:49 -0500 Subject: Is this a contradiction in the docs ? In-Reply-To: <1107342032.273119.194120@o13g2000cwo.googlegroups.com> References: <1107342032.273119.194120@o13g2000cwo.googlegroups.com> Message-ID: <0i4Md.102585$Jk5.77392@lakeread01> Fuzzyman wrote: > The following two passages from the python documentation *appear* to > contradict each other. Equally possible (or more likely !) is that I > misunderstand it : > > eval : > This function can also be used to execute arbitrary code objects (such > as those created by compile()). In this case pass a code object instead > of a string. The code object must have been compiled passing 'eval' as > the kind argument. > > > compile: > The kind argument specifies what kind of code must be compiled; it can > be 'exec' if string consists of a sequence of statements, 'eval' if it > consists of a single expression, or 'single' if it consists of a single > interactive statement (in the latter case, expression statements that > evaluate to something else than None will be printed). > > The docs for compile say that if you are creating a code object from a > sequence of statements you must use the kind argument 'exec'. Eval says > that if you are using the eval function you must use 'eval' as your > kind argument. > > In practise I have found that using the eval function with code objects > compiled with 'exec' as the kind argument works fine. Is this a 'bug' > in the docs ? > Regards, > "Dear List: I live close to a railroad, and the tracks are surrounded by a fence with large signs saying 'Walking on the tracks can be dangerous'. I have walked on the tracks several times, however, and I don't see why the railway company put those signs there. In fact I'm walking along the tracks right now as I enter this post on my hand-held, and [message ends with sound of locomotive horn followed by an ugly squelch]." That's the kind of practice best avoided. Are you breaking the rules just for the fun of it? regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.python.org/pycon/2005/ Steve Holden http://www.holdenweb.com/ From caleb1 at telkomsa.net Mon Feb 7 22:53:05 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Mon, 07 Feb 2005 22:53:05 -0500 Subject: loops -> list/generator comprehensions References: <1107718117.221204.80410@l41g2000cwc.googlegroups.com> <4qCdnXI11-vhGJvfRVn-vQ@comcast.com> Message-ID: Wow, Steve, thanks, you went to some effort here. > I prefer to give names to the values produced by os.walk -- I think it > makes the usage much clearer. However, since I don't use 'dirnames', I > use '_' to indicate this: Actually, I feel silly for not recognising this - I read about the Python3 suggestion for adding a "with" syntax, and the suggestion was rather to use something like _ = instname _.a = 1 _.b = 2 So I actually have seen this "_" placeholder before :) Sorry bout that. > Would > > filenames = [os.path.join(dirpath, filename) > for dirpath, dirnames, filenames in os.walk('.') > for filename in filenames] > > have been clearer for you? Then all you have to do is remember the > order of the for-loop execution: Bizarre as this may sound, it was the '_' that was throwing me off the whole thing (at the 'grok' level I generally read the newsgroup, anyway). For some weird reason, I can read *this* comprehension pretty easily! Does that make sense at all? I figure a little bit of uncertainty along the way probably derails understanding of the whole thing a little bit - and (mental note) I *must* remember this when I explain stuff to people at work, having now experienced it first hand. Thanks again Caleb From todddeluca at gmail.com Tue Feb 1 16:00:24 2005 From: todddeluca at gmail.com (todddeluca at gmail.com) Date: 1 Feb 2005 13:00:24 -0800 Subject: a sequence question In-Reply-To: References: Message-ID: <1107291624.405255.76150@z14g2000cwz.googlegroups.com> Chris Wright wrote: > Hi, > > 1) I want to iterate over a list "N at a time" > sort of like: > > # Two at a time... won't work, obviously > > >>> for a, b in [1,2,3,4]: > ... print a,b > ... > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unpack non-sequence > >>> > > > Is there a nifty way to do with with list comprehensions, > or do I just have to loop over the list ? > > cheers and thanks > > chris wright I wouldn't call this nifty, but it does use list comprehensions: (n-(len(l)%n))%n is the amount of padding (len(l)+(n-(len(l)%n))%n)/n is the number of groups (calculated by adding the padding to the length of l and then dividing by n) >>> l = range(10) >>> n = 3 >>> [(l+[None]*((n-(len(l)%n))%n))[i*n:(i+1)*n] for i in xrange((len(l)+(n-(len(l)%n))%n)/n)] [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]] Regards, Todd From fperez.net at gmail.com Fri Feb 4 18:51:26 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Fri, 04 Feb 2005 16:51:26 -0700 Subject: IPython colors in windows References: <1107487113.732375.110850@c13g2000cwb.googlegroups.com> <36hculF51ho2sU1@individual.net><1107530489.308497.103530@g14g2000cwa.googlegroups.com><36hrjpF4ui8fbU1@individual.net> <36i84qF52ce29U1@individual.net> Message-ID: Fernando Perez wrote: > Ashot wrote: > >> this is what it looks like: >> >> http://www.freshraisins.com/sand/ipythonscreen.PNG >> >> does cygwin have a readline utility in it? Perhaps this is overriding the >> correct one? Thats the only thing I can think of. > > Hi folks, > > could you please test under windows the 1.9 version of readline? OK, make that 1.10: http://sourceforge.net/project/shownotes.php?release_id=302526 Gary specifically targeted the light background problems with this one, so please report here if the whole thing gets fixed. Regards, f From x2164 at mailcity.com Wed Feb 2 09:49:56 2005 From: x2164 at mailcity.com (x2164 at mailcity.com) Date: 2 Feb 2005 14:49:56 GMT Subject: test_socket.py failure References: Message-ID: Nick Coghlan wrote: > x2164 at mailcity.com wrote: > > At the interactive python prompt i did/got the following: > > > > bash-2.04$ ./python > > Python 2.4 (#1, Jan 29 2005, 10:31:35) > > [GCC 2.95.3 20010315 (release)] on linux2 > > Type "help", "copyright", "credits" or "license" for > > more information. > > >>> import socket > > >>> socket.getservbyname('daytime', 'tcp') > > 13 > > > > # The 13 looks ok but look what happen > > # when i asked only for the service, like > > # the line that fails in test_socket. > > > > >>> socket.getservbyname('daytime') > > Traceback (most recent call last): > > File "", line 1, in ? > > socket.error: service/proto not found > > >>> > Hmm, when the second argument is omitted, the system call looks like: > getservbyname("daytime", NULL); > Based on "man getservbyname" on my Linux PC, that should give > the behaviour we > want - any protocol will match. > However: > Linux 2.6.4-52-default (Suse 9.1) > Glibc 2.3.3 > gcc 3.3.3 > So it may be that your older platform doesn't have this > behaviour - I'd be very > interested in what 'man getservbyname' has to say. > Cheers, > Nick. > -- > Nick Coghlan | ncoghlan at email.com | Brisbane, Australia > --------------------------------------------------------------- > http://boredomandlaziness.skystorm.net hey Nick, Just took a look at the man page for getservbyname on this system and it doesn't mention passing NULL as the second argument. The pertinents: ;-) Linux kernel 2.6.10 Glibc 2.2.5 gcc 2.95.3 I'd say your probably right about there being a difference in the behaviour of getservbyname between libc 2.2.5 and and libc-2.3.3 given the differences in man pages and observed return values. I'll try and compare the libcs' getservbyname codes and let you know a little later in the day. I wonder if the developers wanted to tie the python source code so closely to a glibc version and possibly gnu-libc specific? pete jordan x2164 at mailcityDOTcom miami, florida -- ............ From raghulj at gmail.com Mon Feb 21 22:53:04 2005 From: raghulj at gmail.com (Raghul) Date: 21 Feb 2005 19:53:04 -0800 Subject: about uid in imaplib Message-ID: <1109044384.493076.35080@f14g2000cwb.googlegroups.com> Hi guys, How to use "uid" and copy a message to the other folders using python.Please help in explainig with sample code.I think,imaplib uid object need atleast a sample to understand clearly. From steven.bethard at gmail.com Thu Feb 3 01:36:51 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 02 Feb 2005 23:36:51 -0700 Subject: Computing class variable on demand? In-Reply-To: <1107410898.260491.203090@l41g2000cwc.googlegroups.com> References: <1107410898.260491.203090@l41g2000cwc.googlegroups.com> Message-ID: <6eydnSAjiuofW5zfRVn-sw@comcast.com> fortepianissimo wrote: > We all know that using __getattr__() we can compute an instance > variable on demand, for example: > > class Foo: > def __getattr__ (self, name): > if name == 'bar': > self.bar = 'apple' > return self.bar > else: > raise AttributeError() > > Then we can > > f = Foo() > s1 = f.bar > s2 = f.bar # this uses the "cached" result > > My question is can we do the same with class variables? You can do this using a metaclass, e.g.: py> class FooType(type): ... def __getattr__(self, name): ... if name == 'bar': ... self.bar = 'apple' ... return self.bar ... else: ... raise AttributeError('no attribute named %r' % name) ... py> class Foo(object): ... __metaclass__ = FooType ... py> Foo.bar 'apple' However, you probably don't want to. What's your use case? Steve From exogen at gmail.com Mon Feb 21 12:37:48 2005 From: exogen at gmail.com (Brian Beck) Date: Mon, 21 Feb 2005 12:37:48 -0500 Subject: python2.4 generator expression > python2.3 list expression In-Reply-To: References: <0ioj11dsgqhatqc3d7ldeb35rta6d9fk69@4ax.com> Message-ID: Duncan Booth wrote: > The difference between the original "reset the rightmost '1' bit", and your > interpretation: "reset the rightmost bit" is the "'1'". > > The rightmost bit that is set is reset. So 0x10 -> 0, and 0x1010 -> 0x1000. > > If you want to extract the least significant set bit from a number 'x' you > can use (x&-x): My interpretation of Bryan's (mis?)interpretation (heh) was that since in the numbers 2 and 10 (as in his examples), the least significant bit was already 0, performing an operation that set it to 0 should result in the number unchanged. As his tests show, this is not the case. This is because the operation works only if the least significant bit actually NEEDS to be unset. To zero the least significant bit unconditionally, we can use: x &= ~1 -- Brian Beck Adventurer of the First Order From suryaprakashg at gmail.com Fri Feb 11 02:15:28 2005 From: suryaprakashg at gmail.com (suryaprakashg at gmail.com) Date: 10 Feb 2005 23:15:28 -0800 Subject: Python v.s. c++ In-Reply-To: References: Message-ID: <1108106128.266428.188890@g14g2000cwa.googlegroups.com> xiaobin yang wrote: > Hi, if i am already skillful with c++. Is it useful to learn python? thanks! Defenitly , It is much easier to convert an idea to a living model easily in python and with out much effort . You can always mix things with C++ and python ( for optimization or whatever)with swig somewhat mature now to make things easier . look at this once you have your feet in python www.swig.org From aurora00 at gmail.com Fri Feb 18 14:15:27 2005 From: aurora00 at gmail.com (aurora) Date: Fri, 18 Feb 2005 11:15:27 -0800 Subject: unicode and socket References: <1108753426.318777.275250@c13g2000cwb.googlegroups.com> Message-ID: You could not. Unicode is an abstract data type. It must be encoded into octets in order to send via socket. And the other end must decode the octets to retrieve the unicode string. Needless to say the encoding scheme must be consistent and understood by both ends. On 18 Feb 2005 11:03:46 -0800, wrote: > hello all, > I am new in Python. And I have got a problem about unicode. > I have got a unicode string, when I was going to send it out throuth a > socket by send(), I got an exception. How can I send the unicode string > to the remote end of the socket as it is without any conversion of > encode, so the remote end of the socket will receive unicode string? > > Thanks > From markus_GETRIDOFALLCAPSwankus at hotmail.com Tue Feb 22 22:01:52 2005 From: markus_GETRIDOFALLCAPSwankus at hotmail.com (Markus Wankus) Date: Tue, 22 Feb 2005 22:01:52 -0500 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: <37uk2kF5gv38bU1@individual.net> References: <874qg6937w.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <37uk2kF5gv38bU1@individual.net> Message-ID: George Sakkis wrote: > "Ilias Lazaridis" wrote in message news:cvcv9b$nbm$1 at usenet.otenet.gr... > > >>Nick Vargish wrote: >> >>>You can excuse yourself from this one and stop replying to comments, >>>but you don't get to unilaterally declare a discussion over. >> >>[...] >> >>The discussion is over. >> >>At least the in-topic one. >> >>Everything else is babbling, hairsplitting, playing an AI which does not >>understand writings and all this unproductive garbage. >> >>The Essence is this one, as stated before: >> >>[huge copy paste of previous post] > > > > The Essence is irrelevant. > - > - > - > All your thread are belong to us. > - > - > - For great justice! ;o) From tjreedy at udel.edu Sat Feb 26 13:16:36 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Feb 2005 13:16:36 -0500 Subject: any Python equivalent of Math::Polynomial::Solve? References: Message-ID: "Just" wrote in message news:just-ACE943.17364326022005 at news1.news.xs4all.nl... >> Does SciPy do what you want? Specifically Scientific.Functions.FindRoot >> [1] & >> Scientific.Functions.Polynomial [2] >> http://starship.python.net/~hinsen/ScientificPython/ScientificPythonManual/Sci >> entific_9.html >> [2] >> http://starship.python.net/~hinsen/ScientificPython/ScientificPythonManual/Sci >> entific_13.html > > (Hm, I had the impression that scipy != Konrad Hinsen's Scientific > module.) www.scipy.org (first hit on "Python SciPy" google search) Terry J. Reedy From has.temp2 at virgin.net Sun Feb 20 20:32:39 2005 From: has.temp2 at virgin.net (has) Date: 20 Feb 2005 17:32:39 -0800 Subject: recommended way of generating HTML from Python In-Reply-To: <1108933633.259271.182890@o13g2000cwo.googlegroups.com> References: <1108889625.068929.88890@z14g2000cwz.googlegroups.com> <1108933633.259271.182890@o13g2000cwo.googlegroups.com> Message-ID: <1108949559.097766.324440@f14g2000cwb.googlegroups.com> xtian wrote: > Stan (part of nevow, which is part of twisted) is a nice python syntax > for building HTML [...] > I don't know how detachable it is from the rest of nevow. I'd assume it > wouldn't be too difficult to implement in a standalone fashion. FWIW I whipped up a simple self-contained Stan clone a while back: http://freespace.virgin.net/hamish.sanderson/stanlite.py It's a bit quick-n-dirty - I think ideally you'd want it to parse all the HTML element information from a DTD and perform proper validation of input data - but if anyone want to pick it up and run with it, or just use it as-is, they're more than welcome to. HTH has From steven.bethard at gmail.com Thu Feb 17 14:55:06 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 17 Feb 2005 12:55:06 -0700 Subject: How to wrap a class's methods? In-Reply-To: <4214f167$0$44618$a1866201@visi.com> References: <4214f167$0$44618$a1866201@visi.com> Message-ID: Grant Edwards wrote: > I want to subclass an IMAP connection so that most of the > methods raise an exception if the returned status isn't 'OK'. > This works, but there's got to be a way to do it that doesn't > involve so much duplication: > > class MyImap4_ssl(imaplib.IMAP4_SSL): > > def login(*args): > s,r = imaplib.IMAP4_SSL.login(*args) > if s!='OK': > raise NotOK((s,r)) > return r > > def list(*args): > s,r = imaplib.IMAP4_SSL.list(*args) > if s!='OK': > raise NotOK((s,r)) > return r > > def search(*args): > s,r = imaplib.IMAP4_SSL.search(*args) > if s!='OK': > raise NotOK((s,r)) > return r > > [and so on for another dozen methods] You could try something like (Untested!): class Wrapper(object): def __init__(self, func): self.func = func def __call__(*args, **kwargs): self, args = args[0], args[1:] s, r = self.func(*args) if s != 'OK': raise NotOK((s, r)) return r for func_name in ['login', 'list', 'search']: func = Wrapper(getattr(imaplib.IMAP4_SSL, func_name)) setattr(imaplib.IMAP4_SSL, func_name, func) STeVe From deetsNOSPAM at web.de Sun Feb 13 16:04:26 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 13 Feb 2005 22:04:26 +0100 Subject: builtin functions for and and or? References: Message-ID: > So usually I just write a little function any( L, boolean_function = > identity ) or all( ... ). But I am kind of sick of doing that all the > time -- does it exist anywhere in the Python libraries? It seems really > common to me. Put things into your own module and add it to your python path. Then you only have to write it once. > The first way isn't satisfactory because it takes so many lines for what > is > essentially one "primitive" operation. The second way isn't great because > it is not as readable and many readers don't like to see reduce, even if > it > is a common idiom like that. Also I don't believe it short circuits. It doesn't but so doesn't your loop example. Put a break in there once Result is False. -- Regards, Diez B. Roggisch From antonmuhin at rambler.ru Thu Feb 17 12:56:41 2005 From: antonmuhin at rambler.ru (anton muhin) Date: Thu, 17 Feb 2005 20:56:41 +0300 Subject: multimethod (or rather overloading) in Python In-Reply-To: <37k236F5fdtu1U1@individual.net> References: <37k236F5fdtu1U1@individual.net> Message-ID: <37k46qF5g7tt4U1@individual.net> anton muhin wrote: Correction: > Of course, I can imagine some metaclasses magic that would allow to code: > > class MyClass(WithOverloading): > @overloadMethod(A) > def someMetod(self, _): ... > > But it would rather convoluted: the best idea I have so far is to mangle > methods name in the manner most of C++ compilers do. Stupid me. Of course, name magling is impossible and unnecessary. Sorry. Still the question remains. with the best regards, anton. From pierre.barbier at cirad.fr Thu Feb 10 09:26:21 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Thu, 10 Feb 2005 15:26:21 +0100 Subject: is there a safe marshaler? In-Reply-To: <420b6936$0$28982$e4fe514c@news.xs4all.nl> References: <420b6936$0$28982$e4fe514c@news.xs4all.nl> Message-ID: <420b6e98$0$23018$626a14ce@news.free.fr> Irmen de Jong a ?crit : > Pickle and marshal are not safe. They can do harmful > things if fed maliciously constructed data. > That is a pity, because marshal is fast. > I need a fast and safe (secure) marshaler. > Is xdrlib the only option? > I would expect that it is fast and safe because > it (the xdr spec) has been around for so long. > > Or are there better options (perhaps 3rd party libraries)? > > Thanks > > Irmen. What exactly do you mean by "safe" ? Do you want to ensure your objects cannot receive corrupted data ? Do you want to ensure no code will be evaluated during the unmarshalling ? Please, be more precise, Pierre From mahs at telcopartners.com Tue Feb 15 17:16:57 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 15 Feb 2005 14:16:57 -0800 Subject: Can __new__ prevent __init__ from being called? In-Reply-To: References: <87is4tldea.fsf@news2.ososo.de> Message-ID: Peter Hansen wrote: > Felix Wiemann wrote: > >> Sometimes (but not always) the __new__ method of one of my classes >> returns an *existing* instance of the class. However, when it does >> that, the __init__ method of the existing instance is called >> nonetheless, so that the instance is initialized a second time. For >> example, please consider the following class (a singleton in this case): >> > [snip] > >> How can I prevent __init__ from being called on the already-initialized >> object? > > > Is this an acceptable kludge? > > >>> class C(object): > ... instance=None > ... def __new__(cls): > ... if C.instance is None: > ... print 'creating' > ... C.instance = object.__new__(cls) > ... else: > ... cls.__init__ = lambda self: None > ... return cls.instance > ... def __init__(self): > ... print 'in init' > ... > >>> a = C() > creating > in init > >>> b = C() > >>> > > (Translation: dynamically override now-useless __init__ method. > But if that works, why do you need __init__ in the first place?) > > -Peter Or this one: use an alternative constructor: class C(object): instance = None @classmethod def new(cls, *args, **kw): if cls.instance is None: print 'Creating instance.' cls.instance = object.__new__(cls) print 'Created.' cls.instance.__init__(*args,**kw) return cls.instance def __init__(self): print 'In init.' >>> c = C.new() Creating instance. Created. In init. >>> c = C.new() >>> Michael From jtp11 at att.net Tue Feb 8 14:38:21 2005 From: jtp11 at att.net (Jim) Date: 8 Feb 2005 11:38:21 -0800 Subject: Loop in list. In-Reply-To: <36s2b2F53f67pU1@individual.net> References: <1107874174.445345.41230@c13g2000cwb.googlegroups.com> <36s2b2F53f67pU1@individual.net> Message-ID: <1107891501.110687.134390@f14g2000cwb.googlegroups.com> Particularly one who can't spell. Fortran. Jim From aleaxit at yahoo.com Tue Feb 8 06:44:09 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 8 Feb 2005 12:44:09 +0100 Subject: how to convert 4 bytes into a float ? References: <1grny4s.18evsxl1g1c7eaN%aleaxit@yahoo.com> Message-ID: <1gro09j.1e2e2kn1967308N%aleaxit@yahoo.com> Jean-Baptiste PERIN wrote: > I'll have to handle Intel-PC, DEC-VAX and MIPS-SUN/SGI numbers > So I can't escape the painful bit-twiddling I don't recall for sure (even though I did my thesis on a Vax, 25 years ago!) but I think you _might_ be lucky -- VAX used the binary format that became the IEEE standard, if I recall correctly. Intel, MIPS, SUN and SGI surely did follow IEEE standards, endianity apart, and you can correct for endianity with struct.unpack. The problem would be there if you had, say, floats in old IBM 360/370 formats, or Cray's original formats, or the like... > Anyway, struct.unpack will undoubtedly be an incredibly valuable help > > thank you very very very much .. You're welcome! Alex From http Sat Feb 26 05:36:31 2005 From: http (Paul Rubin) Date: 26 Feb 2005 02:36:31 -0800 Subject: Converting HTML to ASCII References: Message-ID: <7xk6ovbob4.fsf@ruckus.brouhaha.com> Jorgen Grahn writes: > You should probably do what some other poster suggested -- download > lynx or some other text-only browser and make your code execute it > in -dump mode to get the text-formatted html. You'll get that > working in an hour or so, and then you can see if you need something > more complicated. Lynx is pathetically slow for large files. It seems to use a quadratic algorithm for remembering where the links point, or something. I wrote a very crude but very fast renderer in C that I can post if someone wants it, which is what I use for this purpose. From danb_83 at yahoo.com Sun Feb 6 23:46:34 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 6 Feb 2005 20:46:34 -0800 Subject: Questions about mathematical signs... References: <614c778e.0502061226.5f40244c@posting.google.com> Message-ID: <1107751594.529913.105480@c13g2000cwb.googlegroups.com> Jeff Epler wrote: > On Sun, Feb 06, 2005 at 12:26:30PM -0800, administrata wrote: > > Hi! I'm programming maths programs. > > And I got some questions about mathematical signs. ... > > 2. Inputing fractions like (a / b) + (c / d), It's tiring work too. > > Can it be simplified? > > Because of the rules of operator precedence, > a / b + c / d > has the same meaning as the expression you gave. And it's important to note that that meaning will change in version 3.0. Until then, it's best to start every module with "from __future__ import division". From akineko at pacbell.net Thu Feb 17 14:28:15 2005 From: akineko at pacbell.net (Aki Niimura) Date: 17 Feb 2005 11:28:15 -0800 Subject: Pmw.Balloon under Windows In-Reply-To: References: <1108579886.983146.56130@z14g2000cwz.googlegroups.com> Message-ID: <1108668495.123773.162340@f14g2000cwb.googlegroups.com> Eric Brunel wrote: > One question: what Python do you use? Is it a regular Windows Python > distribution or the Python delivered with Cygwin? I know by experience > that the Python in Cygwin has quite a lot of problems (mine crashes *very* > often). If you don't already use a "regular" Windows distro, I think using > one may solve your problem. Yes, I noticed the difference. I'm using the Python 2.3.5 installed on Windows. (Pmw 1.2) > I think the default binding for the 'X' button is to call destroy, not quit. > Calling destroy on the main window is almost equivalent to calling quit, so > maybe it can be a solution? I have tried calling root.destroy() as you suggested. It worked. My application is now not generating the error message. Thank you for your suggestion. > Not that I know of. The event_generate method won't help here, ... Good to know that. I think Window is a different beast as it doesn't have a window manager. Thank you, Aki Niimura From gmane-schpam at joefrancia.com Tue Feb 15 17:32:48 2005 From: gmane-schpam at joefrancia.com (Joe Francia) Date: Tue, 15 Feb 2005 17:32:48 -0500 Subject: Calling a function from module question. In-Reply-To: <3LtQd.32674$6u.18210@fed1read02> References: <42125d6d$0$28977$e4fe514c@news.xs4all.nl> <3LtQd.32674$6u.18210@fed1read02> Message-ID: Sean wrote: >>Sean wrote: >> >> >>>Then I would have a script that uses the >>>print_this function defined in the module >>>without using the module name in the call. >> >> >> >>from module_name import print_this >> >>or, even: >> >>from module_name import print_this as other_nice_name >> > > > So what if I have a whole bunch of functions - say 25 of them. > Is there a way to do this without naming each function? > > You do that like so: "from module import *". But you should avoid that, as stated in the Python help: Note that in general the practice of importing * from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions, and certain modules are designed to export only names that follow certain patterns. The "certain patterns" usually occur in huge packages, such as in the various GUI toolkits. E.g., all of the exported PyQt classes are prefaced with Q (QButtonGroup, QTabWidget), so doing "from qt import *" is fairly safe. You can also import a module like so: "import module as m" to save on some typing, if that is your concern. But namespaces are a feature of Python, not a limitation, so the Python way is to use them for clearer code. With a large number of functions like that, it sounds more like you should be inheriting from a class anyway, which I think is what Steven Bethard meant when he suggested refactoring. For more information on the Python way, go to the Python interpreter and type "import this" ;>) -- Soraia: http://www.soraia.com From martin.sand.christensen at gmail.com Tue Feb 15 09:23:09 2005 From: martin.sand.christensen at gmail.com (Martin Christensen) Date: Tue, 15 Feb 2005 15:23:09 +0100 Subject: multi threading in multi processor (computer) References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <420a2938$0$22987$626a14ce@news.free.fr> <1107964587.818199.223980@g14g2000cwa.googlegroups.com> <7xr7jlwieq.fsf@ruckus.brouhaha.com> <420e7ee4$0$28976$e4fe514c@news.xs4all.nl> <37ba2dF5b8slrU1@individual.net> <421133d8$0$28988$e4fe514c@news.xs4all.nl> Message-ID: <877jl9yka9.fsf@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >>>>> "Irmen" == Irmen de Jong writes: Irmen> Naah. What about: http://www.razorvine.net/img/killGIL.jpg Some people have too much spare time and too weird senses of humour... Fortunately for the rest of us. :-) This one actually made me laugh out loud. Martin - -- Homepage: http://www.cs.auc.dk/~factotum/ GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.5 (GNU/Linux) Comment: Using Mailcrypt+GnuPG iEYEARECAAYFAkISBcwACgkQYu1fMmOQldUg2QCgq1ATLCJWqAS7SBsHpcXTduma xjMAoII+AzDwkp2F2NZvw4PUrBUx+GDh =Yqjf -----END PGP SIGNATURE----- From claudio.grondi at freenet.de Sun Feb 6 19:45:43 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 7 Feb 2005 00:45:43 -0000 Subject: IPython colors in windows References: <36hculF51ho2sU1@individual.net> <1107530489.308497.103530@g14g2000cwa.googlegroups.com> <36hrjpF4ui8fbU1@individual.net> <36i84qF52ce29U1@individual.net> <36l1dgF52b9d6U1@individual.net> <4205605f_2@news.unc.edu> <42057751_1@news.unc.edu> <36n1gfF505tarU1@individual.net> Message-ID: <36nog9F4udan0U1@individual.net> Hi, I have just updated previously announced and uploaded to http://people.freenet.de/AiTI-IT/Python/Console.py version of Console.py because I was not satisfied with it (it didn't support arbitrary ANSI escape sequences for setting text colors ...) Now the Console() class supports ANSI escape sequences of the form ESC[#m and ESC[#,#m , so it is possible to set any colors for text and background via escape sequences. Resetting the colors with ESC[0m will set them back to initial(default) ones. Now it is also possible to send a _sequence_ of ANSI escape sequences to Console.write(). e.g. '\x1B[31m' '\x1B[1m' will cause later submitted text to be light red. Running Console.py creates coloured test output which can be checked for integrity. Any feedback is welcome. Claudio "Claudio Grondi" schrieb im Newsbeitrag news:36n1gfF505tarU1 at individual.net... > Hi, > > I have done some more work on Console.py > from the readline package version 1.12, adding > support for background colors and testing of proper > function of them (run the Console.py script to > see coloured output). > Added was also the possibility to set the default > text/background colors for colored output using: > Console.setStandardBackgroundColorTo(strColor) > Console.setStandardForegroundColorTo(strColor) > where strColor can be one of: > [ > '(dark)black' > ,'(dark)red', > ,'(dark)green' > ,'(dark)yellow' > ,'(dark)blue' > ,'(dark)purple' > ,'(dark)cyan' > ,'(dark)white' > ,'light black' > ,'light red' > ,'light green' > ,'light yellow' > ,'light blue' > ,'light purple' > ,'light cyan' > ,'light white' > ] > > There are some comments added where e.g. > the colors are named including their HTML color > notation to clarify which colors are displayed. > I work on Windows 2000 SP 4, so it will be > interesting for me to get some feedback if the > colors are the same in other Windows versions. > Which colors are displayed on Linux/Unix by > the native readline? > > There are also some other changes done to > make the code better readable (from my > personal point of view ;-) > > The blnIPythonFixActive flag allows to set colored > text output of IPython to (dark)white background > (instead of the standard one, which is in my > Console the 'light white' one i.e. I work with white > background as IDLE does). > > Another modification is, that when a text without > escape sequences is passed to Console.write(), > no escape sequences are sent, so, that the > colouring stays the same until it is explicitely > reset. I find this behaviour more strightforward > than the implicit writing of texts in the standard > colors if no colors are specified. > > If someone is interested to check it out I have > uploaded it to: > http://people.freenet.de/AiTI-IT/Python/Console.py > > The extended Console.py module can be used > standalone for writing of any coloured texts > to the console using alternatively . > Console.setStandardBackgroundColorTo(strColor) > Console.setStandardForegroundColorTo(strColor) > with resetting the colors > or the build-in ANSI escape sequences for the > text and the background. > > Utilizing the code or some parts of it in > the next release of readline is welcome. > > Claudio > > "Gary Bishop" schrieb im Newsbeitrag > news:42057751_1 at news.unc.edu... > > On SourceForge you will find release 1.12 of my Python readline > > module. If you don't want to hack the colors, there is no reason to > > upgrade from 1.11 to 1.12. They *should* work the same. > > > > But if you'd like to hack the iPython colors this new version makes it > > possible. In your ipythonrc file add a line like: > > > > execfile hackcolors.py > > > > Now in hackcolors.py you can change colors and backgrounds like this: > > > > ####hackcolors.py#### > > import readline > > > > # reach deep into the bowels of readline to get the color table > > escape_to_color = readline.rl.console.escape_to_color > > > > # change a color > > escape_to_color['0;32'] = 0x72 > > > > del escape_to_color > > del readline > > > > ################# > > > > The two hex digits are the background and foreground color > > respectively. In the example above I'm setting the color to green on a > > grey background. Here is the table that is normally used to translate > > colors. > > > > escape_to_color = { '0;30': 0x0, #black > > '0;31': 0x4, #red > > '0;32': 0x2, #green > > '0;33': 0x4+0x2, #brown? > > '0;34': 0x1, #blue > > '0;35': 0x1+0x4, #purple > > '0;36': 0x2+0x4, #cyan > > '0;37': 0x1+0x2+0x4, #grey > > '1;30': 0x1+0x2+0x4, #dark gray > > '1;31': 0x4+0x8, #red > > '1;32': 0x2+0x8, #light green > > '1;33': 0x4+0x2+0x8, #yellow > > '1;34': 0x1+0x8, #light blue > > '1;35': 0x1+0x4+0x8, #light purple > > '1;36': 0x1+0x2+0x8, #light cyan > > '1;37': 0x1+0x2+0x4+0x8, #white > > '0': None, > > } > > > > An interested party should be able to arbitrarily map colors and their > > backgrounds. > > > > Enjoy, > > gb > > > > From wweston at att.net Tue Feb 1 14:25:25 2005 From: wweston at att.net (wes weston) Date: Tue, 01 Feb 2005 19:25:25 GMT Subject: How do you do arrays In-Reply-To: References: Message-ID: Thomas Bunce wrote: > I am new at Pyton and I am learning from book not classes > so please forgive my being slow > > The below does not work I get an Error of File > "Matrix[index] = k > NameError: name 'iMatrix' is not defined" > > while index < majorlop1: > index = index + 1 > k = random.choice(listvalues) + 1 > iMatrix[index] = k > > The book statement of > array(typecode, initializer) does not make sence > to me how it henerates ore relaes to the org name > for the array. > > Thank You > Tom Thomas, You can do >>> m = [4] >>> m [4] wes From tjreedy at udel.edu Mon Feb 28 13:43:53 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Feb 2005 13:43:53 -0500 Subject: Python - what is the fastest database ? References: <1109592623.116661.101880@g14g2000cwa.googlegroups.com> Message-ID: wrote in message news:1109592623.116661.101880 at g14g2000cwa.googlegroups.com... >> How is it possible that google (super big database) is super fast? > What type database do they use / software ? On the hardware side, Google's secret is massively parallel cluster computing, coupled with proprietary software for splitting tasks and joining results. They have perhaps 200,000 CPUs. A query might be given to hundreds of them for a fraction of a second. Terry J. Reedy From paddy3118 at netscape.net Fri Feb 18 05:57:45 2005 From: paddy3118 at netscape.net (paddy3118 at netscape.net) Date: 18 Feb 2005 02:57:45 -0800 Subject: combining several lambda equations References: <2ae25c6b.0502180224.3d6164a7@posting.google.com> Message-ID: <1108724265.565392.192590@c13g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Paddy McCarthy wrote: > > > #If given:two or more lambda equations > > x=lambda : A < B > > y=lambda : C+6 >= 7 > > > > How do I create another lambda expression Z equivalent to > > > > Z=lambda : (A=7) > > > > # i.e. the anding together of the originals, but without referencing > > # globals x and y as they are artificial in that I will start of with > > # probably a list of lambda equations. > > x=lambda : A < B > y=lambda : C+6 >= 7 > Z=lambda x=x, y=y: x() and y() > del x, y > > Thanks Frederik. I actually have a set of lambdas so my use will be more like: >>> s = set([lambda : A < B, lambda : C+6 >= 7]) >>> x=s.pop(); y=s.pop() >>> Z=lambda x=x, y=y: x() and y() >>> del x,y >>> A,B,C = [2,3,1] >>> Z() True >>> A,B,C = [2,3,0] >>> Z() False >>> A,B,C = [3,3,1] >>> Z() False >>> - Gosh, isn't life fun! - Pad. From ncoghlan at iinet.net.au Sat Feb 5 11:54:03 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 06 Feb 2005 02:54:03 +1000 Subject: variable declaration In-Reply-To: References: <4202A022.3050209@netscape.net> Message-ID: <4204FA2B.6030803@iinet.net.au> Alexander Zatvornitskiy wrote: > var epsilon=0 > var S > S=0 > while epsilon<10: > S=S+epsilon > epselon=epsilon+1#interpreter should show error here,if it's in "strict mode" > print S > > It is easy, and clean-looking. > > Alexander, zatv at bk.ru An alternate proposal, where the decision to request rebinding semantics is made at the point of assignment: epsilon = 0 S = 0 while epsilon < 10: S .= S + epsilon epselon .= epsilon + 1 #interpreter should show error here print S Of course, this is a bad example, since '+= ' can be used already: S = 0 epsilon = 0 while epsilon<10: S += epsilon epselon += 1 #interpreter DOES show error here print S However, here's an example where there is currently no way to make the rebinding intent explicit: def collapse(iterable): it = iter(iterable) lastitem = it.next() yield lastitem for item in it: if item != lastitem: yield item lastitem = item With a rebinding operator, the intent of the last line can be made explicit: def collapse(iterable): it = iter(iterable) lastitem = it.next() yield lastitem for item in it: if item != lastitem: yield item lastitem .= item (Note that doing this *will* slow the code down, though, since it has to check for the existence of the name before rebinding it) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From justaskme at if.you.want.to.contact.me Tue Feb 8 06:29:04 2005 From: justaskme at if.you.want.to.contact.me (Joe) Date: Tue, 08 Feb 2005 12:29:04 +0100 Subject: Big development in the GUI realm References: <200502072347.j17NlPnh012281@mail07.syd.optusnet.com.au> Message-ID: <3r7h01tsdc0m04nuclqp4aadd80vu77q58@4ax.com> On Tue, 8 Feb 2005 10:01:51 +0100, "Fredrik Lundh" wrote: >except that if *you* set things up so the code is combined when run, *you* are >copying, distributing, and/or modifying the program in order to mix, include and/or >combine your work with the GPL:ed work. > >if you leave all that to the user, you're clear. Mmm... I'm not playing games here, no matter what some seem to think. It's obvious that the GPL doesn't say precisely whether it's OK to use an _independent_ library or EXE, ie. a file that is physically different from the calling EXE, as oppposed to either copy/pasting the code as is into a program, or statically linking a library into an EXE. Until now, I understood the GPL to be a way to make sure no one stole code (hence, no static linking or copy/pasting code), and with or without giving back any change they made. OTOH, I though it was OK to use the by code shipping whatever standard binary file was downloaded from the project's site, ie. MYEXE.EXE calling YOURCODE.DLL was OK, when this code was the standard version, untampered, and clearly indicated as not the EXE's work (as shown by the file name and version infos). Hence, either the GPL was not precise enough, or TrollTech should use a different license that specifically prohibits even using Qt through dynamic linking. Conclusion from what I read above: As of now, no court in any country has settled this issue by specifying whether making use of a GPLed program _in any way_ requires the calling program to be GPLed as well, or if there are cases where the EXE can remain closed-source. I'm fine with TT's intentions, though. Joe (no, I don't want whatever stuff I post on the Net to possibly bite me years from now, hence the anonymous posting. Nothing personal.) From fakeadmin at gmail.com Fri Feb 11 01:27:11 2005 From: fakeadmin at gmail.com (rhat) Date: 10 Feb 2005 22:27:11 -0800 Subject: Unit Testing in Python In-Reply-To: References: <1108087841.271630.228970@o13g2000cwo.googlegroups.com> Message-ID: <1108103231.850267.325300@z14g2000cwz.googlegroups.com> I actually meant to link to the last two ONLamp articles you mentioned, so yeah I have seen those (kinda forgot to post them, in fact). Thanks for the other links too, they look pretty interesting. Incidentally, what kind of projects are you guys (planning on) using this technology with? I'm working on educational software, and thought that it might be neat to try unittest out on. Though, in truth, I don't know enough about unit-testing to make a design decision that large yet. Feel free to [reply | flame the n00b], Ryan Kaulakis From elena at monmouth.com Thu Feb 17 18:51:47 2005 From: elena at monmouth.com (elena at monmouth.com) Date: 17 Feb 2005 15:51:47 -0800 Subject: Help with research Message-ID: <1108684307.612656.92010@c13g2000cwb.googlegroups.com> Apologies for this off-topic post. I'm a Java/C++ developer who is also studying psychology. I would really appreciate it if you would complete a survey that I'm using for a research project on programmers. It's easy [Yes/No answers] and takes about 5 minutes. I will be presenting the results at the American Psychological Association convention in August. The study link is: http://www.elena.com The survey measures "cognitive style" (analytical/intuitive) which describes how you process information and learn. The people I've pre-tested it with found it to be pretty interesting. I can go to my friends, however it occurred to me that it might be better to post in a newsgroup and get a larger, more diverse, and random sample. Thanks again for your time, Elena From frans.englich at telia.com Sat Feb 19 18:19:41 2005 From: frans.englich at telia.com (Frans Englich) Date: Sat, 19 Feb 2005 23:19:41 +0000 Subject: Distutils: relative paths Message-ID: <200502192319.41360.frans.englich@telia.com> Hello, I have trouble installing a data directory which is not a child of my package directory in the source directory. My source directory looks like this: ./setup.py schemas/*.xsd foo/*.py And when it's installed, it should look like: site-packages/foo/*.py site-packages/foo/schemas/*.xsd In other words, schemas, from being a sibling of foo, became a child of foo. Now, how is this expressed in the setup.py? I tried this: setup( name="Foo", packages=["foo"], package_data={ "foo": ["../schemas/*.xsd"] }, package_dir={ "foo": "foo"}, [...] but it resulted in schemas being a package, not child of foo(!). I've read the relevant page in the reference manual, http://www.python.org/doc/current/dist/node11.html but I can't find the trick. Any ideas? Cheers, Frans From mt at 3planes.com Tue Feb 1 11:34:47 2005 From: mt at 3planes.com (Michael Tobis) Date: 1 Feb 2005 08:34:47 -0800 Subject: pythonic equivalent of Mathematica's FixedPoint function References: <1107273234.276714.272890@z14g2000cwz.googlegroups.com> <1107273715.614766.32810@f14g2000cwb.googlegroups.com> Message-ID: <1107275687.426288.166820@f14g2000cwb.googlegroups.com> We apologise for the previous apology. http://arago4.tn.utwente.nl/stonedead/albums-cds/sketches/another-monty-python-record/apologies.html -- mt From harlinseritt at yahoo.com Wed Feb 16 08:01:12 2005 From: harlinseritt at yahoo.com (Harlin) Date: 16 Feb 2005 05:01:12 -0800 Subject: Compiler In-Reply-To: References: <420990CF.7000705@ocf.berkeley.edu> Message-ID: <1108556997.434279.137450@g14g2000cwa.googlegroups.com> Easy, easy... Use py2exe: http://starship.python.net/crew/theller/py2exe/ From has.temp2 at virgin.net Wed Feb 9 18:57:10 2005 From: has.temp2 at virgin.net (has) Date: 9 Feb 2005 15:57:10 -0800 Subject: A great Alan Kay quote In-Reply-To: <420a5c1e$0$21630$a1866201@visi.com> References: <420a5c1e$0$21630$a1866201@visi.com> Message-ID: <1107993430.712644.298500@f14g2000cwb.googlegroups.com> Grant Edwards wrote: > In an interview at http://acmqueue.com/modules.php?name=Content&pa=showpage&pid=273 > Alan Kay said something I really liked, and I think it applies > equally well to Python as well as the languages mentioned: > > I characterized one way of looking at languages in this > way: a lot of them are either the agglutination of features > or they're a crystallization of style I'd say Python is somewhere in the middle, though moving slowly towards 'agglutination' in the last couple years. > The rest of the interview is pretty interesting as well. Excellent link, thanks. From rbt at athop1.ath.vt.edu Fri Feb 18 17:44:37 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Fri, 18 Feb 2005 17:44:37 -0500 Subject: re.compile and very specific searches In-Reply-To: <1108758810.163024.169750@g14g2000cwa.googlegroups.com> References: <1108758810.163024.169750@g14g2000cwa.googlegroups.com> Message-ID: <42166FD5.2070106@athop1.ath.vt.edu> John Machin wrote: > Diez B. Roggisch wrote: > > > >>So I'd suggest you dump re and do it like this: >> >>address = "192.168.1.1" >> >>def validate_ip4(address): >> digits = address.split(".") >> if len(digits) == 4: >> for d in digits: >> if int(d) < 0 or int(d) > 255: >> return False >> return True >> > > > The OP wanted to "find" IP addresses -- unclear whether re.search or > re.match is required. Your solution doesn't address the search case. > For the match case, it needs some augmentation. It will fall apart if > presented with something like "..." or "comp.lang.python.announce". AND > while I'm at it ... in the event of a valid string of digits, it will > evaluate int(d) twice, rather unnecessarily & uglily. > > So: match case: > > ! for s in strings_possibly_containing_digits: > ! # if not(s.isdigit() and 0 <= int(s) <= 255): # prettier, but test > on zero is now redundant > ! if not s.isdigit() or int(s) > 255: > > and the search case: DON'T dump re; it can find highly probable > candidates (using a regexp like the OP's original or yours) a damn > sight faster than anything else this side of C or Pyrex. Then you > validate the result, with a cut-down validator that relies on the fact > that there are 4 segments and they contain only digits: This is what I ended up doing... re.compile and then findall(data) does an excellent job finding all strings that look like ipv4 addys, then the split works just as well in weeding out strings that are not actual ipv4 addys. Thanks to all for the advice! From rt-announce-bounces at lists.bestpractical.com Fri Feb 11 00:08:35 2005 From: rt-announce-bounces at lists.bestpractical.com (rt-announce-bounces at lists.bestpractical.com) Date: Fri, 11 Feb 2005 00:08:35 -0500 Subject: Your message to RT-Announce awaits moderator approval Message-ID: Your mail to 'RT-Announce' with the subject Is delivered mail Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://lists.bestpractical.com/cgi-bin/mailman/confirm/rt-announce/3b837be742e4def446d41a87c444e0c8d91c18b4 From moa at extrapolation.com Wed Feb 2 18:48:00 2005 From: moa at extrapolation.com (moa at extrapolation.com) Date: 2 Feb 2005 15:48:00 -0800 Subject: Reinstall python 2.3 on OSX 10.3.5? Message-ID: <1107388080.703032.116150@g14g2000cwa.googlegroups.com> Hi there I started a very long and roundabout process of attempting to install python 2.3.4 along side my apple-installed 2.3 system. To make a long story short, I have completely confabulated my environment ( i deleted the 2.3 binaries and so forth from the system in an attempt to start things fresh), and now I cannot figure out how to reinstall the base 2.3 Apple python distribution. Can somebody please point me in the right direction? best -Nick From tchur at optushome.com.au Mon Feb 7 20:22:45 2005 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 08 Feb 2005 12:22:45 +1100 Subject: Big development in the GUI realm Message-ID: <200502080122.j181MjPL005569@mail22.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From lordchaica at free.fr Mon Feb 7 12:40:02 2005 From: lordchaica at free.fr (chaica) Date: Mon, 07 Feb 2005 17:40:02 +0000 Subject: Tar module issue In-Reply-To: References: Message-ID: <1107798002.4774.25.camel@desktop> Thx for your response. The fact is that I use tar.close() at the end of my code. This is really a random behaviour cause with an archive which has a short directory tree, I don't have this kind of beahavior and the archive works. thx On Mon, 2005-02-07 at 13:01 +0000, Russell Bungay wrote: > Hello, > > > I'm using tarfile module to create an archive. For my example I'm using > > Amsn file and directory tree. > > My variables are like these ones: > > path = /home/chaica/downloads/amsn-0_94/skins/Tux/smileys/shades.gif > > fileName = amsn-0_94/skins/Tux/smileys/shades.gif > > tar.add( path, fileName ) > > and while untaring my archive with tar jxvf I've random errors : > > tar: amsn-0_94/lang/genlangfiles.c: Cannot hard link to > > `amsn-0_94/lang/genlangfiles.c': No such file or directory > > I checked google and saw that errors like these ones could occur when > > you use global path while taring, but I'm not, using fileName which is > > local. > > I used tarfile for the first time at the weekend and noticed one thing > that may help. I don't know if it is a specific solution to your > problem, but it might be worth a try. > > I noticed that if I didn't explicitly close the tarfile with tar.close() > after I had added the files, the resultant file would sometimes not be > written properly (even with completed execution of the whole script). > Explicitly closing the file would make these problems go away. > > I hope that helps, > > R -- chaica From usenet_spam at janc.invalid Wed Feb 2 20:20:36 2005 From: usenet_spam at janc.invalid (JanC) Date: Thu, 03 Feb 2005 01:20:36 GMT Subject: python and gpl References: <7xy8e8vnza.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schreef: > My IANAL amateur reading is that the GPL does in fact apply, at least > in the US. Running the program is not restricted, but loading the > program from disk to memory before you can run it counts as copying > it, which invokes the license, Computer Associates v. Altai, 982 F.2d > 693. I personally believe that doctrine is insane, but that's what > software companies pushed through the courts in order to make > shrink-wrap EULA's enforceable. (Otherwise they'd only be enforceable > if you agreed to the terms before the vendor got your money). In Belgium (and the whole EU, I think) copying a program from disk to memory to be able to run it is covered under "fair use" (just like copying digital data from an audio CD to a DAC to be able to listen to it is fair use), which can't be restricted by companies. AFAIK. IANAL. Etc. ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From jack at performancedrivers.com Tue Feb 15 18:27:59 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Tue, 15 Feb 2005 18:27:59 -0500 Subject: Can __new__ prevent __init__ from being called? In-Reply-To: <87is4tldea.fsf@news2.ososo.de> References: <87is4tldea.fsf@news2.ososo.de> Message-ID: <20050215232759.GB11812@performancedrivers.com> On Tue, Feb 15, 2005 at 10:30:21PM +0100, Felix Wiemann wrote: > Sometimes (but not always) the __new__ method of one of my classes > returns an *existing* instance of the class. However, when it does > that, the __init__ method of the existing instance is called > nonetheless, so that the instance is initialized a second time. For > example, please consider the following class (a singleton in this case): > > >>> class C(object): > ... instance = None > ... def __new__(cls): > ... if C.instance is None: > ... print 'Creating instance.' > ... C.instance = object.__new__(cls) > ... print 'Created.' > ... return cls.instance > ... def __init__(self): > ... print 'In init.' > ... > How can I prevent __init__ from being called on the already-initialized > object? > Is there an easier way than using a metaclass and writing a custom > __call__ method? The standard recipe is to define an alternate init method and call it once when you instantiate the object (I couldn't find it on ASPN though). Here is a cut-n-paste from production code. The work normally done in the magic __init__() is done in init() instead. class Page(context.AppContext): """the One True Singleton """ _single = None # our singleton reference def __new__(cls, *args, **opts): if (Page._single is None): Page._single = object.__new__(cls) Page._single.init(*args, **opts) return Page._single def __init__(self, *args, **opts): """We are a singleton, so setup is done just once in init() because __init__() will be called every time the singleton is re-issued This __init__ just prevents our parent's __init__'s from running other than when told to by our init() """ return def init(self, req = None): """setup Db objects, cgi params etc Here is also where we decide if we are being run from the command line or in mod_python""" context.AppContext.__init__(self, req) # lots of initialization done here return Page is a singleton but it inherits from the class context.AppContext which is just a regular class. The empty Page.__init__ doesn't call the context.AppContext.__init__ but the once-only Page.init does. Hope that helps, -Jack From sjmachin at lexicon.net Fri Feb 25 18:17:58 2005 From: sjmachin at lexicon.net (John Machin) Date: 25 Feb 2005 15:17:58 -0800 Subject: Splitting strings - by iterators? In-Reply-To: References: <38913oF5mi8arU2@individual.net> Message-ID: <1109373478.706104.174080@o13g2000cwo.googlegroups.com> Jeremy Sanders wrote: > On Fri, 25 Feb 2005 17:14:24 +0100, Diez B. Roggisch wrote: > > > Maybe [c]StringIO can be of help. I don't know if it's iterator is lazy. But > > at least it has one, so you can try and see if it improves performance :) > > Excellent! I somehow missed that module. StringIO speeds up the iteration > by a factor of 20! > Twenty?? StringIO.StringIO or cStringIO.StringIO??? I did some "timeit" tests using the code below, on 400,000 lines of 53 chars (uppercase + lowercase + '\n'). On my config (Python 2.4, Windows 2000, 1.4 GHz Athlon chip, not short of memory), cStringIO took 0.18 seconds and the "hard way" took 0.91 seconds. Stringio (not shown) took 2.9 seconds. FWIW, moving an attribute look-up in the (sfind = s.find) saves only about 0.1 seconds. >python -m timeit -s "import itersplitlines as i; d = i.mk_data(400000)" "i.test_csio(d)" 10 loops, best of 3: 1.82e+005 usec per loop >python -m timeit -s "import itersplitlines as i; d = i.mk_data(400000)" "i.test_gen(d)" 10 loops, best of 3: 9.06e+005 usec per loop A few questions: (1) What is your equivalent of the "hard way"? What [c]StringIO code did you use? (2) How did you measure the time? (3) How long does it take *compile* your 400,000-line Python script? !import cStringIO ! !def itersplitlines(s): ! if not s: ! yield s ! return ! pos = 0 ! sfind = s.find ! epos = len(s) ! while pos < epos: ! newpos = sfind('\n', pos) ! if newpos == -1: ! yield s[pos:] ! return ! yield s[pos:newpos+1] ! pos = newpos+1 ! !def test_gen(s): ! for z in itersplitlines(s): ! pass ! !def test_csio(s): ! for z in cStringIO.StringIO(s): ! pass ! !def mk_data(n): ! import string ! return (string.lowercase + string.uppercase + '\n') * n From seberino at spawar.navy.mil Wed Feb 2 01:09:34 2005 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 1 Feb 2005 22:09:34 -0800 Subject: How run valgrind on Python C extensions? Message-ID: <1107324574.108521.183170@z14g2000cwz.googlegroups.com> I have Python C extensions that are giving me seg faults that I'd like to run valgrind on. Can I use valgrind on these through python?? HOW??? Is it easy or must I do some work like recompiling python source with the -g extension? Thanks! Chris From pythonista at gmail.com Tue Feb 1 14:22:35 2005 From: pythonista at gmail.com (Sean Blakey) Date: Tue, 1 Feb 2005 11:22:35 -0800 Subject: How do you do arrays In-Reply-To: References: Message-ID: <372a7624050201112229973af8@mail.gmail.com> On Tue, 01 Feb 2005 10:52:45 -0800, Thomas Bunce wrote: > I am new at Pyton and I am learning from book not classes > so please forgive my being slow > > The below does not work I get an Error of File > "Matrix[index] = k > NameError: name 'iMatrix' is not defined" > > while index < majorlop1: > index = index + 1 > k = random.choice(listvalues) + 1 > iMatrix[index] = k > > The book statement of > array(typecode, initializer) does not make sence > to me how it henerates ore relaes to the org name > for the array. > > Thank You > Tom > -- > http://mail.python.org/mailman/listinfo/python-list > Like any other variable, you need to declare iMatrix before you use it: $ python Python 2.4 (#1, Dec 28 2004, 12:08:51) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import random >>> import array >>> index = 0 >>> majorlop1 = 4 >>> iMatrix = array.array('b') >>> listvalues = [1, 2, 3, 4] >>> while index < majorlop1: ... index = index + 1 ... k = random.choice(listvalues) + 1 ... iMatrix.append(k) ... >>> iMatrix array('b', [3, 5]) >>> You should probably look at the wealth of information at http://www.python.org/doc - the tutorial is a good start on how to use the language, and the library reference has much more depth on the array module. http://docs.python.org/lib/module-array.html -- Sean Blakey Saint of Mild Amusement, Evil Genius, Big Geek Python/Java/C++/C(Unix/Windows/Palm/Web) developer quine = ['print "quine =",quine,"; exec(quine[0])"'] ; exec(quine[0]) From cdieterich at geosci.uchicago.edu Wed Feb 2 23:08:38 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Wed, 2 Feb 2005 22:08:38 -0600 Subject: Finding user's home dir In-Reply-To: <5i9rtc.rq31.ln@orion.homeinvalid> Message-ID: <4808964F-7599-11D9-AA01-000A9582377C@geosci.uchicago.edu> On D? C?adaoin, Feabh 2, 2005, at 13:26 America/Chicago, Nemesis wrote: > Hi all, I'm trying to write a multiplatform function that tries to > return the actual user home directory. I saw that > Please, could you test it on your systems and tell me what you got? > I'd like to know what it returns on different operating systems because > I'm developing a multiplatform software. It works with Python 2.2 and Python 2.3 on Mac OS 10.2 and Debian Linux. Christian From dbasch at yahoo.com Fri Feb 4 15:27:13 2005 From: dbasch at yahoo.com (Derek Basch) Date: Fri, 4 Feb 2005 12:27:13 -0800 (PST) Subject: CGI and HTTP Header Location redirects Message-ID: <20050204202713.36107.qmail@web20828.mail.yahoo.com> Ahhhh... I should have been more specific before. The Apache error log doesn't produce an error. You are probably correct that it is most likely an Apache/Unix problem. I thought perhaps someone had maybe run into this before since it seems like such a basic function to not work. Thanks for the help. Paul Rubin wrote: > Derek Basch writes: > >>Also, after enabling suEXEC on the apache server the script executes >>perfectly with the redirect. Can anyone explain this behavior? I >>would guess that it is related to apache user rights but I can't >>find any reference to such problems via Google. > > > Apache probably isn't able to run the cgi because of lack of exec > permission or something like that. The best way to diagnose such > probs is by checking the apache error log, if you have access to it. > > Best newsgroup for this type of question is > comp.infosystems.www.servers.unix. Lots of apache experts hang out there. __________________________________ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250 From aahz at pythoncraft.com Tue Feb 8 21:51:16 2005 From: aahz at pythoncraft.com (Aahz) Date: 8 Feb 2005 21:51:16 -0500 Subject: An Ode To My Two Loves References: <8665128pkv.fsf@guru.mired.org> Message-ID: In article <8665128pkv.fsf at guru.mired.org>, Mike Meyer wrote: > >COM is dominant on Windows because MS pushes it. CORBA isn't dominant >on Unix because there are a slew of extensible/embeddable languages to >pick from instead - assuming the apps in question came up with a >solution better than rolling their own. See http://www.mired.org:8080/home/mwm/scripting/ > for my thoughts on the >matter before I learned better. "Unable to connect to host" -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "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." --GvR From brown at esteem.com Wed Feb 9 12:18:51 2005 From: brown at esteem.com (Tom Brown) Date: Wed, 9 Feb 2005 09:18:51 -0800 Subject: win32 service and sockets In-Reply-To: <200502081641.37483.brown@esteem.com> References: <200502081641.37483.brown@esteem.com> Message-ID: <200502090918.51709.brown@esteem.com> On Tuesday 08 February 2005 16:41, Tom Brown wrote: > Hi, > > I created a win32 service for XPPro called N4010ATestService.py (see > below). The service runs as a particular user with administrative rights. > It starts a thread that creates a simple socket server > (N4010ASocketServer.py -- also below) that just waits for 20 character > string. When I run the socket server by itself the test client can connect > to the server and send a 20 character string just fine. When I run the > service, the server will bind to the port but the client cannot connect. I > verified the server was listening on the given port using netstat -an. The > client eventually times out. Why isn't the server accepting connections > when run in a service? > > Thanks, > Tom > Well, I have found that it works if I launch the client on the same machine as the service. It will not work from a remote machine. Any ideas? Thanks, Tom From tzot at sil-tec.gr Tue Feb 22 05:27:41 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 22 Feb 2005 12:27:41 +0200 Subject: Memory Based File Objects References: Message-ID: On 22 Feb 2005 02:06:52 -0800, rumours say that michael.bierenfeld at web.de (michael) might have written: >The Image >Documentation says that file object just has to implement seek, tell >and write. Does anybody have an example how to do that or maybe a >snipplet for an "In Memory" File Object with an unknown size. You probably need the StringIO (or cStringIO) module. Check the module reference. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From mfranklin1 at gatwick.westerngeco.slb.com Thu Feb 3 06:07:48 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 03 Feb 2005 11:07:48 +0000 Subject: convert ftp.retrbinary to file object? - Python language lacks expression? In-Reply-To: <19804fd8.0502030208.10ace31e@posting.google.com> References: <19804fd8.0502030208.10ace31e@posting.google.com> Message-ID: Robert wrote: > I just tried to convert a (hugh size) ftp.retrbinary run into a > pseudo-file object with .read(bytes) method in order to not consume > 500MB on a copy operation. > > First I thought, its easy as usual with python using something like > 'yield' or so. > > Yet I didn't manage to do (without using threads or rewriting > 'retrbinary')? Any ideas? > > #### I tried a pattern like: > .... > def open(self,ftppath,mode='rb'): > class FTPFile: #TODO > ... > def iter_retr() > ... > def callback(blk): > how-to-yield-from-here-to-iter_retr blk??? > ftp.retrbinary("RETR %s" % relpath,callback) > def read(self, bytes=-1): > ... > self.buf+=self.iter.next() > ... > .... Hmmmm this is nearly there I think...: import ftplib class TransferAbort(Exception): pass class FTPFile: def __init__(self, server, filename): self.server = server self.filename = filename self.offset = 0 def callback(self, data): self.offset = self.offset + len(data) self.data = data ## now quit the RETR command? raise TransferAbort("stop right now") def read(self, amount): self.ftp = ftplib.FTP(self.server) self.ftp.login() try: self.ftp.retrbinary("RETR %s" %self.filename, self.callback, blocksize=amount, rest=self.offset) except TransferAbort: return self.data f = FTPFile("HOSTNAME", "FILENAME") print f.read(24) print f.read(24) I open the ftp connection inside the read method as it caused an error (on the second call to read) when I opened it in __init__ ??? HTH Martin From richie at entrian.com Thu Feb 3 06:44:21 2005 From: richie at entrian.com (Richie Hindle) Date: Thu, 03 Feb 2005 11:44:21 +0000 Subject: IDLE history, Python IDE, and Interactive Python with Vim In-Reply-To: References: Message-ID: [Ashot] > I have been frustrated for quite some time with a lack of a history > command in IDLE To recall a line from your history in IDLE, cursor up to that line and hit Enter. > I've tried something called pyCrust, but this too didn't have history To recall a line from your history in PyCrust, press Ctrl+UpArrow. -- Richie Hindle richie at entrian.com From plb at iotk.com Tue Feb 8 08:08:26 2005 From: plb at iotk.com (plb) Date: 8 Feb 2005 05:08:26 -0800 Subject: Handling import conflicts when module has the same name as a library module that it needs to import? Message-ID: <1107866095.314395.251150@z14g2000cwz.googlegroups.com> All: I am struggling with an import problem... In my package, myapp, there is a module called logging. This module, naturally, imports the standard library module logging. However, when I try 'import myapp.logging', the 'import logging' statement appears to be finding the myapp.logging module instead of the one in the standard library. How can I ensure that my logging module doesn't try to import itself? --PLB From farcepest at gmail.com Fri Feb 25 13:35:00 2005 From: farcepest at gmail.com (Andy Dustman) Date: 25 Feb 2005 10:35:00 -0800 Subject: Trouble with mysql-python 1.2.0 on Solaris 8 sparc In-Reply-To: <1109255132.541839.207530@o13g2000cwo.googlegroups.com> References: <1108755202.574729.293610@g14g2000cwa.googlegroups.com> <1108925639.345790.230510@c13g2000cwb.googlegroups.com> <1109255132.541839.207530@o13g2000cwo.googlegroups.com> Message-ID: <1109356500.327655.279600@z14g2000cwz.googlegroups.com> What happens when you try to connect? Be sure to check /etc/hosts.allow and .deny on the server, if your server is compiled with TCP wrapper support. From FBatista at uniFON.com.ar Wed Feb 9 08:53:45 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 9 Feb 2005 10:53:45 -0300 Subject: Big development in the GUI realm Message-ID: [Carlos Ribeiro] #- 'onegui' to rule them all... I would really love to use a GUI made by elves... . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rbt at athop1.ath.vt.edu Tue Feb 22 11:31:16 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Tue, 22 Feb 2005 11:31:16 -0500 Subject: searching pdf files for certain info In-Reply-To: References: Message-ID: Tom Willis wrote: > I tried that for something not python related and I was getting > sporadic spaces everywhere. > > I am assuming this is not the case in your experience? > > > On Tue, 22 Feb 2005 10:45:09 -0500, rbt wrote: > >>Andreas Lobinger wrote: >> >>>Aloha, >>> >>>rbt wrote: >>> >>> >>>>Thanks guys... what if I convert it to PS via printing it to a file or >>>>something? Would that make it easier to work with? >>> >>> >>>Not really... >>>The classical PS Drivers (f.e. Acroread4-Unix print-> ps) simply >>>define the pdf graphics and text operators as PS commands and >>>copy the pdf content directly. >>> >>>Wishing a happy day >>> LOBI >> >>I downloaded ghostscript for Win32 and added it to my PATH >>(C:\gs\gs8.15\lib AND C:\gs\gs8.15\bin). I found that ps2ascii works >>well on PDF files and it's entirely free. >> >>Usage: >> >>ps2ascii PDF_file.pdf > ASCII_file.txt >> >>However, bundling a 9+ MB package with a 5K script and convincing users >>to install it is another matter altogether. >>-- >>http://mail.python.org/mailman/listinfo/python-list >> > > > For my purpose, it works fine. I'm searching for certain strings that might be in the document... all I need is a readable file. Layout, fonts and/or presentation is unimportant to me. From ashot at removemolsoftthis.com Thu Feb 3 19:37:09 2005 From: ashot at removemolsoftthis.com (Ashot) Date: Thu, 03 Feb 2005 18:37:09 -0600 Subject: IPython colors in windows Message-ID: I am using IPython in windows and the LightBG setting doesn't correctly because the background of the text is black even if the console background is white. Anyone know whats going on? Thanks. -- ============================== Ashot Petrosian University of Texas at Austin, Computer Sciences (views expressed are solely my own) ============================== From fperez.net at gmail.com Tue Feb 8 00:14:24 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Mon, 07 Feb 2005 22:14:24 -0700 Subject: IDLE history, Python IDE, and Interactive Python with Vim References: Message-ID: Ashot wrote: > yup, this is why I've been using it, its (almost exactly :) what I was looking > for. I had tried it before, but was reluctant to use it because the windows > terminal is not very appealing. Some things I've noticed so far that I think > could be improved, some of which are minor but annoying: I should note that I hardly use %edit myself, it's something that was added at the request of users, and is an OK facility for quick and dirty work. But getting such a system to work reliably in all cases, with the import/execfile/reload issues at play, is really not easy. Especially because it's not even completely clear what the 'right' behaviour should be. %edit makes a few educated guesses, but that's it. My personal coding environment consists of a permanently open editor with multiple files open (XEmacs in my case), and an ipython session open. In ipython, I use %run to run test code, and when said top-level test code relies on modules which are also being changed, I simply put into the top-level scripts reload() statements. This gives me the ipython tracebacks, experimentation, tab-exploration of objects, etc, while I have the full power of Xemacs for the real editing work. IPython is NOT an IDE, so I think it's important to understand its limitations to make the best possible use of it. Perhaps I haven't done a very good job of outlining this to users, I don't know. > edit doesn't work with classes even though it says it should, you have to > point it to a function in the class (perhaps only in windows) > > under windows vim/gvim doesn't jump to the line of the function.. you said > that this should work in vi, but I'm guessing its a Windows thing Works for jed/vim under linux, that's about as much as I know. Probably a win32 thing, as you say. > **the biggest problem for me is edit forgets code in which there were errors. > for example:"ed" type some nonsense, and ed -p doesn't remember. Thats > putting an awful lot of pressure on getting the syntax right everytime =] > Perhaps I am missing something here? Fixed. Will be in the next release, which will probably come out soon (I found an unrelated crash case, and I consider crashes release-triggering bugfixes). > it would be really great if the code executed on save rather than exit, but > I'm not sure if this is possible. This would be very useful for people using > an editor not in the console.. that way you wouldn't have to keep > opening/closing new editor windows. not possible in a cross-platform, cross-editor way. > this isn't a big deal, but it would be nice if there was an easy way to refer > to the entire history (for edit/save/etc) %hist has options to print as many lines as you want. And the %log* commands will dump all of your history straight to a file, and continue recording from then on. > would be nice if you could send stuff to the clipboard. Do you have a linux/OSX/win32 way to do it? If so, I'll gladly include it. Under *nix, mouse-highlighting copies to the X11 primary selection, which I can then paste anywhere with the middle button. > There are a few other things I'm probably forgetting, but having said all > that, I've come off a little negative here. I really like IPython so far, its > got all the things I was looking for, thank you very much for your work. If I > have the time in the future I would definately contribute to this project. No problem, I appreciate the comments. Fair, honest criticism can only make a project better. Note, however, that I _strongly_ suggest you post this kind of stuff on the ipython list. While I monitor c.l.py via gmane, I'm not subscribed and sometimes I'm too busy to read it for weeks at a time, so there's a very good chance I'll simply miss ipython-related posts here. The ipython lists, on the other hand, I keep a close eye on :) Best, f From mahs at telcopartners.com Thu Feb 17 17:01:14 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 17 Feb 2005 14:01:14 -0800 Subject: How to wrap a class's methods? In-Reply-To: <20050217194911.GF2366@grulic.org.ar> References: <4214f167$0$44618$a1866201@visi.com> <20050217194911.GF2366@grulic.org.ar> Message-ID: John Lenton wrote: > On Thu, Feb 17, 2005 at 07:32:55PM +0000, Grant Edwards wrote: > > I'd usually put big fat warnings around this code, and explain exaclty > why I need to do things this way... > > As a low-tech alternative, what about sourcecode generation, since you are targetting a python module? This gives two advantages vs the wrapping function: 1) the magic all occurs at coding time 2) the method signatures are documented. Michael import imaplib import inspect import types instancemethod = types.MethodType # The function template funcwrapper = \ """ def %(name)s%(argspec)s: s,r = imaplib.IMAP4_SSL.%(name)s%(callspec)s if s!='OK': raise NotOK((s,r)) return r""" # A helper function to get the template parameters def getargs(method): argspec = inspect.getargspec(method) callspec = tuple(argspec[:3] + (None,))# No default return {"name": method.__name__, "argspec": inspect.formatargspec(*argspec), "callspec": inspect.formatargspec(*callspec)} # Do the stuff manually: >>> obj = imaplib.IMAP4_SSL >>> attrnames = [meth for meth in dir(imaplib.IMAP4_SSL) if not meth.startswith("_")] >>> attributes = [getattr(obj, attrname) for attrname in attrnames] >>> methods = [attribute for attribute in attributes if inspect.ismethod(attribute)] >>> print "\n".join(funcwrapper % getargs(method) for method in methods) def append(self, mailbox, flags, date_time, message): s,r = imaplib.IMAP4_SSL.append(self, mailbox, flags, date_time, message) if s!='OK': raise NotOK((s,r)) return r def authenticate(self, mechanism, authobject): s,r = imaplib.IMAP4_SSL.authenticate(self, mechanism, authobject) if s!='OK': raise NotOK((s,r)) return r def check(self): s,r = imaplib.IMAP4_SSL.check(self) if s!='OK': raise NotOK((s,r)) return r def close(self): s,r = imaplib.IMAP4_SSL.close(self) if s!='OK': raise NotOK((s,r)) return r def copy(self, message_set, new_mailbox): s,r = imaplib.IMAP4_SSL.copy(self, message_set, new_mailbox) if s!='OK': raise NotOK((s,r)) return r def create(self, mailbox): s,r = imaplib.IMAP4_SSL.create(self, mailbox) if s!='OK': raise NotOK((s,r)) return r def delete(self, mailbox): s,r = imaplib.IMAP4_SSL.delete(self, mailbox) if s!='OK': raise NotOK((s,r)) return r def deleteacl(self, mailbox, who): s,r = imaplib.IMAP4_SSL.deleteacl(self, mailbox, who) if s!='OK': raise NotOK((s,r)) return r def expunge(self): s,r = imaplib.IMAP4_SSL.expunge(self) if s!='OK': raise NotOK((s,r)) return r def fetch(self, message_set, message_parts): s,r = imaplib.IMAP4_SSL.fetch(self, message_set, message_parts) if s!='OK': raise NotOK((s,r)) return r def getacl(self, mailbox): s,r = imaplib.IMAP4_SSL.getacl(self, mailbox) if s!='OK': raise NotOK((s,r)) return r def getquota(self, root): s,r = imaplib.IMAP4_SSL.getquota(self, root) if s!='OK': raise NotOK((s,r)) return r def getquotaroot(self, mailbox): s,r = imaplib.IMAP4_SSL.getquotaroot(self, mailbox) if s!='OK': raise NotOK((s,r)) return r def list(self, directory='""', pattern='*'): s,r = imaplib.IMAP4_SSL.list(self, directory, pattern) if s!='OK': raise NotOK((s,r)) return r def login(self, user, password): s,r = imaplib.IMAP4_SSL.login(self, user, password) if s!='OK': raise NotOK((s,r)) return r def login_cram_md5(self, user, password): s,r = imaplib.IMAP4_SSL.login_cram_md5(self, user, password) if s!='OK': raise NotOK((s,r)) return r def logout(self): s,r = imaplib.IMAP4_SSL.logout(self) if s!='OK': raise NotOK((s,r)) return r def lsub(self, directory='""', pattern='*'): s,r = imaplib.IMAP4_SSL.lsub(self, directory, pattern) if s!='OK': raise NotOK((s,r)) return r def myrights(self, mailbox): s,r = imaplib.IMAP4_SSL.myrights(self, mailbox) if s!='OK': raise NotOK((s,r)) return r def namespace(self): s,r = imaplib.IMAP4_SSL.namespace(self) if s!='OK': raise NotOK((s,r)) return r def noop(self): s,r = imaplib.IMAP4_SSL.noop(self) if s!='OK': raise NotOK((s,r)) return r def open(self, host='', port=993): s,r = imaplib.IMAP4_SSL.open(self, host, port) if s!='OK': raise NotOK((s,r)) return r def partial(self, message_num, message_part, start, length): s,r = imaplib.IMAP4_SSL.partial(self, message_num, message_part, start, length) if s!='OK': raise NotOK((s,r)) return r def print_log(self): s,r = imaplib.IMAP4_SSL.print_log(self) if s!='OK': raise NotOK((s,r)) return r def proxyauth(self, user): s,r = imaplib.IMAP4_SSL.proxyauth(self, user) if s!='OK': raise NotOK((s,r)) return r def read(self, size): s,r = imaplib.IMAP4_SSL.read(self, size) if s!='OK': raise NotOK((s,r)) return r def readline(self): s,r = imaplib.IMAP4_SSL.readline(self) if s!='OK': raise NotOK((s,r)) return r def recent(self): s,r = imaplib.IMAP4_SSL.recent(self) if s!='OK': raise NotOK((s,r)) return r def rename(self, oldmailbox, newmailbox): s,r = imaplib.IMAP4_SSL.rename(self, oldmailbox, newmailbox) if s!='OK': raise NotOK((s,r)) return r def response(self, code): s,r = imaplib.IMAP4_SSL.response(self, code) if s!='OK': raise NotOK((s,r)) return r def search(self, charset, *criteria): s,r = imaplib.IMAP4_SSL.search(self, charset, *criteria) if s!='OK': raise NotOK((s,r)) return r def select(self, mailbox='INBOX', readonly=None): s,r = imaplib.IMAP4_SSL.select(self, mailbox, readonly) if s!='OK': raise NotOK((s,r)) return r def send(self, data): s,r = imaplib.IMAP4_SSL.send(self, data) if s!='OK': raise NotOK((s,r)) return r def setacl(self, mailbox, who, what): s,r = imaplib.IMAP4_SSL.setacl(self, mailbox, who, what) if s!='OK': raise NotOK((s,r)) return r def setquota(self, root, limits): s,r = imaplib.IMAP4_SSL.setquota(self, root, limits) if s!='OK': raise NotOK((s,r)) return r def shutdown(self): s,r = imaplib.IMAP4_SSL.shutdown(self) if s!='OK': raise NotOK((s,r)) return r def socket(self): s,r = imaplib.IMAP4_SSL.socket(self) if s!='OK': raise NotOK((s,r)) return r def sort(self, sort_criteria, charset, *search_criteria): s,r = imaplib.IMAP4_SSL.sort(self, sort_criteria, charset, *search_criteria) if s!='OK': raise NotOK((s,r)) return r def ssl(self): s,r = imaplib.IMAP4_SSL.ssl(self) if s!='OK': raise NotOK((s,r)) return r def status(self, mailbox, names): s,r = imaplib.IMAP4_SSL.status(self, mailbox, names) if s!='OK': raise NotOK((s,r)) return r def store(self, message_set, command, flags): s,r = imaplib.IMAP4_SSL.store(self, message_set, command, flags) if s!='OK': raise NotOK((s,r)) return r def subscribe(self, mailbox): s,r = imaplib.IMAP4_SSL.subscribe(self, mailbox) if s!='OK': raise NotOK((s,r)) return r def thread(self, threading_algorithm, charset, *search_criteria): s,r = imaplib.IMAP4_SSL.thread(self, threading_algorithm, charset, *search_criteria) if s!='OK': raise NotOK((s,r)) return r def uid(self, command, *args): s,r = imaplib.IMAP4_SSL.uid(self, command, *args) if s!='OK': raise NotOK((s,r)) return r def unsubscribe(self, mailbox): s,r = imaplib.IMAP4_SSL.unsubscribe(self, mailbox) if s!='OK': raise NotOK((s,r)) return r def xatom(self, name, *args): s,r = imaplib.IMAP4_SSL.xatom(self, name, *args) if s!='OK': raise NotOK((s,r)) return r >>> From steve at myplace.com Sun Feb 20 20:04:00 2005 From: steve at myplace.com (Steve M) Date: Sun, 20 Feb 2005 19:04:00 -0600 Subject: Tuple index Message-ID: Hello, I'm trying to figure out the index position of a tuple member. I know the member name, but I need to know the members index position. I know that if I use the statement print tuple[4] that it will print the contents of that location. What I don't understand is if I know that foo is a member of tuple, how do I get foo's index position. Thanks-in-Advance Steve From cam.ac.uk at mh391.invalid Mon Feb 14 04:54:17 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 14 Feb 2005 09:54:17 +0000 Subject: - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <1108370491.792820.142200@z14g2000cwz.googlegroups.com> Message-ID: Ilias Lazaridis wrote: > "The Python Foundation could create an official sub-project to create an > automated build target based on the MinGW toolchain. I am sure that many > community members would be more than happy to contribute." An "official sub-project" for something like this is not necessary. Identify what needs to be done and create a patch, and it will be accepted if it is a good patch. -- Michael Hoffman From jeff at ccvcorp.com Wed Feb 16 14:19:28 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 16 Feb 2005 11:19:28 -0800 Subject: Why doesn't join() call str() on its arguments? In-Reply-To: <37hippF4gcimiU1@individual.net> References: <37hippF4gcimiU1@individual.net> Message-ID: <111773qkev2r045@corp.supernews.com> Leo Breebaart wrote: > What I can't find an explanation for is why str.join() doesn't > automatically call str() on its arguments [...] > [...] Presumably there is some > counter-argument involved, some reason why people preferred the > existing semantics after all. But for the life of me I can't > think what that counter-argument might be... One possibility I can think of would be Unicode. I don't think that implicitly calling str() on Unicode strings is desirable. (But then again, I know embarrassingly little about unicode, so this may or may not be a valid concern.) Of course, one could ensure that unicode.join() used unicode() and str.join() used str(), but I can conceive of the possibility of wanting to use a plain-string separator to join a list that might include unicode strings. Whether this is a realistic use-case is, of course, a completely different question... Jeff Shannon Technician/Programmer Credit International From softpro at gmx.net Sun Feb 6 08:06:43 2005 From: softpro at gmx.net (Johannes Ahl-mann) Date: Sun, 6 Feb 2005 14:06:43 +0100 Subject: bad generator performance References: Message-ID: > Um. Under my definition of "recursion", you haven't really removed > recursion in the generator version. That is, you're still calling the > depthFirstIterator method upon each iteration--you've just changed from > list-concatenation to yielding instead, which trades off list-management > overhead for closure-maintenance overhead. yup, i am aware that my generator version is also recursive. but what i thought this would do is "generate" a lazy list of return values (in theory at least). but this still doesn't explain why the yielding is so much slower than the list concatenation! > A truly non-recursive > implementation would probably exist outside of whatever class you've got > this method in, and would keep its own pointer to the current node as it > traversed the tree. i loved the generator solution because it was short, concise and lazy, but if i am going to write the closure/continuation/recursion handling manually i'd rather go with the memory-consuming list concatenation... a non-recursive solution to traversing a recursive data type is bound to get ugly, isn't it? i just wondered if there was a concise, clean way of doing this with generators which i had overlooked, or whether there was some blatant mistake in my code. thx, Johannes From stonis at hotmail.com Wed Feb 2 04:28:46 2005 From: stonis at hotmail.com (Christian) Date: Wed, 02 Feb 2005 10:28:46 +0100 Subject: Apache & Python 500 Error Message-ID: <36bkqfF4sjt0oU1@individual.net> Hello, i have an apache 1.3 server with python on debian. Python works fine but the scripts wont?t work. This easy script i want to do on apache: #!/usr/bin/python import os os.getcwd() in apache config i have done this: AddHandler python-program .py PythonHandler python Order allow,deny Allow from all #PythonDebug On the script is in this directory /var/www/python but i get an 500 error everytime, with "every" script - why that - i?m newbie - sorry for that :) greetings from germany to newsgroup christian From ed-no at spam-eepatents.com Fri Feb 25 02:08:37 2005 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Thu, 24 Feb 2005 23:08:37 -0800 Subject: Nevow examples References: Message-ID: <0q-dndxAyMV4U4PfRVn-vw@centurytel.net> Travis, that's a very nice use of Nevow. I'm going to look into using it for documenting my own stuff. Here's another example, my boss's web site, which uses Twisted/Nevow to implement virtual hosting, dynamic image generation with caching, dynamically-updated parsing of a site-wide config file that determines almost all the layout you see, and dynamic mark-up generation with restructured-text parsing of plain text source files. http://valuablepatents.com A static vhost run under the same Twisted/Nevow server is at http://eepatents.com. I make new servers by simply adding a DNS entry in BIND and then making a new directory in /var/www/ with a site.conf file in it if it's dynamic, or just with static files if it's static, or with a side.mod file if it the vhost's root resource is generated from a named module imported from /var/www/_modules/. I will be providing a release and possibly read-only public access to the SVN repository for the underlying code soon. It will be distributed under the LGPL. --- Ed Suominen Registered Patent Agent Open-Source Software Author (yes, both...) Web Site: http://www.eepatents.com Travis Oliphant wrote: > > There was a request for nevow examples. Nevow is a fantastic > web-development framework for Python. > > I used nevow to create http://www.scipy.org/livedocs/ > > This site uses nevow and self introspection to produce (live) > documentation for scipy based on the internal docstrings. It would be > nice to add the capability for users to update the documentation through > the web-site. But, that functionality is not complete. > > The code itself is available in the util directory of scipy which can be > checked out of CVS (or browsed). Go to http://www.scipy.org for mor > details. > > -Travis Oliphant From peter at somewhere.com Tue Feb 15 10:31:12 2005 From: peter at somewhere.com (Peter Maas) Date: Tue, 15 Feb 2005 16:31:12 +0100 Subject: replacing ASP/VBScript with Python In-Reply-To: References: Message-ID: Peter Maas schrieb: > I have inherited an extremely messy ASP/VBScript application which > is a pain for me to support. Now the customer is thinking about a > redesign. I'd like to rewrite the whole thing in Python but the app > has to meet some conditions like [...] Just noticed that this posting doesn't contain any questions. Here they are: Any comments? Has anybody done something comparable successfully and give some advice? Thanks in advance. :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From ggrp1.20.martineau at dfgh.net Tue Feb 22 05:53:13 2005 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 22 Feb 2005 02:53:13 -0800 Subject: Test for structure References: <1108566497.848623.45360@c13g2000cwb.googlegroups.com> <1108937287.079367.276910@g14g2000cwa.googlegroups.com> <1109012415.692798.185750@l41g2000cwc.googlegroups.com> <1109068655.648301.178740@g14g2000cwa.googlegroups.com> Message-ID: <1109069593.265566.170340@o13g2000cwo.googlegroups.com> Nope, that isn't right either, in the sense that it handles all the cases properly, including "single string" vs "list of strings'. Guess this overly simplistic aslist() does not work after. I should have been more suspicious and cautious before posting. Sorry. Martin From steven.bethard at gmail.com Fri Feb 18 13:58:00 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 18 Feb 2005 11:58:00 -0700 Subject: duplicate docstrings Message-ID: I have two classes that implement the same interface, e.g. something like: class C(object): def foo(self): """Foo things""" ... def bar(self): """Bar things""" ... def baz(self): """Baz things in a C manner""" ... class D(object): def foo(self): """Foo things""" ... def bar(self): """Bar things""" ... def baz(self): """Baz things in a D manner""" ... It bothers me that I'm basically writing the same docstrings multiple times. I guess what I really want to do is just write the docstrings for the interface I'm describing, and only supply docstrings in the classes when they need to differ from the interface docstrings. Is there a good way to do this? If it's necessary, I can have C and D inherit from another class... STeVe From pippo at tin.it Fri Feb 11 18:22:01 2005 From: pippo at tin.it (marco) Date: Sat, 12 Feb 2005 00:22:01 +0100 Subject: check if object is number In-Reply-To: References: Message-ID: <374t0mF4te5vbU1@individual.net> Steven Bethard wrote: > Is there a good way to determine if an object is a numeric type? . . . > > Ideas? Maybe this can help? def isnumber(x): try: return(x == x-0) except: return False print '1:\t', isnumber(1) print '1.25:\t', isnumber(1.25) print '1.0 / 7:\t', isnumber(1.0 / 7) print '1+0j:\t', isnumber((1+0j)) print '"spam":\t', isnumber("spam") output: 1: True 1.25: True 1.0/7: True 1+0j: True "spam": False Ooops! While checking other posts I realized that this is almost the same as Dan Bishop's solution. Marco From caleb1 at telkomsa.net Thu Feb 3 23:28:45 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Thu, 03 Feb 2005 23:28:45 -0500 Subject: Two classes problem References: Message-ID: Gurpreet You can manage the namespace more formally. Or to put it another way, "global" gives me the heebie-jeebies. I recently worked on a project replacing a legacy reactor model in FORTRAN, and between COMMON blocks, and GOTO statements, I didn't know up from down. How about this: *** class a: def __init__(self,test): localtest = test # do stuff with localtest def givetest(self): return localtest def printtest(self): print localtest test = 'Starting text' print 'Outside before class: '+test my_a = a(test) test = my_a.givetest() print 'Outside after class: '+test *** So here we explicitly pass "test" into the class, do stuff with it, and rewrite test again with a method. Does this satisfy the technical problem? regards Caleb On Thu, 3 Feb 2005 11:19:34 +0530, Gurpreet Sachdeva wrote: > The purpose is, I pass a list to a class in a module but I want to use > that list out of the scope of that class and that too not in any other > class or a function but in the main program... > The problem is that when I import that, the statements in the module > which are not in the class are executed first and then the variable > gets intiallised... > I will explain with the example... > > -global test > - > -class a: > - def __init__(self,test): > - global test > - print test > - > -print 'Outside: '+test > > I want to print that variable test which I am giving to the class as > an argument, in the scope of main... > I know it is not a good way of programming but my situation is like > this... > But is this possible or not? If I pass test as 'Garry' can I (by any > way) print 'Outside: Garry' with that print statement... (in the main > scope) > > Thanks and Regards, > Garry From ola.natvig at infosense.no Wed Feb 16 04:33:05 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Wed, 16 Feb 2005 10:33:05 +0100 Subject: super not working in __del__ ? In-Reply-To: References: Message-ID: Duncan Booth wrote: > Fredrik Lundh wrote: > > >>in this case, >> >> def __del__(self): >> super(self.__class__, self).__del__() >> >>should do the trick. > > > Only if nobody ever tries to subclass your class, and if they aren't going > to subclass it why bother to use super in the first place. > > >>>>class Base(object): > > def __del__(self): There should be a super(self.__class__, self)._del__() here if I'm not totaly wong, which could be the case here ;) > print "Base.__del__" > > -- -------------------------------------- Ola Natvig infoSense AS / development From chrisonleadguitar at yahoo.com Tue Feb 1 21:56:20 2005 From: chrisonleadguitar at yahoo.com (Chris Jameyson) Date: Tue, 1 Feb 2005 18:56:20 -0800 (PST) Subject: Python checkin driver version on windows Message-ID: <20050202025620.34269.qmail@web30808.mail.mud.yahoo.com> Is there a way to check driver version information on windows through Python? I'd like to pull driver version, digital sig from the same place that 'device manager' gets it's information. I tried using file system object, but seems like GetFileVersion() from version.dll only extracts versions for .dll and .exe. I need something so I can check .sys files. Thanks in advance. __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From firemoth at gmail.com Tue Feb 1 16:47:04 2005 From: firemoth at gmail.com (Timothy Fitz) Date: Tue, 1 Feb 2005 16:47:04 -0500 Subject: Where are list methods documented? In-Reply-To: <972ec5bd05020110061ce0575c@mail.gmail.com> References: <41ffba7d$0$15879$a1866201@visi.com> <1f7befae050201093732daefb2@mail.gmail.com> <972ec5bd05020110061ce0575c@mail.gmail.com> Message-ID: <972ec5bd05020113472f781f1d@mail.gmail.com> [Tim Peters] > The methods on mutable sequence types are documented in the Library > manual's section on mutable sequence types: > > http://docs.python.org/lib/typesseq-mutable.html > And like -many- python programmers, when he thinks "List" he doesn't immediately think "Mutable Sequence Type." The title should stay but perhaps the tutorial should be updated to point people in the right direction when they're "done" and need to know specifics? (This link of the documentation was non-obvious to me also) From aurora00 at gmail.com Tue Feb 1 11:49:06 2005 From: aurora00 at gmail.com (aurora) Date: Tue, 01 Feb 2005 08:49:06 -0800 Subject: Next step after pychecker References: <41ff0308$0$6503$636a15ce@news.free.fr> Message-ID: A frequent error I encounter try: ...do something... except IOError: log('encounter an error %s line %d' % filename) Here in the string interpolation I should supply (filename,lineno). Usually I have a lot of unittesting to catch syntax error in the main code. But it is very difficult to run into exception handler, some of those are added defensely. Unfortunately those untested exception sometimes fails precisely when we need it for diagnosis information. pychecker sometime give false alarm. The argument of a string interpolation may be a valid tuple. It would be great it we can somehow unit test the exception handler (without building an extensive library of mock objects). From gabriel.cooper at mediapulse.com Tue Feb 8 09:48:39 2005 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Tue, 08 Feb 2005 09:48:39 -0500 Subject: ANN: Zeus Programmers Editor V3.94 In-Reply-To: <4207843C.26FB@zeusedit.com> References: <4207843C.26FB@zeusedit.com> Message-ID: <4208D147.5040405@mediapulse.com> Jussi Jumppanen wrote: >The latest release of the Zeus for Windows programmer's >editor is now available. > So is this mentioned here on the Python mailing list because Zeus was written in Python, or is this just targeted spam for a commerical product? From jjreavis at gmail.com Fri Feb 4 13:12:38 2005 From: jjreavis at gmail.com (Jeff Reavis) Date: 4 Feb 2005 10:12:38 -0800 Subject: advice needed for simple python web app In-Reply-To: <5cqdnZX-cZ9ca5_fRVn-3Q@rogers.com> References: <5cqdnZX-cZ9ca5_fRVn-3Q@rogers.com> Message-ID: <1107540758.589662.16340@z14g2000cwz.googlegroups.com> You might also want to try out Spyce. http://spyce.sourceforge.net/index.html It works in proxy mode, with mod_python, or even as cgi. Some examples: http://spyce.sourceforge.net/eg.html From ncoghlan at iinet.net.au Sat Feb 5 04:15:36 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 05 Feb 2005 19:15:36 +1000 Subject: empty classes as c structs? In-Reply-To: <7rSdne7BcbDeV57fRVn-jg@comcast.com> References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> Message-ID: <42048EB8.2010708@iinet.net.au> Steven Bethard wrote: > Yes -- help me rally behind my generic object PEP which proposes a Bunch > type (probably to be renamed) for the Python standard lib. =) Did you see the suggestion of 'namespace' as a name? Given that the idea is to get access to the contents using the standard Python syntax for accessing module and class namespaces, it seems to make sense. Michael Spencer also posted an interesting idea recently about setting up a view of an existing dictionary, rather than as a separate object: class attr_view(object): def __init__(self, data): object.__setattr__(self, "_data", data) def __getattr__(self, attrname): return self._data[attrname] def __setattr__(self, attrname, value): self._data[attrname] = value Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From kent37 at tds.net Fri Feb 25 08:45:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Feb 2005 08:45:16 -0500 Subject: split a directory string into a list In-Reply-To: <1109338583.168229.297760@z14g2000cwz.googlegroups.com> References: <1109338583.168229.297760@z14g2000cwz.googlegroups.com> Message-ID: <421f28c1$1_3@newspeer2.tds.net> porterboy76 at yahoo.com wrote: > QUESTION: > > How do I split a directory string into a list in Python, eg. > > '/foo/bar/beer/sex/cigarettes/drugs/alcohol/' > > becomes > > ['foo','bar','beer','sex','cigarettes','drugs','alcohol'] >>> '/foo/bar/beer/sex/cigarettes/drugs/alcohol/'.strip('/').split('/') ['foo', 'bar', 'beer', 'sex', 'cigarettes', 'drugs', 'alcohol'] Kent > > I was looking at the os.path.split command, but it only seems to > separate the filename from the path (or am I just using it wrong?). I > don't want to do it manually if I can help it, as there will have to be > exceptions for the cases where there is (not) a trailing (leading) > slash, or escape sequences involving /. Is there a built in command for > this? > From erikbethke at gmail.com Sun Feb 13 11:05:06 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 13 Feb 2005 08:05:06 -0800 Subject: goto, cls, wait commands In-Reply-To: References: <1ixbe7q69lob3.1npuu3z54gx8z.dlg@40tude.net> Message-ID: <1108310706.270392.161870@o13g2000cwo.googlegroups.com> At least I thought this was funny and cool! -Erik From michele.simionato at gmail.com Wed Feb 16 10:03:07 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 16 Feb 2005 07:03:07 -0800 Subject: adding new functionality to a function non-intrusively! In-Reply-To: <1108564620.657526.301320@g14g2000cwa.googlegroups.com> References: <1108564620.657526.301320@g14g2000cwa.googlegroups.com> Message-ID: <1108565856.655370.255590@f14g2000cwb.googlegroups.com> Decorators are your friends. You can wrap a function and give it additional functionality. For instance just yesterday I needed to keep track of how many times a function is called. This can be done with this decorator: .def with_counter(f): . def wrappedf(*args, **kw): . wrappedf.counter += 1 . return f(*args, **kw) . wrappedf.counter = 0 . wrappedf.func_name = f.func_name . return wrappedf . at with_counter # requires Python 2.4 .def g(): . print "called" .print g.counter .g() .print g.counter This is intented just as an appetizer. Look at the cookbook for more examples. Michele Simionato From simoninusa2001 at yahoo.co.uk Sat Feb 12 14:40:04 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 12 Feb 2005 11:40:04 -0800 Subject: ANN: pyMinGW support for Python 2.3.5 (final) is available References: <1108189500.707806.316520@g14g2000cwa.googlegroups.com> Message-ID: <1108237204.920670.213190@f14g2000cwb.googlegroups.com> [snip] > Ha anyone tried cross compiling python with mingw? At work we compile > our software for lots of platforms (including windows) on a linux > build host. The windows builds are done with a mingw cross compiler. > It would be interesting if we could do this with python + extensions > also. Yes, I was thinking of setting up a cross-compiling system, but why would you use mingw instead of just gcc on Linux? Only cross-compiling I've ever done is on RISC OS. I use VMWare to accomplish a similar goal though, compiling stuff for old 64Mb P233's running RedHat7 is a lot faster when done on a 1Gb/2.5GHz VMWare machine! I just finished compiling Qt/PyQt/QScintilla/SIP for Python 2.4 using MinGW on Windows, and can say that MSVC6 was at least twice as fast, and required less patching to get it working, plus it's one less DLL and the binaries are about 20% smaller. I also can't seem to get PyQt apps working on Win98SE when using the MinGW build (2000 and XP work fine). Maybe I'll fork out the 100usd for Visual Studio .NET 2003 after all.... From aleaxit at yahoo.com Mon Feb 7 14:44:10 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 7 Feb 2005 20:44:10 +0100 Subject: string issue References: <36QMd.103084$Jk5.36127@lakeread01> <1grl717.1o4ofg7arp8c2N%aleaxit@yahoo.com> <36plr5F551pg8U1@individual.net> Message-ID: <1grmr97.9o27yo1xzwzd7N%aleaxit@yahoo.com> Reinhold Birkenfeld wrote: ... > > Using ips[:] to make a copy on the fly is very idiomatic, but I've never > > liked it, personally. I see no reason to prefer it to the even shorter > > and arguably less obscure ips*1, for example. > > "Less obscure"? Either you know the `lst[:]' idiom, or you don't. If you > do, it's fine, if you don't, you will have to look it up to understand > its meaning, and that's a good thing. I disagree. > Using `lst*1', on the other hand, does not make clear that a copy is > created. If you don't already know what it does, you may assume that > `lst' is left alone. And indeed it is -- whatever object is bound to the name 'lst' is not modified in the least (neither would it be by slicing lst[:], of course). But the RESULT of x*1 is a DISTINCT object from x whenever it matters -- i.e., whenever x is mutable. x[:] *MIGHT* not be a distinct, separate, independent copy if x is, e.g. a Numeric.array: x = Numeric.arange(7) y = x[:] x[3]=23 now y is modified too. Change the middle statement into 'y = x*1', and the third statement won't alter y. So, *WHAT ON EARTH* could possibly make this weird 'x[:]' form preferable to 'x*1'?! It's MUCH more obvious that the second one returns an independent, separate object initially equal to x -- because it does so in many more cases than those in which x[:] does it! I'm not arguing FOR x*1 -- I'm arguing AGAINST x[:] as being even remotely acceptable. > > My preference is: > > > > for ip in list(ips): > > That is the most intriguing variant, of course. It's very down to earth because the result is obviously a list, whatever 'ips' might turn out to be -- no mystery there, and thus, no intrigue. Maybe we should have a simpler way to specify ``an iterator that is INDEPENDENT from any possible changes in the iterable we're passing'', for this specific use case -- but we don't, and I don't think that copy.copy(ips) is a substantial improvement (it would fail when ips is a file, or a generator-iterator, or many other kinds of iterators, for example). list(ips) may do more work than necessary (e.g., if ips were a tuple) but at least its semantics are quite plain and obvious. Alex From exogen at gmail.com Fri Feb 18 19:31:16 2005 From: exogen at gmail.com (Brian Beck) Date: Fri, 18 Feb 2005 19:31:16 -0500 Subject: selecting dictionaries to maximize counts In-Reply-To: References: Message-ID: Steven Bethard wrote: > Anyway, do you know what name this problem is usually discussed under? > If I knew what to google for, I could probably find at least a few > simple heuristics to try... I think the closest thing would be the 'knapsack problem' or the 'subset sum problem.' http://en.wikipedia.org/wiki/Subset_sum_problem http://en.wikipedia.org/wiki/Knapsack_problem -- Brian Beck Adventurer of the First Order From bdesth.quelquechose at free.quelquepart.fr Sat Feb 5 09:52:49 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 05 Feb 2005 15:52:49 +0100 Subject: who can tell me BASICS of Python In-Reply-To: <1107588047.020906.321750@g14g2000cwa.googlegroups.com> References: <1107588047.020906.321750@g14g2000cwa.googlegroups.com> Message-ID: <4204db7f$0$14112$626a14ce@news.free.fr> fanweixiao at gmail.com a ?crit : > I want to know which compiler I can use ... thank you To compile what ? Python code ? The compiler is in the standard lib. From timr at probo.com Thu Feb 17 23:52:28 2005 From: timr at probo.com (Tim Roberts) Date: Thu, 17 Feb 2005 20:52:28 -0800 Subject: Help needed for to build a CGI shell interface. References: <37jjk4F5eefr4U1@individual.net> <4214d128$0$145$fb624d75@newsspool.solnet.ch> Message-ID: Slalomsk8er wrote: > >What do I want to do? I am building an admintool (deamon and client) and >for this I need to script a interface to the shell, with the console >ansi escape sequences, whitch is fully transparent for the user. Do you honestly plan to expose a command shell via CGI? Can you think of a better way to allow hackers to wreak havoc on your system? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From skip at pobox.com Wed Feb 2 11:04:37 2005 From: skip at pobox.com (System Administrator) Date: Wed, 2 Feb 2005 10:04:37 -0600 Subject: How run valgrind on Python C extensions? In-Reply-To: <1107324574.108521.183170@z14g2000cwz.googlegroups.com> References: <1107324574.108521.183170@z14g2000cwz.googlegroups.com> Message-ID: <16896.64021.313577.542995@montanaro.dyndns.org> Chris> I have Python C extensions that are giving me seg faults that I'd Chris> like to run valgrind on. Chris> Can I use valgrind on these through python?? HOW??? Just run Python under valgrind's control. It will automatically take care of it for you. Chris> Is it easy or must I do some work like recompiling python source Chris> with the -g extension? Should not be necessary. Skip From http Mon Feb 21 12:42:14 2005 From: http (Paul Rubin) Date: 21 Feb 2005 09:42:14 -0800 Subject: Unittest - testing properties (read-only attributes) References: <7xu0o5akr2.fsf@ruckus.brouhaha.com> Message-ID: <7x4qg5n72h.fsf@ruckus.brouhaha.com> Duncan Booth writes: > An assignment expression, if such a thing existed wouldn't help here. > > The point being that the expression must be evaluated inside the exception > handler in assertRaises, so you either need to delay the evaluation with a > lambda, or by passing the function and arguments in separately. If you had > an assignment expression it would be roughly equivalent to: > > self.assertRaises(AttributeError, setattr(self.combat, 'value', 1)) > > which will throw the AttributeError instead of passing the test. Yes. The example I quoted used an assignment expression inside a lambda. The person who posted it, and the person who followed it up with the setattr alternative, both didn't notice that the assignment expression wasn't valid Python. However, my post came out sounding grumpier than I intended ;). From deetsNOSPAM at web.de Fri Feb 25 11:14:24 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 25 Feb 2005 17:14:24 +0100 Subject: Splitting strings - by iterators? References: Message-ID: <38913oF5mi8arU2@individual.net> Jeremy Sanders wrote: > I have a large string containing lines of text separated by '\n'. I'm > currently using text.splitlines(True) to break the text into lines, and > I'm iterating over the resulting list. > > This is very slow (when using 400000 lines!). Other than dumping the > string to a file, and reading it back using the file iterator, is there a > way to quickly iterate over the lines? > > I tried using newpos=text.find('\n', pos), and returning the chopped text > text[pos:newpos+1], but this is much slower than splitlines. > > Any ideas? Maybe [c]StringIO can be of help. I don't know if it's iterator is lazy. But at least it has one, so you can try and see if it improves performance :) -- Regards, Diez B. Roggisch From garabik at kassiopeia.juls.savba.sk Tue Feb 22 03:13:06 2005 From: garabik at kassiopeia.juls.savba.sk (Radovan Garabik) Date: 22 Feb 2005 08:13:06 GMT Subject: display VARCHAR(mysql) and special chars in html References: Message-ID: <3807siF5g9t1cU1@individual.net> Jonas Meurer wrote: > hello, > > my script selects a comment saved as VARCHAR in MySQL and displays it > inside an html page. > > the problem is, that the comment contains several special characters, as > mysterious utf-8 hyphens, german umlauts, etc. > > i could write a function to parse the comment and substitute special > chars with the relevant html code, but maybe this already exists in some > module? just make the page in utf-8, and you'll save you a lot of troubles > > if not, it'll be hard work, as i've to consider many special chars, and > at least iso-8859-1* and utf-8 as charmaps. if you insist... a = u'\u010c' a.encode('ascii', 'xmlcharrefreplace') -- ----------------------------------------------------------- | Radovan Garab?k http://melkor.dnp.fmph.uniba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From reinhold-birkenfeld-nospam at wolke7.net Mon Feb 7 12:12:09 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 07 Feb 2005 18:12:09 +0100 Subject: string issue In-Reply-To: <1grl717.1o4ofg7arp8c2N%aleaxit@yahoo.com> References: <36QMd.103084$Jk5.36127@lakeread01> <1grl717.1o4ofg7arp8c2N%aleaxit@yahoo.com> Message-ID: <36plr5F551pg8U1@individual.net> Alex Martelli wrote: > Bill Mill wrote: > ... >> > > You are modifying the list as you iterate over it. Instead, iterate over >> > > a copy by using: >> > > >> > > for ip in ips[:]: > ... >> Once you know it, it's neat, and I use it sometimes. However, it's a >> little too "magical" for my tastes; I'd rather be more explicit about >> what's going on. > > Using ips[:] to make a copy on the fly is very idiomatic, but I've never > liked it, personally. I see no reason to prefer it to the even shorter > and arguably less obscure ips*1, for example. "Less obscure"? Either you know the `lst[:]' idiom, or you don't. If you do, it's fine, if you don't, you will have to look it up to understand its meaning, and that's a good thing. Using `lst*1', on the other hand, does not make clear that a copy is created. If you don't already know what it does, you may assume that `lst' is left alone. > My preference is: > > for ip in list(ips): That is the most intriguing variant, of course. Reinhold From wweston at att.net Tue Feb 1 15:43:21 2005 From: wweston at att.net (wes weston) Date: Tue, 01 Feb 2005 20:43:21 GMT Subject: How do you do arrays In-Reply-To: References: <1107284817.848551.79000@c13g2000cwb.googlegroups.com> Message-ID: Thomas, If you were allowed to do what you're doing, the list first element would be getting skipped as "index" is always > 0. The thing is, you don't want the "index" var at all for adding to the list; just do jMatrix.append(k). You can iterate over the list with for x in jMatrix: print x Is it basic that indexes from 1 vs. 0? 'just about completely forgotten basic. wes Thomas Bunce wrote: > Tryed it and this is what I got (I did go to the web sight) > > tom(h=500)$ /tmp/501/Cleanup\ At\ Startup/ptesting-128981347.87.py.command; exit > Input the maximu number of tvalue: 114 > Traceback (most recent call last): > File "/Users/tom/Desktop/ptesting.py", line 20, in ? > iMatrix[index] = k > IndexError: list assignment index out of range > logout > [Process completed] > > The complete listing: > > #!/usr/bin/python > import random > import sys > import array > # > ### generates a list of numbers between 1 and target > ### and uses 23 % of these values. > # > > iMatrix = [] > > tvalue = input('Input the maximu number of tvalue: ') > majorlop1 = int tvalue * .23) > listvalues = range(tvalue) > > sep = '- ' > index = 0 > while index < majorlop1: > index = index + 1 > k = random.choice(listvalues) + 1 > iMatrix[index] = k > > while index < majorlop1: > print '- %s %s' % (iMatrix[index], sep) > # > ### > # > I would like to set the size of the List/array independent > of having to intialialize it prior to use. > If it help I will say the bad works I am using OSX > > Thanks Tom > In article <1107284817.848551.79000 at c13g2000cwb.googlegroups.com>, > "Kartic" wrote: > > >>Tom, >> >>Before you use iMatrix[index], you have to tell python to use iMatrix >>as an array. You will do that using iMatrix = [] *outside* the loop. >> >>iMatrix = [] >>while index < majorlop1: # rest of the loop statements >> >>Since you are new, please take a look at the Python tutorial to get you >>started. >>http://docs.python.org/tut/tut.html >> >>Thanks, >>-Kartic From mefjr75 at hotmail.com Sat Feb 26 18:59:44 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 26 Feb 2005 15:59:44 -0800 Subject: remove strings from source References: <2ab23d7a.0502260638.311cc5e9@posting.google.com> <2ab23d7a.0502261508.5bf50b49@posting.google.com> Message-ID: <1109462384.838214.190750@o13g2000cwo.googlegroups.com> qwweeeit wrote: > Thank you for your suggestion, but it is too complicated for me... > I decided to proceed in steps: > 1. Take away all commented lines > 2. Rebuild the multi-lines as single lines ummm, Ok all i can say is did you try this? if not save it as a module then import it into the interperter and try it. This is a dead simple module to do *exactly* what you asked for :) Like i said I have done this before so I will restate *I HAVE FAILED AT THIS BEFORE, MANY TIMES*. Now I have a solution. It handles stdio by default but can write to a filelike object if you give it one. Handles continued lines already, no need to futz around with some solution. Here is an example: Py> filein = """ ... class Stripper: ... '''python comment and whitespace stripper ... ''' ... def __init__(self, raw): ... ''' Store the source text & set some flags. ... ''' ... self.raw = raw ... ... def format(self, out=sys.stdout, comments=0, ... spaces=1, untabify=1,eol='unix'): ... '''Parse and send the colored source.''' ... # Store line offsets in self.lines ... self.lines = [0, 0] ... pos = 0 ... # Strips the first blank line if 1 ... self.lasttoken = 1 ... self.temp = StringIO.StringIO() ... self.spaces = spaces ... self.comments = comments ... ... if untabify: ... self.raw = self.raw.expandtabs() ... self.raw = self.raw.rstrip()+' ' ... self.out = out ... """ Py> replacer = ReplaceParser(filein, out=sys.stdout) Py> replacer.format() class Stripper: s000001 def __init__(self, raw): s000002 self.raw = raw def format(self, out=sys.stdout, comments=0, spaces=1, untabify=1,eol=s000003): s000004 # Store line offsets in self.lines self.lines = [0, 0] pos = 0 # Strips the first blank line if 1 self.lasttoken = 1 self.temp = StringIO.StringIO() self.spaces = spaces self.comments = comments if untabify: self.raw = self.raw.expandtabs() self.raw = self.raw.rstrip()+s000005 self.out = out Py> replacer.StringMap {'s000004': "'''Parse and send the colored source.'''", 's000005': "' '", 's000001': "'''python comment and whitespace stripper :)\n '''", 's000002': "''' Store the source text & set some flags.\n '''", 's000003': "'unix'"} You can also strip out comments with a few line. It can easily get single comments or doubles. add this in your __call__ function: [snip] self.pos = newpos return # kills comments if (toktype == tokenize.COMMENT): return if (toktype == token.STRING): sname = self.StringName.next() [snip] If you insist on writing something go ahead. Let me know what your solution is, I am curious. M.E.Farmer From tzot at sil-tec.gr Tue Feb 22 05:25:02 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 22 Feb 2005 12:25:02 +0200 Subject: how can I make this script shorter? References: Message-ID: On Tue, 22 Feb 2005 00:34:39 -0800, rumours say that Lowell Kirsh might have written: >I have a script which I use to find all duplicates of files within a >given directory and all its subdirectories. It seems like it's longer >than it needs to be but I can't figure out how to shorten it. Perhaps >there are some python features or libraries I'm not taking advantage of. > >The way it works is that it puts references to all the files in a >dictionary with file size being the key. The dictionary can hold >multiple values per key. Then it looks at each key and all the >associated files (which are the same size). Then it uses filecmp to see >if they are actually byte-for-byte copies. > >It's not 100% complete but it's pretty close. I can't advise on code length; my dupefind.py script is 361 lines, but the algorithm is slightly more complex to speed things up (and it also optionally hardlinks identical files on POSIX and NTFS filesystems). If in your case there are lots of files of several MiB each, that often match on size, you could avoid lots of comparisons if you did match based on some hash (md5 or sha). You could also compare first on the hash of the first few kiB (I check 8 kiB) to see if you need to read the whole file or not. So: for every file: if other files exist with the same size: calculate hash for first few kiB if file has same "initial" hash with other files: calculate full hash return all files with same full hash Something like that. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From aleaxit at yahoo.com Sun Feb 6 04:27:31 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 6 Feb 2005 10:27:31 +0100 Subject: [EVALUATION] - E01: The Java Failure - May Python Helps? References: Message-ID: <1grk4ll.s9ln0u1bpp7huN%aleaxit@yahoo.com> Fredrik Lundh wrote: > Markus Wankus wrote: > > > Google his name - he has been banned from Netbeans and Eclipse (and > > Hibernate, and others...) for good reason. Can you imagine how much of > > a Troll you need to be to *actually* get "banned" from the newsgroups of > > open source projects such as those? > > have Pythoneers ever "banned" anyone from a public forum? it's not like > we haven't seen trolls and crackpots before, you know. I don't see how banning is technically possible in unmoderated groups. Shunning, or pelting the troll with abuse whenever he shows up, etc, etc, sure. But, banning? Alex From ivoras at _-_fer.hr Mon Feb 14 15:53:00 2005 From: ivoras at _-_fer.hr (Ivan Voras) Date: Mon, 14 Feb 2005 21:53:00 +0100 Subject: 64 bit Python In-Reply-To: <1cd7e2-qu7.ln1@valpo.de> References: <1cd7e2-qu7.ln1@valpo.de> Message-ID: Mathias Waack wrote: > amounts of data. I figured out that a 32 bit application on HP-UX > cannot address more than 1 GB of memory. In fact (I think due to the > overhead of memory management done by python) a python application > cannot use much more than 500 MB of "real" data. For this reason I don't thik this is likely. Don't know about HP-UX but on some platforms, FreeBSD for example, there is a soft memory-cap for applications. By default, a single application on FreeBSD cannot use more than 512MB of memory, period. The limit can be modified by root (probably involves rebooting). From tzot at sil-tec.gr Tue Feb 22 04:00:09 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 22 Feb 2005 11:00:09 +0200 Subject: python2.4 generator expression > python2.3 list expression References: <0ioj11dsgqhatqc3d7ldeb35rta6d9fk69@4ax.com> Message-ID: <4asl1157chl57do6mp8ah4g32edp2vkill@4ax.com> On Mon, 21 Feb 2005 10:55:05 -0800, rumours say that Bryan might have written: [I] >>>>is to reset the rightmost (less significant) '1' bit of a number (ie >>>>change it to '0'). [bryan] >>>i tried c &= c - 1 but i'm not getting the least significant or >>>rightmost bit reset to zero. am i misunderstanding something? >>> >>> >>>>>>2 & 1 # 2 = 0x10; reset right most would be 0x10 [Duncan] >> The difference between the original "reset the rightmost '1' bit", and your >> interpretation: "reset the rightmost bit" is the "'1'". >> >> The rightmost bit that is set is reset. So 0x10 -> 0, and 0x1010 -> 0x1000. >thanks duncan... you're right, i did intrepret this as "reset the rightmost bit" >instead of "reset the rightmost '1' bit". and i must have read what christos >wrote 100 times!!! Don't worry, Bryan, I'm probably more to blame, since I have this tendency to interject parenthesized sub-sentences all over my paragraphs, that probably confuse more than clarify things ( self.remind(prose is not code) :). Perhaps I should crosspost my replies (esp. the ones with nested parentheses) to comp.lang.lisp ... -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From antonyliu2002 at yahoo.com Sun Feb 27 00:03:51 2005 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Sat, 26 Feb 2005 21:03:51 -0800 (PST) Subject: Is it possible to pass a parameter by reference? Message-ID: <20050227050351.24540.qmail@web54505.mail.yahoo.com> I defined two functions, f1 and f2. f1 modifies the value of a variable called apple. I want to pass the modified value of apple to f2. How can I do this? I got stuck. __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From bdesth.quelquechose at free.quelquepart.fr Thu Feb 10 13:05:26 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 10 Feb 2005 19:05:26 +0100 Subject: goto, cls, wait commands In-Reply-To: <420b89f2$0$21601$a1866201@visi.com> References: <1ixbe7q69lob3.1npuu3z54gx8z.dlg@40tude.net> <420b89f2$0$21601$a1866201@visi.com> Message-ID: <420ba000$0$29241$626a14ce@news.free.fr> Grant Edwards a ?crit : > On 2005-02-10, BOOGIEMAN wrote: > > >>First of all, what's Python command equivalent to QBasic's "goto" ? > > > There isn't one. > > One defines functions and calls them. One uses for and while > loops. One uses list comprehensions. One uses if/elif/else. and even sometimes break, continue, and return !-) From axel at white-eagle.invalid.uk Thu Feb 10 20:25:45 2005 From: axel at white-eagle.invalid.uk (axel at white-eagle.invalid.uk) Date: Thu, 10 Feb 2005 19:25:45 -0600 Subject: [perl-python] combinatorics fun References: <1108075884.250995.62520@g14g2000cwa.googlegroups.com> Message-ID: In comp.lang.perl.misc Xah Lee wrote: > a year ago i wrote this perl program as part of a larger program. > sub combo ($) { > my $max=$_[0]; > my %hh=(); > for (my $j=1; $j < $max; ++$j) { > for (my $i=1; $i <= $max; ++$i) { > my $m = (($i+$j)-1)%$max+1; > if ($i < $m){ $hh{"$i,$m"}=[$i,$m];} > } > } > return \%hh; > } Well, it's not obfuscated Perl. It is, however, an obfuscated algorithm. Sane people would use something along the lines of: sub combo { my $max = shift; my %hh=(); for my $i ( 1 .. $max ) { for my $j ( $i + 1 .. $max ) { $hh{"$i,$j"} = [$i, $j]; } } return \%hh; } Axel From devries at idolstarastronomer.com Thu Feb 24 11:53:32 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: Thu, 24 Feb 2005 11:53:32 -0500 Subject: Canonical way of dealing with null-separated lines? In-Reply-To: References: Message-ID: <20050224165332.GB13386@miyu.cjas.org> On Wed, Feb 23, 2005 at 10:54:50PM -0500, Douglas Alan wrote: > Is there a canonical way of iterating over the lines of a file that > are null-separated rather than newline-separated? I'm not sure if there is a canonical method, but I would recommending using a generator to get something like this, where 'f' is a file object: def readnullsep(f): # Need a place to put potential pieces of a null separated string # across buffer boundaries retain = [] while True: instr = f.read(2048) if len(instr)==0: # End of file break # Split over nulls splitstr = instr.split('\0') # Combine with anything left over from previous read retain.append(splitstr[0]) splitstr[0] = ''.join(retain) # Keep last piece for next loop and yield the rest retain = [splitstr[-1]] for element in splitstr[:-1]: yield element # yield anything left over yield retain[0] Chris From steven.bethard at gmail.com Thu Feb 24 17:20:30 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 24 Feb 2005 15:20:30 -0700 Subject: Interesting decorator use. In-Reply-To: References: <421e2398@nntp0.pdx.net> Message-ID: Tom Willis wrote: >>> Question on decorators in general. Can you parameterize those? > > Wow thanks for the explanation!! Some of it is a bit mind bending to > me at the moment , but I'm going to mess with it a bit. Oh, I also should have mentioned that there's some explanation at: http://www.python.org/peps/pep-0318.html Specifically on parameterizing: """The current syntax also allows decorator declarations to call a function that returns a decorator: @decomaker(argA, argB, ...) def func(arg1, arg2, ...): pass This is equivalent to: func = decomaker(argA, argB, ...)(func) The rationale for having a function that returns a decorator is that the part after the @ sign can be considered to be an expression (though syntactically restricted to just a function), and whatever that expression returns is called. See declaration arguments [15].""" But playing around with it is, IMHO, definitely the best way to figure it out. =) STeVe From 18k11tm001 at sneakemail.com Sat Feb 12 16:08:09 2005 From: 18k11tm001 at sneakemail.com (18k11tm001 at sneakemail.com) Date: 12 Feb 2005 13:08:09 -0800 Subject: Commerical graphing packages? In-Reply-To: <87650x28wu.fsf@pobox.com> References: <420d1595$1@nntp.zianet.com> <1108163937.533683.162220@g14g2000cwa.googlegroups.com> <87650x28wu.fsf@pobox.com> Message-ID: <1108242489.958991.92060@o13g2000cwo.googlegroups.com> >If you're generating lots of graphs programatically, eg. on a web >server, grace is not what you want. Yes, it has a command language, >but IIRC it depends on X11, and windows even pop up as it runs in >batch mode. Bleh. I don't understand what you're talking about. I've been using GRACE in batch mode for years and I've never had a window pop up. The only time a window "pops up" is when you start GRACE interactively. The GRACE command language is not the greatest, but it gets the job done. It may have improved lately too (I run a fairly old version). Another nice feature of GRACE is a fairly active user community and a mailing list for help. They helped get me unstuck several times a while back. From http Sun Feb 13 19:44:31 2005 From: http (Paul Rubin) Date: 13 Feb 2005 16:44:31 -0800 Subject: Kill GIL References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <868y5t6sal.fsf@guru.mired.org> <86sm405d38.fsf@guru.mired.org> Message-ID: <7xu0og6kcw.fsf@ruckus.brouhaha.com> Mike Meyer writes: > > Threads are also good for handling blocking I/O. > > Actually, this is one of the cases I was talking about. I find it > saner to convert to non-blocking I/O and use select() for > synchronization. That solves the problem, without introducing any of > the headaches related to shared access and locking that come with > threads. It's just a different style with its own tricks and traps. Threading for blocking i/o is a well-accepted idiom and if Python supports threads at all, people will want to use them that way. From tim.golden at viacom-outdoor.co.uk Tue Feb 15 10:09:11 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 15 Feb 2005 15:09:11 -0000 Subject: replacing ASP/VBScript with Python Message-ID: <9A28C052FF32734DACB0A288A3533991035AF4@vogbs009.gb.vo.local> [Peter Maas] | | Peter Maas schrieb: | > I have inherited an extremely messy ASP/VBScript application which | > is a pain for me to support. Now the customer is thinking about a | > redesign. I'd like to rewrite the whole thing in Python but the app | > has to meet some conditions like | > | > - IIS frontend | > - MSSQL db server | > - Win32 authentication | > - No 'ugly' URLs like http://server/cgi-bin/frontend.cgi?main.py | > - Performance: intranet with ~ 1000 users | | In the meantime I have searched the internet and found plenty | of options: | | - plain cgi with fastcgi and mod_rewrite for IIS to transform the URL | - quixote cgi with fastcgi and mod_rewrite | - Webware + wkcgi | - Python ASP (registering Python with Pywin32 as ASP language) | - mxODBC + SQL ODBC driver | - pyADO + SQL MDAC driver There has also been noise lately about an ISAPI-Python binding (contributed via Mark Hammond of pywin32 fame, I think) and a WSGI implementation of same. Haven't used either, and haven't got time to trawl for links at the mo, but I'm fairly certain the latest pywin32 has the core stuff. 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 jacek.generowicz at cern.ch Tue Feb 1 06:58:48 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 01 Feb 2005 12:58:48 +0100 Subject: type of simple object References: <1107255752.258025.50870@z14g2000cwz.googlegroups.com> <1107257264.146280.89560@c13g2000cwb.googlegroups.com> <1107258136.815344.145380@c13g2000cwb.googlegroups.com> Message-ID: "ajikoe at gmail.com" writes: > The result > How can I check it since it is not a string right? It is a type, which is a first-class object in its own right. type('hello') == str However, I reiterate, you almost certainly don't really care about what the actual type is. To care about the actual type is to struggle against a fundamental feature of python: Duck Typing. Yes, I admit, there are situations in which you might really care about the actual type. However, given that you do not know how to check the type in Python, the chances are rather high that you are sufficienly new to Python to not realize that, typically, you need not (and should not) care about the actual type. The chances are that you are trying to program in a style which you learned in another language, and which not the most productive in Python. From zyqnews at 163.net Fri Feb 18 14:03:46 2005 From: zyqnews at 163.net (zyqnews at 163.net) Date: 18 Feb 2005 11:03:46 -0800 Subject: unicode and socket Message-ID: <1108753426.318777.275250@c13g2000cwb.googlegroups.com> hello all, I am new in Python. And I have got a problem about unicode. I have got a unicode string, when I was going to send it out throuth a socket by send(), I got an exception. How can I send the unicode string to the remote end of the socket as it is without any conversion of encode, so the remote end of the socket will receive unicode string? Thanks From jack at performancedrivers.com Fri Feb 18 11:52:54 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 18 Feb 2005 11:52:54 -0500 Subject: Help with research In-Reply-To: References: <1108684307.612656.92010@c13g2000cwb.googlegroups.com> Message-ID: <20050218165254.GD9263@performancedrivers.com> On Thu, Feb 17, 2005 at 07:09:44PM -0500, Jeremy Bowers wrote: > On Thu, 17 Feb 2005 15:51:47 -0800, elena wrote: > > I can go to my friends, however it occurred to me that it might be > > better to post in a newsgroup and get a larger, more diverse, and > > random sample. > > Larger, yes, more diverse, yes, more random, probably not in the > statistical/scientific sense. Caveat emptor. Bigtime, I see you have a occupation box for "Software Developer" and "Other." The data for software people (and lawyers) may be noisy becuase they take the questions literally. Because the answers are True/False folks might parse them narrowly for their truth value (and all in an effort to help!). for instance, "I find that it is possible to be too organized when performing certain kinds of tasks." False, I don't find this is possible because I'm not organized. This reminds me of a story, for Psychology 101 all freshman had to participate in three experiments by grad students. One I did involved riding on an excercise bike for ten minutes wearing a heart monitor. After that you could leave as soon as you felt your heartrate was back to normal. The study concluded that people are bad at knowing when their heart rate is elevated. I concluded that undergrads will only do the minimum to pass a course, and are willing to lie about their heartrate if it gets them out the door five minutes sooner. Be careful with data! -Jack From reinhold-birkenfeld-nospam at wolke7.net Sun Feb 6 05:19:09 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 06 Feb 2005 11:19:09 +0100 Subject: Multiple constructors In-Reply-To: References: <6SjNd.38337$K7.21639@fe2.news.blueyonder.co.uk> Message-ID: <36m98tF52msqlU2@individual.net> vincent wehren wrote: > Philip Smith wrote: >> Call this a C++ programmers hang-up if you like. >> >> I don't seem to be able to define multiple versions of __init__ in my matrix >> class (ie to initialise either from a list of values or from 2 dimensions >> (rows/columns)). >> >> Even if Python couldn't resolve the __init__ to use on the basis of argument >> types surely it could do so on the basis of argument numbers??? >> >> At any rate - any suggestions how I code this???? > > Checking the number of arguments ain't all that hard: > > class Klass: > def __init__(*args): > self.args = args > if len(self.args) == 1: > # etc. > > This feels rather unpythonic, though. And it won't work, as `self' is not defined. ;) Reinhold From serpent17 at gmail.com Wed Feb 2 07:36:09 2005 From: serpent17 at gmail.com (Newbie) Date: 2 Feb 2005 04:36:09 -0800 Subject: web camera or else ? 15-30 fps processing of camera videos. In-Reply-To: <36ah30F4tlp7bU1@individual.net> References: <1107295229.657375.318750@o13g2000cwo.googlegroups.com> <36ah30F4tlp7bU1@individual.net> Message-ID: <1107347769.355651.287650@g14g2000cwa.googlegroups.com> Folks: here is a small summary: For Linux based system, xawt seems to be the solution: http://linux.bytesex.org/xawtv/ where one can get access to the stream from any device that has a video output. For win32, it looks like the solution is this: http://videocapture.sourceforge.net/ where one has to use the python programming language. Great help, thank you all, Jake. Matt D wrote: > Newbie wrote: > > I am doing some robotics projects but my main area of interest is > > trying out several algorithms for the processing of the stream of data > > coming from the video. > > > > Same for me! From what I can tell, a cheap webcam will "just work" with > a recent version of windows - i.e. plug it in using USB and then you can > have programmatic access to the data and grab frames very easily. This > setup works fine with my digital camera working as a webcam - real ?10 > webcams should be the same. Not sure what Linux compatibility is like > these days - for that I know for a fact that the Hauppauge USB WinTV > thing works (or at least the hardware version I have works) with Linux. > > For linux I found this (now on the wayback archive - original page is > now 404): > http://web.archive.org/web/20020322015936/http://staff.aist.go.jp/naoyuki.ichimura/research/tips/v4ln_e.htm > > Hopefully that is some help. > > Oh by the way, speed on a modern machine shouldn't be an issue - my > badly written prototype in visual basic of all things (dont laugh - > seemed like a good idea at the time!) was tracking a single coloured > object reliably at significantly greater than 30fps (it automatically > altered the window it searched in based on size and amount of movement > of the object - at times it was approaching 100fps) on a modest by > today's standards 1.4ghz pc, using a 320x240 stream. From alexrait at gmail.com Tue Feb 1 16:53:48 2005 From: alexrait at gmail.com (alexrait1) Date: 1 Feb 2005 13:53:48 -0800 Subject: Suggesion for an undergrad final year project in Python In-Reply-To: <1107241918.722156.123590@c13g2000cwb.googlegroups.com> References: <1107241918.722156.123590@c13g2000cwb.googlegroups.com> Message-ID: <1107294828.333218.132940@l41g2000cwc.googlegroups.com> How about writing some gtk fronted to pgp.. That might be both useful (at least for me) and teach you about pgp and pyGTK, that is writing gui with python. From timr at probo.com Wed Feb 23 02:25:36 2005 From: timr at probo.com (Tim Roberts) Date: Tue, 22 Feb 2005 23:25:36 -0800 Subject: A few q's on python files. References: Message-ID: Joseph Quigley wrote: > >i'm new to python (by a week) but am learning fast (that's what I like >about python--it's simplicity). I got disgusted with C and C++ (i was >learning) probably because of a bad copy of Visual C++ 6.0 that gave me errors. I find that very hard to believe. >I noticed that IDLE doesn't have an option to allow you to convert a .py or >pyc. file into an executable. Why? Am i wrong? Where can I find one (if I'm >right)? Like VB6 and Perl, Python is interpreted, not compiled. You don't compile it into an .exe. You pass the script to the python.exe interpreter, where it is executed. There are packages (like py2exe) that can convert your script into an executable, but they are essentially installers. They package your script, and all the scripts and libraries it needs, into a single file along with the interpreter. When the .exe is executed, it extracts the interpreter and the scripts into a temp directory, and fires up the interpreter. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jjl at pobox.com Fri Feb 4 15:34:12 2005 From: jjl at pobox.com (John J. Lee) Date: 04 Feb 2005 20:34:12 +0000 Subject: "Collapsing" a list into a list of changes References: Message-ID: <87hdksvzcr.fsf@pobox.com> Steven Bethard writes: > Mike C. Fletcher wrote: [...] > > >>> def changes( dataset ): > > ... last = None > > ... for value in dataset: > > ... if value != last: > > ... yield value > > ... last = value > > ... >>> print list(changes(data )) > > which is quite readable/elegant IMO. > > But fails if the list starts with None: > > py> lst = [None,0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5] > py> def changes(dataset): > ... last = None > ... for value in dataset: > ... if value != last: > ... yield value > ... last = value > ... > py> list(changes(lst)) > [0, 1, 2, 3, 2, 4, 5] > > A minor modification that does appear to work: > > py> def changes(dataset): > ... last = object() > ... for value in dataset: > ... if value != last: > ... yield value > ... last = value > ... > py> list(changes(lst)) > [None, 0, 1, 2, 3, 2, 4, 5] Unless the first object in the list has a weird __cmp__ (does happen...). OK, weird __cmp__s are nasty anyway, but still, why compound it through cleverness when you can write a really plodding function that *always* does what it says on the tin? clever-is-evil-ly y'rs, John From farcepest at gmail.com Sun Feb 20 13:53:59 2005 From: farcepest at gmail.com (Andy Dustman) Date: 20 Feb 2005 10:53:59 -0800 Subject: Trouble with mysql-python 1.2.0 on Solaris 8 sparc In-Reply-To: <1108755202.574729.293610@g14g2000cwa.googlegroups.com> References: <1108755202.574729.293610@g14g2000cwa.googlegroups.com> Message-ID: <1108925639.345790.230510@c13g2000cwb.googlegroups.com> Did you build your own MySQL, or did you use a pre-built version? And what version? It's not clear if you're using 4.0 or 4.1. If mysql_config is returning the wrong flags, then that's a bug with MySQL. You should be able to work around this by doing this in setup.py before the call to setup(): extra_compile_args.remove('-m64') From peter at engcorp.com Thu Feb 10 10:11:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Feb 2005 10:11:50 -0500 Subject: convert list of tuples into several lists In-Reply-To: References: <36uihlF58p63iU1@individual.net> <_cWdnZN4wO418pffRVn-qA@comcast.com> Message-ID: Nick Coghlan wrote: > I never really got the impression that Guido was particularly *strongly* > opposed to this use of the extended call syntax. Merely that he was > concerned that it would break down if the relevant list turned out to be > large (that is, the abuse is using *args with a list when the list may > turn out to be large, not a problem specifically with using the star > syntax with zip()). Is there some unexpected limit to the number of arguments that may be passed with the *args format (say, "256 function arguments maximum are supported by Python"), or is this concern just because of the raw memory inherently used by the tuple? In other words, if one is confident that one can whip tuples of the required size around without using up available memory, would there still be such a concern about the *args "abuse"? -Peter From everettcc at hotmail.com Fri Feb 4 13:49:51 2005 From: everettcc at hotmail.com (Chad Everett) Date: Fri, 4 Feb 2005 12:49:51 -0600 Subject: newbie: Syntax error Message-ID: Hi Everyone, I am new to Python and programming in general. I bought the book "Python Programming for the Absolute Beginner" by michael Dawson. I have been working through it but am having trouble. I am trying to make a coin flip program and keep geting a Synax Error "invalid syntax". If anyone has a moment could you please look at it and tell me what I am doing wrong. thanks for your time and patience. Chad # Coin Flip Program # This program flips a coin 100 times and tells the number of heads and tails. # Chad Everett 2/3/2005 print "\t\t********Coin Flip Game*********\n" import random # heads = 1 # tails = 2 tries = random.randrange(2) + 1 count = 1 while count != 100: if tries == 1: heads = 1 count += 1 else tries == 2: # I AM GETTING THE SYNTAX ERROR HERE tails = 1 count += 1 print "heads: " + heads print "tails: " + tails raw_input("Press enter to quit") From vincent at visualtrans.de Wed Feb 2 23:19:29 2005 From: vincent at visualtrans.de (vincent wehren) Date: Thu, 03 Feb 2005 05:19:29 +0100 Subject: Generating .pyc/.pyo from a make file In-Reply-To: <2h48d2-8481.ln1@eskimo.tundraware.com> References: <4308d2-0801.ln1@eskimo.tundraware.com> <42015a85_1@news.arcor-ip.de> <4201607f_2@news.arcor-ip.de> <2h48d2-8481.ln1@eskimo.tundraware.com> Message-ID: Tim Daneliuk wrote: > Steve Holden wrote: > >> Roland Heiber wrote: >> >>> Tim Daneliuk wrote: >>> > Aha! Exactly ... and that makes perfect sense too. D'oh! I guess a > better > distribution strategy would be to have the installation program generate > the pyo > file at installation time... > > Thanks - Also, the *.py? files contain the full pathname of the *.py they have been compiled from. Copying them to other path locations will give you the wrong __file___ information in tracebacks. -- Vincent Wehren From fuzzyman at gmail.com Mon Feb 21 06:17:05 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 21 Feb 2005 03:17:05 -0800 Subject: Keyword Named Args Message-ID: <1108984625.683340.121680@g14g2000cwa.googlegroups.com> A colleague and I have built a Validator object for use with ConfigObj and other general schema situations. A config file is used to store a schema that specifies how to test a value that it is valid. keyword=function(param1, param2) e.g. you could specify : size = range(30, 50) This means that the keyword 'size' must be an integer between 30 and 50. There is a matching function stored in a dictionary that is called and the relevant arguments passed to it. The function name and parameters are parsed from the config file that defines the schema. args, fname = parsefunction('range(30,50)') test = funcdict[fname](*args) What I can't easily see is any way of passing named keyword arguments to the function. Suppose we wanted to pass keyword=param to a function - is there any way of doing this ... obviously passing in 'keyword=param' as text has entirely the wrong result...... Anyone got any clues ? I suspect compiling the function into a code object will help.... but this is a slightly black art for me. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From TValone at DMV.CA.gov Wed Feb 2 18:44:52 2005 From: TValone at DMV.CA.gov (Valone, Toren W.) Date: Wed, 2 Feb 2005 15:44:52 -0800 Subject: Newbie alert Message-ID: <5AE0A72A4C0AD711806A000255FC47DB2A157A@dmv-ent-ex07.dmv.ca.gov> Ok, new to Python and Tkinter.. Following along examples in book, got to dialog windows example coded this # dialog1.py from Tkinter import * class Mydialog: def _int_(self,parent): top = self.top = Toplevel(parent) Label(top, text="Value").pack() self.e = Entry(top) self.e.pack(padx=5) b = Button(top,text="OK", command=self.ok) b.pack(pady=5) def ok(self): print "value is", self.e.get() self.top.destroy() root = Tk() Button(root, text="Hello!").pack() root.update() d = MyDialog(root) root.wait_window(d.top) When I run it IDLE gives me this Traceback (most recent call last): File "C:/Python24/dialog1.py", line 29, in -toplevel- d = MyDialog(root) NameError: name 'MyDialog' is not defined I have a feeling this is something very simple, but I cannot figure it out. Help! From gsakkis at rutgers.edu Fri Feb 11 16:16:02 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Fri, 11 Feb 2005 16:16:02 -0500 Subject: check if object is number References: <374ho0F560ughU1@individual.net> <66WdnbJbuf5yj5DfRVn-iA@comcast.com> Message-ID: <374lklF5b20klU1@individual.net> > George Sakkis wrote: > > "Steven Bethard" wrote in message > > news:gcidnb9g_ojxnpDfRVn-tA at comcast.com... > > > >>Is there a good way to determine if an object is a numeric type? > > > > In your example, what does your application consider to be numeric? > > Well, here's the basic code: > > def f(max=None): > ... > while max is None or n <= max: > ... > # complicated incrementing of n > > So for 'max', technically all I need is <= support. However, the code > also depends on the fact that after incrementing 'n' enough, it will > eventually exceed 'max'. Currently, ints, longs, floats, and Decimals > will all meet this behavior. But I'd rather not specify only those 4 > (e.g. with a typecheck), since someone could relatively easily create > their own new numeric type with the same behavior. Do you know a better > way to test for this kind of behavior? > > Steve The problem is more conceptional rather than technical. So what you're saying is that 3 <= "3.0" should not be allowed, but 3 <= SomeUserDefinedNumericClass(3) is ok, although your program knows nothing a priori about SomeUserDefinedNumericClass. The idea suggested before, try if "x+1" fails or not does not get you far; any class that overrides __add__ may fool this test: class Dummy: def __add__(self,other): return 0 Is Dummy 'numeric' ? Probably not. Whether a given instance is "numeric" (or "sequence", "file-like", etc. for that matter) is a semantic issue. It cannot be resolved by relying on which methods are supported or not, but what these methods *do*; this is something that no programming language can tell you now and in the (foreseeable) future. George From fredrik at pythonware.com Thu Feb 17 15:26:40 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Feb 2005 21:26:40 +0100 Subject: TypeError: send() argument 1 must be string or read-only buffer, not int References: <4214FB83.90209@utstar.com> Message-ID: Manish Gupta wrote: > invoking something like following - > > sock.send(100) > > generates the following error - > > TypeError: send() argument 1 must be string or read-only buffer, not int > > > how can I work around this? I wish to write > msg-length on a stream socket. in what form? sock.send(chr(100)) # single byte sock.send(str(100)+"\n") # ascii characters plus newline sock.send(str(100)+":") # netstring prefix sock.send("%08d" % 100) # eight ascii characters, null-padded sock.send(str(100).encode("utf-16")) # same, in utf-16 with bom sock.send(struct.pack("!i", 100)) # 32-bit integer in network byte order etc. (see the struct module documentation for more alternatives) From fabsk+news at free.fr Thu Feb 17 16:25:13 2005 From: fabsk+news at free.fr (Roger That) Date: Thu, 17 Feb 2005 22:25:13 +0100 Subject: Convert a raw pointer to IDispatch References: <4214a4ef$0$30359$636a15ce@news.free.fr> Message-ID: Le Thu, 17 Feb 2005 19:22:16 +0100, Thomas Heller a ?crit?: >> I am trying to use the function "CreateStreamOnHGlobal" from python code >> (I need to pass an IStream object to MSXML, like I do in C++ code). >> >> I was able to retrieve a pointer on the IStream object in this way: >> >> from ctypes import * >> >> stream = c_int() >> windll.ole32.CreateStreamOnHGlobal(c_long(0), c_long(1), byref(stream)) >> print "%x"%stream.value >> >> The problem is that I would like to attach this pointer to a python >> IDispatch object (in Python only, not using a C++ DLL to do the stuff). >> Do you know a way to do it ? > > What do you want to do with this pointer? Pass it to a function called via > ctypes? Once it is a IDispatch object (like the IDispatch object returned by "win32com.client.Dispatch"), I will call the IStream methods on it and pass it to a DOMDocument of MSXML. It should look like that: stream = c_int() windll.ole32.CreateStreamOnHGlobal(c_long(0), c_long(1), byref(stream)) stream_obj = some_conversion(stream) # IDispatch call stream_obj.Write("some data", 9) doc = win32com.client.Dispatch("MSXML2.DOMDocument.4.0") doc.load(stream_obj) From mep_ at 163.com Fri Feb 11 02:47:13 2005 From: mep_ at 163.com (mep) Date: Fri, 11 Feb 2005 15:47:13 +0800 Subject: ActivePython 2.3.5.236 and ActivePython 2.4.0.244 are available References: Message-ID: <3736boF594g0kU1@individual.net> ActivePython-2.4.0-243-win32-ix86.msi : 29M ActivePython-2.4.0-244-win32-ix86.msi : 18M What make so much difference of the size of them, which distinct monir version number for 1 only. Any explaination? -- Best Regards, Wang Kebo http://www.huihoo.org/~mep "Trent Mick" wrote in message news:mailman.2356.1108082006.22381.python-list at python.org... > I'm pleased to announce that ActivePython 2.3.5 build 236 and > ActivePython 2.4.0 build 244 are now available from: > > http://www.ActiveState.com/Products/ActivePython > > ActivePython 2.3.5.236 is a bug-fix release matching core Python 2.3.5. > ActivePython 2.4.0.244 is a bug-fix release matching core Python 2.4.0. > Both of these releases contain an important security fix for > SimpleXMLRPCServer as detailed here: > > http://www.activestate.com/Products/ActivePython/advisory.plex > http://www.python.org/security/PSF-2005-001/ > > Builds for Linux, Solaris and Windows are available. > > We would welcome any and all feedback to: > ActivePython-feedback at ActiveState.com > Please file bugs against ActivePython at: > http://bugs.ActiveState.com/ActivePython > > > What is ActivePython? > --------------------- > > ActivePython is ActiveState's quality-assured binary build of Python. > Builds for Windows, Linux and Solaris and made freely available. > > ActivePython includes the Python core and core extensions (zlib 1.2.1, > bzip2 1.0.2, bsddb 4.2.52, Tk 8.4.4, and Tix 8.1.4). On Windows, > ActivePython includes the PyWin32 suite of Windows tools developed by > Mark Hammond, including bindings to the Win32 API and Windows COM, the > Pythonwin IDE, and more. > > ActivePython also includes a wealth of Python documentation, including: > - the core Python docs > - Andrew Kuchling's "What's New in Python" series > - the Non-Programmer's Tutorial for Python > - Mark Pilgrim's excellent "Dive into Python", and > - a snapshot of the Python FAQs, HOWTOs and PEPs. > > An online version of the docs can be found here: > http://aspn.activestate.com/ASPN/docs/ActivePython/2.3/welcome.html > http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/welcome.html > In particular the Release Notes: > http://aspn.activestate.com/ASPN/docs/ActivePython/2.3/relnotes.html > http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/relnotes.html > and the Installation Guide: > http://aspn.activestate.com/ASPN/docs/ActivePython/2.3/installnotes.html > http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/installnotes.html > > > Extra Bits > ---------- > > This release of ActivePython also includes the following packages: > > - a Windows "debug" package: debug-built binaries for ActivePython > users building debug versions of their binary Python extensions > - ActivePython23.chm & ActivePython24.chm: an MS compiled help > collection of the full ActivePython documentation set. Linux > users of applications such as xCHM might find this useful. > > These packages are available from: > ftp://ftp.activestate.com/ActivePython/etc/ > > On behalf of the team at ActiveState, > Thanks, and enjoy! > > -- > Trent Mick > trentm at activestate.com > > > > > From a.schmolck at gmx.net Fri Feb 18 19:57:30 2005 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Sat, 19 Feb 2005 00:57:30 +0000 Subject: Python, Matlab and AI question References: Message-ID: Robert Kern writes: > Alexander Schmolck wrote: > >> Actually, I've written a highlevel matlab-python bridge (based on bugfixed and >> slightly extended version of the original pymat) which is quite up-to-date; by >> and large it makes using matlab from python as easy as if matlab were just >> some python library: > > Fantastic! I've added a link to the Scipy Wiki: > > http://www.scipy.org/wikis/topical_software/TopicalSoftware Thanks -- I've now also posted announcements to the relevant forums, so I guess I'll find out pretty soon if others deem it to be useful (working :). 'as From nav+posts at bandersnatch.org Thu Feb 24 10:19:46 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: Thu, 24 Feb 2005 10:19:46 -0500 Subject: How to write a ping client References: <1109039706.092671.137360@f14g2000cwb.googlegroups.com> <421a9d54$0$44652$a1866201@visi.com> <1109068125.070219.54510@o13g2000cwo.googlegroups.com> <1109212294.128292.119680@l41g2000cwc.googlegroups.com> Message-ID: <87650i6l4d.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> "Harlin Seritt" writes: > ? #!/bin/sh ping $1 Enjoy, Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From irmen at -nospam-remove-this-xs4all.nl Wed Feb 2 13:48:03 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Wed, 02 Feb 2005 19:48:03 +0100 Subject: Python for S60 mentioned in a mainstream Finnish e-news website In-Reply-To: References: <651bduh8.fsf@python.net> Message-ID: <42012063$0$28992$e4fe514c@news.xs4all.nl> Ville Vainio wrote: >>>>>>"Thomas" == Thomas Heller writes: > > > >> (Yeah, ctypes will probably be a problem because of the way Symbian > >> handles DLLs) > > Thomas> How *does* symbian handle DLLs? > > By ordinal, so the dll does not include the symbol name (in order to > keep the size small). Linker finds the ordinals from the .LIB file > that corresponds to the DLL. > > (Someone who knows better might want to correct me if I'm wrong). > Heh, this somehow reminds me about the way shared libraries were implemented on the Amiga. No linking step; the function entry points were essentially a big jump table in the library structure with every function having a unique offset from the library's base. Proved to make it very simple to patch OS functions too: just patch the jump address in the jump table to jump to the patched library function... Irmen From wittempj at hotmail.com Wed Feb 2 14:12:34 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 2 Feb 2005 11:12:34 -0800 Subject: Two classes problem References: Message-ID: <1107371554.756894.111800@l41g2000cwc.googlegroups.com> If you create a.py like -test = 'Spam' - -class a: - def __init__(self, arg): - global test - test = arg - self.result = arg + ' added' - def __call__(self): - return self.result and b.py like -import a -a.test = 'donkey' -x = a.a('dinosaur') -print a.test It will print 'dinosaur', so you changed the global variable. The thing is however that this is a highly confusing way of programming for me, so I would not use it just because it is possible From john_sips_teaz at yahooz.com Tue Feb 8 00:18:49 2005 From: john_sips_teaz at yahooz.com (John M. Gabriele) Date: Tue, 08 Feb 2005 00:18:49 -0500 Subject: Is Python as capable as Perl for sysadmin work? References: <1107836010.646355.99020@z14g2000cwz.googlegroups.com> Message-ID: On Mon, 07 Feb 2005 20:13:30 -0800, beliavsky wrote: > > [snip] > > I'm a Windows user, not a Unix sysadmin, but I've noticed that > Cameron Laird has written several articles on Python for system > administration in Unix Review and Sys Admin magazine, for example > http://www.unixreview.com/documents/s=9083/sam0401d/ . Reading his > articles may help you decide if Python is a good fit for your work. Great series of articles. Thanks for the link. :) -- --- if replying via email, remove zees --- From jack at performancedrivers.com Mon Feb 28 15:26:41 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 28 Feb 2005 15:26:41 -0500 Subject: naming convention for scalars, lists, dictionaries ... In-Reply-To: <422386ED.60007@benjiyork.com> References: <1109613115.760962.292360@z14g2000cwz.googlegroups.com> <3YydnR3xNd4k_r7fRVn-3g@comcast.com> <20050228190504.GV9263@performancedrivers.com> <422386ED.60007@benjiyork.com> Message-ID: <20050228202641.GW9263@performancedrivers.com> On Mon, Feb 28, 2005 at 04:02:37PM -0500, Benji York wrote: > Jack Diederich wrote: > >Ditto for me, plural implies list and singular implies instance, > >for (contact) in contacts: > > # do something with contact > > May I ask why you place the parenthesis in the for statement? I like the tuple-ness feel of it and frequently unpack multiple values in for loops. I also like the visual feel, it makes it easy to see what is being unpacked and what is the source. "for (one, two, three) in somelist:" versus "for one, two, three in sometlist:" Even with a colorizing editor (emacs) I find the first version easier to read. YMMV. -Jack From daniel.dittmar at sap.corp Fri Feb 11 05:47:46 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 11 Feb 2005 11:47:46 +0100 Subject: Python in Makefile Question In-Reply-To: References: Message-ID: Efrat Regev wrote: > 1. How can I get the python script to return a value to make, so that if it > decides that there are convention violations make will fail? You can set the return code of your Python script through sys.exit (3) > 2. How can I pass information from the makefile to the python script, e.g., > the base directory to check? Python side: Commandline arguments can be read through the list sys.argv. Parsing of commandline options can be done with the module optparse. Makefile side: I don't know if there is a special variable in GNU make for the directory of the current target. Why don't you set the default for the directory option to the current directory? Most Makefiles won't work anyway if they are called from a different directory. Daniel From luke at tatooine.planet Mon Feb 7 17:30:55 2005 From: luke at tatooine.planet (Luke Skywalker) Date: Mon, 07 Feb 2005 23:30:55 +0100 Subject: Big development in the GUI realm References: <1107795145.049239.73450@l41g2000cwc.googlegroups.com><5ocf01hmspufk3iusvm35p6hj4mes5heke@4ax.com> Message-ID: <0pqf015oqbcfuqkgrki3sbhgor0b6403r1@4ax.com> On Tue, 08 Feb 2005 07:57:51 +1100, Tim Churches wrote: >Thus, it seems to me, and to the expert legal advice which we sought >(note the scope of the advice was Australian law only) that provided no >GLPed source or object code is mixed, included or combined with >non-GPLed code, and that the GPLed and non-GPLed code are distributed or >otherwise made available in packages which are very clearly separate >works, and that any interaction between the two is restricted to >runtime, then the GPL does not require that non-GPLed code to be >distributed under the GPL. That's how I understood things, ie. calling a standard, clearly independent (ie. EXE or DLL) binary downloaded from the project's web site and just calling it is not covered by the GPL since no change has been made whatsoever to the original work. Which makes sense, since the goal of the GPL is to make sure that no one can steal the code, correct bugs or add features without redistributing those changes. Muddy waters, indeed :-) Luke. From ncoghlan at iinet.net.au Thu Feb 10 10:00:09 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 11 Feb 2005 01:00:09 +1000 Subject: Is Python as capable as Perl for sysadmin work? In-Reply-To: <6b8m01tcr3p7p7dq3beekj7q1fgmt9qubr@4ax.com> References: <6b8m01tcr3p7p7dq3beekj7q1fgmt9qubr@4ax.com> Message-ID: <420B76F9.5060101@iinet.net.au> Richie Hindle wrote: > [Steve] > >>Was it INTERCAL that had the COMEFROM statement instead of >>GOTO? I REALLY like the idea of a COMEFROM statement. I think python should >>have a COMEFROM statement > > > It does - see http://entrian.com/goto/ > > (In case you doubt it: yes, it works, but note that it doesn't work at the > interactive prompt, only in a real source file.) > > (The fact that I felt obliged to add the first paragraph on that page is > the funniest part of the whole thing. I really did have people genuinely > thanking me for the module, asking for features, asking for help with > using it, and so on.) > That module is. . . a) impressive b) very, very, wrong c) both a) and b) I think I'm voting for c). . . Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From webmaster at python.org Thu Feb 10 17:55:09 2005 From: webmaster at python.org (webmaster at python.org) Date: Thu, 10 Feb 2005 17:55:09 -0500 Subject: www.python.org down - power outage Message-ID: <20050210225509.GA22130@panix.com> Yes, we know that www.python.org is down. XS4ALL is suffering a power outage. Yes, they have backup and redundant power, but it's not working properly for the segment of the building the web server is located in. Fortunately, mail.python.org is located in a different part of the building, which is still getting power. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "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." --GvR From fuzzyman at gmail.com Mon Feb 14 04:49:03 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 14 Feb 2005 01:49:03 -0800 Subject: mxCGIPython binaries for Python 2.3.5 In-Reply-To: References: <20050211154457.GA23787@phd.pp.ru> <20050211181320.GA23241@caltech.edu> Message-ID: <1108374543.366130.81590@o13g2000cwo.googlegroups.com> Oleg Broytmann wrote: > On Fri, Feb 11, 2005 at 10:13:21AM -0800, Titus Brown wrote: > > what does mxCGIPython do? I can't find anything at that Web site that > > http://www.egenix.com/files/python/mxCGIPython.html > > > doesn't involve downloading & unpacking a file. > > It is unpackable, ready-to-run python binary. > It would be really noice if *someone* would maintain this for windoze... maybe that's really difficult though *sigh*. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > PS. I am neither author nor maintainer, I only provide binaries for > some platforms... > > Oleg. > -- > Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru > Programmers don't die, they just GOSUB without RETURN. From martin at v.loewis.de Sun Feb 13 15:13:26 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Feb 2005 21:13:26 +0100 Subject: For American numbers In-Reply-To: References: <420e7376$1@nntp0.pdx.net> Message-ID: <420fb4e6$0$16575$9b622d9e@news.freenet.de> Peter Hansen wrote: > For the rest of the computer world, unless I've missed > a changing of the guard or something, "kilo" is 1024 > and "mega" is 1024*1024 and so forth... In case this isn't clear yet: you have missed a changing of the guard or something. "kibi" is 1024, "mebi" is 1024*1024 and so forth. "kilo" is 1000. Regards, Martin From fumanchu at amor.org Tue Feb 15 14:45:24 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 15 Feb 2005 11:45:24 -0800 Subject: replacing ASP/VBScript with Python Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339843C@exchange.hqamor.amorhq.net> Peter Maas wrote: > Robert Brewer schrieb: > >>I'm now confident that it is doable and keen on finding > out. The usual > >>question: what is the one and best way to do it? ;) > > > > > > Python ASP (pywin32), but put as little code as possible into the > > ASP--make it just a stub to call the real Python app. That > app will be > > running persistently in the background, which should > obviate most of the > > need for session support. That's been my experience, anyway. > > Sounds reasonable. How do ASP-Python and IIS work together? > Is the Python- > Interpreter loaded each time a Python-ASP is called? No, you get a persistent process (that's what I meant by "running persistently"). Be careful using the Low or Medium "Application Protection" settings, as your app may mix with other applications in the same IIS process. Sometimes, that's what you want (two apps built using the same framework can then share framework modules if you use Low or Medium). On the other hand, the High setting lowers performance. Robert Brewer MIS Amor Ministries fumanchu at amor.org From jerf at jerf.org Wed Feb 2 11:59:55 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 02 Feb 2005 11:59:55 -0500 Subject: CONTEST - What is the (best) solution? References: <1107340503.462196.109440@o13g2000cwo.googlegroups.com> Message-ID: On Wed, 02 Feb 2005 02:35:03 -0800, python wrote: > Each pair in a dictionary is separated by CRLF and in each dictionary > numbers of pairs can be different. > I need to read only the the first and the last dictionaries.What is a > best solution? > Thanks > Lad Who cares about the best solution? Odds are, your process is disk-bound anyhow. Is this a thinly-veiled attempt to get someone to provide you *a* solution, or do you already have one and you are seriously asking for a better one? Because I'd say, take the easiest programming route: Parse the first dict into a variable, then just loop until you run out of file, storing a parsed dict in the "last" variable and just naturally letting later ones overwrite earlier ones. If you want something "best"-er than that (heh heh), you're going to have to tell us how you are measuring better-ness. From kent37 at tds.net Thu Feb 17 14:06:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Feb 2005 14:06:06 -0500 Subject: Alternative to standard C "for" In-Reply-To: References: <1107628331.816935.16760@o13g2000cwo.googlegroups.com> <740c3aec050205104924a82d23@mail.gmail.com> <1108620618.3892.85.camel@lipscomb.mbi.ucla.edu> Message-ID: <4214e79c$1_2@newspeer2.tds.net> James Stroud wrote: > It seems I need constructs like this all of the time > > i = 0 > while i < len(somelist): > if oughta_pop_it(somelist[i]): > somelist.pop(i) > else: > i += 1 > > There has to be a better way... somelist[:] = [ item for item in somelist if not oughta_pop_it(item) ] Kent From jacek.generowicz at cern.ch Tue Feb 1 07:54:12 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 01 Feb 2005 13:54:12 +0100 Subject: type of simple object References: <1107255752.258025.50870@z14g2000cwz.googlegroups.com> <1107257264.146280.89560@c13g2000cwb.googlegroups.com> <1107258136.815344.145380@c13g2000cwb.googlegroups.com> <1107261198.943087.80960@z14g2000cwz.googlegroups.com> Message-ID: "ajikoe at gmail.com" writes: > Thank you guys. > > My function should multiply every element of a list, for example > "something" > and "something" can be an integer or another list. > If it deals with integer than it is ok, but > If it deals with list than it become false for example list*2 = > listlist, and what I really want is to mutlitply its member. Which member? A list can have many members ... or none at all. > That's why I need to know the type of my data in "something". No, you don't need to know its type at all. You need to know whether it is a sequence or not ... which is a far cry from knowing its type. > By the way I am new in python, I heard that it has a MatLab > capabilities, How good is that? Depends on what you mean by "MatLab capabilities". Matlab is highly matrix oriented, therefore it provides lots of fast matrix operations, and syntactic sugar for dealing with matrices. If you want to think of everything as a matrix, then you could well be disappointed by Python. There is a package for driving matlab from Python, which you might find interesting (it might even be what you meant by "MatLab capabilities"). Google is your friend. From tjreedy at udel.edu Thu Feb 24 17:15:30 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Feb 2005 17:15:30 -0500 Subject: Python Online Programming Contest References: <1109278779.955986.193860@z14g2000cwz.googlegroups.com> Message-ID: "Varun" wrote in message news:1109278779.955986.193860 at z14g2000cwz.googlegroups.com... > Hi Friends, > Department of Information Technology, Madras Institute of Technology, > Anna University, India > is conducting a technical symposium, Samhita. As a part of samhita, an > Online Programming Contest is scheduled on Sunday, 27 Feb 2005. Looks like a fun symposium. > This is the first Online Programming Contest in India to support > Python !!!!. > Other languages supported are C and C++. > > For Registration and Rules of the contest, http://www.samhita.info/opc Is this open worldwide or India residents only? I could not find a time, either local or UTC. > For details about samhita http://www.samhita.info/ Terry J. Reedy From kent37 at tds.net Wed Feb 16 22:04:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Feb 2005 22:04:55 -0500 Subject: more os.walk() issues... probably user error In-Reply-To: <4213A24F.1020209@athop1.ath.vt.edu> References: <42137b28$1_3@newspeer2.tds.net> <4213A24F.1020209@athop1.ath.vt.edu> Message-ID: <421406d8$1_1@newspeer2.tds.net> rbt wrote: >>>> ## for fs in fs_objects: >>>> ## >>>> ## for f in fs[2]: >>>> ## if f in file_skip_list: >>>> ## print f >>>> ## fs[2].remove(f) >>>> ## >>>> ## for d in fs[1]: >>>> ## if d in dir_skip_list: >>>> ## print d >>>> ## fs[1].remove(d) > > Will the changes I made (file and dir removals from os.walk()) be > reflected in the generator object? Is it safe to remove objects this way > and pass the results in a generator on to another function? Sorry for > all the questions, I just like to fully understand something before I > start doing it with confidence. Yes. The docs for os.walk() explicitly state, "When topdown is true, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames." So changes to the dir list affect the iteration; changes to the file list directly affect the value you return to the caller. Kent From jfj at freemail.gr Mon Feb 7 04:27:28 2005 From: jfj at freemail.gr (jfj) Date: Mon, 07 Feb 2005 01:27:28 -0800 Subject: Confused with methods In-Reply-To: <1grl5cn.1k7qrmm1ondzhpN%aleaxit@yahoo.com> References: <1grknb0.ygwohl17y6j5yN%aleaxit@yahoo.com> <1grl5cn.1k7qrmm1ondzhpN%aleaxit@yahoo.com> Message-ID: <42073480.6000506@freemail.gr> Alex Martelli wrote: > > I still wouldn't see any "inconsistency" even if two different ways of > proceeding gave the same result in a certain case. That would be like > saying that having x-(-y) give the same result as x+y (when x and y are > numbers) is ``inconsistent''... the word ``inconsistent'' just doesn't > MEAN that! > > "Inconsistent" means sort of the reverse: one way of proceeding giving > different results. But the fact that the same operation on objects of > different types may well give different results isn't _inconsistent_ -- > it's the sole purpose of HAVING different types in the first place...! > Ok! I said I was confused in the first place! G. From harlinseritt at yahoo.com Thu Feb 17 07:20:15 2005 From: harlinseritt at yahoo.com (Harlin) Date: 17 Feb 2005 04:20:15 -0800 Subject: Pausing a program - poll/sleep/threads? In-Reply-To: <7xekffr5ts.fsf@ruckus.brouhaha.com> References: <1108625477.222091.34680@l41g2000cwc.googlegroups.com> <7xekffr5ts.fsf@ruckus.brouhaha.com> Message-ID: <1108642815.203982.140210@g14g2000cwa.googlegroups.com> import time play_something() time.sleep(LengthOfSongInSeconds) do_something() Have you tried that? I'd be interesting in seeing this app you have. ! From jmeile at hotmail.com Fri Feb 11 06:17:02 2005 From: jmeile at hotmail.com (Josef Meile) Date: Fri, 11 Feb 2005 12:17:02 +0100 Subject: Testing web applications In-Reply-To: References: Message-ID: <420C942E.7040901@hotmail.com> Hi Achim, > I'm looking for frameworks to make testing web applications - i.e. > parsing and filling out forms - easier. I found Puffin, which looks good > but not very usable in the current state. I know that I once read about > other nice frameworks, but could not find one via google. Any hints? Zope + Formulator is a nice combination to validating and designing forms and add some functionality. If you want a more complicated content management framework, then you can additionally install plain CMF or Plone, which is based on CMF. There is also something called Silva, but it doesn't have many products as the other two; however, it is also nice. I have heard also about CherryPy, Quixote, Twisted Matrix and Webware, but I haven't tested them. Once I saw that somebody posted a link, which compares some of them, but I lost that thread :-( Regards, Josef From jason at tishler.net Wed Feb 2 08:27:37 2005 From: jason at tishler.net (Jason Tishler) Date: Wed, 2 Feb 2005 08:27:37 -0500 Subject: Building Python with Tcl/Tk on Cygwin_NT-5.1 In-Reply-To: <4200D056.4010000@llnl.gov> References: <41FF5A67.3090606@llnl.gov> <20050201125129.GA432@tishler.net> <41FFA7C9.4070308@llnl.gov> <20050202124435.GA2472@tishler.net> <4200D056.4010000@llnl.gov> Message-ID: <20050202132737.GD2472@tishler.net> Dean, Please keep your replies on-list. On Wed, Feb 02, 2005 at 05:06:30AM -0800, Dean N. Williams wrote: > It appears that I built the Tcl/Tk libraries, but for some reasons > they are not correct. So I am using the Tcl/Tk libraries that were > distributed with Cygwin. This seemed to work... Now I set the > TCL_LIBRARY and TK_LIBRARY environment, but I get the following error > when trying to run idle. > > [Dean Williams at ippc ...ASD_work/bin]$ ./idle > C:\cygwin\usr\local\ASD_work\bin\python2.4.exe (3164): *** unable to > remap C:\cygwin\bin\cygssl-0.9.7.dll to same address as parent(0x740000) > != 0x750000 > 5 [main] python2.4 2144 sync_with_child: child 3164(0x650) died > before initialization with status code 0x1 > 7241 [main] python2.4 2144 sync_with_child: *** child state child > loading dlls > Traceback (most recent call last): > File "./idle", line 5, in ? > main() > File "/usr/local/ASD_work/lib/python2.4/idlelib/PyShell.py", line > 1355, in main > [snip] > File "/usr/local/ASD_work/lib/python2.4/os.py", line 488, in _spawnvef > pid = fork() > OSError: [Errno 11] Resource temporarily unavailable > > Does this have to do with rebaseall? Yes. Rebase your system (via rebaseall) following the instructions in the Cygwin Python but remember to use the "-T" option to specify the DLLs you built locally. After rebasing you should be good to go. > thanks again for all your help... You are welcome. Maybe three times is a charm? :,( Why don't you use the pre-built Python that is part of the standard Cygwin distribution? Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From deetsNOSPAM at web.de Sun Feb 20 10:47:38 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 20 Feb 2005 16:47:38 +0100 Subject: introspection inquiry References: <1108910710.985704.264430@c13g2000cwb.googlegroups.com> <4218A579.2060503@jessikat.fsnet.co.uk> Message-ID: > Unless I misunderstood the question, that won't work. That will > give you the name of the class the object is an instance is of. > I think he wants the name of the class the method was defined in. Where is the difference? The method is defined in a class - and an instance is created from that class. This works as expected: class ExistentialCrisis: def __init__(self, text): self.spam = text print 'In the constructor of the %s class' % self.__class__.__name__ ExistentialCrisis("egal") -- Regards, Diez B. Roggisch From miki.tebeka at zoran.com Tue Feb 1 02:54:43 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 1 Feb 2005 09:54:43 +0200 Subject: Forcing interactive interpreter without (-i) Message-ID: <20050201075442.GL2568@zoran.com> Hello All, If there a way a script can tell Python to enter interactive mode even if the -i command line switch was not given? I want py2exe to create an interactive session, without writing my own REPL. Thanks. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From jeff at ccvcorp.com Wed Feb 16 19:33:53 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 16 Feb 2005 16:33:53 -0800 Subject: Font size In-Reply-To: <4213e033$1@news.comindico.com.au> References: <42126822@news.comindico.com.au> <42129ea1@news.comindico.com.au> <4213e033$1@news.comindico.com.au> Message-ID: <1117phbb4ftst29@corp.supernews.com> Adam wrote: > Here's what I'm trying to do. > We are running a numbers game at our retirement village and using a roulette > wheel to generate the numbers. but this wheel is only about 12 in diameter > and is little more than a toy. So we came up with the idea of using a random > number generator to generate numbers from 0 to 36 and display them in large > figures on my laptop. This is for the benefit of those people who are hard > of hearing. They like to see what is happening. > I was an RPG programmer before retirement but am new to Python. So I used > the following code to generate the numbers but I don't know how to display > them in large figures (about 3 ins high) or get rid of the idle text. The problem is that console displays don't support variable font sizes. In order to do this, you're going to need to write a simple GUI program, which will be significantly more complex. A simple program to display a random number in large text should be relatively easy to do in Tkinter, which has the benefit of being bundled with your Python distribution. (It's got a few downsides, too, but most of them won't apply for this project.) I haven't actually looked at it, but EasyGui (recently mentioned here; google should help you find it) may meet your needs and be simpler to use. Jeff Shannon Technician/Programmer Credit International From R.Brodie at rl.ac.uk Wed Feb 9 13:45:57 2005 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 9 Feb 2005 18:45:57 -0000 Subject: Java Integer.ParseInt translation to python References: <008d01c507f4$451d9b30$2820790d@stso.xcdg.xerox.com> <372a762405013116263a4e93b7@mail.gmail.com> <1107950708.037808.211570@l41g2000cwc.googlegroups.com> Message-ID: "John Machin" wrote in message news:1107950708.037808.211570 at l41g2000cwc.googlegroups.com... > jose isaias cabrera wrote: > > > the question is, how can I make this java (byte) call in python? so > that the > > result would be the right one, "[B at 1616c7" > However some Java code (I can't believe that it was the Java code that > you posted) has printed NINE bytes which bear no relation that I can > see to any of the TWENTY bytes that the posted Java code should have > stowed in retBuf. Well my Java is pretty rusty but I imagine the interpretation of that output is "an array of bytes at address 1616c7". It doesn't actually matter what the contents are. From roy at panix.com Wed Feb 2 11:15:42 2005 From: roy at panix.com (Roy Smith) Date: 2 Feb 2005 11:15:42 -0500 Subject: Python Code Auditing Tool References: <7xhdkvbjab.fsf@ruckus.brouhaha.com> Message-ID: In article , System Administrator wrote: > > >> Does anybody know of a tool that can tell me all possible exceptions > >> that might occur in each line of code? What I'm hoping to find is > >> something like the following: > > Paul> That is impossible. The parameter to the raise statement is a > Paul> class object, which can be anything. > >Sure, but in all but the rarest of cases the first arg to raise is a >specific exception, probably one of the standard exceptions. In the Python >code in the distribution (ignoring the test directory where all sorts of >mischief is done to stress things), here are the most common words following >"raise" where "raise" is the first word on the line: > > % find . -name '*.py' \ > > | egrep -v '\./test' \ > > | xargs egrep '^ *raise ' \ > > | awk '{print $3}' \ > > | sed -e 's/[(,].*//' \ > > | sort \ > > | uniq -c \ > > | sort -rn \ > > | head -15 > 246 ValueError > 227 aetools.Error > 216 Error > 124 TypeError > 101 error > 75 RuntimeError > 53 IOError > 36 NotImplementedError > 36 ImportError > 36 EOFError > 31 SyntaxError > 23 KeyError > 23 AttributeError > 22 DistutilsPlatformError > 21 UnicodeError It's kind of interesting (scarry?) that in roughly 20% of the cases nothing more specific than Error is raised. From simoninusa2001 at yahoo.co.uk Thu Feb 10 14:55:34 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 10 Feb 2005 11:55:34 -0800 Subject: PyQt and Python 2.4 - also WinXP LnF? References: <1108003471.242829.297030@o13g2000cwo.googlegroups.com> Message-ID: <1108065334.812586.63620@g14g2000cwa.googlegroups.com> I've just read the Qt4 GPL for Windows will only support gcc (and maybe MinGW) anyway, not BCC or VisualC++ (or it's free equivalents), so it looks like it would be a daunting task to actually build PyQt.... See http://osnews.com/comment.php?news_id=9675 I guess the Qt used in PyQt from BlackAdder just wasn't built with XP support, and if I can't use it to compile PyQt properly, then it's worthless to me. I guess a lot of this licensing crap will change when Qt4 GPL is actually released, but it's still looking like commercial Qt is the only "easy" way to go, and the Trolls are just making a "difficult" GPL version to shut people up! From peter at engcorp.com Tue Feb 15 07:28:33 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 15 Feb 2005 07:28:33 -0500 Subject: Kill GIL In-Reply-To: <4211e287@duster.adelaide.on.net> References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <86sm405d38.fsf@guru.mired.org> <4211e287@duster.adelaide.on.net> Message-ID: Adrian Casey wrote: > Aahz wrote: >>Threads and forks tend to be problematic. This is one case I'd recommend >>against threads. > > Multiple threads interacting with stdin/stdout? I've done it with 2 queues. > One for feeding the threads input and one for them to use for output. In > fact, using queues takes care of the serialization problems generally > associated with many threads trying to access a single resource (e.g. > stdout). Python Queues are thread-safe so you don't have to worry about > such issues. Hee hee.... do you realize who you're writing these comments to? This is like someone telling _me_ I could be more effective using test-driven development to write my code... ;-) -Peter From invalidemail at aerojockey.com Mon Feb 28 17:53:08 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 28 Feb 2005 14:53:08 -0800 Subject: accessor/mutator functions In-Reply-To: <1109315698.002207.245690@g14g2000cwa.googlegroups.com> References: <1109315698.002207.245690@g14g2000cwa.googlegroups.com> Message-ID: <1109631188.883036.113960@z14g2000cwz.googlegroups.com> mirandacascade at yahoo.com wrote: > When I look at how classes are set up in other languages (e.g. C++), I > often observe the following patterns: > 1) for each data member, the class will have an accessor member > function (a Get function) > 2) for each data member, the class will have a mutator member function > (a Set function) > 3) data members are never referenced directly; they are always > referenced with the accessor and mutator functions > > My questions are: > a) Are the three things above considered pythonic? No. It's not good programming practice in C++, either. If you have a class that's nothing but a big data structure, you ought to use it as a data structure. Writing accessor and mutator methods for its fields is just doing a lot of work to accomplish nothing. If you want to provide access to a certain occasional field, but you're concerned about keeping the interface backwards-compatible, go ahead and use them. But try to observe the following rules of thumb: 1. Don't provide accessor or mutator function to every single member of every single class you write. Only provide accessor/mutator functions if the accessor/mutator methods are a sensible and useful part of the class's interface. 2. Don't think of these methods as accessors or mutators. Instead, think of them as methods that access or mutate a certain abstract property of the object that happens to be represented by a single member. And, keep in mind that, since Python doesn't really have private data, you don't have to worry about adding these functions to make debugging easier. > b) What are the tradeoffs of using getattr() and setattr() rather than > creating accessor and mutator functions for each data member? Don't use getattr and setattr unless you have to construct the name of the attribute at run time. That's what they're for. -- CARL BANKS From steven.bethard at gmail.com Wed Feb 16 12:36:00 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 16 Feb 2005 10:36:00 -0700 Subject: check if object is number In-Reply-To: References: <374ho0F560ughU1@individual.net><66WdnbJbuf5yj5DfRVn-iA@comcast.com> Message-ID: Fredrik Lundh wrote: > Steven Bethard wrote: > >>>Actually no, floats don't meet this behaviour or more specifically >>>floats don't guarantee this behaviour. It depends of course on >>>your implementation of f, but it is possible with floats to keep >>>incrementing and never reach a maximum. >> >>My code won't hit this corner case. I'm incrementing with integers. > > > incrementing what with integers? > > >>> f = 9007199254740992.0 > >>> f == f+1 > True I mean that the number that's being incremented is an integer: py> f = 9007199254740992.0 py> i = 9007199254740991 py> i <= f True py> i += 1 py> i <= f True py> i += 1 py> i <= f False Steve From cam.ac.uk at mh391.invalid Thu Feb 17 04:52:20 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 17 Feb 2005 09:52:20 +0000 Subject: Why doesn't join() call str() on its arguments? In-Reply-To: References: <37hippF4gcimiU1@individual.net> <37hqlrF59l2b2U1@individual.net> <873bvw9nqh.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Nick Craig-Wood wrote: > Why not have another method to do this? I propose joinany which will > join any type of object together, not just strings I think that's what Frederik was proposing. Except that it would be called join and be a built-in (not a str method). -- Michael Hoffman From cpl.19.ghum at spamgourmet.com Sun Feb 6 15:27:08 2005 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sun, 6 Feb 2005 20:27:08 +0000 (UTC) Subject: Googling for wmi and python.... Message-ID: I upgraded Python to 2.4 now the game really starts, looking all over the internet for all the packages ... I needed Tim Goldens WMI ... and googeld, dropping there: http://www.microsoft.com/technet/scriptcenter/scripts/python/misc/wmi/defau lt.mspx With comment: Sample scripts for retrieving WMI configuration information. These sample scripts were written using Python for Windows. For sample scripts written using VBScript, please visit the Script Repository home page. And that is above Tims GREAT WMI.module ... just wanted to drop that note. From jbauer at rubic.com Mon Feb 21 21:17:22 2005 From: jbauer at rubic.com (jbauer at rubic.com) Date: 21 Feb 2005 18:17:22 -0800 Subject: subclassing Decimal References: <1109022264.823730.224910@o13g2000cwo.googlegroups.com> <8sadneLa1dUmxoffRVn-uw@comcast.com> Message-ID: <1109038642.719116.221250@o13g2000cwo.googlegroups.com> STeVe, Thanks for the response. Very clear. yea-though-I-walk-thru-the-valley-of-__new__-I-will-fear-no-super-ly y'rs, -Jeff From claird at lairds.us Tue Feb 1 00:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 01 Feb 2005 05:08:04 GMT Subject: variable declaration References: <1gr9ltj.1tiisn018pnse6N%aleaxit@yahoo.com> Message-ID: In article <1gr9ltj.1tiisn018pnse6N%aleaxit at yahoo.com>, Alex Martelli wrote: >Robert Brewer wrote: > >> Bah. Nothing teaches you a new language like having your job depend upon >> it. People who study languages merely for "personal growth" learn 50% of >> the syntax and 1% of the concepts, and then fritter that learning away >> on inconsequential newsgroups the world over. > >I disagree. I studied Python, even though it had nothing to do with my >job, just with the idea of using it on hobby projects; yet I believe I >can reasonably claim to have learned more than 50% of the syntax and 1% >of the concepts, even though you might claim that, whatever percentage >it may be, it's "frittered away on inconsequential newsgroups". > > >Alex We learned long ago to treat you, Alex, as an exception. While it's rather unpythonic to have implicit rules, let's forgive Robert for failing to mention the one that regards you as an outlier for inferential purposes. From x2164 at mailcity.com Tue Feb 15 13:08:54 2005 From: x2164 at mailcity.com (x2164 at mailcity.com) Date: 15 Feb 2005 18:08:54 GMT Subject: test_socket.py failure References: Message-ID: x2164 at mailcity.com wrote: > hi all, > Linux 2.4.28 > Glibc 2.2.5 > gcc 2.95.3 > I'm new to Python. > I've compiled Python 2.4 from tar file. > When running 'make test' i'm getting a failure > in test_socket. > Running './python Lib/test/test_socket.py' yields: > ====================================================================== > ERROR: testGetServBy (__main__.GeneralModuleTests) > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "Lib/test/test_socket.py", line 330, in testGetServBy > port2 = socket.getservbyname(service) > error: service/proto not found > ---------------------------------------------------------------------- > Ran 58 tests in 3.826s > The value of 'service' was "daytime". > After much hand wringing, editing, and use of 'print' > statements i commented out line 330, > '# port2 = socket.getservbyname(service)' and replaced it > with the line 'port2 = port'. > Running './python Lib/test/test_socket.py' now yields: > testGetServBy (__main__.GeneralModuleTests) ... ok > . > . > . > ---------------------------------------------------------------------- > Ran 58 tests in 5.181s > OK > > Located the code for 'socket_getservbyname' in > 'Modules/socketmodule.c' where the call to the glibc > function 'getservbyname' is made: > Py_BEGIN_ALLOW_THREADS > sp = getservbyname(name, proto); > Py_END_ALLOW_THREADS > if (sp == NULL) { > PyErr_SetString(socket_error, "service/proto not found"); > return NULL; > } > > The only call of socket.getservbyname that failed was when > it was passed the single argument. Since the error message > "service/proto not found" seems to only be generated upon > failure of gibc's 'getservbyname' could it be that > 'PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto)' > generates values for 'name' and/or 'proto' that cause the > failure? > My search for prior reports of failure at line 330 found > a mention of problems at line 331. > Well, at any rate, if someone could point me down the > correct path on this i would appreciate it. > pete jordan > x2164 -> mailcity.com > -> equals at symbol > > http://www.die.net/doc/linux/man/man3/getservbyname.3.html > The above link was provide by Nick Coghlan. Thanks Nick. Well if the man page says it, then it must be so. By way of follow up i wanted to let you know that i think i've found the reason why i was getting the getservbyname behaviour that i described. In my /etc/nsswitch.conf file the original line for scanning the /etc/services file was: services: nisplus [NOTFOUND=return] db files The nisplus module was being used first to scan the file and it apparently returns 'NOTFOUND' when proto is NULL. '[NOTFOUND=return]' then stops any of the other two services, 'db' and 'files', from being used to scan the 'services' file. I changed the 'services:' line to: services: nisplus db files and now if proto is NULL the first line in the 'services' file, matching the service argument passed to getservbyname, is passed back. This seems to be consistent behaviour with the man page link above. I'm not sure removing '[NOTFOUND=return] ' is 100% correct but from information in the libc info page i think it will do. Later i'll post this as a followup to comp.lang.python thread in case someone else might have the problem. Thanks for the help. pete jordan x2164 AT mailcity com From alanmk at hotmail.com Thu Feb 10 12:21:45 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 10 Feb 2005 17:21:45 +0000 Subject: goto, cls, wait commands In-Reply-To: <1ixbe7q69lob3.1npuu3z54gx8z.dlg@40tude.net> References: <1ixbe7q69lob3.1npuu3z54gx8z.dlg@40tude.net> Message-ID: [BOOGIEMAN] > I've just finished reading Python turtorial for non-programmers > and I haven't found there anything about some usefull commands I used in > QBasic. First of all, what's Python command equivalent to QBasic's "goto" ? Oh no! You said the "G" word! That's a dirty word in computer science circles, because of the perception that "goto" (there, I said it, ugh!) can lead people to structure their code badly, i.e. write bad programs. Instead, most modern programming languages offer a range of control and looping constructs that allow you to code your intention more clearly than with goto. Python examples include "while", "for .. in ..", "try .. except ..", etc, etc. So in order to answer your question, you're probably going to have to be more specific on what you want "goto" for. Interestingly, "goto"s are undergoing a bit of renaissance in coding circles, but people have felt compelled to call them something different: continuations. But you're probably not interested in them. And python can't do them anyway. > Secondly, how do I clear screen (cls) from text and other content ? That depends on A: What type of display device you're using B: What type of interface is being rendered on that display (command line, GUI, IDE, etc) C: Perhaps what operating system you are using. > And last, how do I put program to wait certain amount of seconds ? > If I remeber correctly I used to type "Wait 10" and QBasic waits > 10 seconds before proceeding to next command. Ahhhhhh, a simple question! :-) import time time.sleep(10.0) HTH, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From steven.bethard at gmail.com Fri Feb 11 14:11:44 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 11 Feb 2005 12:11:44 -0700 Subject: check if object is number Message-ID: Is there a good way to determine if an object is a numeric type? Generally, I avoid type-checks in favor of try/except blocks, but I'm not sure what to do in this case: def f(i): ... if x < i: ... The problem is, no error will be thrown if 'i' is, say, a string: py> 1 < 'a' True py> 10000000000 < 'a' True But for my code, passing a string is bad, so I'd like to provide an appropriate error. I thought about calling int() on the value, but this will also allow some strings (e.g. '1'). I guess this isn't horrible, but it seems somewhat suboptimal... Ideas? Steve From ilias at lazaridis.com Thu Feb 17 12:43:30 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Thu, 17 Feb 2005 19:43:30 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <37bkemF5a7s7vU1@individual.net> <86ll9piuj8.fsf@guru.mired.org> Message-ID: Stephen Kellett wrote: [...] closing thread http://groups-beta.google.com/group/comp.lang.python/msg/f2ae9cdbe16676d1 . -- http://lazaridis.com From alanmk at hotmail.com Sun Feb 13 09:38:32 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 13 Feb 2005 14:38:32 +0000 Subject: For American numbers In-Reply-To: References: <420e7376$1@nntp0.pdx.net> Message-ID: [Scott David Daniels] >> Kind of fun exercise (no good for British English). >> >> def units(value, units='bytes'): >> magnitude = abs(value) >> if magnitude >= 1000: >> for prefix in ['kilo mega giga tera peta ' >> 'exa zetta yotta').split(): >> magnitude /= 1000. >> if magnitude < 1000.: >> break > > [Peter Hansen] > Only for hard drive manufacturers, perhaps. > > For the rest of the computer world, unless I've missed > a changing of the guard or something, "kilo" is 1024 > and "mega" is 1024*1024 and so forth... Maybe you missed these? http://en.wikipedia.org/wiki/Kibibyte http://en.wikipedia.org/wiki/Mebibyte http://en.wikipedia.org/wiki/Gibibyte kilo-mega-giga-etc-should-be-powers-of-10-ly y'rs, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From davidf at sjsoft.com Thu Feb 3 23:31:28 2005 From: davidf at sjsoft.com (David Fraser) Date: Fri, 04 Feb 2005 06:31:28 +0200 Subject: Is there a market for python developers? In-Reply-To: <1107440354.317628.221090@g14g2000cwa.googlegroups.com> References: <1107440354.317628.221090@g14g2000cwa.googlegroups.com> Message-ID: Mabon Dane wrote: > I am new to python and took my first attempts at working with this > language today. Is there a market for people who work with Python? > Slavery is outlawed in most parts of the world these days :-) From eppstein at ics.uci.edu Fri Feb 25 00:29:12 2005 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 24 Feb 2005 21:29:12 -0800 Subject: [perl-python] generic equivalence partition References: <1109245733.261643.219420@f14g2000cwb.googlegroups.com> Message-ID: In article , David Eppstein wrote: > def parti(aList,equalFunc): > eqv = [] > for i in range(len(aList)): > print i,eqv > for L in eqv: > if equalFunc(aList[i],aList[L[0]]): > L.append(i) > break; > else: > eqv.append([i]) Um, take out the print, that was just there for me to debug my code. -- David Eppstein Computer Science Dept., Univ. of California, Irvine http://www.ics.uci.edu/~eppstein/ From grante at visi.com Thu Feb 10 11:21:06 2005 From: grante at visi.com (Grant Edwards) Date: 10 Feb 2005 16:21:06 GMT Subject: goto, cls, wait commands References: <1ixbe7q69lob3.1npuu3z54gx8z.dlg@40tude.net> Message-ID: <420b89f2$0$21601$a1866201@visi.com> On 2005-02-10, BOOGIEMAN wrote: > First of all, what's Python command equivalent to QBasic's "goto" ? There isn't one. One defines functions and calls them. One uses for and while loops. One uses list comprehensions. One uses if/elif/else. > Secondly, how do I clear screen (cls) from text and other content ? That depends on the host system. Under Unix, you can do os.system('clear'). Or you can use ncurses. Or you can use os.system to run the 'tput' command with appropriate parameters -- see the tput man page. There's probably some way to do it in Windows as well, but I don't do windows. > And last, how do I put program to wait certain amount of > seconds ? time.sleep(1) will wait for 1 second. time.sleep(5.5) will wait for 5.5 seconds. -- Grant Edwards grante Yow! Yow! I like my new at DENTIST... visi.com From phark52 at yahoo.com Sat Feb 26 19:09:18 2005 From: phark52 at yahoo.com (Artificial Life) Date: Sun, 27 Feb 2005 00:09:18 GMT Subject: Xlib in Python? I need XDrawString() Message-ID: All I really want is to write a few strings to the background of my X display. XDrawString() is what I need. The Xlib for Python shows it's out dated. Is there any alternative? From bdesth.quelquechose at free.quelquepart.fr Thu Feb 3 04:43:31 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 03 Feb 2005 10:43:31 +0100 Subject: IDLE history, Python IDE, and Interactive Python with Vim In-Reply-To: <4201e761$0$606$636a15ce@news.free.fr> References: <1107419485.368275.45240@l41g2000cwc.googlegroups.com> <4201e761$0$606$636a15ce@news.free.fr> Message-ID: <4201f00f$0$518$636a15ce@news.free.fr> Pierre Barbier de Reuille a ?crit : > Fuzzyman a ?crit : > >> If you use IPython for your interactive mode stuff, you'll have a nice >> history... >> Regards, >> >> Fuzzy >> http://www.voidspace.org.uk/python/index.shtml >> > > Best event : if your "EDITOR" system variable in "vim", using the "ed" > command in ipython will bring "vim" with (eventually) the code you want > to edit :) > > Now, I wonder if you could embed ipython inside vim ... Don't know, but you can embed ipython inside emacs !-) > Pierre From miki.tebeka at zoran.com Tue Feb 15 04:56:06 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 15 Feb 2005 11:56:06 +0200 Subject: How to implement a file lock ?? In-Reply-To: References: Message-ID: <20050215095545.GD3336@zoran.com> Hello ionel, > is there a cross-platform library or module for file locking? > or at least a win32 implementation. > > i'm trying to get a lock on some file in a cgi script. ( i got my data > erased a few times :P ) I'm using: --------- from os import open as _open, O_CREAT, O_EXCL, O_RDWR lockfile = "/tmp/some_lock" lockfd = None def lock(): global lockfd try: lockfd = _open(lockfile, O_CREAT|O_EXCL|O_RDWR) write(lockfd, "%d" % getpid()) return 1 except OSError: # Already locked lockfd = None return 0 def unlock(): if not lockfd: return 0 try: close(lockfd) remove(lockfile) return 1 except OSError: return 0 --------- You can wrap it in a class. However make sure you unlock either on __del__ with is a bit tricky or atexit.register(unlock) which is better. HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From http Wed Feb 16 11:23:49 2005 From: http (Paul Rubin) Date: 16 Feb 2005 08:23:49 -0800 Subject: low-end persistence strategies? References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <1108570047.677348.146850@f14g2000cwb.googlegroups.com> Message-ID: <7x7jl8bhii.fsf@ruckus.brouhaha.com> "Michele Simionato" writes: > What about bsddb? On most Unix systems it should be already > installed and on Windows it comes with the ActiveState distribution > of Python, so it should fullfill your requirements. As I understand it, bsddb doesn't expose the underlying Sleepycat API's for concurrent db updates, nor does it appear to make any attempt at locking, based on looking at the Python lib doc for it. There's an external module called pybsddb that includes this stuff. Maybe the stdlib maintainers ought to consider including it, if it's considered stable enough. From http Mon Feb 14 17:51:31 2005 From: http (Paul Rubin) Date: 14 Feb 2005 14:51:31 -0800 Subject: Kill GIL (was Re: multi threading in multi processor (computer)) References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <1107964587.818199.223980@g14g2000cwa.googlegroups.com> <7xr7jlwieq.fsf@ruckus.brouhaha.com> Message-ID: <7xekfisqks.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > >[phr] The day is coming when even cheap computers have multiple cpu's. > >See hyperthreading and the coming multi-core P4's, and the finally > >announced Cell processor. > > > >Conclusion: the GIL must die. > > It's not clear to what extent these processors will perform well with > shared memory space. One of the things I remember most about Bruce > Eckel's discussions of Java and threading is just how broken Java's > threading model is in certain respects when it comes to CPU caches > failing to maintain cache coherency. Um??? I'm not experienced with multiprocessors but I thought that maintaining cache coherency was a requirement. What's the deal? If coherency isn't maintained, is it really multiprocessing? > It's always going to be true that getting fully scaled performance > will require more CPUs with non-shared memory -- that's going to > mean IPC with multiple processes instead of threads. But unless you use shared memory, the context switch overhead from IPC becomes a bad bottleneck. See http://poshmodule.sourceforge.net/posh/html/node1.html for an interesting scheme of working around the GIL by spreading naturally multi-threaded applications into multiple processes (using shared memory). It would simplify things a lot if you could just use threads. From tchur at optushome.com.au Mon Feb 7 18:47:25 2005 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 08 Feb 2005 10:47:25 +1100 Subject: Big development in the GUI realm Message-ID: <200502072347.j17NlPnh012281@mail07.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From lbates at syscononline.com Mon Feb 28 15:40:36 2005 From: lbates at syscononline.com (Larry Bates) Date: Mon, 28 Feb 2005 14:40:36 -0600 Subject: Working with dbase files In-Reply-To: <7MyUd.73116$911.65438@fe2.texas.rr.com> References: <7MyUd.73116$911.65438@fe2.texas.rr.com> Message-ID: On MS Windows use built in ODBC support to xBase files which supports read and write access. Larry Bates Stan Cook wrote: > Does anyone know how I can access and read data from a dbase (.dbf) file? > > Regards, > > Stan From grante at visi.com Mon Feb 21 10:22:17 2005 From: grante at visi.com (Grant Edwards) Date: 21 Feb 2005 15:22:17 GMT Subject: - E02 - Support for MinGW Open Source Compiler References: <42172136$0$27576$9b622d9e@news.freenet.de> <42185b05$0$15460$9b622d9e@news.freenet.de> <42189527$0$6260$9b622d9e@news.freenet.de> <4218cafe$0$8790$9b622d9e@news.freenet.de> <1108922969.140196.304380@z14g2000cwz.googlegroups.com> <878y5i9ayp.fsf@localhost.localdomain.i-did-not-set--m Message-ID: <4219fca9$0$44593$a1866201@visi.com> On 2005-02-20, Nick Vargish wrote: > "BrainDead" writes: > >> I believe that you are wasting your time. Looking at your email >> address, this may well be relevant. > [ 4-line URL snipped ] > > Thanks for the historical reference. Please consider a visit to > tinyurl.com before posting a monster like that... :^) I've never understood the problem with long URLs. Many newsreaders let you click on them. If not, you just cut/paste it into a browser (with a shellscript a couple lines long, you can start firefox with the URL on the X clipboard with a single command). -- Grant Edwards grante Yow! I'm a GENIUS! I at want to dispute sentence visi.com structure with SUSAN SONTAG!! From vetter at lincom-asg.com Tue Feb 8 09:26:03 2005 From: vetter at lincom-asg.com (Keith) Date: 8 Feb 2005 06:26:03 -0800 Subject: PHP Embedded In Python In-Reply-To: <1107818262.741563.266050@c13g2000cwb.googlegroups.com> References: <1107814685.908990.58410@z14g2000cwz.googlegroups.com> <1107818262.741563.266050@c13g2000cwb.googlegroups.com> Message-ID: <1107872763.019447.281670@c13g2000cwb.googlegroups.com> jdonnell wrote: > I'm not sure exactly what your trying to do, but I use php and python > together a lot. I usually call the python script from php with the > passthru function like this: > > $outputFromPy = passthru('/path/to/myScript.py'); > ?> I need to go the other direction. I need to call php from within python. Thanks. From thomas at thomas-lotze.de Tue Feb 15 03:43:58 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Tue, 15 Feb 2005 09:43:58 +0100 Subject: StringIO objects sharing a buffer Message-ID: Hi, I want to implement a tokenizer for some syntax. So I thought I'd subclass StringIO and make my new class return tokens on next(). However, if I want to read tokens from two places in the string in turns, I'd either need to do some housekeeping of file pointers outside the tokenizer class (which is ugly) or use two tokenizers on the same data buffer (which seems impossible to me using my preferred approach as a file-like object has exactly one file pointer). Is there a way for multiple StringIO objects to share a buffer of data, or do I have to give up on subclassing StringIO for this purpose? (An alternative would be a tokenizer class that has a StringIO instead of being one and do the file pointer housekeeping in there.) -- Thomas From michele.simionato at gmail.com Sat Feb 26 03:54:11 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 26 Feb 2005 00:54:11 -0800 Subject: Watermark on images In-Reply-To: <1109403419.904324.115860@f14g2000cwb.googlegroups.com> References: <1109403419.904324.115860@f14g2000cwb.googlegroups.com> Message-ID: <1109408051.728870.35790@f14g2000cwb.googlegroups.com> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879 From steven at lczmsoft.com Sat Feb 26 01:03:23 2005 From: steven at lczmsoft.com (steven at lczmsoft.com) Date: 25 Feb 2005 22:03:23 -0800 Subject: Source Encoding GBK/GB2312 In-Reply-To: <421d5a29$1_3@newspeer2.tds.net> References: <1109217736.643721.201240@o13g2000cwo.googlegroups.com> <421d5a29$1_3@newspeer2.tds.net> Message-ID: <1109397803.527602.199770@z14g2000cwz.googlegroups.com> Thank you All ! I am going to update ... From fuzzyman at gmail.com Wed Feb 2 09:14:08 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 2 Feb 2005 06:14:08 -0800 Subject: Is this a contradiction in the docs ? In-Reply-To: <0i4Md.102585$Jk5.77392@lakeread01> References: <1107342032.273119.194120@o13g2000cwo.googlegroups.com> <0i4Md.102585$Jk5.77392@lakeread01> Message-ID: <1107353647.999603.252240@z14g2000cwz.googlegroups.com> Steve Holden wrote: > Fuzzyman wrote: > > > The following two passages from the python documentation *appear* to > > contradict each other. Equally possible (or more likely !) is that I > > misunderstand it : > > > > eval : > > This function can also be used to execute arbitrary code objects (such > > as those created by compile()). In this case pass a code object instead > > of a string. The code object must have been compiled passing 'eval' as > > the kind argument. > > > > > > compile: > > The kind argument specifies what kind of code must be compiled; it can > > be 'exec' if string consists of a sequence of statements, 'eval' if it > > consists of a single expression, or 'single' if it consists of a single > > interactive statement (in the latter case, expression statements that > > evaluate to something else than None will be printed). > > > > The docs for compile say that if you are creating a code object from a > > sequence of statements you must use the kind argument 'exec'. Eval says > > that if you are using the eval function you must use 'eval' as your > > kind argument. > > > > In practise I have found that using the eval function with code objects > > compiled with 'exec' as the kind argument works fine. Is this a 'bug' > > in the docs ? > > Regards, > > > > "Dear List: > > I live close to a railroad, and the tracks are surrounded by a fence > with large signs saying 'Walking on the tracks can be dangerous'. > > I have walked on the tracks several times, however, and I don't see why > the railway company put those signs there. In fact I'm walking along the > tracks right now as I enter this post on my hand-held, and > > [message ends with sound of locomotive horn followed by an ugly squelch]." > > That's the kind of practice best avoided. Are you breaking the rules > just for the fun of it? > Hmm.... documentation on code objects says : Code objects are returned by the built-in compile() function and can be extracted from function objects through their func_code attribute. A code object can be executed or evaluated by passing it (instead of a source string) to the exec statement or the built-in eval() function. It mentions no such restriction. I didn't properly absorb the 'must' in the eval description...... Hmmm... my code will *never* need to run on anything other than CPython because I use py2exe to turn it into a frozen python distribution. So if it was always safe in CPython then that would be fine for me. The reason I like eval is that "If both dictionaries are omitted, the expression is executed in the environment where eval is called". However I think exec might do the same thing anyway. I'll just switch to exec. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > regards > Steve > -- > Meet the Python developers and your c.l.py favorites March 23-25 > Come to PyCon DC 2005 http://www.python.org/pycon/2005/ > Steve Holden http://www.holdenweb.com/ From simon.brunning at gmail.com Wed Feb 16 10:13:47 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 16 Feb 2005 15:13:47 +0000 Subject: Test for structure In-Reply-To: <1108566497.848623.45360@c13g2000cwb.googlegroups.com> References: <1108566497.848623.45360@c13g2000cwb.googlegroups.com> Message-ID: <8c7f10c6050216071314fa528d@mail.gmail.com> On Wed, 16 Feb 2005 07:11:08 -0800 (PST), alex wrote: > how can I check if a variable is a structure (i.e. a list)? For my > special problem the variable is either a character string OR a list of > character strings line ['word1', 'word2',...] > > So how can I test if a variable 'a' is either a single character string > or a list? I tried: > > if a is list: > > but that does not work. I also looked in the tutorial and used google > to find an answer, but I did not. > > Has anyone an idea about that? -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From paul at boddie.org.uk Wed Feb 23 03:07:12 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 23 Feb 2005 00:07:12 -0800 Subject: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux & Windows XP References: <5339b60d.0502220700.3ec7ae56@posting.google.com> <1109090264.676680.99150@o13g2000cwo.googlegroups.com> Message-ID: <5339b60d.0502230007.4442a5cf@posting.google.com> "Serge Orlov" wrote in message news:<1109090264.676680.99150 at o13g2000cwo.googlegroups.com>... > Paul Boddie wrote: > > Anyone who has needed to expose filesystems > > created by Linux distributions before the UTF-8 "big push" to later > > distributions can attest to the fact that the "see no evil" brass > > monkey is wearing a T-shirt with "UTF-8" written on it. > > Unfortunately the monkey is painted in the air with a stick, so > not everyone can see it. Python can't. Given a random linux system > how can you tell if the monkey has pushed it already or not? That's a good question. See this article for an example of the frustration caused: http://groups.google.no/groups?selm=b1npav%24cci%241%40slb6.atl.mindspring.net&output=gplain Paul From http Thu Feb 3 20:38:55 2005 From: http (Paul Rubin) Date: 03 Feb 2005 17:38:55 -0800 Subject: [Fwd: [gnu.org #220719] Re: python and gpl] References: Message-ID: <7x7jlp2jf4.fsf@ruckus.brouhaha.com> Steve Holden writes: > In the absence of other information I Cc'd gnu at gnu.org to ask their > opinion about the relationship between GPL'd Python modules and > programs that imported them In the OP's particular case, he got the agreement of the GPL'd module's author, so it stopped being an issue for that particular module. However the FSF takes the view that dynamic linking a GPL'd module does count as making a derivative work, and I'm pretty sure they have enforced this view (i.e. convinced someone who was doing it that they better stop) in the past. From jeff at ccvcorp.com Fri Feb 4 15:27:52 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 04 Feb 2005 12:27:52 -0800 Subject: returning True, False or None In-Reply-To: References: Message-ID: <1107mkt7gg1t310@corp.supernews.com> Jeremy Bowers wrote: > On Fri, 04 Feb 2005 10:48:44 -0700, Steven Bethard wrote: > >>For a given list: >>* If all values are None, the function should return None. >>* If at least one value is True, the function should return True. >>* Otherwise, the function should return False. > > Yes, I see the smell, you are searching the list multiple times. You > could bail out when you can: > > seenFalse = False > for item in list: > if item: return True > if item is False: seenFalse = True > if seenFalse: > return False > return None I'd modify this approach slightly... def tfn(lst): answer = None for item in lst: if item is True: return True if item is False: answer = False return answer But yeah, the original, straightforward way is probably enough clearer that I wouldn't bother with anything else unless lists might be long enough for performance to matter. Jeff Shannon Technician/Programmer Credit International From vincent at visualtrans.de Sun Feb 6 03:25:37 2005 From: vincent at visualtrans.de (vincent wehren) Date: Sun, 06 Feb 2005 09:25:37 +0100 Subject: Multiple constructors In-Reply-To: <6SjNd.38337$K7.21639@fe2.news.blueyonder.co.uk> References: <6SjNd.38337$K7.21639@fe2.news.blueyonder.co.uk> Message-ID: Philip Smith wrote: > Call this a C++ programmers hang-up if you like. > > I don't seem to be able to define multiple versions of __init__ in my matrix > class (ie to initialise either from a list of values or from 2 dimensions > (rows/columns)). > > Even if Python couldn't resolve the __init__ to use on the basis of argument > types surely it could do so on the basis of argument numbers??? > > At any rate - any suggestions how I code this???? Checking the number of arguments ain't all that hard: class Klass: def __init__(*args): self.args = args if len(self.args) == 1: # etc. This feels rather unpythonic, though. Maybe you could use factory functions, forgetting about __init__ all together (2.2 or higher): class Klass(object): def fromList(seq): result = Klass() # populate attributes here # and return the requested object return result fromList = staticmethod(fromList) def fromDimensions(cols, rows): result = Klass() # populate attributes here # and return the requested object return result fromDimensions = staticmethod(fromDimensions) #more methods here k = Klass.fromList(seq) etc.. Regards -- Vincent Wehren > > Thanks > > Phil > > From steven at lczmsoft.com Sun Feb 20 21:21:55 2005 From: steven at lczmsoft.com (steven at lczmsoft.com) Date: 20 Feb 2005 18:21:55 -0800 Subject: How Do I get Know What Attributes/Functions In A Class? In-Reply-To: References: <1108870842.095282.54200@z14g2000cwz.googlegroups.com> Message-ID: <1108952515.297032.306980@l41g2000cwc.googlegroups.com> Thank you Hans. Could you give me a simple sample of using inspect? From ncoghlan at iinet.net.au Mon Feb 14 04:28:28 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 14 Feb 2005 19:28:28 +1000 Subject: custom classes in sets In-Reply-To: References: Message-ID: <42106F3C.9000302@iinet.net.au> vegetax wrote: > How can i make my custom class an element of a set? > > class Cfile: > def __init__(s,path): s.path = path > > def __eq__(s,other): > print 'inside equals' > return not os.popen('cmp %s %s' % (s.path,other.path)).read() > > def __hashcode__(s): return s.path.__hashcode__() > > the idea is that it accepts file paths and construct a set of unique > files (the command "cmp" compares files byte by byte.),the files can > have different paths but the same content > > but the method __eq__ is never called Your problem is that your class defines an insane hash. For a sane hash, A == B implies hash(A) == hash(B), whereas you have based your hash on the path to the files, but the comparison on the contents of the files. If the paths are all different, then nothing is likely to hash the same, so the set will never get around to trying the direct comparison. Change the hash method to use the size of the file or something else that has to be equal for the comparison to be equal (like the hash of the first line, or of the entire file), and you should see much better behaviour. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From harlinseritt at yahoo.com Mon Feb 28 05:57:18 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 28 Feb 2005 02:57:18 -0800 Subject: Explicit or general importing of namespaces? Message-ID: <1109588238.491145.52060@l41g2000cwc.googlegroups.com> Is there really a major performance difference between doing the following: import Tkinter as TK TK.Label(yada yada) OR from Tkinter import * Label(yada yada) I'm unable to tell a real difference other than in the code writing :-). Thanks, Harlin From axel at straschil.com Thu Feb 3 04:26:28 2005 From: axel at straschil.com (Axel Straschil) Date: Thu, 3 Feb 2005 09:26:28 +0000 (UTC) Subject: Generating modul classes with eval References: Message-ID: Hello! > Note that we don't need eval anywhere. Uuups, that looks realy cool! Thanks for that! Im fooling around with generating html-tags. As there are only two kind of html tags, one who can nest chields, and one who cant, i wantet to play arround with something like: I've got two base classes, _Tag and _ContainerTag (for tags which can nest tags). Instead of getting an htmltag with _Tag(name='html'), I want to have a class for each html-tag. So, I thought of creating that classes dynamicly. my now (nearly) working code is: class _Tag(object): def __init__(self, name, flags=None, **props): [...] class _ContainerTag(_Tag): def __init__(self, name, contents=None, flags=None, **props): super(_ContainerTag, self).__init__(name=name, flags=flags, **props) self._contents = coalesce(contents, []) _module_name = sys.modules[__name__] class_dic = {} class_dic['Br'] = _Tag class_dic['Hr'] = _Tag class_dic['Html'] = _ContainerTag class_dic['Table'] = _ContainerTag for class_name, class_base in class_dic.items(): class TmpClass(class_base): def __init__(self, **props): name = class_name.lower() #super(TmpClass, self).__init__(name=name, **props) class_base.__init__(self, name=name, **props) setattr(_module_name, class_name, TmpClass) br = Br() print br table = Table() print table br is printed OK, but for table, I get: AttributeError: 'TmpClass' object has no attribute '_contents' so, it seems that __init__ of _Tag is not called. If I try to do the commented line super(TmpClass, self).__init__(name=name, **props) instead of class_base.__init__(self, name=name, **props) I get: TypeError: super(type, obj): obj must be an instance or subtype of type for print table, print br ist processed OK. Thanks for help and your perfekt examples, AXEL. From aleaxit at yahoo.com Sun Feb 6 10:57:31 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 6 Feb 2005 16:57:31 +0100 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1grifns.14san6f1b076mdN%aleaxit@yahoo.com> <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com> <1grj036.r13xcy1d72inbN%aleaxit@yahoo.com> <2qba01d1men2ai48gp4cojo2e28rd5g9ob@4ax.com> <1grjzia.1a4qr9q1t3p77bN%aleaxit@yahoo.com> Message-ID: <1grkmo3.5kt3jumncr52N%aleaxit@yahoo.com> Roy Smith wrote: > > which is good news for sellers of books, tools, training, consultancy > > services, and for Python programmers everywhere -- more demand always > > helps. *BUT* the price is eternal vigilance... > > I'm not sure what that last sentence is supposed to mean, but I have You seem to...: > visions (nightmares?) of someday having ANSI, ISO, IEEE, or some other such > organization notice that something useful exists which they haven't yet > standardized/broken and decide to form a committee to do it. ...so we'd better be careful (==eternal vigilance)... Alex From sharidas at zeomega.com Thu Feb 10 08:49:54 2005 From: sharidas at zeomega.com (Satchidanand Haridas) Date: Thu, 10 Feb 2005 19:19:54 +0530 Subject: implementing singleton class at the module level Message-ID: <420B6682.6090001@zeomega.com> Hi, I was looking at ways to implement a Singleton class. I saw some methods described on the PythonSingleton wiki (http://c2.com/cgi/wiki?PythonSingleton). I implemented the following. module: A.py ---------------------- class Singleton: def __init__(self): #do something singleton_instance = Singleton() Then in any other module (eg B.py): from A import singleton_instance singleton_instance will be created only once and can be reused in other modules. But is this ok? I am trying to figure out what are the disadvantages of using the above method. I would appreciate any comments. thanks. regards, Satchit From ted_lilley at yahoo.com Fri Feb 18 05:28:41 2005 From: ted_lilley at yahoo.com (Thomas Lilley) Date: Fri, 18 Feb 2005 02:28:41 -0800 (PST) Subject: COM+metaclass+property issue Message-ID: <20050218102841.14987.qmail@web51902.mail.yahoo.com> I'm trying to manufacture a class that provides attributes which mimic the HTML collections offered by the Internet Explorer COM object. My platform is Win32 (Windows XP) and ActiveState's latest Python 2.3. The problem is, my attributes are based on properties, which work fine except for when I have a win32com collection returned, they don't appear to have any information in them. Part of my code: from win32com.client import Dispatch class metaie(type): def __init__(cls, name, bases, dict): super(metaie, cls).__init__(name, bases, dict) for tag in cls.tags: setattr(cls, tag, property(lambda self: self.ie.Document.getElementsByTagName(tag))) class ie(object): __metaclass__ = metaie tags = ["a", "area", "body", "button", "fieldset", "form", "frame", "head", "html", "img", "li", "link", "ol", "table", "td", "tr", "ul"] def __init__(self): self.ie = Dispatch("InternetExplorer.Application") An example of the problem: >>>myie = ie() >>>myie.ie.Document.Navigate(http://www.google.com/) >>>myie.table.length 0 >>>myie.ie.getElementsByTagName("table").length 2 A quick note: ie is my wrapper class, while ie.ie is the win32com Dispatch object representing Internet Explorer. My code should be creating a property attribute for each tag in the tags list and binding it to getElementsByTagName() with the tag pre-loaded by the lambda expression. This means that reading the attribute myie.table should be equivalent to a call to ie.ie.Document.getElementsByTagName("table"). But for some reason, it's not working. Other property assignments in the metaclass that don't refer to getElementsByTagName work fine (for example, I make ie.url an attribute that navigates to whatever location you assign to it). Is there any guru who understands these tools out there who can help? In case you're wondering, the reason I brought metaclasses into the picture is that you can't iterate through a list of attribute assignments within the class definition using setattr or __dict__ because the former requires a class name (doesn't exist until the class statement completes) and the latter doesn't seem to exist for classes, at least, I couldn't find a class __dict__. --------------------------------- Do you Yahoo!? Meet the all-new My Yahoo! ? Try it today! -------------- next part -------------- An HTML attachment was scrubbed... URL: From sean_mcilroy at yahoo.com Mon Feb 28 15:06:06 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 28 Feb 2005 12:06:06 -0800 Subject: canvassing for assistance Message-ID: Hi all! I've written a utility for making diagrams. It could also be a good environment for experimenting with a Tk canvas, so I'm including the code here (see below). The problem is that, when I save a canvas and include the resulting postscript file in a LaTeX document, I often find that the right edge of the canvas has been cut off and/or that there's a bunch of extra space at the bottom that forces the picture to take up a whole page just by itself. The Introduction to Tkinter lists a bunch of options for the Canvas postscript method, but it doesn't say anything about the semantics of any of them, and there are several that sound like they could be what I need. So, if anybody knows how to exercise finer control over the Canvas postscript method, I'd be grateful to hear about it. Peace, STM ############################################### ## FRESH SHELL: import canvasser ## (so that text can be copied from the shell) ############################################### pencil = 1 eraser = 10 color = 'black' def save(): from tkSimpleDialog import askstring filename = askstring('save diagram','enter name of diagram: ') + '.eps' canvas.postscript(file=filename,width=100,height=100,pagewidth=100,pageheight=100) def circle(x,y,radius=25,color=None): r = radius return canvas.create_oval(x-r,y-r,x+r,y+r,fill=color) ################################################################################# __P__ = None __I__ = None def draw(event): global __P__ Q = [event.x,event.y] canvas.create_line(__P__[0],__P__[1],Q[0],Q[1],width=pencil,fill=color) __P__ = Q def erase(event): r = eraser x,y = event.x,event.y for x in canvas.find_overlapping(x-r,y-r,x+r,y+r): canvas.delete(x) def carry(event): if __I__==None: return C = canvas.coords(__I__) x,y = event.x,event.y if len(C)==2: canvas.coords(__I__,x,y) else: a,b = C[:2] f = lambda i: ( i%2 and [y-b] or [x-a] ) [0] D = [x,y] + [C[i] + f(i) for i in range(2,len(C))] canvas.coords(__I__,*D) def scale(event): C = canvas.coords(__I__) if len(C)<>4: return canvas.coords(__I__,C[0],C[1],event.x,event.y) def point(event): codeArea.insert(INSERT,str(event.x) + ',' + str(event.y)) def item(event): codeArea.insert(INSERT,str(canvas.find_closest(event.x,event.y)[0])) def mouseDown(event): global __P__,__I__ m = mode.get() if m==0: __P__ = [event.x,event.y] elif m==2: point(event) elif m==3: item(event) elif m>=4: __I__ = canvas.find_closest(event.x,event.y) def mouseDrag(event): m = mode.get() if m==0: draw(event) elif m==1: erase(event) elif m==4: carry(event) elif m==5: scale(event) def mouseUp(event): global __P__,__I__ __P__ = None __I__ = None def runCode(dummy): x = codeArea.get() y = [i for i in range(len(x)) if x[i]=='=' and x[:i].count('(')==0] z = y and x[:y[0]] + '=' + x[y[0]+1:] or x print '>>> ' + z try: exec z in globals() except: print 'ERROR' codeArea.delete(0,END) from Tkinter import * print '*'*80 print 'REMINDER: canvas; pencil,eraser,color; save,circle' print '*'*80 root = Tk() canvas = Canvas(root,background='white') canvas.bind('',mouseDown) canvas.bind('',mouseDrag) canvas.bind('',mouseUp) canvas.pack(side=TOP,expand=1,fill=BOTH) codeArea = Entry(root,font=6) codeArea.pack(side=TOP,expand=1,fill=X) codeArea.bind('',runCode) ctrl = Frame(root) mode = IntVar() Radiobutton(ctrl,indicatoron=0,variable=mode,value=0,text='draw').pack(side=LEFT) Radiobutton(ctrl,indicatoron=0,variable=mode,value=1,text='erase').pack(side=LEFT) Radiobutton(ctrl,indicatoron=0,variable=mode,value=2,text='point').pack(side=LEFT) Radiobutton(ctrl,indicatoron=0,variable=mode,value=3,text='item').pack(side=LEFT) Radiobutton(ctrl,indicatoron=0,variable=mode,value=4,text='carry').pack(side=LEFT) Radiobutton(ctrl,indicatoron=0,variable=mode,value=5,text='scale').pack(side=LEFT) ctrl.pack(side=TOP,pady=10) root.title('canvasser') root.mainloop() From Serge.Orlov at gmail.com Sat Feb 12 03:17:15 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: Sat, 12 Feb 2005 11:17:15 +0300 Subject: sre is broken in SuSE 9.2 References: <1108060527.378911.146240@o13g2000cwo.googlegroups.com><1108064973.719544.228970@z14g2000cwz.googlegroups.com><1108133339.401022.272310@f14g2000cwb.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Serge Orlov wrote: > >>>>>> re.compile(ur'\w+', re.U).findall(u'\xb5\xba\xe4\u0430') >>>>>> [u'\xb5\xba\xe4\u0430'] >> >> I can't find the strict definition of isalpha, but I believe average >> C program shouldn't care about the current locale alphabet, so >> isalpha is a union of all supported characters in all alphabets > > btw, what does isalpha have to do with this example? It has to do with this thread. u'\xe4'.isalpha() returns false in Suse. It's in the same boat as \w Serge. From peter at engcorp.com Thu Feb 10 09:01:28 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 10 Feb 2005 09:01:28 -0500 Subject: newbie question In-Reply-To: <9tidneo6EZm1QpffRVn-sg@rogers.com> References: <1107990182.516041.120410@o13g2000cwo.googlegroups.com> <9tidneo6EZm1QpffRVn-sg@rogers.com> Message-ID: Dan Perl wrote: > I can't say that is not part of the reason, but the example in the OP is a > clear illustration of cases where something like an increment/decrement > operator would be very useful. The OP didn't show how he was using the "while (n--)" at all, so it can hardly be a clear illustration of how it's useful. In fact, it's even possible it was entirely unnecessary in the original code... at this point I'd be really interested in seeing just what code is inside the "while" statement, and possibly what follows it (if the following code relies on the value of "n"). > OTOH, I was thinking of saying in my > previous posting that I prefer > for n in range(start, 0, -1): > to > n = start > while (n--) > I think that the first form is more readable, although that may be just me. > I would actually even prefer the 'for' statement in C to the 'while' > statement: > for (n=start; n<=0; n--) I'm not sure if it's just picking nits, but I'd like to point out that neither of your alternatives is actually equivalent to the while (n--) form... nor was Jeff Shannon's attempt (in that case it leaves the loop with n equal to 0, not -1). The fact that it's so easy to get confused with post-decrement is perhaps an excellent reason to keep it out of Python. -Peter From rbt at athop1.ath.vt.edu Mon Feb 14 09:14:30 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 14 Feb 2005 09:14:30 -0500 Subject: safest way to open files on all platforms Message-ID: I believe that this is the safest way to open files on Windows, Linux, Mac and Unix, but I wanted to ask here just to be sure: fp = file('filename', 'rb') The 'b' on the end being the most important ingredient (especially on Windows as a simple 'r' on a binary file might cause some sort of corruption). Anyway, am I right in saying this? That 'rb' is the safest way to open files for reading and that it should work well on *all* Python supported platforms? Many thanks, RBT From jdadson at yahoo.com Wed Feb 9 18:11:10 2005 From: jdadson at yahoo.com (Jive Dadson) Date: Wed, 09 Feb 2005 23:11:10 GMT Subject: negative integer division References: <4208039c$0$28559$8fcfb975@news.wanadoo.fr> <42096EAD.879E8A5F@yahoo.com> <86wtti76cp.fsf@guru.mired.org> <420A916C.94F7F175@yahoo.com> <420a9513$0$29477$a1866201@visi.com> Message-ID: <420A98C7.103157A@yahoo.com> Grant Edwards wrote: > > On 2005-02-09, Jive Dadson wrote: > > >> [C] isn't - it's a portable assembler. > > > > I've heard that many times, but it makes no sense to me. > > I think the point is that C is a low-level, hardware twiddling > language to be used by people writing things like kernel code -- And Python interpreters? > > The fact that C ended up in the rather inappropriate role of > a user-land application language is different problem. In the early 80's, either C was the "appropriate language" or there was none ... and that's coming from someone who wrote a commercial Pascal compiler, runtime support, and debugger. I did it all in C. Pascal, as we all know, was ill-conceived. C++ was a momentous advance, but it intensionally inherited many of C's warts. I've forgotten what we are arguing about, but I'm sure I'm right. J. From simon.brunning at gmail.com Tue Feb 8 10:00:45 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 8 Feb 2005 15:00:45 +0000 Subject: Loop in list. In-Reply-To: <1107874174.445345.41230@c13g2000cwb.googlegroups.com> References: <1107874174.445345.41230@c13g2000cwb.googlegroups.com> Message-ID: <8c7f10c6050208070030bb428b@mail.gmail.com> On Tue, 08 Feb 2005 06:50:31 -0800 (PST), Jim wrote: > Where did this type of structure come from: > > mat = ['a' for i in range(3)] ? > > This will produce a list of three elements but > I don't see reference for it in any of the books. It's called a "List Comprehension". There's a good historical reason for the name, but you can be excused in not having looked under that name in the index. See for details. They *should* be mentioned in most books, provided that it's vaguely recent and covers Python 2.0 or later. List comps have a cool new little sister, generator expressions - see . -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From theller at python.net Wed Feb 23 02:48:10 2005 From: theller at python.net (Thomas Heller) Date: Wed, 23 Feb 2005 08:48:10 +0100 Subject: how to interrupt time.sleep ? References: <19k4miq1ddzn9.11addj27xoc2w$.dlg@40tude.net> Message-ID: BOOGIEMAN writes: > I have line "time.sleep(60)" in my code > > How do I cancel waiting 60 seconds if I want to continue with program > imediately ? Like "Press some button if you don't want to wait" > > If it can't be canceled what's the other solution to > "wait certain time/or press any button to continue" problem ? On windows at least, pressing ^C interrupts time.sleep(). print "Press ^C if you don't want to wait" try: time.sleep(60) except KeyboardInterrupt: pass Thomas From apardon at forel.vub.ac.be Mon Feb 28 05:11:24 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Feb 2005 10:11:24 GMT Subject: Why do descriptors (and thus properties) only work on attributes. References: <7xoee5kpiv.fsf@ruckus.brouhaha.com> <38g8hvF5oc44qU1@individual.net> Message-ID: Op 2005-02-28, Diez B. Roggisch schreef : > Antoon Pardon wrote: > >> Op 2005-02-28, Paul Rubin schreef : >>> Antoon Pardon writes: >>>> Can anyone explain why descriptors only work when they are an attribute >>>> to an object or class. I think a lot of interesting things one can >>>> do with descriptors would be just as interesting if the object stood >>>> on itself instead of being an attribute to an other object. >>> >>> How would that work? >> >> Well AFAIU a descriptor is an object with at least one method out of >> __get__, __set__ or __del__. I don see why implicitly calling one >> of these methods would be any more difficult when they are autonomous >> objects than when they are attributes. > > I still don't see how that is supposed to work for "a lot of interesting > things". Can you provide examples for one of these interesting things? Lazy evaluation where the value of something is calculated the first time it is needed but accessed from some storage if it is needed again. -- Antoon Pardon From 18k11tm001 at sneakemail.com Fri Feb 11 20:19:30 2005 From: 18k11tm001 at sneakemail.com (18k11tm001 at sneakemail.com) Date: 11 Feb 2005 17:19:30 -0800 Subject: pre-check for string-to-number conversion In-Reply-To: References: <1108163692.700703.183870@o13g2000cwo.googlegroups.com> Message-ID: <1108171170.585372.3660@f14g2000cwb.googlegroups.com> Yes, I suppose exceptions are the best way to handle this problem. Thanks. From jackdied at jackdied.com Fri Feb 4 10:59:29 2005 From: jackdied at jackdied.com (Jack Diederich) Date: Fri, 4 Feb 2005 10:59:29 -0500 Subject: OT: why are LAMP sites slow? In-Reply-To: <7xacqkc0uq.fsf@ruckus.brouhaha.com> References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xhdktt36q.fsf@ruckus.brouhaha.com> <7xacqkc0uq.fsf@ruckus.brouhaha.com> Message-ID: <20050204155929.GC1607@performancedrivers.com> On Thu, Feb 03, 2005 at 10:09:49PM -0800, Paul Rubin wrote: > aurora writes: > > I'm lost. So what do you compares against when you said LAMP is slow? > > What is the reference point? Is it just a general observation that > > slashdot is slower than we like it to be? [reordered Paul's email a bit] > > If you mean MySQL or SQL database in general is slow, there are truth > > in it. The best thing about SQL database is concurrent access, > > transactional semantics and versatile querying. Turns out a lot of > > application can really live without that. If you can rearchitect the > > application using flat files instead of database it can often be a > > big bloom. > > This is the kind of answer I had in mind. *ding*ding*ding* The biggest mistake I've made most frequently is using a database in applications. YAGNI. Using a database at all has it's own overhead. Using a database badly is deadly. Most sites would benefit from ripping out the database and doing something simpler. Refactoring a database on a live system is a giant pain in the ass, simpler file-based approaches make incremental updates easier. The Wikipedia example has been thrown around, I haven't looked at the code either; except for search why would they need a database to look up an individual WikiWord? Going to the database requires reading an index when pickle.load(open('words/W/WikiWord')) would seem sufficient. > Yes, that's the basic observation, not specifically Slashdot but for > lots of LAMP sites (some PHPBB sites are other examples) have the same > behavior. You send a url and the server has to grind for quite a > while coming up with the page, even though it's pretty obvious what > kinds of dynamic stuff it needs to find. Just taking a naive approach > with no databases but just doing everything with in-memory structures > (better not ever crash!) would make me expect a radically faster site. > For a site like Slashdot, which gets maybe 10 MB of comments a day, > keeping them all in RAM isn't excessive. (You'd also dump them > serially to a log file, no seeking or index overhead as this happened. > On server restart you'd just read the log file back into ram). You're preaching to the choir, I don't use any of the fancy stuff in Twisted but the single threaded nature means I can keep everything in RAM and just serialize changes to disk (to survive a restart). This allows you to do very naive things and pay no penalty. My homespun blogging software isn't as full featured as Pybloxsom but it is a few hundred times(!) faster. Pybloxsom pays a high price in file stats because it allows running under CGI. Mine would too as a CGI but it isn't so *shrug*. > > A lot of these is just implementation. Find the right tool and the > > right design for the job. I still don't see a case that LAMP based > > solution is inherently slow. > > I don't mean LAMP is inherently slow, I just mean that a lot of > existing LAMP sites are observably slow. A lot of these are just implementation. Going the dumb non-DB way won't prevent you from making bad choices but if a lot of bad choices are made simply because of the DB (my assertion) dropping the DB would avoid some bad choices. I think Sourceforge has one table for all project's bugs & patches. That means a never used project's bugs take up space in the index and slow down access to the popular projects. Would a naive file-based implementation have been just as bad? maybe. If there is interest I'll follow up with some details on my own LAMP software which does live reports on gigs of data and - you guessed it - I regret it is database backed. That story also involves why I started using Python (the prototype was in PHP). -Jack From ncoghlan at iinet.net.au Tue Feb 8 05:37:15 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 08 Feb 2005 20:37:15 +1000 Subject: variable declaration In-Reply-To: References: <4202A022.3050209@netscape.net> Message-ID: <4208965B.4010309@iinet.net.au> Just wrote: > In article , > Nick Coghlan wrote: > > >>Antoon Pardon wrote:ons already existing. >> >>>The compilor might generate a RESTORE instruction. >> >>Whether it is done as a LOAD/STORE or a RESTORE, it has to perform the same >>work >>- check the name exists in the local namespace, and throw an exception if it >>doesn't. If it the name does exist, perform a normal store operation. > > > But the compiler would _know_ in which scope the variable was defined, > no? I wouldn't expect the behaviour of name rebinding to be any different from other forms of augmented assignment as far as the existence of the left-hand side goes. Py> def f(): ... x += 1 ... Py> f() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in f UnboundLocalError: local variable 'x' referenced before assignment -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From cjbottaro at alumni.cs.utexas.edu Tue Feb 15 18:34:42 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Tue, 15 Feb 2005 17:34:42 -0600 Subject: super not working in __del__ ? Message-ID: I get this exception when I run the following code: Exception exceptions.TypeError: 'super() argument 1 must be type, not None' in > ignored Here is the code: class Txrposdn(PRI.BasicBatch): def __init__(self, *argv): super(Txrposdn, self).__init__(*argv) def __del__(self): super(Txrposdn, self).__del__() if __name__ == "__main__": prog = Txrposdn(args) prog.go() The weird thing is that if move that last code segment into its own function, the exception doesn't happen: def main(): prog = Txrposdn(args) prog.go() if __name == "__main__": main() What is going on? Thanks for the help. From xeoicq at netscape.net Mon Feb 14 04:31:06 2005 From: xeoicq at netscape.net (xeoicq at netscape.net) Date: 14 Feb 2005 01:31:06 -0800 Subject: keep a local COM Server alive Message-ID: <1108373466.005539.302110@g14g2000cwa.googlegroups.com> I wrote a COM server in Python where all the clients use the same global object(test_obj). So far it works, but when the last client is closed the Python COM enviornment is closed and the global object is lost. How can I prevent that? I need that new clients use the same global object and not a new created one. I figured out a workaround, but there must be another solution. The code looks like: class test: ..... test_obj=test() class test_f: _reg_clsid_ = ... _reg_progid_ = "test.cl" _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER _public_methods_ = ... def __init__(self): self.delegate=test_obj ..... ..... ..... #####Workaround to keep pythoncom alive if not __name__=='__main__': import win32com.client dummy=win32com.client.Dispatch("test.cl") ############################################# if __name__=='__main__': import win32com.server.register win32com.server.register.UseCommandLine(test_f, debug=0) From jelleferinga at gmail.com Tue Feb 1 11:01:55 2005 From: jelleferinga at gmail.com (jelle) Date: 1 Feb 2005 08:01:55 -0800 Subject: pythonic equivalent of Mathematica's FixedPoint function In-Reply-To: <1107273234.276714.272890@z14g2000cwz.googlegroups.com> References: <1107273234.276714.272890@z14g2000cwz.googlegroups.com> Message-ID: <1107273715.614766.32810@f14g2000cwb.googlegroups.com> doh... https://sourceforge.net/projects/fixedpoint pardon me From joyner.david at comcast.net Fri Feb 18 23:44:59 2005 From: joyner.david at comcast.net (David Joyner) Date: Fri, 18 Feb 2005 23:44:59 -0500 Subject: newbie question on python 2.4 and tkinter In-Reply-To: References: Message-ID: <4216C44B.6010009@comcast.net> Hi: I'm trying to compile python 2.4 with tkinter. (I'm trying to write a gui interface which calls a program called GAP - I'm hoping to use subprocess, a python 2.4 module, since I was getting deadlocks using popen). The instructions at the python web site said basically to edit the /Modules/Setup file and recompile. The edits consist of determining with location of various Tcl/Tk libraries, header files, etc. I was wondering if anyone could help out with how to determine these. I have a suse 9.1 box and a new debian laptop, both of which I would like to configure with python 2.4 and tkinter. - David Joyner From ilias at lazaridis.com Thu Feb 17 12:46:54 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Thu, 17 Feb 2005 19:46:54 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: <421284dc$0$14312$626a14ce@news.free.fr> References: <42123751$0$10042$626a14ce@news.free.fr> <421244f0$0$30339$636a15ce@news.free.fr> <421284dc$0$14312$626a14ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: [...] closing thread http://groups-beta.google.com/group/comp.lang.python/msg/f2ae9cdbe16676d1 . -- http://lazaridis.com From tim.leeuwvander at nl.unisys.com Thu Feb 3 02:41:25 2005 From: tim.leeuwvander at nl.unisys.com (Leeuw van der, Tim) Date: Thu, 3 Feb 2005 08:41:25 +0100 Subject: Crashing Python interpreter! (windows XP, python2.3.4, 2.3.5rc1, 2.4.0) Message-ID: -----Original Message----- From: python-list-bounces+tim.leeuwvander=nl.unisys.com at python.org on behalf of John Machin Sent: Thu 2/3/2005 12:03 AM To: python-list at python.org Subject: Re: Crashing Python interpreter! (windows XP, python2.3.4, 2.3.5rc1,2.4.0) > Leeuw van der, Tim TOP-POSTED: > > Hi all, > > [...] > > > > Leeuw van der, Tim schrieb: > > > I'm using the following combination of software: > > > - Pydev Eclipse plugin (pydev 0.8.5) > > > - eclipse 3.0.1 > > > - windows XP SP1 > > > - pygtk 2.4.1 > > > - GTK 2.6.1 (for windows32 native) > > > > > When trying to get a list of possible completions for the 'gtk' > import object, the python interpreter crashes. Happens with all > versions listed in the subject: python 2.3.4, 2.3.5rc1, 2.4.0. > > > > Do you have a file called drwtsn32.log anywhere on your computer? No, unfortunately I cannot find such file anywhere on my computer.... What do I do to get such file? Or anything equally useful? --Tim From duncan.booth at invalid.invalid Sun Feb 6 06:26:58 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Feb 2005 11:26:58 GMT Subject: dynamic func. call References: <1107536928.150898.114000@o13g2000cwo.googlegroups.com> Message-ID: ajikoe at gmail.com wrote: > Try this: > > def myfunc(): > print "helo" > > s = "myfunc()" > a = eval(s) > No, please don't try that. Good uses for eval are *very* rare, and this isn't one of them. Use the 'a = locals()[x]()' suggestion (or vars() instead of locals()), or even better put all the functions callable by this method into a class and use getattr() on an instance of the class. A Pythonic way to do this sort of thing is to put all the functions that are callable indirectly into a class and give them names which contain a prefix to make it obvious that they are callable in this way and then add the prefix onto the string: class C: def command_myfunc(self): return 42 def default_command(self): raise NotImplementedError('Unknown command') def execute(self, s): return getattr(self, 'command_'+s, self.default_command)() commands = C() print commands.execute('myfunc') That way you can be quickly tell which functions can be called indirectly and which can't; you can control what happens when no suitable function exists; and you can easily extend the functionality by subclassing your base class. From jeff at ccvcorp.com Wed Feb 9 12:36:55 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 09 Feb 2005 09:36:55 -0800 Subject: interactive execution In-Reply-To: <4209845C.EB468DC1@yahoo.com> References: <42096A7A.2D8CF4E1@yahoo.com> <110isa55vfvhr79@corp.supernews.com> <42098308.7F0C6A41@yahoo.com> <4209845C.EB468DC1@yahoo.com> Message-ID: <110kifce0as6cd9@corp.supernews.com> Jive Dadson wrote: > Yeah. I got it. > > exec "foo = 555" in globals(), locals() does the trick. You can do it with your own dicts, too -- but they must already exist, exec doesn't create them out of nowhere. >>> myglobals = {'a':2, 'b':5} >>> mylocals = {'c': 3} >>> exec "d = a * b + c" in myglobals, mylocals >>> myglobals {'a': 2, '__builtins__': {...}, 'b': 5} >>> mylocals {'c': 3, 'd': 13} >>> This gives you some control over what the exec'ed statement actually sees, as well as what happens with the results. (But as I mentioned before, there is no real security here if you're exec'ing arbitrary code -- there's no sandboxing involved, and the exec'ed string *can* use that __builtins__ reference (among other things) to do all sorts of malicious stuff.) Jeff Shannon Technician/Programmer Credit International From greg.lindstrom at novasyshealth.com Wed Feb 23 08:40:14 2005 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Wed, 23 Feb 2005 07:40:14 -0600 Subject: Fonts and PIL Message-ID: <421C87BE.7050903@novasyshealth.com> Hello- I'm running Python 2.3 on a windows box and would like to use PIL to superimpose text over an existing pgn image. I have no problem getting the text on the image but can not figure out how to manage fonts. How to set the font style and size. From reading the archives I surmise that I want to work with *.pil files. I've searched my box for the font files but did not find them. I've googled for information on pil font files and it appears to be involved with Zope. So, can any of you honcho-level types help me out? How can I set font size and style in my PIL application? Thanks again! --greg -- Greg Lindstrom 501 975.4859 Computer Programmer greg.lindstrom at novasyshealth.com NovaSys Health Little Rock, Arkansas "We are the music makers, and we are the dreamers of dreams." W.W. From alan.gauld at btinternet.com Sun Feb 27 04:07:28 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Feb 2005 09:07:28 +0000 (UTC) Subject: lambda strangeness?? Message-ID: I was playing with lambdas and list compregensions and came across this unexpected behaviour: >>> adds = [lambda y: (y + n) for n in range(10)] >>> adds[0](0) 9 >>> for n in range(5): print adds[n](42) ... 42 43 44 45 46 >>> adds[0](0) 4 Can anyone explain the different answers I'm getting? FWIW the behaviour I expected was what seems to happen inside the for loop... It seems to somehow be related to the last value in the range(), am I somehow picking that up as y? If so why? Or is that just a coincidence? And why did it work inside the for loop? Puzzled, Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From danperl at rogers.com Fri Feb 4 00:12:23 2005 From: danperl at rogers.com (Dan Perl) Date: Fri, 4 Feb 2005 00:12:23 -0500 Subject: advice needed for simple python web app References: <5cqdnZX-cZ9ca5_fRVn-3Q@rogers.com> <1107491985.187092.268580@o13g2000cwo.googlegroups.com> Message-ID: "M.E.Farmer" wrote in message news:1107491985.187092.268580 at o13g2000cwo.googlegroups.com... >I am no web expert but have recently used cherrypy to 'webify' a > script. It is very easy to get going and has its own server or can be > run behind Apache. > The only real problem I see is that the docs are still a little lite > for the new 2.0 series ,but they do have a newsgroup where the author > still answers questions. > Cherrypy2 is fairly logical and most of it is covered in the examples > on there website. > I can not speak for the other packages,have not used them yet ;) > hth, > M.E.Farmer Thanks. I am no web expert either so I appreciate advice coming from someone who was in a similar situation. Twisted and CherryPy seemed to me to be the main choices based on what I understand from their front pages with my limited knowledge on web apps. Twisted feels more "developed" but also more complex at the same time. I wanted opinions before I invest the time in studying either one of them. Your opinion helps. Dan From Serge.Orlov at gmail.com Tue Feb 22 11:37:44 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 22 Feb 2005 08:37:44 -0800 Subject: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux & Windows XP References: <5339b60d.0502220700.3ec7ae56@posting.google.com> Message-ID: <1109090264.676680.99150@o13g2000cwo.googlegroups.com> Paul Boddie wrote: > One side-effect of the "big push" to UTF-8 amongst the Linux > distribution vendors/maintainers is the evasion of issues such as > filesystem encodings and "real" Unicode at the system level. In > Python, when you have a Unicode object, you are dealing with > idealised > sequences of characters, whereas in many system and library APIs out > there you either get back a sequence of anonymous bytes or a sequence > of UTF-8 bytes that people are pretending is Unicode, right up until > the point where someone recompiles the software to use UTF-16 > instead, > thus causing havoc. Anyone who has needed to expose filesystems > created by Linux distributions before the UTF-8 "big push" to later > distributions can attest to the fact that the "see no evil" brass > monkey is wearing a T-shirt with "UTF-8" written on it. Unfortunately the monkey is painted in the air with a stick, so not everyone can see it. Python can't. Given a random linux system how can you tell if the monkey has pushed it already or not? Serge. From tjreedy at udel.edu Mon Feb 14 12:31:42 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Feb 2005 12:31:42 -0500 Subject: Problem with nested lists as arrays References: <1108382521.266024.281620@g14g2000cwa.googlegroups.com> Message-ID: wrote in message news:1108382521.266024.281620 at g14g2000cwa.googlegroups.com... 'Having trouble' is too vague to figure out. However, I would delete this: > def getEmptySlot(self): > i = 0 > j = 0 > while i <= self.dim-1: > while j <= self.dim-1: > if self.elements[j][i] == -1: > return [j, i] > j = j+1 > j = 0 > i = i + 1 and maintain an .empty attribute, which is trivially updated in > def swapElements(self, fromx, fromy, tox, toy): > dummy = self.elements[toy][tox] > > self.elements[toy][tox] = self.elements[fromy][fromx] > self.elements[fromy][fromx] = dummy as (fromy,fromx). Note that there is no need to pass tox, toy to this routine. Indeed, I would include the last two lines in your move routine. Since dummy is always the same object, I would also just keep it as self._dummy instead of looking it up each time. Terry J. Reedy From ilias at lazaridis.com Tue Feb 15 14:25:48 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Tue, 15 Feb 2005 21:25:48 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <37bkemF5a7s7vU1@individual.net> <86ll9piuj8.fsf@guru.mired.org> Message-ID: Adam DePrince wrote: > On Tue, 2005-02-15 at 13:29, Ilias Lazaridis wrote: >>Mike Meyer wrote: >>>Ilias Lazaridis writes: [...] >>MinGW compatibility is not [only] my need. >> >>It is an community need [at least partially] > > And herein lies the beauty of the noble meritocratic free software > movement. > > If the community needs it, a member of said community has both complete > unfettered freedom and a supportive environment to make it. Which is this "supportive environment"? > Any amount > of success at such an endeavor, even a feeble failure of an attempt, > would bring kudos the hero who attempts such a feat and possibly > organize unfathomable resources in the attendance of such a lofty goal. > > Make us proud Ilias. But whatever you do, don't beg. I don't beg. If you think this, than please reread the thread (or at least the root-trunk) > Adam DePrince . -- http://lazaridis.com From erikbethke at gmail.com Mon Feb 21 11:36:54 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 21 Feb 2005 08:36:54 -0800 Subject: detecting the change in desktop resolution - how? Message-ID: <1109003814.313466.85180@l41g2000cwc.googlegroups.com> Hello All, I am trying to clean up some polish bugs with the Shanghai game I am working on and I am currently stuck on trying to get the right event for detecting when the user has changed the desktop resolution. I have tried trapping the following events: 1) SDL_ACTIVEEVENT 2) SDL_VIDEOEXPOSE 3) SDL_VIDEORESIZE These are the events that are passed through to pygame as pygame.ACTIVEEVENT and so on... #3 - SDL_VIDEORESIZE This is what I looked at first and I was wrong, this is only for the WINDOW being resized... not the desktop resoltion #2 - SDL_VIDEOEXPOSE After watching the events in a debugger when I change the desktop resolution I find out that this IS the event that is generated from changing the desktop resolution. Okay no problem right? Time to call: self.screen = self.pygame.display.set_mode( size ) and draw() again right? Well sure, now my game repaints properly when the desktop resolution changes. So What is the problem? Well now EVERY TIME another window draws on top of my game's window a SDL_VIDEOEXPOSE event is triggered. There does not appear to be any flags associated with this event. So I am having trouble distinguishing from an overlapping window and changing the desktop resolution. So I tried this: 1) call pygame.display.Info() at the startup of my game and save off this structure 2) call it again after getting a SDL_VIDEOEXPOSE event and comparing to see if it has changed at all. The problem with this is that apparantly the VidInfo structure DOES NOT change when changing desktop resolution... So then I tried using SDL_ACTIVEEVENT and simply leaving the display black and unpainted after the user changes the resolution until the user rolls the mouse over the game window and bringing it back to focus. This works. However, it gets annoying watching the screen repaint everytime the window gains focus.... Do you guys have any leads for me to try? This HAS to be a problem solved many times before... Thank you, -Erik From douardda at free.fr Wed Feb 2 18:40:16 2005 From: douardda at free.fr (David Douard) Date: Thu, 03 Feb 2005 00:40:16 +0100 Subject: continuous plotting with Tkinter References: <42010f48$0$3408$5402220f@news.sunrise.ch> Message-ID: <420161de$0$17053$626a14ce@news.free.fr> Martin Blume wrote: > I have a number-crunching application that spits out > a lot of numbers. Now I'd like to pipe this into a python > app and plot them using Tkinter, such as: > $ number_cruncher | myplot.py > But with Tkinter once I call Tkinter's mainloop() I > give up my control of the app and I can't continue to > read in data from stdin. Or can I? If so, how? > > Regards > Martin Maybe the simpler is to run the Tk mainloop in a separate thread. You may have a look a candygram which gives a very simple to use multi-thread semantics (ala Haskell) and is simpler to use than the threading module. From ericjardim at gmail.com Fri Feb 11 16:36:46 2005 From: ericjardim at gmail.com (Eric Jardim) Date: 11 Feb 2005 13:36:46 -0800 Subject: PyQt documentation In-Reply-To: <373u0qF58g57fU1@individual.net> References: <1108088253.552834.44690@z14g2000cwz.googlegroups.com> <373it0F4uglf9U1@individual.net> <1108131643.216301.92510@o13g2000cwo.googlegroups.com> <373u0qF58g57fU1@individual.net> Message-ID: <1108157806.674018.58490@l41g2000cwc.googlegroups.com> [...] > So maybe a better way for you would be to learn python by its own, then > trying to use it in conjunction with qt. [...] The purpose of doing this help is not to help *me*, but help *anyone* who wants to use PyQt. I myself am quite confortable with the Qtdoc. But there are cases that the PyQt doc and Qt doc are not enough. This happened to me when I tryed to use the QTextStream objects. There is nothing on the docs where it says that you cannot use this object for writing. It is silly, but I had to search the web and send a message to the mailing list to know that one *don't* use the Qt stream classes for writing. It may be silly, but is time comsumption and can confuse someone, especially newbies. [...] > So again: I don't see the > need for that doc. But that's IMHO, of course. [...] *You* may not need. But think about other people. By the way, I found 9 "I"s on your last message. Don't be that selfish :) The proposal is up. [Eric Jardim] From kent37 at tds.net Sat Feb 19 15:51:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 19 Feb 2005 15:51:18 -0500 Subject: could that be a mutable object issue ? In-Reply-To: References: Message-ID: <4217a3b9$1_1@newspeer2.tds.net> Philippe C. Martin wrote: > If I do this: > > > > print 'LEN OF BOOK BEFORE APPEND: ', len(pickle.dumps(self.__m_rw)) > self.__m_rw.books.append( [p_col1,p_col2,p_col3] ) > print 'LEN OF BOOK AFTER APPEND: ', len(pickle.dumps(self.__m_rw)) > > I get the same length before and after append. > > when I print self.__m_rw.books, I see my 'appends' in there, yet the > pickled object does not change. How is __m_rw.books defined? If it is a class attribute of the class of __m_rw you will see this behavior. e.g. >>> class Mrw: ... books = [] ... >>> m=Mrw() >>> class Mrw: ... books = [] ... >>> __m_rw = Mrw() >>> __m_rw.books.append(1) >>> __m_rw.books [1] but __m_rw.books will not be pickled with __m_rw because it belongs to the class, not the instance. The fix is to declare books as an instance attribute: class Mrw: def __init__(self): self.books = [] Kent > > Any clue ? > > Thanks > > > Philippe > > > From fredrik at pythonware.com Mon Feb 14 17:31:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Feb 2005 23:31:38 +0100 Subject: Python 2.4 unable to find module. References: <1108419681.177120.219300@c13g2000cwb.googlegroups.com> Message-ID: wrote: > Python built and installed fine. PyXML built and installed with no > complaining but, when I give the commands below it cannot find the > module. > > Obviously Iam missing somehting. Do you have any suggestions where to > look for "pathing", Security or permissions problems? did you use the Python you just built when installing PyXML? (if you used a different version, PyXML was probably installed somewhere else) try running $ python -v -v -c "from xml.dom.ext.reader import Sax2" and check that Python looks for the ext.reader where you expect it to be (if you're not sure where PyXML installed itself, run the installation script again and check the output carefully) From martin at v.loewis.de Thu Feb 17 04:40:17 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 17 Feb 2005 10:40:17 +0100 Subject: Help with C extensions under VC6 / WinXP and Python 2.4 In-Reply-To: References: Message-ID: <42146681.8000407@v.loewis.de> Scott wrote: > I'm specifically trying to perform step 6. Creating a brand > new project using VC6. The instructions are outdated. Don't use VC6 to build extension modules for Python 2.4. Regards, Martin From harlinseritt at yahoo.com Sat Feb 26 07:41:21 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 26 Feb 2005 04:41:21 -0800 Subject: function expression with 2 arguments In-Reply-To: <1109419984.213993.49280@f14g2000cwb.googlegroups.com> References: <1109419984.213993.49280@f14g2000cwb.googlegroups.com> Message-ID: <1109421681.400554.116380@g14g2000cwa.googlegroups.com> Not exactly sure what you're looking for but you can do the following: def dosomething(numlist): return numlist[0] + numlist[1] numlist = [ 5, 10] val = dosomething(numlist) If so, that would be somewhat pointless. It's always best to keep it simple. It looks like the function you wrote above is very adequate for the results you want returned. From xah at xahlee.org Wed Feb 16 16:55:02 2005 From: xah at xahlee.org (Xah Lee) Date: 16 Feb 2005 13:55:02 -0800 Subject: [perl-python] problem: reducing comparison (correction) In-Reply-To: <1108471704.220626.27530@g14g2000cwa.googlegroups.com> References: <1108450348.253772.158120@z14g2000cwz.googlegroups.com> <1108471704.220626.27530@g14g2000cwa.googlegroups.com> Message-ID: <1108590902.480489.122610@g14g2000cwa.googlegroups.com> Xah Lee wrote: > In imperative languages such as Perl and Python and Java, in general it > is not safe to delete elements when looping thru a list-like entity. > (it screws up the iteration) One must make a copy first, and work with > the copy. Correction: When looping thru a list-like entity and delete elements in the vary list, there's a question whether it will change the iteration. (For example, if one loops thru 1 to 9, and deleted 8 while at 2, should the loop still do 8?) For some languages and or list entities, the answer may be yes or no. However, in imperative languages such as Perl and Python and Java, often this is not allowed by the language, partially as a protection to safeguard and assume programers as ignoramuses, but partially because the internal issues of these languages can't handle it. The work around in these languages is always to make a copy of the list-entity, and work with the copy. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From harlinseritt at yahoo.com Fri Feb 25 02:47:57 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 24 Feb 2005 23:47:57 -0800 Subject: wxpython tutorials In-Reply-To: <1109309093.384392.59230@l41g2000cwc.googlegroups.com> References: <1109309093.384392.59230@l41g2000cwc.googlegroups.com> Message-ID: <1109317677.324835.119510@g14g2000cwa.googlegroups.com> Here is the old one... http://www.wxpython.org/tutorial.php It truly is a short tutorial though. This one's even better: http://wiki.wxpython.org/index.cgi/FrontPage I am not a wxPython enthusiast. I like Tkinter much better. If you have an interest, take a look at: http://www.pythonware.com/library/tkinter/introduction/ by Frederik Lundh. It is very easy to understand. Tkinter is easier to learn. It is better documented IMO. Tkinter is just as functional as any other GUI toolkit for Python. Creating your own widget sets is usually a breeze. Tkinter is not ugly if done properly. Tkinter apps are ported easily. On and on :-) From sjuranic at gmail.com Tue Feb 22 18:48:48 2005 From: sjuranic at gmail.com (Steve Juranich) Date: Tue, 22 Feb 2005 16:48:48 -0700 Subject: python tutorial/projects In-Reply-To: References: Message-ID: <56190b6c050222154816a2e2a3@mail.gmail.com> I think the tutorial offered at www.python.org/tut/tut.html is as good a starting place as any. I wouldn't be able to suggest a "non-trivial" project without knowing more about your background. Can you do a flashcard program? recipe organizer? SETI at Home client? (I think you see where this is going). Good luck. On Tue, 22 Feb 2005 15:23:37 -0800, Danny wrote: > Does anyone know of a good python tutorial? > I was also looking for some non-trivial projects to do in python. > > Basically I would like to claim on my resume, that I know python, with > out bad karma. > > Danny > -- > http://mail.python.org/mailman/listinfo/python-list > From rschroev_nospam_ml at fastmail.fm Thu Feb 17 09:51:29 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 17 Feb 2005 14:51:29 GMT Subject: os.walk() In-Reply-To: References: Message-ID: rbt wrote: > The problem I run into is that some of the files and dirs are not > removed while others are. I can be more specific and give exact examples > if needed. On WinXP, 'pagefile.sys' is always removed, while > 'UsrClass.dat' is *never* removed, etc. Keep in mind that the comparisons are done case sensitive; are you sure that there's no problem regarding uppercase/lowercase? -- "Codito ergo sum" Roel Schroeven From robin at SPAMREMOVEjessikat.fsnet.co.uk Sun Feb 20 12:46:25 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sun, 20 Feb 2005 17:46:25 +0000 Subject: introspection inquiry In-Reply-To: References: <1108910710.985704.264430@c13g2000cwb.googlegroups.com> <4218A579.2060503@jessikat.fsnet.co.uk> Message-ID: <4218CCF1.1050601@jessikat.fsnet.co.uk> Michael Hoffman wrote: > Robin Becker wrote: > >> self.__class__.__name__ > > > Unless I misunderstood the question, that won't work. That will > give you the name of the class the object is an instance is of. > I think he wants the name of the class the method was defined in. > > Here's a way to do that using metaclasses and Python's magic > double-underscore attribute-mangling feature: > > """ > class SelfKnowledge(type): > def __init__(cls, name, bases, dict): > setattr(cls, "_%s__%s" % (name, "class_name"), name) > type.__init__(cls, name, bases, dict) > > class Nietzsche(object): > __metaclass__ = SelfKnowledge > > def __init__(self, text): > self.spam = text > print "In the constructor of the %s class" % self.__class_name > > class Kierkegaard(Nietzsche): > def __init__(self, text): > print "Now in the constructor of %s" % self.__class_name > Nietzsche.__init__(self, text) > > Nietzsche("Thus Spake Zarathustra") > print > > Kierkegaard("Fear and Trembling") > """ > > $ python test1.py > In the constructor of the Nietzsche class > > Now in the constructor of Kierkegaard > In the constructor of the Nietzsche class I guess if you're right something along the lines of import inspect class A: _class_name=inspect.currentframe().f_code.co_name def __init__(self,text,_defining_class_name=_class_name): print 'text=',text,'_defining_class_name=',_defining_class_name class B(A): pass b=B('aaa') ==>text= aaa _defining_class_name= A could work as well, but if we only need the local name why not just insert directly. -- Robin Becker From rt-announce-bounces at lists.bestpractical.com Sun Feb 13 18:53:22 2005 From: rt-announce-bounces at lists.bestpractical.com (rt-announce-bounces at lists.bestpractical.com) Date: Sun, 13 Feb 2005 18:53:22 -0500 Subject: Your message to RT-Announce awaits moderator approval Message-ID: Your mail to 'RT-Announce' with the subject Delivery service mail Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://lists.bestpractical.com/cgi-bin/mailman/confirm/rt-announce/e66d287ed65ec6d7a8c42491896433657fa0c0a6 From samantha7395 at hotmail.com Sat Feb 19 12:12:28 2005 From: samantha7395 at hotmail.com (Samantha) Date: Sat, 19 Feb 2005 09:12:28 -0800 Subject: Probably over my head... Trying to get Font Names References: <8oydnSIY04Xby4jfRVn-iA@adelphia.com> Message-ID: Mike I did get the last msg. Still trying to get things under control..... S "Mike C. Fletcher" wrote in message news:mailman.2816.1108754431.22381.python-list at python.org... > Samantha wrote: > >>Mike, >>Not sure why that email bounced. >> > That last one bounced too, btw. > >>I downloaded these files: >>WinTTX2.0b1.exe >>TTFQuery-1.0.0.win32.exe >>numarray-1.1.1.win32-py2.4.exe >> >>They all seemed to install. Is WinTTX2.0b1.exe not the fontTools file? >> > I believe WinTTX is a font-editing program from which fontTools was split > out into a separate project. > > As well, though I don't *know* that this will cause problems, I'd thought > fontTools required Numeric (Numpy) rather than Numarray. Would try the > fontTools package first with the Numarray you've installed, and if you > then find problems with it not being able to find Numeric, install the > Numpy release. > > HTH, > Mike > > ________________________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://www.vrplumber.com > http://blog.vrplumber.com > PyCon is coming... > From s.varun at gmail.com Thu Feb 24 21:18:09 2005 From: s.varun at gmail.com (Varun) Date: 24 Feb 2005 18:18:09 -0800 Subject: Python Online Programming Contest In-Reply-To: References: <1109278779.955986.193860@z14g2000cwz.googlegroups.com> Message-ID: <1109297889.083424.294860@z14g2000cwz.googlegroups.com> Hi, It is open for anyone across the world. All times are local ( GMT +5:30). The contest will be on Feb 27 (this sunday) and i will ensure that the times are clearly specified. -Varun From irmen.NOSPAM at xs4all.nl Fri Feb 18 16:42:25 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 18 Feb 2005 22:42:25 +0100 Subject: unicode and socket In-Reply-To: References: <1108753426.318777.275250@c13g2000cwb.googlegroups.com> Message-ID: <42166231$0$28988$e4fe514c@news.xs4all.nl> aurora wrote: > You could not. Unicode is an abstract data type. It must be encoded > into octets in order to send via socket. And the other end must decode > the octets to retrieve the unicode string. Needless to say the encoding > scheme must be consistent and understood by both ends. So use pickle. --Irmen From maxwell at ldc.upenn.edu Wed Feb 16 21:58:42 2005 From: maxwell at ldc.upenn.edu (maxwell at ldc.upenn.edu) Date: 16 Feb 2005 18:58:42 -0800 Subject: Problem using/installing numarray Message-ID: <1108609122.631534.50720@g14g2000cwa.googlegroups.com> I'm trying to use the 'numarray' package (v1.1.1) under Python 2.4 running under CygWin. I initially downloaded the Windows executable version of the numarray package, and installed it under C:\program files\python\lib\site-packages. That works with the Windows version of Python, but not the CygWin version, where it fails with the msg: ImportError: No module named _conv The file _conf.pyd exists, but my guess is that the .pyd suffix is not recognized under the CygWin version of Python. (But that doesn't make sense...) So I decided to download the .tgv version of the numarray package into /lib/site-packages (under my CygWin dir), and build it. Unfortunately, the build fails with the msg: building 'numarray._conv' extension gcc -shared -Wl,--enable-auto-image-base \ build/temp.cygwin-1.5.12-i686-2.4/Src/_convmodule.o \ -L. -lpython2.4 -o \ build/lib.cygwin-1.5.12-i686-2.4/numarray/_conv.dll \ -L/lib -lm -lc -lgcc -L/lib/mingw -lmingwex /usr/lib/gcc-lib/i686-pc-cygwin/3.3.3/../../../../i686-pc-cygwin/bin/ld: \ cannot find -lpython2.4 collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 (I've tried to indicate the wrapped lines above by continuing them with "\", but no guarantees this won't wrap again...) At first I thought this was a problem with a path, but even hard coding the path at the command line doesn't seem to work: > gcc -l/lib/python2.4 /usr/lib/gcc-lib/i686-pc-cygwin/3.3.3/../../../../i686-pc-cygwin/bin/ld: \ cannot find -l/lib/python2.4 I have a _directory_ /lib/python2.4, but it sounds like gcc is looking for some kind of library file. Suggestions? Mike Maxwell From mjackson at alumni.caltech.edu Thu Feb 3 08:36:40 2005 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 3 Feb 2005 13:36:40 GMT Subject: global variables References: <1107385488.822768.317250@l41g2000cwc.googlegroups.com> <1107388493.465599.140480@g14g2000cwa.googlegroups.com> <3YSdnYVEmOCW8pzfRVn-sg@comcast.com> <1107391350.933650.321440@z14g2000cwz.googlegroups.com> <1107392092.290042.221600@c13g2000cwb.googlegroups.com> Message-ID: Steve Holden writes: > M.E.Farmer wrote: > > > Ok it has been a long day, > > In my reply to Steven Bethard , Steve should read Steven ;) > > > > M.E.Farmer > > > Well, since he signs himself "Steve" too I guess we'll just have to put > up with the ambiguities. Or perhaps, given my (lack of) typing skill, I > should just start signing myself "Stvev"? What's this doing *here*? I thought the discussion of the pitfalls of name rebinding was taking place in the "variable declaration" thread. -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson People who write obscurely are either unskilled in writing or up to mischief. - Sir Peter Medawar From http Tue Feb 15 22:48:32 2005 From: http (Paul Rubin) Date: 15 Feb 2005 19:48:32 -0800 Subject: SHA1 broken Message-ID: <7xvf8t17xr.fsf_-_@ruckus.brouhaha.com> FYI. >From : The research team of Xiaoyun Wang, Yiqun Lisa Yin, and Hongbo Yu (mostly from Shandong University in China) have been quietly circulating a paper announcing their results: * collisions in the the full SHA-1 in 2**69 hash operations, much less than the brute-force attack of 2**80 operations based on the hash length. * collisions in SHA-0 in 2**39 operations. * collisions in 58-round SHA-1 in 2**33 operations. ... This is the same group that broke MD5 a few months ago and so this is probably real. It doesn't immediately turn everyone's applications inseecure (2**69 operations is still more than the 2**64 operations that it takes to break MD5 by brute force) and if it's like the MD5 result, finds only free rather than targeted collisions. So don't panic. Nonetheless I think Python should add SHA256/SHA384/SHA512 to the stdlib for 2.4, and new applications should use them instead of SHA1 even though they're slower. These are the new NIST hash algorithms announced when AES was standardized. Their design is a bit different from SHA1 and probably more likely to resist this type of attack. From caleb1 at telkomsa.net Thu Feb 10 00:05:24 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Thu, 10 Feb 2005 00:05:24 -0500 Subject: Is Python as capable as Perl for sysadmin work? References: <4209b8a4$0$223$edfadb0f@dread12.news.tele.dk> Message-ID: Roy > How about the Yoda version: > > do: > statement > do not do: > statement The Yoda version actually goes statement :do statement :not do Caleb From drew at gremlinhosting.com Thu Feb 3 09:10:28 2005 From: drew at gremlinhosting.com (Andrew James) Date: Thu, 03 Feb 2005 14:10:28 +0000 Subject: Python-list Digest, Vol 17, Issue 54 In-Reply-To: <20050203134542.CC5741E4009@bag.python.org> References: <20050203134542.CC5741E4009@bag.python.org> Message-ID: <420230D4.1010603@gremlinhosting.com> Diez/Steve, Thanks for your responses. I did consider using the req object to store my request-life variables, but then I'm still stuck with having to pass the req object to every class in my application (and have to import modpython into every script as well) if I want to get some information about the user. I've abstracted the communications to the client at a high level in my application and I don't really want to force knowledge of modpython any further down than I need to. Your responses will give me the required lifetime for my variables, but not the required access at all levels of code (unless req is a global variable?). Do you have any other suggestions as to how this might be implemented? Many thanks, Andrew > > Hi all, > I'm writing an application which runs within Apache and uses mod_python > to provide basic authentication and return content to the user, > something like: > > import modpython > .... > def handler(): > # main part of the application starts here > ... > > def authenhandler(): > ... > # Store information about the user in an object > u = new User(req.user, pass) > > I'd like to be able to pass the u object somehow from authenhandler to > handler in an elegant fashion, but without using global variables (as I > understand it these persist for the life of the child process which will > be more than one request, which is not what I want, and could be a > security hole). > > I suppose that I could use session variables, but since this part of my > application provides a WebDAV server, basic authentication credentials > are passed on each request (so I don't really want to have to look after > keeping track of sessions when I don't have to). I would rather not > modify all my existing classes to support an extra parameter in their > constructors. > > What I'm really looking for is some sort of global dictionary like PHP's > $REQUEST or $SESSION, which I can assign freely to during the life of > the request *from anywhere in my application* and which gets cleaned up > for me automatically afterwards. Does something like this exist in > mod_python? > > If the approach above isn't possible, what would your recommendations be > for a solution to this issue? > > Many thanks for your time, > Andrew James > > > ------------------------------------------------------------------------ > > Subject: > Re: ModPython: passing variables between handlers? > From: > "Diez B. Roggisch" > Date: > Thu, 03 Feb 2005 14:38:54 +0100 > To: > python-list at python.org > > To: > python-list at python.org > > Content-Transfer-Encoding: > 7Bit > Precedence: > list > MIME-Version: > 1.0 > References: > > Message-ID: > <36enlsF50l2q1U1 at individual.net> > Content-Type: > text/plain; charset=us-ascii > Message: > 8 > > >>import modpython >>.... >>def handler(): >> # main part of the application starts here >> ... >> >>def authenhandler(): >> ... >> # Store information about the user in an object >> u = new User(req.user, pass) > > > > > >>What I'm really looking for is some sort of global dictionary like PHP's >>$REQUEST or $SESSION, which I can assign freely to during the life of >>the request *from anywhere in my application* and which gets cleaned up >>for me automatically afterwards. Does something like this exist in >>mod_python? >> >>If the approach above isn't possible, what would your recommendations be >>for a solution to this issue? > > > I have absolutely no experience with mod_python, so take this with a grain > of salt - but you code above suggests that there is a request object: req. > You already use it: req. How about storing u in req like this: > > def authenhandler(): > # Store information about the user in an object > req.u = new User(req.user, pass) > > > > > > > ------------------------------------------------------------------------ > > Subject: > Re: ModPython: passing variables between handlers? > From: > Steve Holden > Date: > Thu, 03 Feb 2005 08:31:24 -0500 > To: > python-list at python.org > > To: > python-list at python.org > > Content-Transfer-Encoding: > 7bit > Precedence: > list > MIME-Version: > 1.0 > References: > > In-Reply-To: > > Message-ID: > > Content-Type: > text/plain; charset=us-ascii; format=flowed > Message: > 9 > > > Andrew James wrote: > >> Hi all, >> I'm writing an application which runs within Apache and uses >> mod_python to provide basic authentication and return content to the >> user, something like: >> >> import modpython >> ..... >> def handler(): >> # main part of the application starts here >> ... >> >> def authenhandler(): >> ... >> # Store information about the user in an object >> u = new User(req.user, pass) >> >> I'd like to be able to pass the u object somehow from authenhandler to >> handler in an elegant fashion, but without using global variables (as >> I understand it these persist for the life of the child process which >> will be more than one request, which is not what I want, and could be >> a security hole). >> >> I suppose that I could use session variables, but since this part of >> my application provides a WebDAV server, basic authentication >> credentials are passed on each request (so I don't really want to have >> to look after keeping track of sessions when I don't have to). I would >> rather not modify all my existing classes to support an extra >> parameter in their constructors. >> >> What I'm really looking for is some sort of global dictionary like >> PHP's $REQUEST or $SESSION, which I can assign freely to during the >> life of the request *from anywhere in my application* and which gets >> cleaned up for me automatically afterwards. Does something like this >> exist in mod_python? >> >> If the approach above isn't possible, what would your recommendations >> be for a solution to this issue? >> > RTFM ;-) > > If you want these values to have the same lifetime as your requests then > it would appear to make sense to have them be request attributes, no? > > Section 4.5.3 of the mod_python docs says little else about the request > object but """You can dynamically assign attributes to it as a way to > communicate between handlers.""". > > regards > Steve > From pobrien at orbtech.com Mon Feb 14 14:21:54 2005 From: pobrien at orbtech.com (Pat) Date: 14 Feb 2005 11:21:54 -0800 Subject: - E02 - Support for MinGW Open Source Compiler References: <1108398011.213872.321390@o13g2000cwo.googlegroups.com> Message-ID: <1108408914.405899.129990@o13g2000cwo.googlegroups.com> >>users. I can't expect them to purchase a .NET compiler or go through a >See above. That answers the cost question (assuming that your interpretation of the licensing is correct, since I'm not a lawyer nor qualified to render much of an opinion on that). But there is still the issue of going through a bunch of configuration hassle that scares me away from expecting my users to make use of the MS tools. Unless things have gotten easier since Mike Fletcher wrote about the situation. But thanks for the licensing info. Much appreciated. :-) Patrick K. O'Brien Orbtech http://www.orbtech.com Schevo http://www.schevo.org Pypersyst http://www.pypersyst.org From jjl at pobox.com Thu Feb 10 18:42:13 2005 From: jjl at pobox.com (John J. Lee) Date: 10 Feb 2005 23:42:13 +0000 Subject: lambda and for that matter goto not forgetting sugar References: Message-ID: <87is50j82y.fsf@pobox.com> from goto.py ( http://entrian.com/goto/ ): . # Label: "label .x" XXX Computed labels. :-) John From dmitry_belous at ua.fm Thu Feb 10 08:31:21 2005 From: dmitry_belous at ua.fm (Dmitry Belous) Date: Thu, 10 Feb 2005 15:31:21 +0200 Subject: some question about tp_basicsize Message-ID: <145288699.20050210153121@ua.fm> Hi, All I use C++ to create new types(inherited from PyTypeObject) and objects(inherited from PyObject) and virtual destructor to destroy objects. sizeof() is different for different objects and therefore i don't know what i must do with tp_basicsize. Will the following source code work? Must i set tp_basicsize to right size? (Can I use zero for tp_basicsize?) static void do_instance_dealloc(PyObject* obj) { if(obj->ob_type == &mytype_base) delete static_cast(obj); } PyTypeObject mytype_base = { ... 0, /*tp_basicsize*/ /*i don't know size of object*/ ... &do_instance_dealloc, /*tp_dealloc*/ ... }; class myobject_base : public PyObject { public: myobject_base() : ob_type(mytype_base) {} virtual ~myobject_base() {} }; class myobject_specific : public myobject_base { public: std::string name; myobject_specific() : myobject_base() {} }; From philippe at philippecmartin.com Tue Feb 8 13:14:54 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 08 Feb 2005 18:14:54 GMT Subject: broke tkinter References: Message-ID: I'll check, thanks. Philippe On Tue, 08 Feb 2005 18:03:11 +0000, wes weston wrote: > Philippe C. Martin wrote: >> Hi, >> >> I decided to clean my system and rebuild python from scratch. >> >> I downloaded tk8.4.9, tcl8.4.9 and Python2-4.tar.bz2. >> >> I installed tcl then tk using './configure --prefix=/usr' >> >> tkcvs is now working OK >> >> >> trying to compile python (configure = './configure --prefix=/usr', I get >> this: >> >> >> In file included >> from /home/philippe/downloaded/Python-2.4/Modules/_tkinter.c:67: >> /usr/include/tk.h:337: error: syntax error before "CONST84" >> In file included from /usr/include/tk.h:1576, >> >> from /home/philippe/downloaded/Python-2.4/Modules/_tkinter.c:67: >> >> Any clue! >> >> Regards, >> >> Philippe >> >> > Phillipp, > Might you be getting the wrong header file/tk version? > > http://wiki.tcl.tk/3669 talks about it. > > wes From jcribbs at twmi.rr.com Sun Feb 20 17:06:01 2005 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Sun, 20 Feb 2005 17:06:01 -0500 Subject: ANNOUNCE: KirbyBase 1.8 Message-ID: <421909C9.4030605@twmi.rr.com> KirbyBase is a simple, plain-text, database management system written in Python. It can be used either embedded in a python script or in a client/server, multi-user mode. You use python code to express your queries instead of having to use another language such as SQL. KirbyBase is disk-based, not memory-based. Database changes are immediately written to disk. You can find more information on KirbyBase at: http://www.netpromi.com/kirbybase.html You can download KirbyBase for Python at: http://www.netpromi.com/files/KirbyBase_Python_1.8.zip The most noticeable things about this release are (1) the ability to sort the result set by multiple fields, (2) the ability to have the result set returned as a nicely formatted report, suitable for printing, and (3) the ability to do an insert or an update using a record object (thanks, Fred Pacquier, for the suggestion). The manual has also been updated to reflect the new features. Also, for those of you who have asked how Kirby is doing, I have a couple of new pictures of him on the website. :-) I would like to thank everyone who has emailed me with comments, bug reports, and enhancement requests/ideas. Hearing from people who actually use KirbyBase is what makes working on it worthwhile. Please keep the emails coming! Changes in Version 1.8: ******** IMPORTANT - Method Interface Changes **************** -Added the ability to sort the result set of a select by multiple fields and to specify whether each field should be sorted ascending or descending. This necessitated a change to the interface of the select method. I moved the position of sortField in the argument list and also changed it to be a list instead of a string. I also changed the name of sortField to sortFields. I also moved sortDesc in the arguement list and also made it a list. ****************************************************************** -Added another allowable value, 'report', to the keyword parameter, returnType in the select method. This returns the result set in a pretty print format. Along with this, added another keyword parameter called rptSettings to the select method. This is only used if rptType is 'report'. It is a 2 element list. The first element specifies the number of records to print on a page. The second element is boolean specifying whether to print a dashed line between records. -Added ability to pass field values to update and insert using an object with attributes set equal to the field names. -Fixed a bug in _getMatches. If a field of type int or float had a blank value in the table (i.e. ''), the code was attempting to convert it to it's proper type (i.e. int or float) before doing the match comparison. This would cause an exception to occur. Now, if the field is an int,float,date or datetime and it is blank, I convert it to None. This allows the numeric comparisons to work correctly for null fields. -Fixed a bug in select. If a field in the result set was equal to '', I was letting it stay that way, when I should really be converting it to None before returning the result set. -Cleaned up the internals a bit. Mainly, I tried to use functions in the operator module like lt and ge instead of hardcoding < and >= in an if statement. Jamey Cribbs jcribbs at twmi.rr.com From ggrp1.20.martineau at dfgh.net Mon Feb 21 03:33:23 2005 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 21 Feb 2005 00:33:23 -0800 Subject: Test for structure References: <1108566497.848623.45360@c13g2000cwb.googlegroups.com> <1108937287.079367.276910@g14g2000cwa.googlegroups.com> Message-ID: <1108974803.420441.18850@z14g2000cwz.googlegroups.com> Yes, both string and lists have a __getitem__ attribute: >>> c1 = 'abc' >>> c2 = ['de', 'fgh', 'ijkl'] >>> hasattr(c1, '__getitem__') True >>> hasattr(c2, '__getitem__') True In other words you could index elements of either one using []. Likewise, both a string and list would produce a usable iterator using the following logic: try: itr = iter(a) except TypeError: # 'a' is not iterable else: # 'a' is iterable In either case, you can't tell a string and list apart, which is what the OP wanted to know, namely how to differentiate the two. EAPF is fine, but what operation would answer the string vs list question? Perhaps the test for an __iter__ attribute *is* the way to go because you can tell the difference between the two type. Again I don't know because the OP doesn't give enough information. I suspect, but don't know, that it could be so that either one string or a list of strings as an argument could treated as a list of 0 or more strings and accessed by indices by most of the rest of the code. I think the technique suggested by Robin Munn nearly a year ago (and referenced by the link in Simon Brunning's post): http://groups-beta.google.com/group/comp.lang.python/msg/c8befd4bed517bbc namely: try: a + '' except TypeError: pass else: a= [a] would be a good usable solution, although it's not totally infallible. It may not be possible to give a better answer without more real information about the desired usage. Martin ===================== Steven Bethard wrote: > Terry Hancock wrote: > > But you probably shouldn't do that. You should probably just test to > > see if the object is iterable --- does it have an __iter__ method? > > > > Which might look like this: > > > > if hasattr(a, '__iter__'): > > print "'a' quacks like a duck" > > Martin Miller top-posted: > > I don't believe you can use the test for a __iter__ attribute in this > > case, for the following reason: > > > >>>>c1 = 'abc' > >>>>c2 = ['de', 'fgh', 'ijkl'] > >>>>hasattr(c1, '__iter__') > > False > > > >>>>hasattr(c2, '__iter__') > > True > > Right. str and unicode objects support iteration through the old > __getitem__ protocol, not the __iter__ protocol. If you want to use > something as an iterable, just use it and catch the exception: > > try: > itr = iter(a) > except TypeError: > # 'a' is not iterable > else: > # 'a' is iterable > > Another lesson in why EAPF is often better than LBYL in Python[1]. > > STeVe > > [1] http://www.python.org/moin/PythonGlossary From deetsNOSPAM at web.de Wed Feb 16 09:59:57 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 16 Feb 2005 15:59:57 +0100 Subject: Getting milliseconds in Python References: <1108565135.167562.196830@z14g2000cwz.googlegroups.com> Message-ID: <37h5epF5ck38lU2@individual.net> mjs7231 wrote: > I am trying to record how long an operation takes, but can't seem to > find a function that will allow me to record the timestamp in > milliseconds, maybe I am looking in the wrong place? I have no idea where you look - but the time-module has IMHO a descriptive enough name - so look there and be a happy camper. -- Regards, Diez B. Roggisch From cjbottaro at alumni.cs.utexas.edu Fri Feb 4 13:59:01 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Fri, 04 Feb 2005 12:59:01 -0600 Subject: empty classes as c structs? Message-ID: I find myself doing the following very often: class Struct: pass ... blah = Struct() blah.some_field = x blah.other_field = y ... Is there a better way to do this? Is this considered bad programming practice? I don't like using tuples (or lists) because I'd rather use symbolic names, rather than numeric subscripts. Also, I don't like having to declare the empty Struct class everytime I want to do this (which is very often). Feedback is appreciated, thanks. From peter at engcorp.com Wed Feb 16 20:38:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Feb 2005 20:38:13 -0500 Subject: Font size In-Reply-To: <4213e033$1@news.comindico.com.au> References: <42126822@news.comindico.com.au> <42129ea1@news.comindico.com.au> <4213e033$1@news.comindico.com.au> Message-ID: Adam wrote: > We are running a numbers game at our retirement village and using a roulette > wheel to generate the numbers. but this wheel is only about 12 in diameter > and is little more than a toy. So we came up with the idea of using a random > number generator to generate numbers from 0 to 36 and display them in large > figures on my laptop. This is for the benefit of those people who are hard > of hearing. They like to see what is happening. > I was an RPG programmer before retirement but am new to Python. So I used > the following code to generate the numbers but I don't know how to display > them in large figures (about 3 ins high) or get rid of the idle text. > > from random import randint > rand = randint(0,36) > print rand > > my os = XP I'd suggest this as the possible best-bang-for-the-buck solution, at least in terms of quick success. If it's not good enough, at least you've got now a baseline to compare against. In XP, under the Start menu, under All Programs then Accessibility you should find a "Magnifier" tool. Run this, right-click and change the options to a magnification level of 9, then drag the window somewhere convenient and make it a decent size. Then run your Python script, and move the mouse near where the output shows up. The result is a "coarse" magnification of the font, as in individual pixels will show up as large squares, but from any kind of distance it's likely to look good enough to be usable... And you don't need to learn a GUI framework to use it. :-) -Peter From troyf at pobox.com Thu Feb 3 17:06:48 2005 From: troyf at pobox.com (troyf at pobox.com) Date: 3 Feb 2005 14:06:48 -0800 Subject: Extreme Python Message-ID: <1107468408.186079.275670@c13g2000cwb.googlegroups.com> Hello all, I've created a web/email group for topics related to both Extreme Programming (or other Agile methodologies) and Python. If you're interested, please visit http://groups-beta.google.com/group/extreme-python/ and subscribe. Or just post directly to extreme-python at googlegroups.com. Hope to see you there! Troy Frever Extreme Programmer and Coach Aviarc Corporation From rkern at ucsd.edu Mon Feb 14 18:47:40 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 14 Feb 2005 15:47:40 -0800 Subject: - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <1108370491.792820.142200@z14g2000cwz.googlegroups.com> <37bcdkF5bg7knU1@individual.net> <37bel6F59jvkgU1@individual.net> Message-ID: Ilias Lazaridis wrote: > Duncan Booth wrote: > >> Ilias Lazaridis wrote: >> >>>> There is a OS-tool-chain supported on windows, cygwin. >>> >>> >>> this depends on cygwin.dll, which is GPL licensed >>> >>> [or am I wrong?] >> >> >> It is GPL licensed with an amendment which prevents the GPL spreading >> to other open source software with which it is linked. >> >> "In accordance with section 10 of the GPL, Red Hat, Inc. permits >> programs whose sources are distributed under a license that complies >> with the Open Source definition to be linked with libcygwin.a without >> libcygwin.a itself causing the resulting program to be covered by the >> GNU GPL." > > > If I understand this right, I cannot produce commercial software with > the cygwin toolset. Wait, you demand a completely open source toolchain on a proprietary operating system to develop proprietary software? The mind *boggles*. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mefjr75 at hotmail.com Wed Feb 2 19:01:13 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 2 Feb 2005 16:01:13 -0800 Subject: global variables In-Reply-To: <1107385488.822768.317250@l41g2000cwc.googlegroups.com> References: <1107385488.822768.317250@l41g2000cwc.googlegroups.com> Message-ID: <1107388493.465599.140480@g14g2000cwa.googlegroups.com> alex wrote: > Hi, > > is it possible to create 'global' variables that can be seen in all > other classes? > > Alex Hello, What about using a class? Py> class globalVar: ... pass Py> globals = globalVar() Now you can assign 'variables' to it. And use it anywhere you need it. Py> globals.image_height = (255,777) Py> globals.image_mode = 'RGB' Py> globals.image_names = ['this.jpg', that.jpg'] etc... hth, M.E.Farmer From mwm at mired.org Sat Feb 12 22:47:46 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 12 Feb 2005 21:47:46 -0600 Subject: SCons build tool speed References: Message-ID: <864qgh6rz1.fsf@guru.mired.org> Peter Hansen writes: > ted wrote: >> How does the speed of the Scons build tool compare with Ant? Right >> now with out Ant builds take around an hour. Hoping to speed that up. > > Don't tools like Scons, Ant, and for that matter "make" just > execute other programs? So that 99% of the time is consumed > external to the Scons, Ant, or make process itself? Why > do you think the speed of the build tool is of any significance > compared to the time for things like compilers and linkers > to execute? Actually, these tools do a number of things oter than run other programs. For instance, they parse input files to construct a build tree, walk the build tree figuring out what needs to be rebuilt, and only *then* do they get around to executing those other programs. Assuming that the work prior to running those other programs is "neglible" can lead to some truly atrocious build-time behavior. In fact, one major advantage that ant/scons/jam/etc. have over Make is that they avoid the defacto standard "recursive make" build system. See for details on that. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fredrik at pythonware.com Wed Feb 2 13:06:48 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Feb 2005 19:06:48 +0100 Subject: Reference count question References: <003401c5090b$2f0f4fb0$90010d0a@umanis.com> Message-ID: "cedric paille" wrote: > I'm making python's modules to extend my application's functions with a built in script editor. > At now all works very well, but i'd like to know if i'm not forgetting some references inc/dec.... > > Here is a portion of my code: > > static PyObject * > Scene_GetNodeGraph(PyObject *self, PyObject *args) > { > NodeGraph* Ng = NodeGraph::GetInstance(); > std::vector NodG; > Ng->GetNodeGraph(NodG); > PyObject* List = PyList_New(NodG.size()); after this operation, this function "owns" the object. you should check for a NULL value, though. PyList_New may fail. adding "if (!List) return NULL;" should do the trick. > PyObject* Str = NULL; > std::vector::iterator it = NodG.begin(); > int i = 0; > for (;it != NodG.end();it++) > { > Str = PyString_FromString(it->AsChar()); after this operation, the function "owns" the string. you should check for a NULL value, though. PyString_FromString may fail (don't forget to release the list). > PyList_SetItem(List,i,Str); after this operation, the list "owns" the string. you should check the return value, though. PyList_SetItem may (in theory) fail. i++; } return List; this hands List ownership over to the caller. } > Can someone take a look at this and tell me if i must add some inc/decref ? the reference handling looks correct, but you might wish to add some error handling to avoid crashes under low-memory conditions. From bpeng at rice.edu Sat Feb 5 16:16:34 2005 From: bpeng at rice.edu (Bo Peng) Date: Sat, 05 Feb 2005 15:16:34 -0600 Subject: changing local namespace of a function In-Reply-To: References: <4204400C.5060608@iinet.net.au> Message-ID: > Exec is slow since compiling the string and calls to globals() use a lot > of time. The last one is most elegant but __getattr__ and __setattr__ > are costly. The 'evil hack' solution is good since accessing x and y > takes no additional time. Previous comparison was not completely fair since I could pre-compile fun2 and I used indirect __setattr__. Here is the new one: >>> import profile >>> a = {'x':1, 'y':2} >>> N = 100000 >>> # solution one: use dictionary directly ... def fun1(d): ... for i in xrange(0,N): ... d['z'] = d['x'] + d['y'] ... >>> # solution two: use exec ... def makeFunction(funcStr, name): ... code = compile(funcStr, name, 'exec') ... def f(d): ... exec code in d ... return f ... >>> def fun2(d): ... myfun = makeFunction('z = x + y', 'myfun') ... for i in xrange(0,N): ... myfun(d) ... del d['__builtins__'] ... ... # solution three: update local dictionary >>> # Note that locals() is NOT d after update() so ... # z = x + y ... # does not set z in d ... def fun3(d): ... exec "locals().update(d)" ... for i in xrange(0,N): ... d['z'] = x + y ... >>> # solution four: use dict wrapper ... # this makes code easier to write and read ... class wrapdict(object): ... """Lazy attribute access to dictionary keys. Will not access ... keys that are not valid attribute names!""" ... def __init__(self, mydict): ... self.__dict__ = mydict ... ... # use wrapper >>> def fun4(d): ... wd = wrapdict(d) ... for i in xrange(0,N): ... wd.z = wd.x + wd.y ... >>> profile.run('fun1(a)') 3 function calls in 0.060 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.060 0.060 :1(?) 1 0.000 0.000 0.060 0.060 profile:0(fun1(a)) 0 0.000 0.000 profile:0(profiler) 1 0.060 0.060 0.060 0.060 python-10176FWs.py:2(fun1) >>> profile.run('fun2(a)') 200004 function calls in 2.130 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 2.130 2.130 :1(?) 100000 0.520 0.000 0.520 0.000 myfun:1(?) 1 0.000 0.000 2.130 2.130 profile:0(fun2(a)) 0 0.000 0.000 profile:0(profiler) 1 0.590 0.590 2.130 2.130 python-10176EqB.py:1(fun2) 1 0.000 0.000 0.000 0.000 python-10176Sgy.py:2(makeFunction) 100000 1.020 0.000 1.540 0.000 python-10176Sgy.py:4(f) >>> profile.run('fun3(a)') 4 function calls (3 primitive calls) in 0.070 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 2/1 0.000 0.000 0.070 0.070 :1(?) 1 0.000 0.000 0.070 0.070 profile:0(fun3(a)) 0 0.000 0.000 profile:0(profiler) 1 0.070 0.070 0.070 0.070 python-10176R0H.py:4(fun3) >>> profile.run('fun4(a)') 4 function calls in 0.100 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.100 0.100 :1(?) 1 0.000 0.000 0.100 0.100 profile:0(fun4(a)) 0 0.000 0.000 profile:0(profiler) 1 0.000 0.000 0.000 0.000 python-10176e-N.py:6(__init__) 1 0.100 0.100 0.100 0.100 python-10176rIU.py:1(fun4) Since d['x'] is fast but cumbersome exec "z=x+y' is still slow. exec "locals().update(d)" is evil d.x is elegant and only a little slower than d['x'] I am announcing the winner of the contest: dictwrap! (applause) Bo From steve at myplace.com Mon Feb 21 15:57:27 2005 From: steve at myplace.com (Steve M) Date: Mon, 21 Feb 2005 14:57:27 -0600 Subject: Tuple index References: <1108951559.490554.305310@l41g2000cwc.googlegroups.com> Message-ID: John Machin wrote: > > Steve M wrote: >> Hello, >> >> I'm trying to figure out the index position of a tuple > member. >> I know the member name, but I need to know the members index > position. > > Tuples, like lists, don't have members in the sense that they can be > "named" like t.foo. The only way of referring to them is by index, > t[4]. > >> I >> know that if I use the statement print tuple[4] that it will print > the >> contents of that location. What I don't understand is if I know that > foo is >> a member of tuple, how do I get foo's index position. > > You *can't* "know that foo is a member of tuple". > > Consider this: > >>>> foo = 'carol' >>>> t = (123,456,789,'bob',foo,'ted') >>>> t[4] > 'carol' > > Is that what you mean by "foo is a member of t'? Well, it's not. foo is > a reference to the string 'carol'. t[4] is also a reference to the > string 'carol'. > > Now read on ... > >>>> foo = 'alice' >>>> t > (123, 456, 789, 'bob', 'carol', 'ted') >>>> t[4] > 'carol' >>>> > > Now foo is a reference to the string 'alice'. Nothing to do with t, > either before or now. > > Have you read the tutorial found at http://docs.python.org/tut/tut.html > ? I guess I explained my problem incorrectly. Let me try again. tuple = ("fred", "barney", "foo") I know that foo is an element of tuple, but what I need to know is what the index of foo is, tuple[?]. Hopefully this explains what I'm trying do do better. Sorry about the earlier confusion. Steve From peter at engcorp.com Fri Feb 11 22:00:58 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 11 Feb 2005 22:00:58 -0500 Subject: dos box appears when clicking .pyc In-Reply-To: <4ZGdne8O2fch3ZDfRVn-oQ@comcast.com> References: <4ZGdne8O2fch3ZDfRVn-oQ@comcast.com> Message-ID: <7tOdnYo6Ntp47JDfRVn-vQ@powergate.ca> Larry Bates wrote: > Change the association for .pyc files to pythonw.exe > from python.exe. This might help further (taken from a properly configured machine): c:\>assoc .pyc .pyc=Python.CompiledFile c:\>ftype Python.CompiledFile Python.CompiledFile="C:\a\python24\python.exe" "%1" %* c:\>assoc .pyw .pyw=Python.NoConFile c:\>ftype Python.NoConFile Python.NoConFile="C:\a\python24\pythonw.exe" "%1" %* Note "pythonw" for ".pyw" files, and just "python" for ".pyc" files. If you want .pyc files NOT to open up the DOS box, you need to change the association to what the .pyw files use, which is not the default and possibly will not always do what you want. -Peter From ilias at lazaridis.com Mon Feb 14 18:09:51 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Tue, 15 Feb 2005 01:09:51 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: Message-ID: [Sorry, I'm to tired to read more posts today. I'll try to answer to each message adressed to me tomorrow. Thank you for your time.] - I find this thread facinating. I don't know wich of the posters in this thread belong to the python team. Nearly no one community member gives simply some answers to this very simple questions. Please summarize all the efforts the community has taken to write within this thread. This sum of efforts should be enouth to setup a basic official MinGW compilation. I have the strange feeling, that some people within the community and the team are not intrested in this. - copied from another answer: "The Python Foundation could create an official sub-project to create an automated build target based on the MinGW toolchain. I am sure that many community members would be more than happy to contribute." - Let's see: The process would be: a) A Python Foundation official states: "of course we accept diversity and of course we are intrested that our source-code-base compiles directly with MinGW (and other compilers)". b) the pyMinGW developer states: "I am intrested that my patches are included within the main python source code base" [of course this contribution would deserve to be mentioned somewhere] c) One part of the Python Community states: "look those loosers, like to use MinGW toolkit - pah! I'll continue to use my super-optimizing, xx% faster results, less hassle Microsoft-Compiler" d) One part of the Python Community states: "I'm very happy that my toolset of choice gets official support, to which I can contribute as a community member" e) there is no point e. People start simply to cooperate, thus python's evolution is ensured. - I try to sleep after this communicational desaster here. Good night to all. . -- http://lazaridis.com From smile-s at alloymail.com Tue Feb 15 13:16:53 2005 From: smile-s at alloymail.com (samar bazied) Date: Tue, 15 Feb 2005 13:16:53 -0500 Subject: some qustions on python Message-ID: <20050215181653.0D39ACDF8F@ws3-2.us4.outblaze.com> Hi.. plz can u help me?? I am very new in python and I have some qustions about it. can u give me design process of python and their related langauges? and I will be very habby if u give me small evaluation of python>> plz.. plz... plz.... help me.. ------------ -- _______________________________________________ Sign-up for your own FREE Personalized E-mail at Mail.com http://www.mail.com/?sr=signup 1 cent a minute calls anywhere in the U.S.! http://www.getpennytalk.com/cgi-bin/adforward.cgi?p_key=RG9853KJ&url=http://www.getpennytalk.com From qwweeeit at yahoo.it Sat Feb 26 09:38:04 2005 From: qwweeeit at yahoo.it (qwweeeit) Date: 26 Feb 2005 06:38:04 -0800 Subject: remove strings from source Message-ID: <2ab23d7a.0502260638.311cc5e9@posting.google.com> For a python code I am writing I need to remove all strings definitions from source and substitute them with a place-holder. To make clearer: line 45 sVar="this is the string assigned to sVar" must be converted in: line 45 sVar=s00001 Such substitution is recorded in a file under: s0001[line 45]="this is the string assigned to sVar" For curious guys: I am trying to implement a cross variable reference tool and the variability (in lenght) of the string definitions (expecially if multi-line) can cause display problems. I need your help in correctly identifying the strings (also embedding the r'xx..' or u'yy...' as part of the string definition). The problem is mainly on the multi-line definitions or in cached strings (embedding chr() definitions or escape sequences). From just at xs4all.nl Thu Feb 3 06:57:18 2005 From: just at xs4all.nl (Just) Date: Thu, 03 Feb 2005 12:57:18 +0100 Subject: Generating .pyc/.pyo from a make file References: <4308d2-0801.ln1@eskimo.tundraware.com> <42015a85_1@news.arcor-ip.de> <4201607f_2@news.arcor-ip.de> <2h48d2-8481.ln1@eskimo.tundraware.com> Message-ID: In article , vincent wehren wrote: > Tim Daneliuk wrote: > > Steve Holden wrote: > > > >> Roland Heiber wrote: > >> > >>> Tim Daneliuk wrote: > >>> > > Aha! Exactly ... and that makes perfect sense too. D'oh! I guess a > > better > > distribution strategy would be to have the installation program generate > > the pyo > > file at installation time... > > > > Thanks - > > Also, the *.py? files contain the full pathname of the *.py they have > been compiled from. True. > Copying them to other path locations will give you > the wrong __file___ information in tracebacks. This is not 100% accurate: yes, the traceback shows the original source file path, yet module.__file__ does point to the actual .pyc file it was loaded from. Just From john at grulic.org.ar Fri Feb 18 11:35:28 2005 From: john at grulic.org.ar (John Lenton) Date: Fri, 18 Feb 2005 13:35:28 -0300 Subject: low-end persistence strategies? In-Reply-To: <1108742241.070703.197260@z14g2000cwz.googlegroups.com> References: <1108622622.119311.43200@f14g2000cwb.googlegroups.com> <1108629775.800508.3400@f14g2000cwb.googlegroups.com> <1108702957.327528.22010@z14g2000cwz.googlegroups.com> <1108707658.105102.298300@z14g2000cwz.googlegroups.com> <1108742241.070703.197260@z14g2000cwz.googlegroups.com> Message-ID: <20050218163528.GF17991@grulic.org.ar> On Fri, Feb 18, 2005 at 07:57:21AM -0800, Michele Simionato wrote: > Uhm ... I reading /usr/src/linux-2.4.27/Documentation/mandatory.txt > The last section says: > > """ > 6. Warning! > ----------- > > Not even root can override a mandatory lock, so runaway processes > can wreak havoc if they lock crucial files. The way around it is to > change the file permissions (remove the setgid bit) before trying to > read or write to it. Of course, that might be a bit tricky if the > system is hung :-( > """ > > so lockf locks do not look completely harmless ... if you read the whole file, you will have read that turning on mandatory locks is not trivial. I never said it was harmless, and in fact (as that section explains) it's a bad idea for most cases; there are some (very few) situations where you need it, however, and so you can get at that functionality. Having to mount your filesystem with special options and twiddling the permission bits is a pretty strong hint that the implementors didn't think it was a good idea for most cases, too. Hmm, just read that file, and it doesn't mention the "have to mount with special options" bit. But if you look in mount(8), you see an entry under the options list, mand Allow mandatory locks on this filesystem. See fcntl(2) and if you look in fcntl(2), you see that Mandatory locking (Non?POSIX.) The above record locks may be either advi? sory or mandatory, and are advisory by default. To make use of mandatory locks, mandatory locking must be enabled (using the "?o mand" option to mount(8)) for the file system containing the file to be locked and enabled on the file itself (by disabling group execute permis? sion on the file and enabling the set?GID permission bit). Advisory locks are not enforced and are useful only between cooperating processes. Mandatory locks are enforced for all processes. if I have come across as recommending mandatory locks in this thread, I apologize, as it was never my intention. It is a cool feature for the .001% of the time when you need it (and the case in discussion in this thread is not one of those), but other than that it's a very, very bad idea. In the same league of badness as SysV IPC; I'd still mention SysV IPC to someone who asked about IPC on Linux, however, because there are places where it is useful even though most times it's a stupid way to do things (yes, Oracle, *especially* you). -- John Lenton (john at grulic.org.ar) -- Random fortune: A pencil with no point needs no eraser. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From danperl at rogers.com Fri Feb 4 00:08:58 2005 From: danperl at rogers.com (Dan Perl) Date: Fri, 4 Feb 2005 00:08:58 -0500 Subject: advice needed for simple python web app References: <5cqdnZX-cZ9ca5_fRVn-3Q@rogers.com> <7xr7jxnddh.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xr7jxnddh.fsf at ruckus.brouhaha.com... > "Dan Perl" writes: >> Basically, what I'm looking for is a web server that accepts an HTTP >> request and invokes a python script. But I would like a "pythonic" >> solution so a web server like Apache is a solution that I would like >> to avoid. The server should also be as simple as possible to >> administrate. > > CGI and CGIHTTPServer (or whatever it's called) is conceptually the >> simplest. What does your app do? The application is just something I'm playing with to learn a little bit on web apps. It uses an HTML form to send an email. The form takes inputs like the From:, To: and Subject: fields and a text field. I found the "Internet Protocols and Support" chapter in the Library Reference that covers also the CGIHTTPServer. It's definitely something I will have to read. Thanks. Dan From kdahlhaus at yahoo.com Wed Feb 16 12:30:04 2005 From: kdahlhaus at yahoo.com (kdahlhaus at yahoo.com) Date: 16 Feb 2005 09:30:04 -0800 Subject: Python to be used for Mod Language in Battlefield 1942 Sequel Message-ID: <1108575004.191726.249560@g14g2000cwa.googlegroups.com> I love the orignal so much, now to hear that mod's will be created in Python, well it brings tears of joy..... Python Used as Modding Language for Battlefield 2 Programming First Person Shooters (Games) Posted by Zonk on Friday February 11, @11:27AM from the snakes-and-guns dept. Dutch Dopey writes "In an interview with Lars Gustavsson of DICE, it was mentioned that Battlefield 2's modding tools are going to be delivered with the game, and that the tools are the same ones used to develop the game. The modding language in use is Python, and will support all aspects of the language http://developers.slashdot.org/developers/05/02/11/1439230.shtml?tid=156&tid=204 From tjreedy at udel.edu Mon Feb 21 15:25:22 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 21 Feb 2005 15:25:22 -0500 Subject: Test for structure References: <1108566497.848623.45360@c13g2000cwb.googlegroups.com><1108937287.079367.276910@g14g2000cwa.googlegroups.com><1108974803.420441.18850@z14g2000cwz.googlegroups.com> Message-ID: "Steven Bethard" wrote in message news:GvKdnbutV6lQt4ffRVn-jA at comcast.com... > I don't like this idea much because it depends on str and unicode _not_ > having a particular function. I haven't seen any guarantee anywhere that > str or unicode won't ever grow an __iter__ method. So this code seems > dangerous as far as future compatibility goes. When CPython's support for the old iteration protocol goes away, which I expects it will someday, strings will have to grow an __iter__ method. Even now, I think this difference between strings and lists is more of an accident than a logical design. So the test is opaque and specific to current CPython. The validity of something like a = a+'', however, is inherent to the nature of strings. Terry J. Reedy From martin at v.loewis.de Mon Feb 21 17:57:28 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 21 Feb 2005 23:57:28 +0100 Subject: IDLE Problem: win98\Python2.4 In-Reply-To: References: <22eSd.1969$MY6.1483@newsread1.news.pas.earthlink.net> <1109004976.267201.200950@z14g2000cwz.googlegroups.com> Message-ID: <421A6758.8050401@v.loewis.de> kim kubik wrote: > A little knowledge is indeed a dangerous thing; forgive my > stupidity - it will happen again, so I'm apologizing in advance! No need to apologize! This is a frequent mistake, and it might be sensible to change Python to be more resistent against it. For example, it might be possible to check whether TCL_LIBRARY points to a "good" Tcl version if set, in lib-tk/FixTk.py. Then, if it is somehow determined to be incorrect (i.e. by containing an outdated tcldll, but no current one), TCL_LIBRARY could be ignored, and the included library could be used. Alternatively, a more detailed warning if import _tkinter failed and TCL_LIBRARY is set could be produced (instead of silently "fixing" the problem for the user). Patches in this direction are welcome. Regards, Martin From snail at objmedia.demon.co.uk Thu Feb 17 13:49:38 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Thu, 17 Feb 2005 18:49:38 +0000 Subject: [EVALUATION] - E02 - ULTIMATE RECIPE TO RESOLVE ALL ISSUES References: Message-ID: In message , Ilias Lazaridis writes >This thread proofs simply the inability of this community [1] to focus >on a simple essence. Incorrect analysis. This thread proves that you have no concept of how to interact with the community. If you had done what many people asked you to do, which is do some work yourself, then ask questions about the few answers you didn't discover yourself, you would have got lots of helpful answers. You were told this many times by many people. Also on the odd occasion someone did proffer some on-topic advice, sometimes in long articles that must have taken some time to produce you'd dismiss the article with "It is not on topic, I have not read it". How could you know if it is not on topic if you don't read it? Apart from the gross rudeness in such an attitude it demonstrates your arrogance, selfishness and utter contempt for those replying to you. And then you have the gall to blame your failure on others... Next you'll be telling me the world is flat and held up by an infinite array of tortoises. -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From deetsNOSPAM at web.de Mon Feb 21 08:02:48 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 21 Feb 2005 14:02:48 +0100 Subject: lambda closure question References: <1108798951.128843.79810@f14g2000cwb.googlegroups.com> <1108802613.284686.200170@o13g2000cwo.googlegroups.com> Message-ID: <37u4dpF5cboqvU1@individual.net> > But I'll get back at what seems you actually wanted to say: > That there is no way to rebind 'x' or in my case 'l' and > with that I have to agree although I personnaly find that > a lack in python It's not only that way in python, but in java too. So it seems that there is a fundamental principle behind it: In a language that allows sideeffects, these will actually happen. If you're after side-effect free programming, I recommend using a functional programming language like ocaml or haskell. In these, you can't mutate objects at all, only recreate them and rebind them to new variables. This prevents whole classes of errors - but of course it also introduces all kinds of other constraints on your programming style, e.g. using monads and so on. -- Regards, Diez B. Roggisch From lard at tardis.ed.ac.molar.uk Tue Feb 1 08:13:14 2005 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Tue, 01 Feb 2005 13:13:14 GMT Subject: equivelant of Java's toString() method? (not repr) In-Reply-To: References: Message-ID: Alex Hunsley wrote: > Pretty simple seeming question, but can't find answer via google or docs... > > I am using urllib2 as follows: > > handle = urlopen(req, postdata) # and URL to return a handle on > ... > print handle.info() > > the print statement prints out the headers: > > Content-Type: text/html;charset=ISO-8859-1 > Content-Length: 2845 > Date: Tue, 01 Feb 2005 12:40:28 GMT > Server: Apache Coyote/1.0 > Connection: close > > which is the string I want to use. > However, if I write a function call using this: > > log(handle.info()) > > I get this: > > TypeError: cannot concatenate 'str' and 'instance' objects > > (The log function expects a string) > What is the magic incantation to get the string I want so I can pass it > to my function? > I've tried repr() but that isn't it (I suspected it wouldn't be). > I suppose I'm looking for the equivelant of Java's toString() method... > > thanks! > alex Replying to meself... D'oh! Just found the str() function which is just what I need! log(str(handle.info())) works fine.... thx alex From jeff at ccvcorp.com Thu Feb 3 16:13:17 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 03 Feb 2005 13:13:17 -0800 Subject: Basic file operation questions In-Reply-To: References: <1107379669.870799.256030@g14g2000cwa.googlegroups.com> Message-ID: <11054ttdjkcls45@corp.supernews.com> Caleb Hattingh wrote: > Peter > >> Yes, you can even write >> >> f = open("data.txt") >> for line in f: >> # do stuff with line >> f.close() >> >> This has the additional benefit of not slurping in the entire file at >> once. > > Is there disk access on every iteration? I'm guessing yes? It > shouldn't be an issue in the vast majority of cases, but I'm naturally > curious :) Disk access should be buffered, possibly both at the C-runtime level and at the file-iterator level (though I couldn't swear to that). I'm sure that the C-level buffering happens, though. Jeff Shannon Technician/Programmer Credit International From roy at panix.com Wed Feb 16 19:26:46 2005 From: roy at panix.com (Roy Smith) Date: Wed, 16 Feb 2005 19:26:46 -0500 Subject: Why doesn't join() call str() on its arguments? References: <37hippF4gcimiU1@individual.net> Message-ID: In article , David Eppstein wrote: > In article <37hippF4gcimiU1 at individual.net>, > Leo Breebaart wrote: > > > What I can't find an explanation for is why str.join() doesn't > > automatically call str() on its arguments, so that e.g. > > str.join([1,2,4,5]) would yield "1245", and ditto for e.g. > > user-defined classes that have a __str__() defined. > > That would be the wrong thing to do when the arguments are unicodes. Why would it be wrong? I ask this with honest naivete, being quite ignorant of unicode issues. From steve at holdenweb.com Fri Feb 4 14:27:44 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 04 Feb 2005 14:27:44 -0500 Subject: string issue In-Reply-To: References: Message-ID: <36QMd.103084$Jk5.36127@lakeread01> rbt wrote: > Either I'm crazy and I'm missing the obvious here or there is something > wrong with this code. Element 5 of this list says it doesn't contain the > string 255, when that's *ALL* it contains... why would it think that??? > > import time > > ips = ['255.255.255.255', '128.173.120.79', '198.82.247.98', > '127.0.0.1', '255.0.0.0', '255', '128.173.255.34'] > > for ip in ips: > if '255' in ip: > try: > print "Removing", ip > ips.remove(ip) > except Exception, e: > print e > > print ips > time.sleep(5) > > Someone tell me I'm going crazy ;) You are modifying the list as you iterate over it. Instead, iterate over a copy by using: for ip in ips[:]: ... regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From robey at flaminglunchbox.net Wed Feb 2 01:31:06 2005 From: robey at flaminglunchbox.net (Robey Holderith) Date: Wed, 02 Feb 2005 01:31:06 -0500 Subject: Newbie Question References: Message-ID: On Tue, 01 Feb 2005 17:47:39 -0800, Joel Eusebio wrote: > > Hi Everybody, > > I'm pretty new to Python and would like to ask a few questions. I have this > setup on a Fedora Core 3 box. > > Python 2.3.4 > wxPython-common-gtk-ansi-2.5.3.1-fc2_py2.3 > mod_python-3.1.3-5 > Apache/2.0.52 > > I have a test.py which looks like this: > from mod_python import apache > def handler(req): > req.write("Hello World!") > return apache.OK > This code looks like you are attempting to define a handler. In this case the handler needs to be properly set up in either your httpd.conf or a .htaccess (assuming your configuration allows for that). > Whenever I access test.py from my browser it says "The page cannot be found" > , I have the file on /var/www/html, what did I miss? You don't access handlers like you do CGI. This problem likely lies in your configuration and not in your code. I would look at mod_python's documentation some more and probably start with mod_python's PublisherHandler for initial testing and experimentation. -Robey Holderith > Thanks in advance, > Joel From mhuffnagle at knowtechnology.net Tue Feb 8 13:18:13 2005 From: mhuffnagle at knowtechnology.net (Marc Huffnagle) Date: Tue, 08 Feb 2005 18:18:13 GMT Subject: Is Python as capable as Perl for sysadmin work? In-Reply-To: References: Message-ID: Jeff Epler wrote: > > There's another little-known fact about Python: No string is permitted > to end with a backslash! You might think that variations like > r'\' > or > """"""\\\\\"""""" > would allow you to create this elusive value, but you'd mistaken! > Now, this may not bother Unix sysadmins, but the honest truth is that > you'll be administrating Windows systems, too, anywhere you work! >>> a = "\\" >>> print a \ Marc From phil at riverbankcomputing.co.uk Thu Feb 10 04:18:34 2005 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 10 Feb 2005 09:18:34 -0000 (GMT) Subject: PyQt and Python 2.4 - also WinXP LnF? In-Reply-To: <1108003471.242829.297030@o13g2000cwo.googlegroups.com> References: <1108003471.242829.297030@o13g2000cwo.googlegroups.com> Message-ID: <47718.82.68.80.137.1108027114.squirrel@river-bank.demon.co.uk> > After quite a while of wxPython I'm getting back into PyQt, mainly due > to the announcement by Trolltech that they will make a GPL version of > Qt4 for Windows (and Phil-T said he will make a PyQt to go with it > eventually!) > > I'm currently using PyQt 3.12 that comes with the BlackAdder demo, it > seems to work fine with Python 2.3.5 except that it doesn't support the > WinXP look'n'feel, the QStyle "WindowsXP" isn't included, and using a > manifest file doesn't seem to fix this. > > Does anyone know if the latest PyQt (3.13?) is built with this support? > I thought this had been supported since 3.10 or earlier, is it just the > BlackAdder build that's "broken"? PyQt supports the WindowsXP style if Qt has been built with it enabled. > I'm writing an XMMS remote control program, so it will be GPL when > released (if it's ever good enough to release!) so I'm looking at > buying the commercial PyQt3 or BlackAdder whilst waiting for the GPL > PyQt4 > > Can I use the commercial PyQt without a commercial Qt - I guess I could > as long as I don't distribute the qt-mt333.dll? I have no use for Qt > itself, not interested in C++, so it seems a bit much to have to buy a > license just for a DLL! No. PyQt is supplied as a source package. You don't have the Qt .h files needed to compile it. One point of the BlackAdder license is that you can't use the bundled version of Qt to build C++ applications - even if that C++ application is another version of PyQt. > Also, would I have to build it all myself or does Riverbank/TheKompany > provide binaries like PyQt 3.13 for Python 2.4, as I don't have Visual > Studio I can't build it myself. We don't provide binaries, but the free MSVC, Borland and MinGW compilers are all supported. > OK, I'm off to check on my build of PyQt on my Fedora2/Python 2.4 > machine ;-) Phil From theller at python.net Thu Feb 10 13:21:25 2005 From: theller at python.net (Thomas Heller) Date: Thu, 10 Feb 2005 19:21:25 +0100 Subject: pyFMOD writing a callback function in Python References: <370m88F525p5uU1@individual.net> Message-ID: Marian Aldenh?vel writes: > Hi, > > I am using the FMOD audio-library with the pyFMOD python bindings. pyFMOD uses > ctypes. I was looking into this recently, because another poster also asked about pyFMOD: which FMOD version do you use? I was only able to find fmodapi374.zip (for windows), and that version doesn't seem to work with the pyFMOD release I found. > It is possible to register callback functions with FMOD that are > called at certain points in the processing pipeline or when certain events > happen. > > I am expecially interested in the one that fires when a currently playing > stream ends. This is what the declaration in pyFMOD looks like: > > _FSOUND_Stream_SetEndCallback = > getattr(fmod,"_FSOUND_Stream_SetEndCallback at 12") > _FSOUND_Stream_SetEndCallback.restype = c_byte > def FSOUND_Stream_SetEndCallback(stream, callback, userdata): > result = _FSOUND_Stream_SetEndCallback(c_int(stream), c_int(callback), > c_int(userdata)) > if not result: raise fmod_exception() > > I cannot make it work, however. I tried: > > def _sound_end_callback(stream,buf,len,userdata): > print "_sound_end_callback(): Stream has reached the end." > > as simplest possible callback function. I am registering it like this: > > pyFMOD.FSOUND_Stream_SetEndCallback(_currenttrack,_sound_end_callback,0) > > And this is how my program dies: > > File "d:\projekte\eclipse\workspace\gettone\gettonesound.py", line > 175, in sound_tick > pyFMOD.FSOUND_Stream_SetEndCallback(_currenttrack,_sound_end_callback,0) > File "c:\programme\Python23\lib\site-packages\pyFMOD.py", line 690, > in FSOUND_Stream_SetEndCallback > result = _FSOUND_Stream_SetEndCallback(c_int(stream), > c_int(callback), c_int(userdata)) > TypeError: int expected instead of function instance The first problem is that the FSOUND_Stream_SetEndCallback function, as given, converts all parameters to integers. Second, you cannot pass a Python function directly as callback, you have to create a function prototype first which specifies calling convention, return type, and argument types. Third, you instantiate the prototype with a Python callable, which creates the C callable callback function, and use that in the FSOUND_Stream_SetEndCallback call. All in all, it should look similar (I can't test it!) to this code: _FSOUND_Stream_SetEndCallback = getattr(fmod,"_FSOUND_Stream_SetEndCallback at 12") _FSOUND_Stream_SetEndCallback.restype = c_byte def FSOUND_Stream_SetEndCallback(stream, callback, userdata): result = _FSOUND_Stream_SetEndCallback(c_int(stream), callback, c_int(userdata)) if not result: raise fmod_exception() # from the FMOD header file: ##typedef signed char (F_CALLBACKAPI *FSOUND_STREAMCALLBACK) ## (FSOUND_STREAM *stream, void *buff, int len, void *userdata); # funtion prototype FSOUND_STREAMCALLBACK = WINFUNCTYPE(c_char, c_int, c_void_p, c_int, c_void_p) # create callback function callback_function = FSOUND_STREAMCALLBACK(_sound_end_callback) # and then put it to work: FSOUND_Stream_SetEndCallback(stream, callback_function, userdata) You should also be aware that you have to keep the callback_function object alive *as long as the FMOD library is using it*! If you don't, it will probably crash. > I am very new to Python and have zero idea what the problem is nor how to > solve it. In some of my other languages I would have to explicitly make a > function pointer and possibly have to cast that to an int to pass it to > SetEndCallback, but that seems very inappropriate in Python... Thomas From ncoghlan at iinet.net.au Thu Feb 10 07:59:31 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 10 Feb 2005 22:59:31 +1000 Subject: empty classes as c structs? In-Reply-To: <1grpz9z.tycvyx1jrdzeiN%aleaxit@yahoo.com> References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <1gric2n.17myhon1hfrc6gN%aleaxit@yahoo.com> <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> <9rmdnVR1lr-LYJvfRVn-gg@comcast.com> <4207606E.4040806@iinet.net.au> <1grnyld.1t8l5kw1nr5aqsN%aleaxit@yahoo.com> <1grpz9z.tycvyx1jrdzeiN%aleaxit@yahoo.com> Message-ID: <420B5AB3.7090405@iinet.net.au> Alex Martelli wrote: > Nick Coghlan wrote: >>For bindings, you could just go with standard Python semantics - normal >>name binding always happens in the innermost scope, so binding a name in a >>namespace should happen in the directly referenced namespace. Then you can >>shadow names from outer scopes, and later regain access to them using >>'del'. > > > ...which you can't do in "standard Python semantics" - if a name is > local, it's local throughout. You can't do that with a namespace > object, which is why I think the best semantics for bindings in that > case isn't all that clear. Heh. I was getting two sets of terminology confused. The nested scopes of functions, and the 'fallback to class' of class instances. It was the latter I actually meant by 'standard Python semantics' for binding in a 'chained' namespace: Py> class C(object): ... x = 1 ... Py> c = C() Py> c = C() Py> c.x 1 Py> del c.x Traceback (most recent call last): File "", line 1, in ? AttributeError: 'C' object attribute 'x' is read-only Py> c.x = 2 Py> c.x 2 Py> del c.x Py> c.x 1 Py> del c.x Traceback (most recent call last): File "", line 1, in ? AttributeError: x (Huh, I wonder why the error message changed second time around) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tjreedy at udel.edu Tue Feb 1 22:25:59 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 1 Feb 2005 22:25:59 -0500 Subject: Suggesion for an undergrad final year project in Python References: <1107241918.722156.123590@c13g2000cwb.googlegroups.com> Message-ID: "Sridhar" wrote in message news:1107241918.722156.123590 at c13g2000cwb.googlegroups.com... > Hi, > > I am doing my undergrade CS course. I am in the final year, and would > like to do my project involving Python. Our instructors require the > project to have novel ideas. Can the c.l.p people shed light on this > topic? Some months ago, maybe a year ago, Brett Cannon asked on the Py-Dev mailing list a similar question about a CS master's thesis. He got around 10 sensible suggestions. Perhaps a few could be scaled down to a senior thesis level. In any case, you could check the archives at www.python.com of the pydev summaries that he prepares every two weeks ago. Terry J. Reedy From adam at cognitcorp.com Tue Feb 15 14:20:35 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Tue, 15 Feb 2005 14:20:35 -0500 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <37bkemF5a7s7vU1@individual.net> <86ll9piuj8.fsf@guru.mired.org> Message-ID: <1108495235.4186.18.camel@localhost.localdomain> On Tue, 2005-02-15 at 13:29, Ilias Lazaridis wrote: > Mike Meyer wrote: > > Ilias Lazaridis writes: > > > >>MinGW compatibility is not my need. > > > > Then why do you waste so much effort whining about it not being given > > to you? > > > >>It is an community need. > > > > Based on the evidence at hand, this is a false statement. > > > > > MinGW compatibility is not [only] my need. > > It is an community need [at least partially] And herein lies the beauty of the noble meritocratic free software movement. If the community needs it, a member of said community has both complete unfettered freedom and a supportive environment to make it. Any amount of success at such an endeavor, even a feeble failure of an attempt, would bring kudos the hero who attempts such a feat and possibly organize unfathomable resources in the attendance of such a lofty goal. Make us proud Ilias. But whatever you do, don't beg. Adam DePrince From scott+python at CS.Princeton.EDU Wed Feb 16 21:45:50 2005 From: scott+python at CS.Princeton.EDU (Scott) Date: Wed, 16 Feb 2005 21:45:50 -0500 Subject: Help with C extensions under VC6 / WinXP and Python 2.4 In-Reply-To: References: Message-ID: <4214055E.2090408@cs.princeton.edu> John Machin wrote: > On Wed, 16 Feb 2005 20:57:18 -0500, Scott > wrote: > > >>I've installed Python 2.4 under WinXP and am attempting to >>create an extension module using the steps outlined here: >>http://python.org/doc/2.4/ext/win-cookbook.html >> >>I'm specifically trying to perform step 6. Creating a brand >>new project using VC6. >> >>The trouble I have is that there are no PC or PCbuild >>subdirectories in C:\Python24. Where do I find these? > > > As the quoted URL says (2nd para): > """ > To build extensions using these instructions, you need to have a copy > of the Python sources of the same version as your installed Python. > [snip] > The example files described here are distributed with the Python > sources in the PC\ example_nt\ directory > """ > > i.e. you have to download a copy of the Python source distribution. Since I had an include directory, I assumed (incorrectly) that I already had the sources. Thanks for the reiteration -- it's what I needed. > > >>Ultimately, what I want to do is interface some Python >>code with a DLL that controls an A/D board. I expect >>I'll need to write an extension module to act as a shim >>between this DLL and the Python code. > > > Possibly not; check out the ctypes module -- > http://starship.python.net/crew/theller/ctypes/ Thanks for the pointer. This looks promising. Scott From john at grulic.org.ar Tue Feb 8 18:31:18 2005 From: john at grulic.org.ar (John Lenton) Date: Tue, 8 Feb 2005 20:31:18 -0300 Subject: Big development in the GUI realm In-Reply-To: <5175a81c05020815194228af51@mail.gmail.com> References: <1107795145.049239.73450@l41g2000cwc.googlegroups.com> <5ocf01hmspufk3iusvm35p6hj4mes5heke@4ax.com> <4207c8db$0$21623$a1866201@visi.com> <5175a81c05020815194228af51@mail.gmail.com> Message-ID: <20050208233118.GB10229@grulic.org.ar> On Tue, Feb 08, 2005 at 09:19:58PM -0200, Gabriel B. wrote: > > However, imagine simple situation: > > 1. I write proprietary program with open plugin api. I even make the api > > itself public domain. Program works by itself, does not contain any > > GPL-ed code. > > No need to continue. You write something that uses a plugin, Eolas > sues you. Don't have to mind about trolltech not if you live in a sane country. -- John Lenton (john at grulic.org.ar) -- Random fortune: Preserve wildlife -- pickle a squirrel today! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From steven.bethard at gmail.com Fri Feb 11 12:20:37 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 11 Feb 2005 10:20:37 -0700 Subject: convert list of tuples into several lists In-Reply-To: <420c5241$0$6619$8fcfb975@news.wanadoo.fr> References: <36uihlF58p63iU1@individual.net> <1107998078.610891.111510@z14g2000cwz.googlegroups.com> <420c5241$0$6619$8fcfb975@news.wanadoo.fr> Message-ID: Pierre Quentel wrote: > Could someone explain why this doesn't work : > > Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> def f(*args,**kw): > ... print args, kw > ... > >>> f(*[1,2]) > (1, 2) {} > >>> f(*[1,2],x=1) > File "", line 1 > f(*[1,2],x=1) > ^ > SyntaxError: invalid syntax > >>> http://docs.python.org/ref/calls.html Steve From jeff at ccvcorp.com Thu Feb 10 12:36:42 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 10 Feb 2005 09:36:42 -0800 Subject: newbie question In-Reply-To: References: <1107990182.516041.120410@o13g2000cwo.googlegroups.com> <1107992130.921664.68860@z14g2000cwz.googlegroups.com> <110lgig2to6r139@corp.supernews.com> Message-ID: <110n6qr9i7eg239@corp.supernews.com> Dennis Lee Bieber wrote: > On Wed, 09 Feb 2005 18:10:40 -0800, Jeff Shannon > declaimed the following in comp.lang.python: > > >>for i in range(n)[::-1]: >> func(n) > > > Shouldn't that be > func(i) > (the loop index?) You're right, that's what I *meant* to say. (What, the interpreter doesn't have a "do what I mean" mode yet? ;) ) >>The '[::-1]' iterates over the range in a reverse (decreasing) >>direction; this may or may not be necessary depending on the >>circumstances. > > Eeee.... sneaky... (I'm a bit behind on latest syntax additions) > > I'd probably have coded something like > > for n1 in range(n): > func(n-n1) > > though, and note that I do admit it here [...] Given a need/desire to avoid extended slicing (i.e. being stuck with an older Python, as I often am), I'd actually do this by changing the input to range(), i.e. for i in range(n, 0, -1): # ... That (IMO) makes the decreasing-integer sequence a bit clearer than doing subtraction in the function parameter list does. Actually, it's possibly clearer than the extended slicing, too, so maybe this would be the better way all around... ;) > I haven't done the detailed > analysis to properly set the end point... And as Peter Hansen points out, none of the Python versions leave n in the same state that the C loop does, so that's one more way in which an exact translation is not really possible -- and (IMO again) further evidence that trying to do an exact translation would be ill-conceived. Much better to consider the context in which the loop is used and do a looser, idiomatic translation. Jeff Shannon Technician/Programmer Credit International From jb_perin at yahoo.fr Tue Feb 8 05:22:29 2005 From: jb_perin at yahoo.fr (Jean-Baptiste PERIN) Date: Tue, 08 Feb 2005 11:22:29 +0100 Subject: how to convert 4 bytes into a float ? Message-ID: I read 4 bytes from a binary file. These bytes represent a floating point number (mantisse exponent form) How can I get a float from these bytes ? From alecw at pobox.com Wed Feb 9 17:24:59 2005 From: alecw at pobox.com (Alec Wysoker) Date: Wed, 09 Feb 2005 17:24:59 -0500 Subject: Crash in thread on program termination Message-ID: <6.1.2.0.0.20050209171159.0254b1a8@mail.comcast.net> I have several programs that have two or more threads. The threads that are not the main thread are daemon threads, i.e. the fact that they are running should not stop the program from terminating if the main thread (the only non-daemon thread) terminates. I do not join to these threads, but just run off the end of the main module to terminate the program. I'm using Python 2.3.4. I occasionally get the following error: Traceback (most recent call last): File "C:\Python23\lib\threading.py", line 451, in __bootstrap self.__stop() File "C:\Python23\lib\threading.py", line 460, in __stop self.__block.notifyAll() File "C:\Python23\lib\threading.py", line 256, in notifyAll self.notify(len(self.__waiters)) File "C:\Python23\lib\threading.py", line 238, in notify currentThread() # for side-effect TypeError: 'NoneType' object is not callable What seems to be happening is that at the time the thread is stopped, the threading module object is no longer in an unhealthy state. I.e. threading.currentThread is None. I hacked around this problem by substituting my own code for _Condition.notifyAll() that would not call notify() if there were no waiters to be notified. However, that merely allowed the code to get a little further, before crashing with a similar problem, i.e. threading._StringIO is None instead of being a class object. Traceback (most recent call last): File "C:\Python23\lib\threading.py", line 443, in __bootstrap s = _StringIO() TypeError: 'NoneType' object is not callable I turned on threading.__debug__ and threading._VERBOSE to get some debug output, and one thing that is strange is that I don't get the debugging output I expect. # From threading.Thread.__bootstrap(): try: self.run() except SystemExit: if __debug__: self._note("%s.__bootstrap(): raised SystemExit", self) except: if __debug__: self._note("%s.__bootstrap(): unhandled exception", self) s = _StringIO() _print_exc(file=s) _sys.stderr.write("Exception in thread %s:\n%s\n" % (self.getName(), s.getvalue())) else: if __debug__: self._note("%s.__bootstrap(): normal return", self) finally: self.__stop() # Line 451 I.e. I would expect to get one of the messages ('raised SystemExit', 'unhandled exception', or 'normal return') before self.__stop() is called at line 451. However, I do not see any of those messages. Any ideas or suggestions? I am baffled. Thanks, Alec Wysoker From invalidemail at aerojockey.com Wed Feb 9 21:19:59 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 9 Feb 2005 18:19:59 -0800 Subject: negative integer division References: <4208039c$0$28559$8fcfb975@news.wanadoo.fr> <42096EAD.879E8A5F@yahoo.com> <86wtti76cp.fsf@guru.mired.org> <420A916C.94F7F175@yahoo.com> Message-ID: <1108001999.565042.207190@o13g2000cwo.googlegroups.com> Jive Dadson wrote: > > Now, I'll agree with you if you want to argue that some machines do > > negative integer division in stupifyingly horrible ways. > > That's why I think it was a stupifyingly horrible decision. > Understandable, but in the end an s.h.d. nonetheless. C language is chock-full of things that are stupidly horrible decisions. This is one of very least of them. The philosophy of C was to turn opeations into one or two instructions, if they could. Just about any operator in C can be, and having / invoke a small subprogram would have been the absolute wrong thing to do. The other philosophy of C was to make it easy for the programmer to hand-optimize stuff. Which means no way was it going to force the programmer to use quick_div to get the division in two instructions. It was the right decision. I would say that a better thing to call this is a stupidly horrible circumstance. The circumstance is that an archaic language designed to be hand-optimized and has unfortuntate importabilities has ever became everyone's shizzle. (I'm hating C today; I was asked to write something in C and I can't use anything else because someone has to use to code.) -- CARL BANKS From fperez.net at gmail.com Fri Feb 4 20:25:56 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Fri, 04 Feb 2005 18:25:56 -0700 Subject: IPython colors in windows References: <1107487113.732375.110850@c13g2000cwb.googlegroups.com> <36hculF51ho2sU1@individual.net><1107530489.308497.103530@g14g2000cwa.googlegroups.com><36hrjpF4ui8fbU1@individual.net> <36i84qF52ce29U1@individual.net> Message-ID: Ashot wrote: > One more thing I was wondering about: why not highlight the source code in > the errors since you already have this functionality (with '??' command). > It would be nice to have it highlighed on the prompt as well, but I > imagine this may be more difficult.. I've been using IPython for about a > week and thats one of the two things I miss.. On the input line, there's no way: ipython only gets what you type when you hit return. It would require writing a full-blown IDE to get that. For the errors, it's a bit tricky because I'd have to use the tokenization code right inside the exception traceback builder. That's not particularly easy, esp. considering that the traceback handler doesn't necessarily have full code objects. Tokenizing a chunk of code which may begin half-way through a function, with possibly an open triply-quoted multiline string in the middle, can get tricky. I'm not saying it's impossible, but it's certainly not a very straightforward task. I simply haven't found it to be a priority, given that other parts of ipython need a lot more work. Heck, those tracebacks are already miles ahead of what you get from plain python (try 'xmode verbose' for real detailed info), so for now I'm willing to leave them as they are. But since it's definitely something which would be a nice improvement, I'll gladly accept any patches which implement it in a clean, robust way. Regards, f From administrata at hotmail.com Tue Feb 15 08:39:50 2005 From: administrata at hotmail.com (administrata) Date: 15 Feb 2005 05:39:50 -0800 Subject: Problems in making calulating program. Message-ID: <614c778e.0502150539.4aa742a1@posting.google.com> I wrote this to add 2 numbers... print "Please input data" number1 = int(raw_input(" ")) number2 = int(raw_input("+ ")) total = number1 + number2 print total raw_input("") I want to make output like this... 1 + 1 = 2 But, actually... it looks like this... 1 + 1 2 HELP; From jack at performancedrivers.com Fri Feb 25 01:19:21 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 25 Feb 2005 01:19:21 -0500 Subject: Python Online Programming Contest In-Reply-To: <1109297889.083424.294860@z14g2000cwz.googlegroups.com> References: <1109278779.955986.193860@z14g2000cwz.googlegroups.com> <1109297889.083424.294860@z14g2000cwz.googlegroups.com> Message-ID: <20050225061921.GP9263@performancedrivers.com> On Thu, Feb 24, 2005 at 06:18:09PM -0800, Varun wrote: > Hi, > It is open for anyone across the world. All times are local ( GMT > +5:30). The contest will be on Feb 27 (this sunday) and i will ensure > that the times are clearly specified. How long is the contest? ICFP is three days (first 24 hours are the "lightning" submissions for people with wives/lives). I'm thinking about entering even on this short notice but I'd like to know what I'm getting into. Also, consider posting to slashdot if you want more attention. Each ICFP generates a bunch of before/during/after mentions on slashdot each year. If there is an Indian slashdot kind of thing you might be better off posting there. I assume you are trying to get butts in seats for the conference so maybe 100k mostly western eyeballs on slashdot wouldn't help with that goal. On the other hand, it couldn't hurt! -Jack http://performancedrivers.com/icfp2002/ [2003 snipped, debacle] http://performancedrivers.com/icfp2004/ From fredrik at pythonware.com Wed Feb 2 13:03:10 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 2 Feb 2005 19:03:10 +0100 Subject: Awkwardness of C API for making tuples References: <1107289261.185768.116790@f14g2000cwb.googlegroups.com> Message-ID: Dave Opstad wrote: > This would certainly be simpler, although I'm not sure I'm as clear as > to what happens if, say, in the middle of this loop a PyInt_FromLong > fails. I know that PyTuple_SetItem steals the reference; does that mean > I could just Py_DECREF the tuple and all the pieces will be > automagically freed? yes. tuples release their members when you release the tuple (this is pretty obvious, if you think about it). they also handle uninitialized items property (this is also pretty obvious). here's the code, btw (from tupledealloc in Objects/tupleobject.c): while (--i >= 0) Py_XDECREF(op->ob_item[i]); From dek at scooby.lbl.gov Sun Feb 27 13:03:09 2005 From: dek at scooby.lbl.gov (David E. Konerding DSD staff) Date: Sun, 27 Feb 2005 18:03:09 +0000 (UTC) Subject: any Python equivalent of Math::Polynomial::Solve? References: Message-ID: On 2005-02-26, Just wrote: > While googling for a non-linear equation solver, I found > Math::Polynomial::Solve in CPAN. It seems a great little module, except > it's not Python... I'm especially looking for its poly_root() > functionality (which solves arbitrary polynomials). Does anyone know of > a Python module/package that implements that? > > Just Although I dont' really work on it any more, the Py-ML module which interfaces Python to Mathematica would almost certain be able to do this, although you'd need an installation of Mathematica. http://sourceforge.net/projects/py-ml/ From apardon at forel.vub.ac.be Mon Feb 7 08:55:35 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Feb 2005 13:55:35 GMT Subject: variable declaration References: <4202A022.3050209@netscape.net> Message-ID: Op 2005-02-07, Nick Coghlan schreef : > Antoon Pardon wrote: >> Op 2005-02-05, Nick Coghlan schreef : >> >> >>>[ ... ] >>> >>>With a rebinding operator, the intent of the last line can be made explicit: >>> >>>def collapse(iterable): >>> it = iter(iterable) >>> lastitem = it.next() >>> yield lastitem >>> for item in it: >>> if item != lastitem: >>> yield item >>> lastitem .= item >>> >>>(Note that doing this *will* slow the code down, though, since it has to check >>>for the existence of the name before rebinding it) >> >> >> I think that most of the time it won't slow down the code as the >> checking will have been done during the compilation phase. It >> may even speed up code like this, because the compilation >> phase will have established that it is a rebinding and so >> code for testing whether a new variable is created or not >> is not necessarry here. >> > > Since unbound locals are generally detected at runtime rather than compile time, > I see no real reason why this case would be any different. Static checks would > be in the hands the tools like pychecker (as is currently the case for > references to unbound locals) > > Py> def f(): > ... x > ... x= 3 > ... > Py> f() > Traceback (most recent call last): > File "", line 1, in ? > File "", line 2, in f > UnboundLocalError: local variable 'x' referenced before assignment > > So I'd expect the compiler to generate slower code for it (probably just a > LOAD/STORE pair instead of just a STORE instruction), Why should we limit ourselves to instructions already existing. The compilor might generate a RESTORE instruction. > but the optimiser should > eventually be able to do something to eliminate the performance penalty due to > the technically unnecessary LOAD. I doubt it will be able to beat a STORE_FAST > when it comes to trying to get a performance improvement, though :) But maybe a RESTORE_FAST could. -- Antoon Pardon From ncoghlan at iinet.net.au Fri Feb 4 07:55:02 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 04 Feb 2005 22:55:02 +1000 Subject: python equivalent to haskells iterate. In-Reply-To: <20050204104037.44037.qmail@web26501.mail.ukl.yahoo.com> References: <20050204104037.44037.qmail@web26501.mail.ukl.yahoo.com> Message-ID: <420370A6.8080500@iinet.net.au> Graeme Caldwell wrote: > What this does is takes as a paramter a decimal integer and converts > it to a sequence in which each member is numeral from each position in > the integer. For this specific problem, the builtin 'str' is your best bet: digit_list = map(int, str(val)) (If you only want to display the digits, you can use list(str(val)) to leave them as strings rather than converting back to an int) However, that doesn't really fit with the general 'iterate' question you were asking. For that, something like a generator function is likely to help: def digits(val): if val: while val: val, digit = divmod(val, 10) yield digit else: yield 0 digit_list = list(reversed(list(digits(val)))) Basically, I think the 'yield' keyword and generator functions are likely what you are looking for when it comes to easily building iterators. However, continuing on with the attempt to write Haskell in Python, making the generator function 'dumber' by eliminating its knowledge of the termination condition gets us closer to the original: from itertools import takeWhile def next_digit(val): while 1: val, digit = divmod(val, 10) yield digit digit_list = list(reversed(list( takewhile(lambda digit: digit, next_pair(val))))) For cases where you don't need to do an assignment each time through the loop (e.g. by dividing by progressively larger multiples of 10 instead of using repeated division), you can ditch the function and use a generator expression instead: from itertools import takewhile, count digit_list = reversed( list( takewhile( lambda digit: digit, (((val // (10 ** i)) % 10) for i in count()) ) ) ) Usually you're going to be better served by making the generator function smarter if you're going to be writing one anyway, though. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From usenet_spam at janc.invalid Mon Feb 7 17:27:33 2005 From: usenet_spam at janc.invalid (JanC) Date: Mon, 07 Feb 2005 22:27:33 GMT Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xy8e5jagh.fsf@ruckus.brouhaha.com> <1107490052.542546.285950@c13g2000cwb.googlegroups.com> <11076nqn1ats421@corp.supernews.com> Message-ID: Jeffrey Froman schreef: > M.E.Farmer wrote: > >> Div is a block level tag and span isn't. >> You can also group them??together?and?nest?them. > > One caveat here -- I don't believe you can (should) nest a
> inside a , or for that matter, nest any block-level element > inside an inline element. The following nesting is valid AFAIK:
While this isn't:
-- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From t-meyer at ihug.co.nz Wed Feb 23 18:45:32 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Thu, 24 Feb 2005 12:45:32 +1300 Subject: reading only new messages in imaplib In-Reply-To: Message-ID: [Raghul] >>> Is it posssible to read only the new messages or unread >>> messages using imaplib in python? If it is possible pls >>> specify the module or give a sample code. [Tony Meyer] >> This will print out the first 20 chars of each undeleted message. >> You should be able to figure out how to do what you want from it. [...] [Raghul] > Received: by twmail. > Received: from mail. [...] > it prints something like this. what it actually display. Did you read what I wrote, or just run the code? As I said, it displays the first 20 characters of each undeleted message. If you can't see where the 'first 20 characters' bit is in the code, then you really need to forget about IMAP for the moment and start with the Python tutorial. > And pls tell me what it actually does? I can't understand >>> import imaplib Imports the imaplib module. >>> i = imaplib.IMAP4("mail.example.com") Creates an imaplib.IMAP4 instance to be connected to the mail.example.com server. >>> i.login("username", "password") Logs into the server with the username "username" and the password "password". >>> i.select() Selects the inbox. >>> for msg_num in i.search(None, "UNDELETED")[1][0].split(): Does an IMAP search for UNDELETED messages. Assumes that [0] of the response is "OK" and that [1] of the response is a tuple of the string of the ids. Splits the string on whitespace and iterates through it. ... msg = i.fetch(str(msg_num), "RFC822") Fetches the message (header and body in RFC822 format) for the given message number. ... print msg[1][0][1][:20] Digs down through the response (use imaplib.debug = 4 to see it) to get the message as a string. Prints out 20 characters of it. As basically everyone has said, you must read the IMAP RFC and understand it in order to use imaplib. Please do so. =Tony.Meyer From aurora00 at gmail.com Mon Feb 7 13:52:11 2005 From: aurora00 at gmail.com (aurora) Date: Mon, 07 Feb 2005 10:52:11 -0800 Subject: Python Binary and Windows References: Message-ID: Thanks for making me aware of the difflib module. I don't know there is such cool module exists. You can make it available to other Windows program as a COM object. The win32 api should be all you need. It might be slightly challenging because some parameters are list of strings which might need a little work to translate into COM parameters. > Hi. > > I'd like to compile (?) the DiffLib Python code into a binary form that > can > be called by other Windows apps - like, I'd like to compile it into a > DLL. > > Is this possible? > > Many thanks! > > From bvande at po-box.mcgill.ca Sun Feb 27 15:25:13 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun, 27 Feb 2005 15:25:13 -0500 Subject: Need help running external program In-Reply-To: References: <38ejcfF5lu11pU1@individual.net> Message-ID: <42222CA9.1010002@po-box.mcgill.ca> Rigga said unto the world upon 2005-02-27 15:04: > Tim Jarman wrote: >>No, the r was the point - it's there to tell Python not to do any escaping >>on the string. Try it again with the r and see what happens. >> > > Brilliant!!! that works a treat thankyou!!, where on earth did you find out > about the 'r' any pointers to documentation appreciated. > > Thanks > > RiGGa Best, Brian vdB From petite.abeille at gmail.com Thu Feb 10 13:47:04 2005 From: petite.abeille at gmail.com (PA) Date: Thu, 10 Feb 2005 19:47:04 +0100 Subject: A great Alan Kay quote In-Reply-To: <200502101943.36347.francis.girard@free.fr> References: <420a5c1e$0$21630$a1866201@visi.com> <200502101943.36347.francis.girard@free.fr> Message-ID: On Feb 10, 2005, at 19:43, Francis Girard wrote: > I think he's a bit nostalgic. Steve Wart about "why Smalltalk never caught on": http://hoho.dyndns.org/~holger/smalltalk.html Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From grante at visi.com Tue Feb 1 16:57:45 2005 From: grante at visi.com (Grant Edwards) Date: 01 Feb 2005 21:57:45 GMT Subject: how about writing some gui to a known console application References: <1107294520.224155.131640@f14g2000cwb.googlegroups.com> Message-ID: <41fffb59$0$21637$a1866201@visi.com> On 2005-02-01, alexrait1 wrote: > Do something useful... (at least for me) > For instance I need a gtk frontend for pgp. > So here you can have an opportunity to learn both pyGTK and pgp. A lot > of python code... :) Um, to whom are you addressing your commands? -- Grant Edwards grante Yow! Kids, don't gross me at off... "Adventures with visi.com MENTAL HYGIENE" can be carried too FAR! From peter at engcorp.com Sat Feb 26 19:08:45 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 26 Feb 2005 19:08:45 -0500 Subject: Thread scheduling In-Reply-To: References: <1109456481.214243.140670@l41g2000cwc.googlegroups.com> Message-ID: <09Kdndga9dgQkrzfRVn-hg@powergate.ca> Jack Orenstein wrote: > I am using Python 2.2.2 on RH9, and just starting to work with Python > threads. Is this also the first time you've worked with threads in general, or do you have much experience with them in other situations? > This program seems to point to problems in Python thread scheduling. While from time to time bugs in Python are found, it's generally more productive to suspect one's own code. In any case, you wouldn't have posted it here if you didn't suspect your own code at least a bit, so kudos to you for that. :-) > done = 0 > def run(id): > global done > print 'thread %d: started' % id > global counter > for i in range(nCycles): > counter += 1 > if i % 10000 == 0: > print 'thread %d: i = %d, counter = %d' % (id, i, counter) > print 'thread %d: leaving' % id > done += 1 > > for i in range(nThreads): > thread.start_new_thread(run, (i + 1,)) > while done < nThreads: > time.sleep(1) > print 'Still waiting, done = %d' % done > print 'All threads have finished, counter = %d' % counter Without having tried to run your code, and without having studied it for long, I am going to point out something that is at the very least an inherent defect in your code, though you might not have used Python (or threads?) for long enough to realize why. Note that I don't know if this is the cause of your particular problem, just that it _is_ a bug. You've got two shared global variables, "done" and "counter". Each of these is modified in a manner that is not thread-safe. I don't know if "counter" is causing trouble, but it seems likely that "done" is. Basically, the statement "done += 1" is equivalent to the statement "done = done + 1" which, in Python or most other languages is not thread-safe. The "done + 1" part is evaluated separately from the assignment, so it's possible that two threads will be executing the "done + 1" part at the same time and that the following assignment of one thread will be overwritten immediately by the assignment in the next thread, but with a value that is now one less than what you really wanted. Look at the bytecode produced by the statement "done += 1": >>> import dis >>> def f(): ... global done ... done += 1 ... >>> dis.dis(f) 3 0 LOAD_GLOBAL 0 (done) 3 LOAD_CONST 1 (1) 6 INPLACE_ADD 7 STORE_GLOBAL 0 (done) (ignore the last two lines: they just "return None") 10 LOAD_CONST 0 (None) 13 RETURN_VALUE Note here the "store_global" that is separate from the add operation itself. If thread A gets loses the CPU (so to speak) just before that operation, and thread B executes the entire suite of operations, then later on when thread A executes that operation it will effectively result in only a single addition operation being performed, not two of them. If you really want to increment globals from the thread, you should look into locks. Using the "threading" module (as is generally recommended, instead of using "thread"), you would use threading.Lock(). There are other thread synchronization primitives in the threading module as well, some of which might be more suitable for your purposes. Note also the oft-repeated (in this forum) recommendation that if you simply use nothing but the Queue module for inter-thread communication, you will be very unlikely to stumble over such issues. -Peter From breamoreboy at aol.com Sun Feb 20 13:09:29 2005 From: breamoreboy at aol.com (BrainDead) Date: 20 Feb 2005 10:09:29 -0800 Subject: - E02 - Support for MinGW Open Source Compiler In-Reply-To: <4218cafe$0$8790$9b622d9e@news.freenet.de> References: <42172136$0$27576$9b622d9e@news.freenet.de> <42185b05$0$15460$9b622d9e@news.freenet.de> <42189527$0$6260$9b622d9e@news.freenet.de> <4218cafe$0$8790$9b622d9e@news.freenet.de> Message-ID: <1108922969.140196.304380@z14g2000cwz.googlegroups.com> [Snip] Martin, I believe that you are wasting your time. Looking at your email address, this may well be relevant. http://groups-beta.google.com/group/de.admin.net-abuse.news/browse_frm/thread/8914399857641c05/4163a4fb8a624349?q=Ilias&_done=%2Fgroup%2Fde.admin.net-abuse.news%2Fsearch%3Fgroup%3Dde.admin.net-abuse.news%26q%3DIlias%26qt_g%3D1%26searchnow%3DSearch+this+group%26&_doneTitle=Back+to+Search&&d#4163a4fb8a624349 Regards. Mark Lawrence. From nospam at nospam.fr Fri Feb 11 03:04:14 2005 From: nospam at nospam.fr (jean-michel) Date: Fri, 11 Feb 2005 09:04:14 +0100 Subject: python equivalent to access reports References: Message-ID: "flupke" a ?crit dans le message de news:D9LOd.8257$yJ7.474177 at phobos.telenet-ops.be... > a lot of applications here a made with access. Tables, forms, reports > and the like. Now i rather use Python to do this but i'm not sure how to > proceed. I can use wxPython for a gui via wxGlade for rapid testing and > design (forms), MySQL as db (tables) but the report part is what's > bothering me. > > Any other ideas? Hello, You can use wxwindows (http://www.wxpython.org/) which have some very nice report classes. If you want to know more, you just have to download and try the demo. ++jm From Dennis.Benzinger at gmx.net Thu Feb 17 18:01:46 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Fri, 18 Feb 2005 00:01:46 +0100 Subject: Whats up with re module vs pre In-Reply-To: <1108675920.201110.81250@z14g2000cwz.googlegroups.com> References: <1108675920.201110.81250@z14g2000cwz.googlegroups.com> Message-ID: <42152254$1@news.uni-ulm.de> pythonUser_07 wrote: > This is a very generic observation as I don't have a lot of specifics > with me right now. I have noticed over the past two years that the > python "re" module is somewhat unreliable. What do you mean with unreliable? Can you show an example where re does not work as expected? > At the suggestion of > someone quite some time ago, I started to use the deprecated "pre" > module. "import pre as re". All my problems went away. > > So here I am two years later, writing another script and I had > forgotten about "pre" and wallah > > $ python proc.py > Traceback (most recent call last): > File "proc.py", line 39, in ? > c = collect("nohup.out") > File "proc.py", line 20, in collect > m = p.search(cont) > RuntimeError: maximum recursion limit exceeded > > As soon as I switched "import re" to "import pre as re" my program > worked as expected. In the words of Jerry Sienfeld, what's up with > that? Try again with Python 2.4. The re module is now non-recursive (http://www.python.org/2.4/highlights.html), so you shouldn't get any "maximum recursion limit exceeded" errors. Bye, Dennis From simoninusa2001 at yahoo.co.uk Fri Feb 11 15:13:12 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 11 Feb 2005 12:13:12 -0800 Subject: PyQt and Python 2.4 - also WinXP LnF? In-Reply-To: <1108065099.593832.314470@f14g2000cwb.googlegroups.com> References: <1108003471.242829.297030@o13g2000cwo.googlegroups.com> <1108065099.593832.314470@f14g2000cwb.googlegroups.com> Message-ID: <1108152792.710263.117650@z14g2000cwz.googlegroups.com> I've just got Qt 3.3.3 and PyQt 3.1.3 compiled for Python 2.4 using the instructions for MinGW here: http://kscraft.sourceforge.net/convert_xhtml.php?doc=pyqt-windows-install.xhtml It was a pretty nasty experience, hacking python24.dll and patching sip/PyQt, but i got it all working after about 4 hours! It still doesn't support the XP LnF, but at least I have a non-limited QtDesigner etc. now, and something I can distribute for Windows which supports Python 2.4/QScintilla. I couldn't get it to work with the free MS compiler (VC2003 command line tools and 1.1 SDK) as they were missing libraries etc. I guess the docs are referring to a full Visual Studio .NET 2003 From grante at visi.com Tue Feb 22 10:42:59 2005 From: grante at visi.com (Grant Edwards) Date: 22 Feb 2005 15:42:59 GMT Subject: Copy functio in imaplib References: <1109049046.015244.121070@l41g2000cwc.googlegroups.com> Message-ID: <421b5303$0$46534$a1866201@visi.com> On 2005-02-22, Raghul wrote: > What is message_set in the python documentation for copy in imaplib? It's a list of message numbers. The ones returned by a "SEARCH" command. > Is they referring message set to the particular mail message > in my inbox or something else. ? Have you read the IMAP RFC? http://www.faqs.org/rfcs/rfc2060.html -- Grant Edwards grante Yow! Are you mentally here at at Pizza Hut?? visi.com From wittempj at hotmail.com Thu Feb 17 15:25:29 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Feb 2005 12:25:29 -0800 Subject: TypeError: send() argument 1 must be string or read-only buffer, not int In-Reply-To: References: Message-ID: <1108671929.813837.140620@c13g2000cwb.googlegroups.com> if you want to send the value '1000' over a socket connection in a socket object do something like sock.send(str(1000)) if socket is a socket.socket object. From nitinzep at yahoo.com Fri Feb 11 17:41:11 2005 From: nitinzep at yahoo.com (Nitin Chaumal) Date: 11 Feb 2005 14:41:11 -0800 Subject: Trouble using telentlib Message-ID: <467fdeba.0502111441.4a558e2a@posting.google.com> I sarched the existing threads but didnt find an answer to this. I am writing simple script which uses telentlib to open a session with a unix machine and run "tail -f logfile.txt" on one of the logfiles. import telnetlib HOST = "192.X.X.X" user = "myname" password = "mypass" tn = telnetlib.Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") tn.write("tail -f /tmp/logfile.txt\n") # what do i write here ? # tn.write("exit\n") I want to read every line of the output into a string and run regex on it. I tried tn.interact() which does show me the ouput but the CPU usage on my win2k machine reaches 99% !! :( How do i execute a command and then read its output, then another command and read its output and so on. I tried to find docs on telnetlib but in vain. Can somebody guide me please Thanks Nitin From jerf at jerf.org Thu Feb 17 09:48:00 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 17 Feb 2005 09:48:00 -0500 Subject: Alternative to standard C "for" References: <1107628331.816935.16760@o13g2000cwo.googlegroups.com> <740c3aec050205104924a82d23@mail.gmail.com> <1108620618.3892.85.camel@lipscomb.mbi.ucla.edu> Message-ID: On Thu, 17 Feb 2005 10:22:01 -0800, James Stroud wrote: > It seems I need constructs like this all of the time > > i = 0 > while i < len(somelist): > if oughta_pop_it(somelist[i]): > somelist.pop(i) > else: > i += 1 > > There has to be a better way... > > Any thoughts? Others have pointed out somelist = [x for x in somelist if not oughta_pop_it(x)] but I'd also point out what I haven't seen, that your algorithm is O(n^2) making fairly reasonable assumptions, whereas the list comprehension is O(n). For long lists, that adds up fast. In fact, if you pop two things off in the first half of the list, you've already lost and everything after that is a waste. The only time you want to do that is when you're memory-constrained, since it will take less memory... and I gotta say, I don't think Python is the best "memory-constrained" language in the world :-) Besides, if you're really dealing with that much data, it's probably time to use a database of some sort and tell *it* what things to eliminate. From onurb at xiludom.gro Tue Feb 15 13:52:31 2005 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 15 Feb 2005 19:52:31 +0100 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <42123751$0$10042$626a14ce@news.free.fr> Message-ID: <421244f0$0$30339$636a15ce@news.free.fr> Ilias Lazaridis wrote: > bruno modulix wrote: > >> Ilias Lazaridis wrote: >> >>> >>> there are other reasons behind the decision to not support the MinGW >>> open-source-complier directly out of the main source-code base. >>> >> Yes, of course. The reason is they are lying about their commitment to >> open source. They are currently trying to port Python to .NET, and >> when done they'll retire the current implementation and lock everyone >> to a proprietary platform. I know it's hard to believe, but there are >> clues... > > > impressive. > > but things are much simpler. Could you be more prolific ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From danperl at rogers.com Sun Feb 6 18:47:46 2005 From: danperl at rogers.com (Dan Perl) Date: Sun, 6 Feb 2005 18:47:46 -0500 Subject: How to read POSTed data References: <4205d419$0$6610$8fcfb975@news.wanadoo.fr> <42067a0d$0$10490$8fcfb975@news.wanadoo.fr> Message-ID: "Pierre Quentel" wrote in message news:42067a0d$0$10490$8fcfb975 at news.wanadoo.fr... > >> Pierre, I am repeating some questions I already stated in another thread, >> 'CGI POST problem', but do you have any opinions on how CGIHTTPServer's >> do_POST handles requests? It looks to me like it always expects form >> data to be part of the POST command header, in the path of the URL, just >> like a GET request. Am I understanding the code incorrectly? > > The code in CGIHTTPServer is not very easy to understand, but it does > read the request body, as many bytes as indicated in the Content-Length > header. See line 262 (in the Python 2.4 distribution) or 250 in Python 2.3 > (this is the Windows version) : > > data = self.rfile.read(nbytes) > > Then this data is sent to the standard input of the CGI script. If this > script is a Python program using the cgi module, it usually creates a > cgi.FieldStorage() instance : upon creation, the standard input is read > (in self.read_urlencoded() for instance) and the string collected is > processed to produce a dictionary-like object, with keys matching the form > field names > > This is compliant with the CGI specification (HTTP doesn't say anything > about the management of data sent by POST requests). The code I sent is an > alternative to CGI, leaving the management of this data (available in > self.body) to a method of the RequestHandler instance Thanks, Pierre, this got me much further but I hit another stumbling block. I can see now that CGIHTTPServer writes all the header lines into os.environ and creates a subprocess for the script with os.popen2 or os.popen3 (it's Windows), passing the form data to the new process through sys.stdin (I believe it is sys.stdin although the Library Reference descriptions of popen2 and popen3 say that would be sys.stdout). But I don't see any of those headers updated in the os.environ of the cgi script's process. Is the parent's os.environ passed to the subprocesses created with popen2/popen3 on Windows? cgi.FieldStorage.read_urlencoded needs the content-length that should be passed through os.environ. Dan From wangtianthu at gmail.com Wed Feb 2 18:04:11 2005 From: wangtianthu at gmail.com (Tian) Date: 2 Feb 2005 15:04:11 -0800 Subject: Question about pyFMOD importing Message-ID: <39d7536d.0502021504.4a822c4b@posting.google.com> I am trying to use pyFMOD, I have installed all other supporting libraries (hopefully), such as ctypes, numarray, I also installed FMOD itself and copied its DLL files to python/DLLs. When I try to import pyFMOD in python, i got this message: >>> import pyFMOD Traceback (most recent call last): File "", line 1, in -toplevel- import pyFMOD File "C:\Python24\Lib\site-packages\pyFMOD.py", line 2, in -toplevel- fmod = windll.fmod File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 346, in __getattr__ dll = self._dlltype(name) File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 283, in __init__ self._handle = _LoadLibrary(self._name) WindowsError: [Errno 126] The specified module could not be found Seems there are something wrong in ctype and its related DLL? How should I install it right? Another question, where can I find a tutorial of pyFMOD? the document of FMOD itself is daunting and I don't know how exactly pyFMOD wraps it. Thanks!! Tian From xah at xahlee.org Sat Feb 26 19:06:46 2005 From: xah at xahlee.org (Xah Lee) Date: 26 Feb 2005 16:06:46 -0800 Subject: generic equivalence partition In-Reply-To: <1109453893.313217.66290@f14g2000cwb.googlegroups.com> References: <1109245733.261643.219420@f14g2000cwb.googlegroups.com> <1109419631.693212.236890@z14g2000cwz.googlegroups.com> <1109453893.313217.66290@f14g2000cwb.googlegroups.com> Message-ID: <1109462806.608717.309810@o13g2000cwo.googlegroups.com> People, ... sorry for the latching on on this broadside issue, but it is impotant ... here's are some germane points from another online discussion: the bug-reporting issue has came up so many times by so many people i thought i'd make a comment of my view. when a software is ostensibly incorrect, and if it is likely in connection to egregious irresponsibility as most software companies are thru their irresponsible licensing, the thing one should not do is to fawn up to their ass as in filing a bug report, and that is also the least effective in correcting the software. the common attitude of bug-reporting is one reason that contributed to the tremendous egregious irresponsible fuckups in computer software industry that each of us have to endure daily all the time. (e.g. software A clashed, software B can't do this, C can't do that, D i don't know how to use, E download location currently broken, F i need to join discussion group to find a work-around, G is all pretty and dysfunctional... ) when a software is ostensibly incorrect and when the company is irresponsible with their licensing, the most effective and moral attitude is to do legal harm to the legal entity. This one an do by filing a law suit or spreading the fact. Filing a law suit is appropriate in severe and serious cases, and provided you have such devotion to the cause. For most cases, we should just spread the fact. When a company see facts flying about their incompetence or irresponsibility, they will immediately mend the problem source, or cease to exist. Another harm sprang from the fucking bug-reporting attitude rampant among IT morons is the multiplication of pop-ups that bug users for bug-reporting, complete with their privacy intrusion legalese. http://xahlee.org/UnixResource_dir/writ/responsible_license.html Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html Xah Lee wrote: > folks: > > when using google to post a reply, it sometimes truncates the subject > line. i.e. [perl-python] is lost. This software error is obvious, they > could not have not noticed it. > > another thing more egregious is that google _intentionally_ edit with > people's posts. (e.g. they change email address lines without author's > permission, and they also change program codes so it no longer run). > Please spread these google irresponsibility to all related forums on > software responsibility and online forum issues. > > Ostensible incorrect behavior like these by google is egregious enough > to generate a law suit and if such company do not take software > correctness seriously, we must punish them. > > Please spread this awareness. > > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html From fperez.net at gmail.com Sun Feb 6 19:35:37 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Sun, 06 Feb 2005 17:35:37 -0700 Subject: IPython colors in windows References: <36hculF51ho2sU1@individual.net> <1107530489.308497.103530@g14g2000cwa.googlegroups.com> <36hrjpF4ui8fbU1@individual.net> <36i84qF52ce29U1@individual.net> <36l1dgF52b9d6U1@individual.net> <4205605f_2@news.unc.edu> <42057751_1@news.unc.edu> <36n1gfF505tarU1@individual.net> <36nog9F4udan0U1@individual.net> Message-ID: Claudio Grondi wrote: > Hi, > > I have just updated previously announced > and uploaded to > http://people.freenet.de/AiTI-IT/Python/Console.py > version > of Console.py because I was not satisfied with > it (it didn't support arbitrary ANSI escape > sequences for setting text colors ...) I'd suggest you post some of this info, once you hash out the details with Gary, to the ipython-users list. I'm sure others there would appreciate your efforts towards enhancing the functionality available to win32 users. Best, f From michele.simionato at gmail.com Mon Feb 21 00:51:35 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 20 Feb 2005 21:51:35 -0800 Subject: questions concerning cgi.FieldStorage(keep_blank_values=1) In-Reply-To: References: Message-ID: <1108965095.438688.46170@f14g2000cwb.googlegroups.com> Jonas: > in this application, i need keys to be delivered with the url, some with > and some without value (for example 'script.py?key1&key2=foo'. You are missing an "=" sign after key1. Confront with this example: from cgi import parse_qsl QS = "x=1&y=2&x=3&z=&y=4" print parse_qsl(QS) print parse_qsl(QS, keep_blank_values=True) which gives [('x', '1'), ('y', '2'), ('x', '3'), ('y', '4')] [('x', '1'), ('y', '2'), ('x', '3'), ('z', ''), ('y', '4')] Here the blank value "z=" is converted into "z=''". Michele Simionato From ncoghlan at iinet.net.au Sat Feb 12 03:21:58 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 12 Feb 2005 18:21:58 +1000 Subject: namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP In-Reply-To: <420DB64E.9020000@iinet.net.au> References: <420DB64E.9020000@iinet.net.au> Message-ID: <420DBCA6.5040208@iinet.net.au> Nick Coghlan wrote: > Py> class NS(namespaces.Namespace): > ... x = prop > ... Oops - c&p error here. This was actually: Py> class NS(namespaces.Namespace): ... x = prop ... __x__ = prop ... Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From adam at cognitcorp.com Tue Feb 15 20:07:56 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Tue, 15 Feb 2005 20:07:56 -0500 Subject: newbie question convert C to python In-Reply-To: <3P6dnYqXu9GngI_fRVn-2g@comcast.com> References: <1108440952.526232.234130@c13g2000cwb.googlegroups.com> <7xr7jixxdm.fsf@ruckus.brouhaha.com> <3P6dnYqXu9GngI_fRVn-2g@comcast.com> Message-ID: <1108516076.4371.23.camel@localhost.localdomain> On Tue, 2005-02-15 at 11:03, Steven Bethard wrote: > Paul Rubin wrote: > > doodle4 at gmail.com writes: > > > >>How do i handle this piece of code in python: > >> > >># define vZero 15 > >># define vOne 20 > >> > >>unsigned int vTable[Zero][One] > >> > >>if(vGroup[vZero][vOne] == 0) > >> { > >> vGroup[vZero][vOne]-- > >> ..... > >> ..... > >> } > > > > Simplest might be with a dictionary: > > > > vGroup = {} # I assume you meant vGroup not vTable > > if vGroup[(vZero, vOne)] == 0: > > vGroup[(vZero, vOne)] -= 1 > > ..... > > ..... > > Or, if you like, the parentheses are unnecessary: > > vGroup = {} > if vGroup[vZero, vOne] == 0: > vGroup[vZero, vOne] -= 1 > ..... > > This (or the semantically identical version with parentheses) is > definitely the best approach if you expect to have a lot of empty spots > in your table. > > STeVe One of the problems I see is the access of uninitialized values. In C, you *can* read these and it isn't a bad idea if you used memset, calloc or friends. If I know for sure this will be sparse, I'd reproduce it in python like this. vTable = [] for x in xrange( vZero ): vTable.append( [0,] * vOne ) Now you have a vZero x vOne "array" of zeros. Treat it as you would such a creature in C ... vTable[0][0] = 1 or whatever you want to do. I've seen this question before. Lot in the archives for the subject "2D array" from Dec 7th 2004 - Dec 10th 2004. Steven and I recommended roughly opposite solutions at the time :-) Adam DePrince From ncoghlan at iinet.net.au Sun Feb 13 00:23:03 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 13 Feb 2005 15:23:03 +1000 Subject: Kill GIL In-Reply-To: <868y5t6sal.fsf@guru.mired.org> References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <1107964587.818199.223980@g14g2000cwa.googlegroups.com> <7xr7jlwieq.fsf@ruckus.brouhaha.com> <868y5t6sal.fsf@guru.mired.org> Message-ID: <420EE437.5030009@iinet.net.au> Mike Meyer wrote: > Jack Diederich writes: > > >>From reading this >>thread every couple months on c.l.py for the last few years it is my >>opinion that the number of people who think threading is the only solution >>to their problem greatly outnumber the number of people who actually have >>such a problem (like, nearly all of them). > > > Here here. I find that threading typically introduces worse problems > than it purports to solve. In my experience, threads should mainly be used if you need asynchronous access to a synchronous operation. You spawn the thread to make the call, it blocks on the relevant API, then notifies the main thread when it's done. Since any sane code will release the GIL before making the blocking call, this scales to multiple CPU's just fine. Another justification for threads is when you have a multi-CPU machine, and a processor intensive operation you'd like to farm off to a separate CPU. In that case, you can treat the long-running operation like any other synchronous call, and farm off a thread that releases the GIL before start the time-consuming operation. The only time the GIL "gets in the way" is if the long-running operation you want to farm off is itself implemented in Python. However, consider this: threads run on a CPU, so if you want to run multiple threads concurrently, you either need multiple CPU's or a time-slicing scheduler that fakes it. Here's the trick: PYTHON THREADS DO NOT RUN DIRECTLY ON THE CPU. Instead, they run on a Python Virtual Machine (or the JVM/CLR Runtime/whatever), which then runs on the CPU. So, if you want to run multiple Python threads concurrently, you need multiple PVM's or a timeslicing scheduler. The GIL represents the latter. Now, Python *could* try to provide the ability to have multiple virtual machines in a single process in order to more effectively exploit multiple CPU's. I have no idea if Java or the CLR work that way - my guess it that they do (or something that looks the same from a programmer's POV). But then, they have Sun/Microsoft directly financing the development teams. A much simpler suggestion is that if you want a new PVM, just create a new OS process to run another copy of the Python interpreter. The effectiveness of your multi-CPU utilisation will then be governed by your OS's ability to correctly schedule multiple processes rather than by the PVM's ability to fake multiple processes using threads (Hint: the former is likely to be much better than the latter). Additionally, schemes for inter-process communication are often far more scaleable than those for inter-thread communication, since the former generally can't rely on shared memory (although good versions may utilise it for optimisation purposes). This means they can usually be applied to clustered computing rather effectively. I would *far* prefer to see effort expended on making the idiom mentioned in the last couple of paragraphs simple and easy to use, rather than on a misguided effort to "Kill the GIL". Cheers, Nick. P.S. If the GIL *really* bothers you, check out Stackless Python. As I understand it, it does its best to avoid the C stack (and hence threads) altogether. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From raghulj at gmail.com Mon Feb 21 23:56:13 2005 From: raghulj at gmail.com (Raghul) Date: 21 Feb 2005 20:56:13 -0800 Subject: copying or moving the mail message using imaplib In-Reply-To: <421ab853$0$44647$a1866201@visi.com> References: <1109044151.869953.187270@c13g2000cwb.googlegroups.com> <1109046578.692118.24350@l41g2000cwc.googlegroups.com> <421ab853$0$44647$a1866201@visi.com> Message-ID: <1109048173.384888.79560@o13g2000cwo.googlegroups.com> Thanx I got some clear view about this. In the above program I used uid method to copy thje mail to "Inbox".This shows the out put of my mail messages and In the copy of messages I got the output when printing the "dat" ('OK', [None]) ('OK', ['2 (UID 16 FLAGS (\\Seen))']) 2 I cannot see the message in the INBOX. Can anyone give me a solution. From JoshuaACohen at gmail.com Wed Feb 16 11:44:01 2005 From: JoshuaACohen at gmail.com (Josh) Date: 16 Feb 2005 08:44:01 -0800 Subject: Win32api shellexecute Bshow Message-ID: <1108572241.817012.219940@z14g2000cwz.googlegroups.com> Hi All, I am trying to print a pdf file from python using the Win32api shellexecute method and am having a problem, or perhaps just a misunderstanding, with the bshow parameter. Am I correct to assume that if the bshow parm is set to 0, that the program will not show when launched? e.g.: win32api.ShellExecute (0, "print", "test.pdf", None, ".", 0) When this statment is executed, Adobe Acrobat is launched and made visible to the user, however the actual PDF is hidden. I do not wish for Acrobat to be seen either. Any thoughts? Thanks Josh From pobrien at orbtech.com Mon Feb 14 15:36:16 2005 From: pobrien at orbtech.com (Pat) Date: 14 Feb 2005 12:36:16 -0800 Subject: - E02 - Support for MinGW Open Source Compiler In-Reply-To: References: <1108411017.507814.229600@c13g2000cwb.googlegroups.com> Message-ID: <1108413376.110181.240600@o13g2000cwo.googlegroups.com> Fredrik Lundh wrote: > "Pat" wrote: > > > Okay, I think we are pretty much talking about the same thing. My > > problem is not that I'm unable or unwilling to purchase a good > > compiler. My problem is that I don't want to make it a requirement of > > my users. The twist is that my users will be working out of a > > Subversion repository that includes source code for extensions written > > in C. Those extensions need to be compiled, and the code changes too > > frequently for me to want to deal with supplying compiled binaries. > > here's what I do to supply compiled binaries for 2.1 through 2.4: > > > mkall > > upload dist > > > So I'm looking for options for Windows users who do not have, and are > > unwilling to get, a Microsoft compiler. For some users, minGW is an > > attractive option. For those who want to use minGW, I'm trying to > > establish whether or not minGW is a viable option, particularly for > > Python 2.4. > > here's what I just did (time in minutes): > > +00: googled for the mingw home page > +00: found the mingw download page > +02: finally figured out what to download > +03: noticed that my usual SF site only offered 1K/s; aborted download > +07: finished downloading the mingw kit from another SF site > +17: finished installing > +18: added \mingw\bin to the path > +18: typed "python setup.py install --compiler=mingw32" > +18: got a linker error; googled for help > +19: copied python24.dll to \mingw\lib > +20: finished building the sample library (cElementTree); all tests pass > > so what's your excuse for not doing this? ;-) A few things. Primarily the fact that I'm not very experienced in C (the extensions that I need to have compiled are not written by me). Secondarily, the fact that the discussion threads I read made it seem much more complicated than what you just described. Third, the fact that some of the code we've tried to compile didn't compile cleanly, the way your cElementTree did (but I can't remember what exactly the problem was and I didn't do the compiling). And, finally, an aversion to trial-and-error solutions. I prefer to Google and ask questions when I'm out of my element. Thanks for the info. -- Patrick K. O'Brien Orbtech http://www.orbtech.com Schevo http://www.schevo.org Pypersyst http://www.pypersyst.org From sjmachin at lexicon.net Tue Feb 22 05:54:48 2005 From: sjmachin at lexicon.net (John Machin) Date: 22 Feb 2005 02:54:48 -0800 Subject: how can I make this script shorter? In-Reply-To: References: Message-ID: <1109069688.328226.89190@g14g2000cwa.googlegroups.com> Lowell Kirsh wrote: > I have a script which I use to find all duplicates of files within a > given directory and all its subdirectories. It seems like it's longer > than it needs to be but I can't figure out how to shorten it. Perhaps > there are some python features or libraries I'm not taking advantage of. > > The way it works is that it puts references to all the files in a > dictionary with file size being the key. The dictionary can hold > multiple values per key. Then it looks at each key and all the > associated files (which are the same size). Then it uses filecmp to see > if they are actually byte-for-byte copies. > > It's not 100% complete but it's pretty close. > > Lowell To answer the question in the message subject: 1,$d And that's not just the completely po-faced literal answer that the question was begging for: why write something when it's already been done? Try searching this newsgroup; there was a discussion on this very topic only a week ago, during which the effbot provided the URL of an existing python file duplicate detector. There seems to be a discussion every so often ... However if you persist in DIY, read the discussions in this newsgroup, search the net (people have implemented this functionality in other languages); think about some general principles -- like should you use a hash (e.g. SHA-n where n is a suitably large number). If there are N files all of the same size, you have two options (a) do O(N**2) file comparisons or (b) do N hash calcs followed by O(N**2) hash comparisons; then deciding on your need/whim/costs-of-false-negatives/positives you can stop there or you can do the file comparisons on the ones which match on hashes. You do however need to consider that calculating the hash involves reading the whole file, whereas comparing two files can stop when a difference is detected. Also, do you understand and are you happy with using the (default) "shallow" option of filecmp.cmp()? From mike at teczno.com Mon Feb 21 01:51:31 2005 From: mike at teczno.com (Michal Migurski) Date: Sun, 20 Feb 2005 22:51:31 -0800 Subject: Moving to Python from PHP - 3 questions In-Reply-To: <42191783.2000608@joefrancia.com> References: <42191783.2000608@joefrancia.com> Message-ID: >> Thank you. My impression of Zope in the past has been that it does >> what I need, along with 10,000 other things I don't (built in WebDAV >> server?!), but clearly I owe it another chance. I've been initially >> attracted to mod_python because of its raw simplicity and its >> apparent similarity to mod_php and mod_perl, which I am familiar >> with. I'll give Zope a try. > > I am moving my band's website from an antiquated and horrible PHPNuke > site to a Python-based site, and so have done quite a bit of research > about this (though I never considered myself a PHP expert). Here's > what I've come up with... [snip] This is awesome, quote a bit to chew on. Thank you Joe! ------------------------------------------------------ michal migurski- contact info, blog, and pgp key: sf/ca http://mike.teczno.com/contact.html From jeff at ccvcorp.com Thu Feb 10 13:11:28 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 10 Feb 2005 10:11:28 -0800 Subject: how can I replace a execfile with __import__ in class to use self variables In-Reply-To: <1108006620.737336.166370@o13g2000cwo.googlegroups.com> References: <1107998777.476599.7890@o13g2000cwo.googlegroups.com> <1108006620.737336.166370@o13g2000cwo.googlegroups.com> Message-ID: <110n8s311uf5ka9@corp.supernews.com> Wensheng wrote: > I just realized I can pass the object itself: > like > p=__import__("printit") > p.pr(self) Leaving no reason not do do *this* part as import printit printit.pr(self) rather than using the internal hook function to do exactly the standard thing. > in printit.py > ------------- > def pr(self): > print self.var > ------------------- (Though frankly I don't see the advantage of having this tiny function in a separate file to begin with...) Jeff Shannon Technician/Programmer Credit International From x at y.z Tue Feb 15 11:45:31 2005 From: x at y.z (D H) Date: Tue, 15 Feb 2005 10:45:31 -0600 Subject: replacing ASP/VBScript with Python In-Reply-To: References: Message-ID: Peter Maas wrote: > Peter Maas schrieb: > >> I have inherited an extremely messy ASP/VBScript application which >> is a pain for me to support. Now the customer is thinking about a >> redesign. I'd like to rewrite the whole thing in Python but the app >> has to meet some conditions like >> >> - IIS frontend >> - MSSQL db server >> - Win32 authentication >> - No 'ugly' URLs like http://server/cgi-bin/frontend.cgi?main.py >> - Performance: intranet with ~ 1000 users > > > In the meantime I have searched the internet and found plenty of options: > > - plain cgi with fastcgi and mod_rewrite for IIS to transform the URL > - quixote cgi with fastcgi and mod_rewrite > - Webware + wkcgi > - Python ASP (registering Python with Pywin32 as ASP language) > - mxODBC + SQL ODBC driver > - pyADO + SQL MDAC driver > Can those do Windows authentication though? I guess you could with Python ASP. If you really are stuck with ASP/IIS/Windows, then you might find using boo or ironpython easier since they work with .NET. I'm just saying it is an option, not that you shouldn't use CPython. > - I'd like to do session handling in Python because ASP's session > object is quite limited and some of the ASP app's mess is caused > by trying to use it for compound data type storage. OTOH I could > pickle Python objects to a string and store that in an ASP session. For storing complex data objects, instead of pickle, you can either use .NET serialization: http://boo.codehaus.org/XML+Serialization or db4objects, a GPL tool: http://www.db4o.com/ There is a sample of using boo with db4o here: http://db4oboobrowser.sourceforge.net/ Or ORMs like Gentle.NET can work with MSSQL: http://www.mertner.com/confluence/display/Gentle/Home From gene.tani at gmail.com Wed Feb 16 22:31:32 2005 From: gene.tani at gmail.com (gene.tani at gmail.com) Date: 16 Feb 2005 19:31:32 -0800 Subject: [perl-python] problem: reducing comparison In-Reply-To: References: <1108450348.253772.158120@z14g2000cwz.googlegroups.com> Message-ID: <1108611092.143351.216130@o13g2000cwo.googlegroups.com> This could have been a really unique thread: 15 messages, 1 author From dima at trit.invalid Mon Feb 28 16:29:19 2005 From: dima at trit.invalid (Dima Dorfman) Date: 28 Feb 2005 21:29:19 GMT Subject: Why do descriptors (and thus properties) only work on attributes. References: <7xoee5kpiv.fsf@ruckus.brouhaha.com> <38g8hvF5oc44qU1@individual.net> Message-ID: On 2005-02-28, Antoon Pardon wrote: > Op 2005-02-28, Diez B. Roggisch schreef : >> I still don't see how that is supposed to work for "a lot of interesting >> things". Can you provide examples for one of these interesting things? > > Lazy evaluation where the value of something is calculated the first > time it is needed but accessed from some storage if it is needed again. I do this all the time. It's not very hard and doesn't require any extra language support, but I would like for there to be an authoritative list of type slots (autopromise_ops). import operator def promise(thunk): x = [] def promised(): if not x: x.append(thunk()) return x[0] return promised autopromise_ops = [x for x in dir(operator) if x.startswith('__')] autopromise_ops += ['__getattribute__', '__call__', '__str__', '__repr__'] autopromise_ops += ['__getattr__', '__setattr__', '__delattr__'] def autopromise(thunk): p = promise(thunk) d = {} for op in autopromise_ops: def bindhack(op=op): return lambda self, *a, **kw: getattr(p(), op)(*a, **kw) d[op] = bindhack() return type('autopromise', (), d)() def test(): lis = [] def thunk(): lis.append('ran thunk') return 'value' s = autopromise(thunk) p = s * 30 assert p == 'value' * 30 p = s * 10 assert p == 'value' * 10 assert lis == ['ran thunk'] # Just once print 'autopromise sanity test passed' An autopromise object is good almost everywhere the real one would be, and usually the only way to tell the difference is to call id or type on it. The main exception is when the thunk returns a builtin type (like a string or int) and you want to pass it to a builtin function that expects a particular type (this would also apply to Python functions that break duck typing on purpose, but those would just be getting the breakage they deserve). From cpmcdaniel at gmail.com Wed Feb 16 16:43:42 2005 From: cpmcdaniel at gmail.com (cpmcdaniel at gmail.com) Date: 16 Feb 2005 13:43:42 -0800 Subject: Using 'in' with a Dict Message-ID: <1108590222.589358.7310@o13g2000cwo.googlegroups.com> I was wondering if the following two "if" statements compile down to the same bytecode for a standard Dictionary type: m = {"foo": 1, "blah": 2} if "foo" in m: print "sweet" if m.has_key("foo"): print "dude" From marian at mba-software.de Mon Feb 7 00:24:52 2005 From: marian at mba-software.de (=?ISO-8859-1?Q?Marian_Aldenh=F6vel?=) Date: Mon, 07 Feb 2005 06:24:52 +0100 Subject: pygame.mixer.music not playing In-Reply-To: <1107748705.808825.319270@f14g2000cwb.googlegroups.com> References: <36mb0iF54udklU1@individual.net> <1107700800.258876.298010@z14g2000cwz.googlegroups.com> <36mvjkF54gvnrU1@individual.net> <1107748705.808825.319270@f14g2000cwb.googlegroups.com> Message-ID: <36ocddF541n0fU1@individual.net> Hi, > Also you can try and look for another sound package, like maybe pyFMOD I have looked at it. While I do not like some of the boasting on the FMOD site it does seem very suitable. FMOD is cross-platform but pyFMOD is available only as Win32-Setup. Does that mean it cannot be made to work on Linux or is it just not packaged for it? It looks like your standard DLL-Import-File as known from other languages and uses ctypes (had to install that first). How hard can it be to make a version that loads a shared library with the same API on Linux? To make pyFMOD work with the current version of FMOD I had to fix it in a few obvious places. After doing so the new version of my micro-program looks like this: import time from pyFMOD import * res = FSOUND_Init(44100, 32, 0) print "FSOUND_Init() =", res stream = FSOUND_Stream_Open("file1.mp3",0,0,0) print "FSOUND_Stream_Open() =", stream res = FSOUND_Stream_Play(FSOUND_FREE,stream) print "FSOUND_Stream_Play() =", res while True: print "FSOUND_Stream_GetTime() =", FSOUND_Stream_GetTime(stream) time.sleep(1) And plays fine. Now I need to read up on FMODs API to find out how to eliminate the "while True;" but that should not be a problem. This would give me a very rich API with full control. I am having fun! Thank you all. Ciao, MM -- Marian Aldenh?vel, Rosenhain 23, 53123 Bonn. +49 228 624013. http://www.marian-aldenhoevel.de "Wir brauchen keine Opposition, wir sind bereits Demokraten." From invalidemail at aerojockey.com Sun Feb 27 14:22:23 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 27 Feb 2005 11:22:23 -0800 Subject: any Python equivalent of Math::Polynomial::Solve? In-Reply-To: <1109485184.587035.176540@l41g2000cwc.googlegroups.com> References: <1109485184.587035.176540@l41g2000cwc.googlegroups.com> Message-ID: <1109532143.591685.319010@f14g2000cwb.googlegroups.com> Carl Banks wrote: > . from Numeric import * > . from LinearAlgebra import * > . > . def quinticroots(p): > . cm = zeros((5,5),Float32) > . cm[0,1] = cm[1,2] = cm[2,3] = cm[3,4] = 1.0 > . cm[4,0] = -p[0] > . cm[4,1] = -p[1] > . cm[4,2] = -p[2] > . cm[4,3] = -p[3] > . cm[4,4] = -p[4] > . return eigenvalues(cm) Here's an improved version. It uses 64-bit numbers (I had used type Float32 because I often use a float32 type at work, not in Python, unfortunately), and array assignment. . def quinticroots(p): . cm = zeros((5,5),Float) . cm[0,1] = cm[1,2] = cm[2,3] = cm[3,4] = 1.0 . cm[4,:] = -array(p) . return eigenvalues(cm) -- CARL BANKS From markus_wankusGETRIDOFALLCAPS at hotmail.com Thu Feb 3 22:50:09 2005 From: markus_wankusGETRIDOFALLCAPS at hotmail.com (Markus Wankus) Date: Thu, 03 Feb 2005 22:50:09 -0500 Subject: IDLE history, Python IDE, and Interactive Python with Vim In-Reply-To: References: Message-ID: <_hCMd.22184$Ck1.1630530@news20.bellglobal.com> I highly recommend trying pyDev. 0.9 just came out, and I find 0.85 very usable and quite cool. There is nice debug support, and context-sensitive code completion as well as real-time validation of your code. This is an exciting project with a bright future in my opinion. Markus. Ashot wrote: > This is sort of both Python and Vim related (which is why I've posted > to both newsgroups). > > Python related: > ---------------------- > I have been frustrated for quite some time with a lack of a history > command in IDLE (in fact with IDLE in general). Often I'll develop new > code at the command line, testing each line as I go. Currently I have > to copy and paste, removing outputs and the ">>>" at each line. > Is it perhaps possible to make some kind of hack to do this (dump a > command history)? > > Idle in general isn't that great IMO, so I was wondering also if there > are better alternatives out there? What do people use mostly? I've > tried something called pyCrust, but this too didn't have history and > some other things I was looking for. On a more general note, although > the agility and simplicity of Python make programming tools like an IDE > less necessary, it still seems that Python is lacking in this > departement. The PyDev plug-in for Eclipse seems like good step in > this direction, although I haven't tried it yet. Does anyone have any > experience with this, or perhaps can point me to other tools. > > Vim related: > ---------------------- > Ideally, it would be nice to have a command mapped to a keystroke that > can append the last executed command to a file. Even better would be a > system that would integrate the file editing and interactive command > line tool more seamlessly. Something along the lines of a debugger + > file editor + command line utility, where file editor = vim. I know > that vim has a utility for running python commands from its command > prompt, but I have had a hard time getting this to work in windows and > haven't explored it. Has anyone seen/tried a system along these lines, > perhaps incorporating the python debugger (pdb)? I can see something > that will run the file you are editing in vim up to the cursor or a > mark with a set_trace at the line you are editing. > > > Any info is appreciated, thanks. > > -- > Ashot Petrosian > University of Texas at Austin, Computer Sciences From rzantow at ntelos.net Mon Feb 21 11:03:34 2005 From: rzantow at ntelos.net (rzed) Date: Mon, 21 Feb 2005 11:03:34 -0500 Subject: help please References: <1108254434.871062.314510@g14g2000cwa.googlegroups.com> <1108260752.791847.180060@l41g2000cwc.googlegroups.com> <1108324679.451793.147890@z14g2000cwz.googlegroups.com> <1108329540.239064.144920@f14g2000cwb.googlegroups.com> <1108334012.336816.221460@g14g2000cwa.googlegroups.com> <1108921146.274248.11500@g14g2000cwa.googlegroups.com> <1108959170.585091.202240@z14g2000cwz.googlegroups.com> Message-ID: <732f6$421a051a$40046a98$4613@ispnews.usenetserver.com> "gargonx" wrote in message news:1108959170.585091.202240 at z14g2000cwz.googlegroups.com... > Even if i put it in exactly the way you did: > > >>> import re > >>> charmatcher = re.compile(r' [A-Z] [\d]?') > >>> > >>> ext = dict(D="V1", O="M1", G="S1") > >>> std = dict(S="H") > >>> > >>> decode_replacements ={} > >>> decode_replacements.update([(std[key], key) for key in std]) > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: keys Works with 2.4, but not with 2.3.4: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> charmatcher = re.compile(r' [A-Z] [\d]?') >>> >>> ext = dict(D="V1", O="M1", G="S1") >>> std = dict(S="H") >>> >>> decode_replacements ={} >>> decode_replacements.update([(std[key], key) for key in std]) >>> >>> print decode_replacements {'H': 'S'} Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> charmatcher = re.compile(r' [A-Z] [\d]?') >>> >>> ext = dict(D="V1", O="M1", G="S1") >>> std = dict(S="H") >>> >>> decode_replacements ={} >>> decode_replacements.update([(std[key], key) for key in std]) Traceback (most recent call last): File "", line 1, in ? AttributeError: keys >>> >>> print decode_replacements {} From steven.bethard at gmail.com Wed Feb 2 23:28:31 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 02 Feb 2005 21:28:31 -0700 Subject: streaming a file object through re.finditer In-Reply-To: <1107396145.400036.271010@g14g2000cwa.googlegroups.com> References: <1107396145.400036.271010@g14g2000cwa.googlegroups.com> Message-ID: Erick wrote: > Hello, > > I've been looking for a while for an answer, but so far I haven't been > able to turn anything up yet. Basically, what I'd like to do is to use > re.finditer to search a large file (or a file stream), but I haven't > figured out how to get finditer to work without loading the entire file > into memory, or just reading one line at a time (or more complicated > buffering). Can you use mmap? http://docs.python.org/lib/module-mmap.html "You can use mmap objects in most places where strings are expected; for example, you can use the re module to search through a memory-mapped file." Seems applicable, and it should keep your memory use down, but I'm not very experienced with it... Steve From apardon at forel.vub.ac.be Mon Feb 7 08:28:04 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Feb 2005 13:28:04 GMT Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> Message-ID: Op 2005-02-05, Roy Smith schreef : > In article , > Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org (Alexander > Zatvornitskiy) wrote: > >> And, one more question: do you think code like this: >> >> var S=0 >> var eps >> >> for eps in xrange(10): >> S=S+ups >> >> is very bad? Please explain your answer:) > > Let me answer that by way of counter-example. > > Yesterday I was writing a little perl script. I always use "use strict" in > perl, which forces me to declare my variables. Unfortunately, my code was > giving me the wrong answer, even though the interpreter wasn't giving me > any error messages. > > After a while of head-scratching, it turned out that I had written "$sum{x} > += $y" instead of "$sum{$x} += $y". The need to declare variables didn't > find the problem. I *still* needed to test my work. Given that I needed > to write tests anyway, the crutch of having to declare my variables really > didn't do me any good. I you come to the conclusion that it doesn't do you any good, why did you use it? I find it odd that someone who prefers to use it in a language where it is optional is argues that it shouldn't be included as an option is an other language. I would think that if he thinks it so bad he wouldn't use it in that other language in the first place. -- Antoon Pardon From 18k11tm001 at sneakemail.com Fri Feb 11 18:18:57 2005 From: 18k11tm001 at sneakemail.com (18k11tm001 at sneakemail.com) Date: 11 Feb 2005 15:18:57 -0800 Subject: Commerical graphing packages? In-Reply-To: <420d1595$1@nntp.zianet.com> References: <420d1595$1@nntp.zianet.com> Message-ID: <1108163937.533683.162220@g14g2000cwa.googlegroups.com> Check out GRACE. It's not specifically designed for Python, but I've been using with Python for a couple of years or more. I'm very happy with it, and it's free. It works both interactively and in batch mode. Do a google on GRACE. From steve at holdenweb.com Thu Feb 3 09:58:42 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Feb 2005 09:58:42 -0500 Subject: Popularizing SimpleHTTPServer and CGIHTTPServer In-Reply-To: References: <1107412654.121488.157070@c13g2000cwb.googlegroups.com> Message-ID: Jorey Bump wrote: > "Michele Simionato" wrote in > news:1107412654.121488.157070 at c13g2000cwb.googlegroups.com: > > >>Just submitted a recipe with this goal in mind: >> >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/365606 > > > You may want to warn people that if they run those commands in their home > directory, they will instantly share all of their data with anyone that can > access the machine. Because the server runs as the user, it will have > permission to serve all of the files in the directory. I'd recommend that > they cd into a directory created specifically for the purpose of testing. > > Does anyone know how to use SimpleHTTPServer to: > > 1. Support virtual hosts? > > 2. Support SSL? > > I'd like to use SimpleHTTPServer to create some simple reporting utilities, > but can't get past these two points. Is there a NotSoSimpleHTTPServer? You want ExtremelyBloodyComplicatedHTTPServer :-) regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From service at zp-solutions.com Tue Feb 1 07:03:31 2005 From: service at zp-solutions.com (Nico Grubert) Date: Tue, 01 Feb 2005 13:03:31 +0100 Subject: Remove HTML tags (except anchor tag) from a string using regular expressions Message-ID: <41FF7013.7030309@zp-solutions.com> Hello, I want to remove all html tags from a string "content" except xxx. My script reads like this: ### import re content = re.sub('<([^!>]([^>]|\n)*)>', '', content) ### It works fine. It removes all html tags from "content". Unfortunately, this also removes xxx occurancies. Any idea, how to modify this to remove all html tags except xxx? Thanks in advance, Nico From brown at esteem.com Fri Feb 4 21:54:52 2005 From: brown at esteem.com (Tom Brown) Date: Fri, 4 Feb 2005 18:54:52 -0800 Subject: how to send an int over a socket In-Reply-To: <200502041827.45302.brown@esteem.com> References: <200502041827.45302.brown@esteem.com> Message-ID: <200502041854.52836.brown@esteem.com> On Friday 04 February 2005 18:27, Tom Brown wrote: > Hi, > > I have what seems to be a simple problem. But I can not for the life of me > find a way to send an integer over a socket. The send method will only > accept strings. Here is what I am trying to do: > > testmessage = 'test message' > msglen = len(testmessage) > sock.send(msglen) > sock.send(testmessage) > > Now, I know I can do this: > > testmessage = 'test message' > sock.send('\xC') # send hard coded length of testmessage in hex in string > sock.send(testmessage) > > However, in my actual program I will not know the length of testmessage in > advance. So how do I convert msglen into a suitable format for the send > method? > > Thanks, > Tom Ok, I think I've found what I was looking for. The marshal.dumps() function will convert my integer into a string representation of a fixed size. This way, on the other side, I know how many bytes to read to get the size of the string. Thanks, Tom From noreply at python.org Tue Feb 1 10:53:42 2005 From: noreply at python.org (Post Office) Date: Tue, 1 Feb 2005 16:53:42 +0100 Subject: MDaemon Warning - virus found: Returned mail: see transcript for details Message-ID: <20050201155412.C70B21E400A@bag.python.org> ******************************* WARNING ****************************** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. Attachment Virus name Action taken ---------------------------------------------------------------------- file.zip Email-Worm.Win32.Mydoom.m Removed ********************************************************************** The original message was received at Tue, 1 Feb 2005 16:53:42 +0100 from python.org [96.182.125.158] ----- The following addresses had permanent fatal errors ----- ----- Transcript of the session follows ----- ... while talking to python.org.: 554 ... Message is too large 554 ... Service unavailable From steven at lczmsoft.com Wed Feb 23 23:02:16 2005 From: steven at lczmsoft.com (steven at lczmsoft.com) Date: 23 Feb 2005 20:02:16 -0800 Subject: Source Encoding GBK/GB2312 Message-ID: <1109217736.643721.201240@o13g2000cwo.googlegroups.com> When I specify an source encoding such as: # -*- coding: GBK -*- or # -*- coding: GB2312 -*- as the first line of source, I got the following error: SyntaxError: 'unknown encoding: GBK' Does this mean Python does not support GBK/GB2312? What do I do? - narke From bergt at cs.pdx.edu Sat Feb 19 20:31:52 2005 From: bergt at cs.pdx.edu (Travis Berg) Date: Sat, 19 Feb 2005 17:31:52 -0800 (PST) Subject: segfault when calling Python from C thread Message-ID: I'm running into a problem when trying to perform a callback to a Python function from a C extension. Specifically, the callback is being made by a pthread that seems to cause the problem. If I call the callback from the parent process, it works fine. The PyObject is static, and holds the same value in both Parent and thread, so I'm at a loss as to what would be different in the pthread from the parent that would cause a segfault on the callback. The machine specifics are an x86 intel processor with RedHat linux. Here is some clips of the C callback code showing how I'm storing the callback, then what the actual callback function is like. Any ideas? The function being called is a simply to display the string of text, and execution never seems to reach back to the Python code at all. Thanks, Travis B. /* callback function to the Python code */ static PyObject * my_callback = NULL; /* setting callback function */ static PyObject * my_set_callback(PyObject *dummy, PyObject *args) { PyObject *result = NULL; PyObject *temp; PyObject *arglist; if (PyArg_ParseTuple(args, "O:set_callback", &temp)) { if (!PyCallable_Check(temp)) { PyErr_SetString(PyExc_TypeError, "parameter must be callable"); return NULL; } Py_XINCREF(temp); /* Add a reference to new callback */ Py_XDECREF(my_callback); /* Dispose of previous callback */ my_callback = temp; /* Remember new callback */ /* return "None" */ Py_INCREF(Py_None); result = Py_None; } return result; } /* calling callback */ void callback(char * str) { PyObject *arglist; PyObject *result; if(str == NULL) return; if(my_callback == NULL) { printf("no callback function provided, returning...\n"); return; } /* Time to call the callback */ arglist = Py_BuildValue("(s)", str); result = PyEval_CallObject(my_callback, arglist); Py_DECREF(arglist); if(result == NULL) return; Py_DECREF(result); } From aco at mi2.hr Thu Feb 24 14:02:14 2005 From: aco at mi2.hr (Aleksandar Erkalovic) Date: Thu, 24 Feb 2005 20:02:14 +0100 Subject: [ANN] TamTam collaboration software Message-ID: Hi, on address (temporary): http://tamtam.mi2.hr:8888/NoviTam/ you can find TamTam collaborative software. This is new version (rewrite) using Twisted and Nevow. This is not official announcement just a small notice for people who are interested to check it, give me some critics, help in ideas or maybe help in development. Aco -- http://aco.mi2.hr/ From b at b.b Sun Feb 13 18:33:50 2005 From: b at b.b (Roose) Date: Sun, 13 Feb 2005 23:33:50 GMT Subject: builtin functions for and and or? References: Message-ID: "Diez B. Roggisch" wrote in message news:cuofcj$jvt$02$1 at news.t-online.com... > > So usually I just write a little function any( L, boolean_function = > > identity ) or all( ... ). But I am kind of sick of doing that all the > > time -- does it exist anywhere in the Python libraries? It seems really > > common to me. > > Put things into your own module and add it to your python path. Then you > only have to write it once. Well it's not as convenient as having it built in. The thing is I'm not just writing for myself. I used it at my old job, and now I'm using it at my new job. There's a requirement that the user shouldn't have to modify his setup beyond installing Python to run any scripts. At my first job we had one way of dealing with this. Now there is another way. And then I need a way to deal with it at home with my personal stuff. Also the stuff typically doesn't go under the Python dir, because that is not mapped to source control. And anyway people don't like mixing in our code with 3rd party code. The result that the path of least resistance is just to copy in a 4 line function or two into the program and be done with it, even though it goes against my sense of aesthetics. It would be a lot simpler if it was included in the distribution. I would be willing to add it (even though it is completely trivial). I think it would go fine in itertools (I would even put them as builtins, but I'm not going to go there because probably not everyone uses it as often as I do). What do people think? I have never done this, would I just write up a PEP? > > > The first way isn't satisfactory because it takes so many lines for what > > is > > essentially one "primitive" operation. The second way isn't great because > > it is not as readable and many readers don't like to see reduce, even if > > it > > is a common idiom like that. Also I don't believe it short circuits. > > It doesn't but so doesn't your loop example. Put a break in there once > Result is False. > > -- > Regards, > > Diez B. Roggisch From tech at gpao.cc Tue Feb 1 03:52:49 2005 From: tech at gpao.cc (Olivier Noblanc ATOUSOFT) Date: Tue, 1 Feb 2005 09:52:49 +0100 Subject: find isset() php function equivalent in python Message-ID: <41ff435f$0$18835$8fcfb975@news.wanadoo.fr> Hello What is the equivalent function of php isset() in python Thank you very much. olivier noblanc http://www.logiciel-erp.fr From kent37 at tds.net Mon Feb 7 18:33:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Feb 2005 18:33:37 -0500 Subject: Subclassing cElementTree.Element Message-ID: <4207f801$1_2@newspeer2.tds.net> Is it possible to subclass cElementTree.Element? I tried >>> import cElementTree as et >>> class Elt(et.Element): ... pass ... Traceback (most recent call last): File "", line 1, in ? TypeError: Error when calling the metaclass bases cannot create 'builtin_function_or_method' instances I want to create a tree where I can navigate from a node to its parent. The standard Element class doesn't seem to support this so I am trying to make a subclass that does. The XML files in question are large so the speed of cElementTree is very helpful. Thanks, Kent (apologies if this is a duplicate post) From mac at ceti.pl Wed Feb 9 17:32:55 2005 From: mac at ceti.pl (mac) Date: Wed, 9 Feb 2005 22:32:55 +0000 (UTC) Subject: Seekable output from ClientForm? References: <35993bcb.0502091338.34591a7@posting.google.com> Message-ID: In article <35993bcb.0502091338.34591a7 at posting.google.com>, Matej Cepl wrote: > Hi, > > using python 2.3, ClientForm, and ClientCookie and I have this code: > > opener = ClientCookie.build_opener(ClientCookie.HTTPRefererProcessor, > ClientCookie.HTTPRefreshProcessor, > ClientCookie.SeekableProcessor) > > response = opener.open(lxURL) > forms = ClientForm.ParseResponse(response) > form = forms[0] > response.seek(0) > > form['extpatid'] = MyNEUlogin > form['extpatpw'] = MyNEUpassword > formopener = form.click() > > response2 = ClientCookie.urlopen(formopener) > > guidednews = re.compile("s_guidednews.html") > > response2.seek(0) > h = htmllib.HTMLParser(formatter.NullFormatter()) > h.feed(response2.read()) > print h.anchorlist > > Unfortunately, it doesn't work, because response2 was created by > ClientForm and it is not seekable (apparently, I get "AttributeError: > addinfourl instance has no attribute 'seek'"). > > How to make output of ClientForm seekable, please? Instead of: response2 = ClientCookie.urlopen(formopener) try: opener.open(formopener) Cheers, Maciek From steven.bethard at gmail.com Tue Feb 15 20:03:14 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 15 Feb 2005 18:03:14 -0700 Subject: __new__ does not call __init__ as described in descrintro.html (WAS: Can __new__ prevent __init__ from being called?) Message-ID: Felix Wiemann wrote: > Steven Bethard wrote: >> http://www.python.org/2.2.3/descrintro.html#__new__ > [snip] > > I'm just seeing that the web page says: > > | If you return an existing object, the constructor call will still > | call its __init__ method. If you return an object of a different > | class, its __init__ method will be called. > > However, the latter doesn't seem to be true, or am I missing > something? > >>>>class A(object): > ... def __init__(self): > ... print 'Init of A.' > ... > >>>>instance = A() > Init of A. > >>>>class B(object): > ... def __new__(self): > ... return instance > ... def __init__(self): > ... print 'Init of B.' > ... > >>>>B() # <--------- A's __init__ is *not* called. > <__main__.A object at 0x4062424c> > >>>>instance = object.__new__(B) >>>>B() # <--------- B's __init__ is called > Init of B. > <__main__.B object at 0x406243ec> > > So there seems to be some type-checking in type.__call__. Yeah, I saw the same thing in playing around with this. Don't know what to make of it. I wonder if we should file a documentation bug? I can't find __new__ explained anywhere in the Language Reference. Can documentation bugs be filed for descrintro.html? STeVe From francis.girard at free.fr Sun Feb 6 14:50:40 2005 From: francis.girard at free.fr (Francis Girard) Date: Sun, 6 Feb 2005 20:50:40 +0100 Subject: remove duplicates from list *preserving order* In-Reply-To: References: Message-ID: <200502062050.41424.francis.girard@free.fr> Hi, I think your last solution is not good unless your "list" is sorted (in which case the solution is trivial) since you certainly do have to see all the elements in the list before deciding that a given element is not a duplicate. You have to exhaust the iteratable before yielding anything. Besides that, I was thinking that the best solution presented here proceed in two steps : 1- Check that an element is not already in some ordered data type of already seen element 2- If not, put the element in that structure That's probably twice the work. There might be some way to do both at the same time, i.e. - Put the element in the data structure only if not already there and tell me, with some boolean, if you did put the element. Then you have to do the work of finding the right place where to insert (fetch) the element only once. I don't see any easy way to do this in python, other than rolling your sleeves and code your own data structure in Python, which would be slowlier than the provided dict or set C implementation. I think this a hole into the Pythin libs. Regards Francis Girard Le jeudi 3 F?vrier 2005 21:39, Steven Bethard a ?crit?: > I'm sorry, I assume this has been discussed somewhere already, but I > found only a few hits in Google Groups... If you know where there's a > good summary, please feel free to direct me there. > > > I have a list[1] of objects from which I need to remove duplicates. I > have to maintain the list order though, so solutions like set(lst), etc. > will not work for me. What are my options? So far, I can see: > > def filterdups(iterable): > result = [] > for item in iterable: > if item not in result: > result.append(item) > return result > > def filterdups(iterable): > result = [] > seen = set() > for item in iterable: > if item not in seen: > result.append(item) > seen.add(item) > return result > > def filterdups(iterable): > seen = set() > for item in iterable: > if item not in seen: > seen.add(item) > yield item > > Does anyone have a better[2] solution? > > STeve > > [1] Well, actually it's an iterable of objects, but I can convert it to > a list if that's helpful. > > [2] Yes I know, "better" is ambiguous. If it helps any, for my > particular situation, speed is probably more important than memory, so > I'm leaning towards the second or third implementation. From gabriel.barros at gmail.com Sun Feb 27 01:46:28 2005 From: gabriel.barros at gmail.com (Gabriel B.) Date: Sun, 27 Feb 2005 03:46:28 -0300 Subject: simple input that can understand special keys? Message-ID: <5175a81c05022622466f9c2321@mail.gmail.com> i'm writting an application that will use Tinker in a newer future. Now it's console only. I simply ommit some data on the display, print() some other and go on. The problem is that i can't test the actions tiggered by special keys, like Page Up/Down or the F1...12 Right now i'm using raw_input() since even the Tk version will have only one input place, and for debuging i'm literally writting pageup, pagedow and the F's. But i want to put it in test while i write the GUI. is there any hope for me? I wanted to stay only with the console for now. And it's windows by the way :) Thanks From philippe at philippecmartin.com Mon Feb 7 17:25:35 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 07 Feb 2005 22:25:35 GMT Subject: socket question References: <36pm9uF53qlqdU1@individual.net> <1107802933.017870.84480@g14g2000cwa.googlegroups.com> Message-ID: Thanks, it was a bind problem: socket.gethostname() returns 'localhost' where '' is was was needed. Regards, Philippe On Mon, 07 Feb 2005 11:02:13 -0800, Kartic wrote: > > Philippe C. Martin wrote: >> >> My problem is that I cannot connect to my server if the client is > not on >> >> the same PC (although I'm doing the above). > > > Does the machine running the server code also have a firewall installed > that blocks access to the server port from outside? That is the only > possibility I can think of that prevents a non-local client from > connecting. > > Also, please do a netstat -a on the machine running the server and see > the IP addresses to which the listening port is bound. > > Thanks, > -Kartic From daniel.dittmar at sap.corp Thu Feb 10 10:23:09 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Thu, 10 Feb 2005 16:23:09 +0100 Subject: sre is broken in SuSE 9.2 In-Reply-To: References: Message-ID: Denis S. Otkidach wrote: > On all platfroms \w matches all unicode letters when used with flag > re.UNICODE, but this doesn't work on SuSE 9.2: I think Python on SuSE 9.2 uses UCS4 for unicode strings (as does RedHat), check sys.maxunicode. This is not an explanation, but perhaps a hint where to look. Daniel From neutrinman at myrealbox.com Thu Feb 17 21:13:46 2005 From: neutrinman at myrealbox.com (neutrinman at myrealbox.com) Date: 17 Feb 2005 18:13:46 -0800 Subject: how can i randomly choose keys in dictionary Message-ID: <1108692826.040660.71750@g14g2000cwa.googlegroups.com> Hi,there. How can I choose a key in dictionary randomly? Say, random.choice() in lists, or in lists: lists = [1,2,3,4] position = random.range(len(lists)) word = lists[position] From mwm at mired.org Fri Feb 25 16:13:41 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 25 Feb 2005 15:13:41 -0600 Subject: Converting HTML to ASCII References: <20050225185147.43095.qmail@web20703.mail.yahoo.com> Message-ID: <86is4gfim2.fsf@guru.mired.org> Michael Spencer writes: > gf gf wrote: >> [wants to extract ASCII from badly-formed HTML and thinks BeautifulSoup is too complex] > > You haven't specified what you mean by "extracting" ASCII, but I'll > assume that you want to start by eliminating html tags and comments, > which is easy enough with a couple of regular expressions: > > >>> import re > >>> comments = re.compile('', re.DOTALL) > >>> tags = re.compile('<.*?>', re.DOTALL) > ... > >>> def striptags(text): > ... text = re.sub(comments,'', text) > ... text = re.sub(tags,'', text) > ... return text > ... > >>> def collapsenewlines(text): > ... return "\n".join(line for line in text.splitlines() if line) > ... > >>> import urllib2 > >>> f = urllib2.urlopen('http://www.python.org/') > >>> source = f.read() > >>> text = collapsenewlines(striptags(source)) > >>> > > This will of course fail if there is a "<" without a ">", probably in > other cases too. But it is indifferent to whether the html is > well-formed. It also fails on tags with a ">" in a string in the tag. That's well-formed but ill-used HTML. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From deetsNOSPAM at web.de Sun Feb 27 11:17:02 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 27 Feb 2005 17:17:02 +0100 Subject: Sharing a method (function) among several objects. References: <1109517248.084515.104280@z14g2000cwz.googlegroups.com> Message-ID: > Since they are not the same or similar, it's not logical to use a > common superclass. As python supports multiple inheritance, it's very well "logical" to do it by subclassing. > > So I'm asking, what's a good way to allow those objects to share that > function? > > The best solution I've found so far is to put that function in a > module, and have all objects import and use it. But I doubt that's a > good use-case for modules; writing and importing a module that contains > just a single function seems like an abuse. A module is a unit of code that (should) encapsulate a certain functionality. So it's perfect for your needs. There is no law or even rule of thumb that makes claims about module size (or the lack of, for this matter). So create a module - it doesn't cost you anything. -- Regards, Diez B. Roggisch From qwweeeit at yahoo.it Mon Feb 7 09:14:38 2005 From: qwweeeit at yahoo.it (qwweeeit) Date: 7 Feb 2005 06:14:38 -0800 Subject: PySol: using Qt (as a case study) Message-ID: <2ab23d7a.0502070614.32881704@posting.google.com> PySol uses TKinter as GUI system. Wanting to learn python I am studying PySol, but having choosed Qt as my GUI, I am asking if someone can comment on my choice both on pysol as as an application worth to study (I want to implement a card game) and mainly on Qt choice. Perhaps it would be better if I choose an application already written in python and Qt (or PyQt)... but I do not know any in the card games field. A last thing. I was not favourably impressed by the behaviour of the PySol Programming Group (www.pysol.org): "Due to recent happenings (some distributions "patch" out sound support, some companies sell disguised PySol versions as their own programs, ...) any work on PySol4 has been stopped, and only the source code remains available. After more than six years of work on PySol I realize more and more that the GNU GPL does not work out for game-like programs, and I'm seriously considering using some stricter license for PySol5." From noreply at python.org Fri Feb 11 10:59:36 2005 From: noreply at python.org (Mail Delivery Subsystem) Date: Fri, 11 Feb 2005 16:59:36 +0100 Subject: MDaemon Warning - virus found: Returned mail: Data format error Message-ID: <20050211160013.3DBF41E401C@bag.python.org> ******************************* WARNING ****************************** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. Attachment Virus name Action taken ---------------------------------------------------------------------- mxs.zip Email-Worm.Win32.Mydoom.m Removed ********************************************************************** The message was not delivered due to the following reason: Your message was not delivered because the destination computer was unreachable within the allowed queue period. The amount of time a message is queued before it is returned depends on local configura- tion parameters. Most likely there is a network problem that prevented delivery, but it is also possible that the computer is turned off, or does not have a mail system running right now. Your message could not be delivered within 6 days: Host 196.50.210.36 is not responding. The following recipients could not receive this message: Please reply to postmaster at python.org if you feel this message to be in error. From aleaxit at yahoo.com Sun Feb 6 17:26:11 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 6 Feb 2005 23:26:11 +0100 Subject: empty classes as c structs? References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <1gric2n.17myhon1hfrc6gN%aleaxit@yahoo.com> <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> <4qCdnXM11-uVGJvfRVn-vQ@comcast.com> Message-ID: <1grl4od.1niw3nhvo753cN%aleaxit@yahoo.com> Steven Bethard wrote: > Seems pretty reasonable -- the only thing I worry about is that > classmethods and other attributes (e.g. properties) that are accessible > from instances can lead to subtle bugs when a user accidentally > initializes a Bunch object with the attributes of the same name, e.g.: > > b = Bunch(getDict=1) > > where > > b.getDict() > > now fails with something like "TypeError: 'int' object is not callable". Well, that's the problem with confusing items and attributes in the first place, of course -- which IS Bunch's purpose;-) > (For another discussion about this problem, see [1]). > > I don't know what the right solution is here... I wonder if I should > write a classmethod-style descriptor that disallows the calling of a > function from an instance? Or maybe I should just document that the > classmethods should only be called from the class? Hmm... Another approach is to add a few "reserved words" to the ones Python itself would reject in the initialization. Just you cannot do: b = Bunch(continue=23) you may choose to forbid using getDict=42 - if you do that you probably want to forbid any magicname too, since e.g. b = Bunch(__dict__=99) can't work ``right'' no matter what, while setting e.g. __deepcopy__ similarly might confuse any copy.deepcopy(b), etc, etc. > How do you feel about getDict and setDict also being classmethods? Uh? I want to get or set the dict of a specific instance -- not those of the whole class. How would you design them as classmethods...? Alex From premshree.pillai at gmail.com Mon Feb 28 12:20:04 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Mon, 28 Feb 2005 22:50:04 +0530 Subject: [ANN] PyAC 0.1.0 Message-ID: PyAC 0.1.0 (http://sourceforge.net/projects/pyac/) * ignores non-image files * optional arg is_ppt for ordering presentation images (eg., Powerpoint files exported as images) * misc fixes Package here: http://sourceforge.net/project/showfiles.php?group_id=106998&package_id=115396&release_id=309010 -- Premshree Pillai http://www.livejournal.com/users/premshree/ From ilias at lazaridis.com Wed Feb 23 12:45:46 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Wed, 23 Feb 2005 19:45:46 +0200 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: <8BIQdyL$iLHCFw9a@objmedia.demon.co.uk> References: <874qg6937w.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <37uk2kF5gv38bU1@individual.net> <421c91c8$0$44647$a1866201@visi.com> <383qkkF5k6rf4U1@individual.net> <8BIQdyL$iLHCFw9a@objmedia.demon.co.uk> Message-ID: <421CC14A.4050708@lazaridis.com> Stephen Kellett wrote: [...] > Who's Guido? Guido is the one, who should care by time about the status of the python-community. - I've send an addition CC of this message to the python-foundation, which will hopefully take some steps to improve the build-system. [EVALUATION] - E02 - Support for MinGW Open Source Compiler Essence: http://groups-beta.google.com/group/comp.lang.python/msg/5ba2a0ba55d4c102 - Thank's for every bit of contribution, which has made this thread an worthfull insight into the python-community. . -- http://lazaridis.com From exogen at gmail.com Fri Feb 18 18:48:09 2005 From: exogen at gmail.com (Brian Beck) Date: Fri, 18 Feb 2005 18:48:09 -0500 Subject: selecting dictionaries to maximize counts In-Reply-To: References: Message-ID: Steven Bethard wrote: > I have a list of dictionaries. Each dictionary holds counts of various > 'words', e.g.: > > py> countdicts = [ > ... dict(a=9, b=9, c=9), > ... dict(a=8, b=7), > ... dict(a=4, b=5, c=12)] > > I need to select dicts with the constraint that the number of each > 'word' totalled over all selected dicts doesn't exceed a given > MAX_VALUE. Right now, I do this by: Not that you can't still improve performance of course, but this is an NP-complete problem if you didn't know, so don't bang your head too hard... -- Brian Beck Adventurer of the First Order From marcel.vandendungen at gmail.com Wed Feb 2 16:46:25 2005 From: marcel.vandendungen at gmail.com (Marcel van den Dungen) Date: Wed, 02 Feb 2005 22:46:25 +0100 Subject: Basic file operation questions In-Reply-To: <1107379669.870799.256030@g14g2000cwa.googlegroups.com> References: <1107379669.870799.256030@g14g2000cwa.googlegroups.com> Message-ID: alex wrote: > Hi, > > I am a beginner with python and here is my first question: > How can I read the contents of a file using a loop or something? I open > the file with file=open(filename, 'r') and what to do then? Can I use > something like > > for xxx in file: > .... > > > Thanks for help > Alex > take a look at this: http://www.devshed.com/c/a/Python/File-Management-in-Python/ HTH, -- Marcel From steven.bethard at gmail.com Mon Feb 21 17:15:43 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 21 Feb 2005 15:15:43 -0700 Subject: Tuple index In-Reply-To: References: <1108951559.490554.305310@l41g2000cwc.googlegroups.com> Message-ID: Steve M wrote: > I'm actually doing this as part of an exercise from a book. What the program > is supposed to do is be a word guessing game. The program automaticly > randomly selects a word from a tuple. You then have the oportunity to ask > for a hint. I created another tuple of hints, where the order of the hints > correspond to the word order. I was thinking if I could get the index > position of the randomly selected word, I pass that to the hints tuple to > display the correct hint from the hints tuple. I'm trying to do it this way > as the book I'm using has not gotten to lists yet. I'm guessing it also hasn't gotten to dicts yet either? Perhaps a somewhat more natural way of doing this would be something like: py> hints = dict(word1="here's hint 1!", ... word2="here's hint 2!", ... word3="here's hint 3!") py> words = list(hints) py> import random py> selected_word = random.choice(words) py> selected_word 'word3' py> print hints[selected_word] here's hint 3! That said, if you want to find the index of a word in a tuple without using list methods, here are a couple of possibilities, hopefully one of which matches the constructs you've seen so far: py> t = ("fred", "barney", "foo") py> for i, word in enumerate(t): ... if word == "barney": ... break ... py> i 1 py> for i in range(len(t)): ... if t[i] == "barney": ... break ... py> i 1 py> i = 0 py> for word in t: ... if word == "barney": ... break ... i += 1 ... py> i 1 HTH, STeVe From flupke at nonexistingdomain.com Thu Feb 17 11:32:35 2005 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 17 Feb 2005 16:32:35 GMT Subject: site indexer and search script Message-ID: Hi, for an old intranet that is still used here, i would like to add a search function. I think there migth already be an indexer/search script available in python. I've googled and come across a few scripts but i'm not sure which one is really easy and good at the task. Any good scripts (and easy to configure) around? I would like to use python to generate the corresponding results page, what would i use for that, again bearing in mind that it needs to be done quite quickly so i cannot afford to waste to much time ? Is mod_python usable for such a simple page generation or would i better focus on Twisted or CherryPie? Thanks, Benedict From softpro at gmx.net Mon Feb 14 23:50:49 2005 From: softpro at gmx.net (Johannes Ahl-mann) Date: Tue, 15 Feb 2005 05:50:49 +0100 Subject: image fourier transform Message-ID: hi, i've been looking all around the net (google is my friend ;-) for a module to apply fourier transformations on images. the different ones in numerical python and scientific python seem all to be operating on sequences and therefore seem to be 1D fourier transform. anyone know a library/module to do 2D image FFT in a simple manner. or am i just too dumb to see how this is supposed to work with the 1D fourier transforms?? thx, Johannes From p at ulmcnett.com Mon Feb 28 11:00:16 2005 From: p at ulmcnett.com (Paul McNett) Date: Mon, 28 Feb 2005 08:00:16 -0800 Subject: wxGrid In-Reply-To: <1109574065.613518.241750@l41g2000cwc.googlegroups.com> References: <1109574065.613518.241750@l41g2000cwc.googlegroups.com> Message-ID: <42234010.7070009@ulmcnett.com> Gensek wrote: > I have a grid. I want to sort it when a column label is clicked. I know > about the EVT_GRID_LABEL_LEFT_DCLICK event, but that is not enough. I > do not merely need to know that a label was clicked. I need to know > which label was clicked. I do not know how to do that. I suspect you > might know. I request that you tell me. Please see: http://wiki.wxpython.org/index.cgi/DrawingOnGridColumnLabel It tells you how to draw a sort indicator on the clicked header, which involves first figuring out which header was clicked. As you've found, the entire header region is one wxWindow, not one per column, which does make it a bit more difficult to sort out which column header was clicked. This sample does not go on to show you how to actually do the sorting, however. > I also wish to know some other things: how to find out the location of > a mouse pointer in a wxWindow (or at least the frame), Bind a function to the wx.EVT_MOTION event, and then call GetPosition() of the event instance, which returns a (x,y) tuple of the mouse position at the time the event was generated. x and y are relative to the window that emitted the event. > and how to > change the color of a single specified pixel in a bitmap. I don't know how to do this, but I'd take a look at the docs for wxBitmap for starters. > I use Python 2.3, wxPython 2.4.2. You should upgrade to wxPython 2.5.3 (2.5.4 is around the corner though). If you have a bunch of code already written for 2.4, you'll want to upgrade carefully and refer to the migration guide at http://wxpython.org first. Otherwise, if you are just starting with wxPython, trust me you definitely want to upgrade ASAP - a lot of bugs have been fixed and new features added since 2.4.2, and wxPython experts will be better able to help you if you use a recent version... Also, you may find more and better help by joining the wxpython-users list - you can find a link at http://wxpython.org. -- pkm ~ http://paulmcnett.com From bpeng at rice.edu Fri Feb 4 15:27:42 2005 From: bpeng at rice.edu (Bo Peng) Date: Fri, 04 Feb 2005 14:27:42 -0600 Subject: changing local namespace of a function Message-ID: Dear list, I have many dictionaries with the same set of keys and I would like to write a function to calculate something based on these values. For example, I have a = {'x':1, 'y':2} b = {'x':3, 'y':3} def fun(dict): dict['z'] = dict['x'] + dict['y'] fun(a) and fun(b) will set z in each dictionary as the sum of x and y. My function and dictionaries are a lot more complicated than these so I would like to set dict as the default namespace of fun. Is this possible? The ideal code would be: def fun(dict): # set dict as local namespace # locals() = dict? z = x + y Many thanks in advance. Bo From apardon at forel.vub.ac.be Tue Feb 8 05:00:41 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 8 Feb 2005 10:00:41 GMT Subject: variable declaration References: <4202A022.3050209@netscape.net> Message-ID: Op 2005-02-08, Nick Coghlan schreef : > Antoon Pardon wrote:ons already existing. >> The compilor might generate a RESTORE instruction. > > Whether it is done as a LOAD/STORE or a RESTORE, it has to perform the same work > - check the name exists in the local namespace, and throw an exception if it > doesn't. If it the name does exist, perform a normal store operation. It has to check if the name exists anyway. Because if it doesn't it has to be created in the namespace directory and in the other case only the value part has to be changed. I have the impression you are looking at this too much from the view of the current implementation where putting a an entry in a directory is seen as an atomic operation. So a possibility might be to augment dictionaries with a put method. d.put(key, value) would throw an exception if the key wasn't already in the dictionary but would otherwise behave as d[key] = value. A STORE would then be implemented as a d[key] = value A RESTORE would then be implemented as a d.put(key,value) The latter wouldn't have to do more, it would just behave different. >>>but the optimiser should >>>eventually be able to do something to eliminate the performance penalty due to >>>the technically unnecessary LOAD. I doubt it will be able to beat a STORE_FAST >>>when it comes to trying to get a performance improvement, though :) >> >> >> But maybe a RESTORE_FAST could. > > STORE_FAST is set up to store a local as fast as is reasonably possible. The > space for the local is preallocated in the fast locals C array. How is an > instruction which does that *and something else* ever meant to be faster? I don't know enough about pythons internals to answer here. Maybe you have a point in this case, but you already stated that a RESTORE would need more work then a STORE where IMO that was not the case, so I'm not convinced the same kind of solution is not applicable here. -- Antoon Pardon From dbickett at gmail.com Sat Feb 5 14:18:07 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sat, 5 Feb 2005 14:18:07 -0500 Subject: Which IDE supports python and wxpython? In-Reply-To: References: Message-ID: <1d6cdae30502051118f976284@mail.gmail.com> I know of two: Boa Constructor: http://boa-constructor.sourceforge.net/ wxGlade: http://wxglade.sourceforge.net/ -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From luke at tatooine.planet Mon Feb 7 21:49:40 2005 From: luke at tatooine.planet (Luke Skywalker) Date: Tue, 08 Feb 2005 03:49:40 +0100 Subject: Big development in the GUI realm References: Message-ID: On Tue, 08 Feb 2005 13:24:35 +1100, Tim Churches wrote: >: NOTE! This copyright does *not* cover user programs that use kernel >: services by normal system calls - this is merely considered normal use >: of the kernel, and does *not* fall under the heading of "derived work". OK, so according to Linus, the GPL allows a proprietary program to make calls to the kernel, but TrollTech says the GPL doesn't allow a proprietary program to make calls to the Qt library. It's this double-standard that I find confusing, since both projects are said to be based on the same license. I wouldn't have any problem if Qt had built its own GPL-derived, custom license, but they claim it's the same ol' GPL. Hence the questioning. Luke. From __peter__ at web.de Sun Feb 20 12:41:30 2005 From: __peter__ at web.de (Peter Otten) Date: Sun, 20 Feb 2005 18:41:30 +0100 Subject: intersection of 2 list of pairs References: <1108920276.253388.23590@f14g2000cwb.googlegroups.com> Message-ID: les_ander at yahoo.com wrote: > I have 2 lists of tuples that look like: > E1=[('a','g'),('r','s')] and > E2=[('g','a'),('r','q'),('f','h')]. > In this tuple, the ordering does not > matter, i.e. (u,v) is the same as (v,u). > > What I want to do is the following: > given 2 list of tuples, E1 and E2, I want to create another list with > tuples that are common to both. So in the above example I would like > to return ('a','g') as being common. > How about >>> e1 = [('a', 'g'), ('r', 's')] >>> e2 = [('g', 'a'), ('r', 'q'), ('f', 'h')] >>> s2 = set(e2) >>> s2.update((b, a) for (a, b) in e2) >>> list(set(e1) & s2) [('a', 'g')] If you are on 2.3, continue to use Set instead of set and modify the update line to use a list comprehension: s2.update([(b, a) for (a, b) in e2]) Peter From alan.mcintyre at esrgtech.com Sat Feb 5 08:54:41 2005 From: alan.mcintyre at esrgtech.com (Alan McIntyre) Date: Sat, 05 Feb 2005 08:54:41 -0500 Subject: "Collapsing" a list into a list of changes In-Reply-To: <1107606972.861993.250330@f14g2000cwb.googlegroups.com> References: <1107606972.861993.250330@f14g2000cwb.googlegroups.com> Message-ID: Tony, Actually I only want to remove a certain kind of duplication; if an item occurs twice - say like this: [1,1,1,2,2,2,1,1,1], then I need to keep the order and occurrence of the individual values: [1,2,1]. Using a dict as you proposed loses the order of occurrence, as well as multiple occurrences of groups of the same item. If I didn't need those two qualities of the list to be preserved, though, I think I'd use something like your solution (if I was using a Python older than 2.3) or Steve Coats' solution posted above using Set. Thanks! Alan Tony wrote: > Here is a version using dictionary properties, ie no duplication of > keys. > > def condense(l): > d={} > for item in l: > d[item]=1 > l=d.keys() > return l > > Cheers > Tony > From MrJean1 at gmail.com Fri Feb 11 14:31:27 2005 From: MrJean1 at gmail.com (python) Date: 11 Feb 2005 11:31:27 -0800 Subject: Injecting a C side object into the local dict In-Reply-To: <1108135964.686350.115090@f14g2000cwb.googlegroups.com> References: <1108135964.686350.115090@f14g2000cwb.googlegroups.com> Message-ID: <1108150287.774583.105690@l41g2000cwc.googlegroups.com> Take a look at Pyrex. More at /Jean Brouwers Jamie R. Parent wrote: > Hello, > > How do you go about taking a variable which was declared in C and pass > that through to a Python script? I have tried doing this by adding a > simple string which is a PyObject from C into the local dictionary and > retrieving it from script via a locals()["myCvar"] print statement. > This however does not seem to work. It would seem that when the scripts > are ran the local dictionary with the added item is wiped clean and a > new local dictionary is instead used. Any direction or help would be > appreciated. > > Cheers, > Jamie. From fredrik at pythonware.com Mon Feb 14 15:15:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Feb 2005 21:15:07 +0100 Subject: - E02 - Support for MinGW Open Source Compiler References: <1108405626.130007.320710@l41g2000cwc.googlegroups.com> <1108411017.507814.229600@c13g2000cwb.googlegroups.com> Message-ID: "Pat" wrote: > Okay, I think we are pretty much talking about the same thing. My > problem is not that I'm unable or unwilling to purchase a good > compiler. My problem is that I don't want to make it a requirement of > my users. The twist is that my users will be working out of a > Subversion repository that includes source code for extensions written > in C. Those extensions need to be compiled, and the code changes too > frequently for me to want to deal with supplying compiled binaries. here's what I do to supply compiled binaries for 2.1 through 2.4: > mkall > upload dist > So I'm looking for options for Windows users who do not have, and are > unwilling to get, a Microsoft compiler. For some users, minGW is an > attractive option. For those who want to use minGW, I'm trying to > establish whether or not minGW is a viable option, particularly for > Python 2.4. here's what I just did (time in minutes): +00: googled for the mingw home page +00: found the mingw download page +02: finally figured out what to download +03: noticed that my usual SF site only offered 1K/s; aborted download +07: finished downloading the mingw kit from another SF site +17: finished installing +18: added \mingw\bin to the path +18: typed "python setup.py install --compiler=mingw32" +18: got a linker error; googled for help +19: copied python24.dll to \mingw\lib +20: finished building the sample library (cElementTree); all tests pass so what's your excuse for not doing this? ;-) From removethis.kartic.krishnamurthy at gmail.com Tue Feb 22 18:30:09 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Tue, 22 Feb 2005 23:30:09 GMT Subject: searching pdf files for certain info In-Reply-To: References: Message-ID: <5gPSd.34704$H05.24580@twister.nyroc.rr.com> rbt said the following on 2/22/2005 8:53 AM: > Not really a Python question... but here goes: Is there a way to read > the content of a PDF file and decode it with Python? I'd like to read > PDF's, decode them, and then search the data for certain strings. > > Thanks, rbt Hi, Try pdftotext which is part of the XPdf project. pdftotext extracts textual information from a PDF file to an output text file of your choice. I have used it in the past (not with Python) to do what you are attempting. It is a small program and you can invoke from python and search for the string/pattern you want. You can download for your OS from: http://www.foolabs.com/xpdf/download.html Thanks, -Kartic From brent.hughes at comcast.net Fri Feb 4 15:35:04 2005 From: brent.hughes at comcast.net (Brent W. Hughes) Date: Fri, 4 Feb 2005 13:35:04 -0700 Subject: Possibly OT: Controlling winamp with Python References: <1107548407.626431.171350@z14g2000cwz.googlegroups.com> Message-ID: The Python program won't decide whether a commercial is playing, I will. At that point, I will run my program which will press mute, wait 20 seconds, and then press mute again. Actually, I could leave the program running but minimized to the task bar. When I hear the advertisement, I just click on the program in the task bar. It knows what to do from there. Brent "Kartic" wrote in message news:1107548407.626431.171350 at z14g2000cwz.googlegroups.com... > Brent, > > Question : how will your python script distinguish between a commercial > and a song? > > I can understand if you are writing a streaming client in Python; in > that case you can analyze the audio stream and decide if it is a > commercial or a song/music. > > Did you check to see if there is already a Winamp plugin that would > achieve this for you? > > Thanks, > -Kartic > From peter at engcorp.com Sun Feb 27 11:22:39 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 27 Feb 2005 11:22:39 -0500 Subject: Text To Speech with pyTTS In-Reply-To: <4221b0b6$0$1998$afc38c87@news.optusnet.com.au> References: <4221b0b6$0$1998$afc38c87@news.optusnet.com.au> Message-ID: Mike P. wrote: > I was wondering if anyone has had any luck with the python text to speech > (pyTTS) module available on Sourceforge: > http://sourceforge.net/projects/uncassist I saw the following blog entry by Joey deVilla: http://farm.tucows.com/blog/Platforms/Windows/_archives/2005/1/19/266813.html and immediately tried it out. All I did was download the PyTTS package for Python (2.4, not 2.3), and install it, then ran Joey's sample above. It worked as advertised. This was on Windows XP SP2. -Peter From michele.simionato at gmail.com Fri Feb 18 01:20:58 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 17 Feb 2005 22:20:58 -0800 Subject: low-end persistence strategies? In-Reply-To: References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <1108622622.119311.43200@f14g2000cwb.googlegroups.com> <1108629775.800508.3400@f14g2000cwb.googlegroups.com> <1108702957.327528.22010@z14g2000cwz.googlegroups.com> Message-ID: <1108707658.105102.298300@z14g2000cwz.googlegroups.com> Ok, I have yet another question: what is the difference between fcntl.lockf and fcntl.flock? The man page of my Linux system says that flock is implemented independently of fcntl, however it does not say if I should use it in preference over fcntl or not. Michele Simionato From mad.mick at gmx.de Fri Feb 4 23:12:51 2005 From: mad.mick at gmx.de (Mick Krippendorf) Date: Sat, 5 Feb 2005 05:12:51 +0100 Subject: returning True, False or None References: <6Z6dnVfTmdUDopnfRVn-1A@rcn.net> Message-ID: <36iv03F4urakqU1@individual.net> Fahri Basegmez wrote: > reduce(lambda x, y: x or y, lst) This doesn't solve the OPs problem since >>> reduce(lambda x, y: x or y, [False, None]) returns None instead of False. Mick. From simoninusa2001 at yahoo.co.uk Tue Feb 22 00:36:37 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 21 Feb 2005 21:36:37 -0800 Subject: Considering python - have a few questions. In-Reply-To: <1108417424.289500.85300@g14g2000cwa.googlegroups.com> References: <1108417424.289500.85300@g14g2000cwa.googlegroups.com> Message-ID: <1109050597.266659.137140@z14g2000cwz.googlegroups.com> I'd go with a MySQL / Python / Apache route, but if it's Windows, maybe not. Also, you shouldn't store images in a database - images should be on the filesystem with their paths stored in the database. I'd definitely say going the web application route would be easier (and more portable) than the GUI route, and a free Windows PyQt is still a long way off, so stick with wxPython if you want a non-web GUI. From donn at u.washington.edu Mon Feb 14 19:08:31 2005 From: donn at u.washington.edu (Donn Cave) Date: Mon, 14 Feb 2005 16:08:31 -0800 Subject: Kill GIL References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <86sm405d38.fsf@guru.mired.org> <86y8dqixo6.fsf@guru.mired.org> Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > Yes. I just get a bit irritated with some of the standard lines that > people use. Hey, stop me if you've heard this one: "I used threads to solve my problem - and now I have two problems!" Donn Cave, donn at u.washington.edu From news at outbacklinux.com Tue Feb 15 06:52:38 2005 From: news at outbacklinux.com (Adrian Casey) Date: Tue, 15 Feb 2005 21:22:38 +0930 Subject: Kill GIL References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <86sm405d38.fsf@guru.mired.org> Message-ID: <4211e287@duster.adelaide.on.net> Aahz wrote: > In article , > Frans Englich wrote: >> >>Personally I need a solution which touches this discussion. I need to run >>multiple processes, which I communicate with via stdin/out, >>simultaneously, and my plan was to do this with threads. Any favorite >>document pointers, common traps, or something else which could be good to >>know? > > Threads and forks tend to be problematic. This is one case I'd recommend > against threads. Multiple threads interacting with stdin/stdout? I've done it with 2 queues. One for feeding the threads input and one for them to use for output. In fact, using queues takes care of the serialization problems generally associated with many threads trying to access a single resource (e.g. stdout). Python Queues are thread-safe so you don't have to worry about such issues. From dscottr at bellatlantic.net Fri Feb 25 13:20:49 2005 From: dscottr at bellatlantic.net (Scott Robinson) Date: Fri, 25 Feb 2005 18:20:49 GMT Subject: Tuple index References: <1108951559.490554.305310@l41g2000cwc.googlegroups.com> <1109023881.232830.183100@o13g2000cwo.googlegroups.com> <1109026865.523218.214010@g14g2000cwa.googlegroups.com> Message-ID: On 21 Feb 2005 15:01:05 -0800, "John Machin" wrote: > >Steve M wrote: >> John Machin wrote: >> >> > >> > Steve M wrote: >> >> I'm actually doing this as part of an exercise from a book. What >the >> > program >> >> is supposed to do is be a word guessing game. The program >automaticly >> >> randomly selects a word from a tuple. >> > >> > Care to tell us which book is using a tuple for this, but hasn't >got to >> > lists yet? >> > >> > Cheers, >> > John >> >> Python Programming for the absoulte beginner by Michael Dawson > >In a review I found on the web: >http://www.skattabrain.com/css-books-plain/1592000738.html >"Dawson will take you by the hand and lead you down the garden path." > >Malapropism? Intentional humour? The book teaches you enough about programming and python to get you programming. It was the only python book in my local library so I read it while trying to learn the basics of python. It got me to the point where I could comfortably write Fortran-style python (I am not claiming that anyone else will leave the book that way, only that was as far as I had progressed in understanding python). I think that this book suggests using pickle/unpickle to send data over the internet. This is an amazingly bad idea, which is obvious once you understand how overloading works (I'm pretty sure overloading isn't covered in that book). In short, I think that this book is a good introduction to programming, and it will explain the basics of python, but it doesn't really begin to explain how to program in python. Scott Robinson From steve at holdenweb.com Thu Feb 3 15:45:42 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Feb 2005 15:45:42 -0500 Subject: Why does super() require the class as the first argument? In-Reply-To: <20050203140230680-0500@braeburn.themorgue.org> References: <20050203140230680-0500@braeburn.themorgue.org> Message-ID: <99wMd.102711$Jk5.10106@lakeread01> Kevin Smith wrote: > I like the idea of the super() function, but it doesn't seem to solve > the problem that I'm trying to fix. I don't like hard-coding in calls > to super classes using their names: > > class A(object): > def go(self): > ... > > class B(A): > def go(self): > ... > A.go(self) > > I don't like this because if I ever change the name of 'A', I have to go > through all of the methods and change the names there too. super() has > the same problem, but I'm not sure why. It seems like I should be able > to do: > > class B(A): > def go(self): > ... > super(self).go() > > I can create a super() that does this as follows: > > _super = super > def super(obj, cls=None): > if cls is None: > return _super(type(obj), obj) > return super(cls, obj) > > I guess I'm just not sure why it wasn't done that way in the first place. > You perhaps already know that super() searches the method resolution order (list of superclasses) to find a given class's superclass. However, in cases involving multiple inheritance (and specifically when subclassing two classes that have common ancestors) it's necessary to "flatten out" the inheritance tree. The reason that super() takes a class as argument is because the superclass depends *not* on the class in which the method is defined, but on *the class of the instance calling the method*. If we take the example from pp 89-90 of Python in a Nutshell you might understand. Consider these definitions: class A(object): def met(self): print 'A.met' class B(A): def met(self): print 'B.met' A.met(self) class C(A): def met(self): print 'C.met' A.met(self) class D(B,C): def met(self): print 'D.met' B.met(self) C.met(self) d = D() d.met() Unfortunately this prints out D.met B.met A.met C.met A.met In other words, A.met is called by both its subclasses, which is usually not quite what you want. If we change the code to class A(object): # mro: A, object def met(self): print 'A.met' class B(A): # mro: B, A, object def met(self): print 'B.met' super(B, self).met() class C(A): # mro: C, A, object def met(self): print 'C.met' super(C, self).met() class D(B,C): # mro: D, B, C, A, object def met(self): print 'D.met' super(D, self).met() d = D() d.met() This does indeed print D.met B.met C.met A.met Why? The superobject (the object returned by super) has an mro which begins AFTER the first argument to super. This has the happy effect of changing the mro according to the class of self - super(X, self) is superobject, effectively an instance of a class distinguishable from self.__class__ only by the fact that its mro is shorter, losing everything up to and including X. Does this help at all? This is quite a subtle point, but it will repay study with an understanding of exactly how you can linearize your diamond-shaped inheritance graphs. Very pythonic ... regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From a.schmolck at gmx.net Fri Feb 18 19:49:50 2005 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Sat, 19 Feb 2005 00:49:50 +0000 Subject: [ANN] mlabwrap v0.9b3 Message-ID: I have recently uploaded mlabwrap v0.9b3, a high-level python to matlab(tm) bridge, you can get it from It should work with recent python >=2.3 and matlab(tm) >=6.0; I've used it extensively myself but this is the first announcement to a wider public -- so I'd very much like to hear some feedback (even if it's just "works fine"). Here is a short demo snippet: >>> from mlabwrap import mlab >>> import Numeric >>> mlab.lookfor('singular value') GSVD Generalized Singular Value Decompostion. SVD Singular value decomposition. [...] >>> help(mlab.svd) mlab_command(*args, **kwargs) SVD Singular value decomposition. [U,S,V] = SVD(X) produces a diagonal matrix S, of the same dimension as X and with nonnegative diagonal elements in [...] >>> mlab.svd(array([[1,2], [1,3]])) array([[ 3.86432845], [ 0.25877718]]) 'as From gabriel.cooper at mediapulse.com Fri Feb 4 10:13:40 2005 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Fri, 04 Feb 2005 10:13:40 -0500 Subject: bytecode obfuscation In-Reply-To: <1f060c4c05020313268582f6d@mail.gmail.com> References: <1f060c4c05020313268582f6d@mail.gmail.com> Message-ID: <42039124.1000105@mediapulse.com> snacktime wrote: >Also, I'm curious how much demand their is for this application in the >Python world. The application replaces online credit card >processors(Verisign, Authorizenet) by providing a platform that >connects directly to the bank networks for credit card processing, and >also provides other features such as recurring billing, reporting, >etc.. Everything except the libraries that actually connect to the >bank networks would be open source, and those libraries aren't >something that you would even want to touch anyways. > > Personally, I would avoid running any software that processed my users' credit cards that wasn't open source. Not to say I wouldn't use it, but it would have to come from a known-reliable source with their full backing to imply the security of their name. e.g. If it was a bytecode library downloadable directly from bankofamerica.com. The risk of devious programming is too high to bother. So I pay Verisign or Authorizenet one cent on the dollar. In exchange, my clients' identities aren't being stolen. Hope this help, Gabriel. From kenneth.m.mcdonald at sbcglobal.net Mon Feb 14 14:55:13 2005 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Mon, 14 Feb 2005 19:55:13 GMT Subject: DHTML control from Python? Message-ID: <140220051355142173%kenneth.m.mcdonald@sbcglobal.net> Are there any ways to use Python (rather than JavaScript) for controlling DHTML? I don't mind writing JavaScript stubs which can be called by Python, so long as I need to do so only once for a particular feature. I'm running Mac OS X 10.3, so comments as to the best browser for testing this would also be appreciated. If you could also email as well as posting a reply, I'd be grateful. email to : kenneth.m.mcdonald _at_ sbcglobal.net Thanks, Ken McDonald From jerf at jerf.org Thu Feb 17 10:13:36 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 17 Feb 2005 10:13:36 -0500 Subject: Why doesn't join() call str() on its arguments? References: <37hippF4gcimiU1@individual.net> <37hqlrF59l2b2U1@individual.net> <873bvw9nqh.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <421450CC.9080504@swiftdsl.com.au> <87psyz8h9o.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <4214A800.4010509@swiftdsl.com.au> Message-ID: On Fri, 18 Feb 2005 01:19:44 +1100, news.sydney.pipenetworks.com wrote: > Thanks for the pointer. Let's see how many zen points are for the OP's > idea vs against Along with the fact that I agree with Nick that you've seriously miscounted (most of your "fors" are simply irrelevant and I think you added them to bolster your point, at least I *hope* you don't think they are all relevant... for instance if you really think "Flat is better than nested" applies here, you don't understand what that one is saying...), I'd point out that the Zen that can be comprehended by checking off items in a list is not the true Zen. From http Mon Feb 14 17:16:31 2005 From: http (Paul Rubin) Date: 14 Feb 2005 14:16:31 -0800 Subject: is there a safe marshaler? References: <420b6936$0$28982$e4fe514c@news.xs4all.nl> <1108051828.483222.62670@z14g2000cwz.googlegroups.com> <7xmzu6q4cv.fsf@ruckus.brouhaha.com> <4211185b$0$28982$e4fe514c@news.xs4all.nl> Message-ID: <7xbramzt1c.fsf@ruckus.brouhaha.com> Irmen de Jong writes: > > There's another issue with marshal that makes it unsuitable for Pyro, > > which is that its data format is (for legitimate reasons) not > > guaranteed to be the same across different Python releases. That > > means that if the two ends of the Pyro application aren't using the > > same Python version, they might not be able to interoperate. > > Paul, the default serialization protocol that Pyro uses is pickle > (with the highest available protocol number). So there is a risk > already that it doesn't interoperate with older Python versions, > unless you configure the max pickle protocol or switch to using > one of the supported XML serializations. Yes, however, you can at least set the protocol level. Marshal doesn't give you that option. What do you do about the security issue if you're using pickle? Do you have to trust the other end to not send you malicious pickles? From alexandre.tp at gmail.com Sat Feb 12 17:59:01 2005 From: alexandre.tp at gmail.com (top) Date: 12 Feb 2005 14:59:01 -0800 Subject: Assigning to self References: <10uo6hbn040qt24@news.supernews.com> <10ur80gf6utag00@corp.supernews.com> Message-ID: <1108249141.239243.153800@c13g2000cwb.googlegroups.com> Jeff Shannon wrote: > class __Foo: > "I am a singleton!" > pass > > def Foo(foo_obj = __Foo()): > assert isinstance(foo_obj, __Foo > return foo_obj this is a bit simpler, I think, and takes advantage from Python's free name-rebinding. class Singleton(object): def __call__(self): return self Singleton = Singleton() And, now, every time you say obj = Singleton(), you're getting the same instance. Of course, this corrupt the __call__ method of the class, and isn't inheritance-safe at all, but if you want only one or two classes like this, it isn't very much work to implement it. Also, it's free of weird metaclasses, __new__s, or __dict__ hacks, I think. Just putting my two-cents into this, -- - Alexandre From jeff at ccvcorp.com Fri Feb 4 19:00:04 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 04 Feb 2005 16:00:04 -0800 Subject: [noob] Error! In-Reply-To: <614c778e.0502041459.39da55c1@posting.google.com> References: <614c778e.0502041459.39da55c1@posting.google.com> Message-ID: <110832ml3eim08b@corp.supernews.com> administrata wrote: > Write a Car Salesman program [...] This sounds like homework, and we generally try to avoid solving peoples' homework problems for them, but I can offer a suggestion. > error occurs, i think the problem is in actual_price. but, > I don't know how to comebine percentage and raw_input. > help me... It's hard to be sure since you don't say what the error is, nor anything about what you expect to see and what you actually see. However, if you're pretty sure that the problem is the line where you calculate actual_price, then fire up an interactive interpreter and try fiddling with things. You've got a lot of subexpressions there; pick some values and try each subexpression, one at a time, and take a look at what you get. I bet that it won't take you long to figure out why you're not getting the result you expect. Jeff Shannon Technician/Programmer Credit International From tom.willis at gmail.com Tue Feb 22 11:12:01 2005 From: tom.willis at gmail.com (Tom Willis) Date: Tue, 22 Feb 2005 11:12:01 -0500 Subject: searching pdf files for certain info In-Reply-To: References: Message-ID: I tried that for something not python related and I was getting sporadic spaces everywhere. I am assuming this is not the case in your experience? On Tue, 22 Feb 2005 10:45:09 -0500, rbt wrote: > Andreas Lobinger wrote: > > Aloha, > > > > rbt wrote: > > > >> Thanks guys... what if I convert it to PS via printing it to a file or > >> something? Would that make it easier to work with? > > > > > > Not really... > > The classical PS Drivers (f.e. Acroread4-Unix print-> ps) simply > > define the pdf graphics and text operators as PS commands and > > copy the pdf content directly. > > > > Wishing a happy day > > LOBI > > I downloaded ghostscript for Win32 and added it to my PATH > (C:\gs\gs8.15\lib AND C:\gs\gs8.15\bin). I found that ps2ascii works > well on PDF files and it's entirely free. > > Usage: > > ps2ascii PDF_file.pdf > ASCII_file.txt > > However, bundling a 9+ MB package with a 5K script and convincing users > to install it is another matter altogether. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Thomas G. Willis http://paperbackmusic.net From cam.ac.uk at mh391.invalid Wed Feb 16 06:49:38 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 16 Feb 2005 11:49:38 +0000 Subject: [perl-python] problem: reducing comparison In-Reply-To: <1108450348.253772.158120@z14g2000cwz.googlegroups.com> References: <1108450348.253772.158120@z14g2000cwz.googlegroups.com> Message-ID: Xah Lee wrote: > attached below is the Perl documentation that i wrote for a function > called "reduce", which is really the heart of a larger software. Don't shadow built-ins. Especially for a function name. -- Michael Hoffman From Serge.Orlov at gmail.com Fri Feb 25 08:11:54 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 25 Feb 2005 05:11:54 -0800 Subject: auto-completion history In-Reply-To: References: Message-ID: <1109337114.660916.189340@o13g2000cwo.googlegroups.com> porterboy wrote: > Hi Folks, > > I have auto-completion set up in my python interpreter so that if I > hit the tab key it will complete a variable or a python command*. eg. > if I type > >>> imp > and if I then hit the tab key, the interpreter will complete it to... > >>> import > > Now, I also use Matlab at the command line a lot and it has a nice > additional auto-completion feature, whereby, if you type a few > letters and hit the up-arrow, it will go back to the last command > you typed > that began with those letters. If you keep hitting > up-arrow it will cycle through all the commands you typed beginning > with these letters. eg. if I type... > > Does a feature like this already exist in python??? It's not in python, it's in readline library. To read the documentation do 'man readline' readline.parse_and_bind('"\e[A": history-search-backward') works for me. To find out what your up arrow key sends remove \e[A and hit on your keyboard Control-v and then up arrow. Serge. From harlinseritt at yahoo.com Thu Feb 10 17:41:17 2005 From: harlinseritt at yahoo.com (Harlin) Date: 10 Feb 2005 14:41:17 -0800 Subject: goto, cls, wait commands In-Reply-To: <1ixbe7q69lob3.1npuu3z54gx8z.dlg@40tude.net> References: <1ixbe7q69lob3.1npuu3z54gx8z.dlg@40tude.net> Message-ID: <1108075277.078837.106170@o13g2000cwo.googlegroups.com> No goto needed. If this makes no sense (which it may not if all you've been exposed to is BASIC) it wouldn't be a bad idea to Google why you should never use a goto statement. To do a clear screen you'll need to use the method that your command shell uses. The shortcut to this is for Windows, 'cls' and Linux (and other Unix derivatives) is 'clear'. To put this into your programs you'll need to import the OS module. Then use the method, system() to run the command: import os os.system('cls') or os.system('clear') To do a 'wait' you can use the Time module. import time seconds = 10 #This is an integer value time.sleep(seconds) Only on Unix systems can you use the system command 'sleep'. However, in the name of portability it's better to use the Python modules whenever possible (they'll work on any system that supports Python). Hope it helps. Harlin From dontwant at spam.com Thu Feb 10 18:06:10 2005 From: dontwant at spam.com (Courageous) Date: Thu, 10 Feb 2005 15:06:10 -0800 Subject: Python v.s. c++ References: <420BE10C.5090407@swiftdsl.com.au> Message-ID: >Joking aside, you will love python and is well worth it since you can >still use your c++ skills. If a program is fine art, Python is my medium, upon which I paint my imagination, without any thought of the canvas before me. C// From donn at u.washington.edu Mon Feb 14 12:31:09 2005 From: donn at u.washington.edu (Donn Cave) Date: Mon, 14 Feb 2005 09:31:09 -0800 Subject: Kill GIL References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <868y5t6sal.fsf@guru.mired.org> <86sm405d38.fsf@guru.mired.org> <1108358757.577366@yasure> Message-ID: In article , Dave Brueck wrote: > Donn Cave wrote: [... re stackless inside-out event loop ] > > I put that together with real OS threads once, where the I/O loop was a > > message queue instead of select. A message queueing multi-threaded > > architecture can end up just as much a state transition game. > > Definitely, but for many cases it does not - having each thread represent a > distinct "worker" that pops some item of work off one queue, processes it, > and > puts it on another queue can really simplify things. Often this maps to > real-world objects quite well, additional steps can be inserted or removed > easily (and dynamically), and each worker can be developed, tested, and > debugged > independently. Well, one of the things that makes the world interesting is how many different universes we seem to be coming from, but in mine, when I have divided an application into several thread components, about the second time I need to send a message from one thread to another, the sender needs something back in return, as in T2 = from_thread_B(T1). At this point, our conventional procedural model breaks up along a state fault, so to speak, like ... to_thread_B(T1) return def continue_from_T1(T1, T2): ... So, yeah, now I have a model where each thread pops, processes and pushes messages, but only because my program spent the night in Procrustes' inn, not because it was a natural way to write the computation. In a procedural language, anyway - there are interesting alternatives, in particular a functional language called O'Haskell that models threads in a "reactive object" construct, an odd but elegant mix of state machine and pure functional programming, but it's kind of a research project and I know of nothing along these lines that's really supported today. Donn Cave, donn at u.washington.edu From grante at visi.com Tue Feb 1 13:46:35 2005 From: grante at visi.com (Grant Edwards) Date: 01 Feb 2005 18:46:35 GMT Subject: Where are list methods documented? References: <41ffba7d$0$15879$a1866201@visi.com> <41ffc37a$0$15874$a1866201@visi.com> Message-ID: <41ffce8b$0$15868$a1866201@visi.com> On 2005-02-01, Tim Peters wrote: > [Grant Edwards] >> I did. I looked up sort in the library index, and it took me >> to 3.3.5 Emulating container types, > > It doesn't for me. Here: > > http://docs.python.org/lib/genindex.html#letter-s > > There are two entries for "sort": > > sort (IMAP4_stream method) > sort (list method) > > You're looking for the second one . Aargh. My bad. I was in the language reference index. I seem to have a very hard time ending up in the document I'm trying for. For some reason, I fairly consistently click on the wrong link in the document index. :( -- Grant Edwards grante Yow! I'm definitely not at in Omaha! visi.com From sjmachin at lexicon.net Sat Feb 19 00:57:59 2005 From: sjmachin at lexicon.net (John Machin) Date: 18 Feb 2005 21:57:59 -0800 Subject: exercise: partition a list by equivalence In-Reply-To: References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> <1108768870.455974.244590@c13g2000cwb.googlegroups.com> <1108774366.122896.293720@l41g2000cwc.googlegroups.com> Message-ID: <1108792679.403090.220050@o13g2000cwo.googlegroups.com> John Lenton wrote: > On Fri, Feb 18, 2005 at 04:52:46PM -0800, John Machin wrote: > > > > needs "if rev[first] == rev[second]: continue" here > > > > > > an 'is' is enough, and better. > > > > Good point. You're redeeming yourself :-) > > this, together with you saying that it is hard to explain, makes me > think that you aren't comfortable thinking of lists as mutable > objects. How so? There is no connection between is/== and mutability. Let me amplify: The point about 'is' is a good one, and aids your redemption after your failure to have adequate guards caused your algorithm not to work. > > > > > what is magic about it? is it really that horrible? > > > > Try explaining to the newbies over on the tutor list how despite "res" > > only ever *explicitly* having little bits like [3, 4] appended to it, > > it (or more properly the thing to which it refers) is actually > > festering and growing and being mutated under the surface until at the > > finale it bursts out dripping slime just like the creature from the > > black lagoon ... > > understanding why that works, and why it is 'is' and not '==', are > both part of the same thing. What same thing is that? > Lists are mutable, and you can mutate > them, and they mutate. Unless you actually write code that uses the > fact you will forget it, and it will bite you. Of course, don't use it > just for the heck of it, but that creature you dismiss as a > slime-dripping mutation is actually quite useful. You are confusing mutability of lists (without which they would be called tuples!) with my point that the 'res' list was having its contents fiddled with implicitly through other "pointers". > > While I'm at being unpolite, do you really think this code was harder > to understand than the code posted by anton, using numarray? I only read it as far as the bit where it creating a matrix of size O(N**2) -- in my app N can be over a million so I lost interest rapidly. > > And, of course, if this code were for anything non-throw-awayable, > there would've been quite a bit of explaining going on between those > lines of code. > Not of course, but of necessity. > Ok, now back to being polite :) Welcome back. From stefan.behnel-n05pAM at web.de Mon Feb 14 04:59:57 2005 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 14 Feb 2005 10:59:57 +0100 Subject: [PATCH] allow partial replace in string.Template Message-ID: Hi! Here's a trivial patch against Lib/string.py that adds two new methods. The first replaces the template by a partially resolved substitution and the second creates a new, partially substituted template. I find those two useful enough for integration in the stdlib, especially the replacing one is very useful when pre-replacing some placeholders outside of string generation loops or when building a string from a template step by step. Maybe the method names need some discussion. Also, the creation of a new Template does not handle sub-classes. I didn't know the best was to do this. Use type(self)? That doesn't necessarily mean the constructor of that type takes the same arguments... Any comments? Stefan --- Lib/string.py~ 2004-11-01 04:52:43.000000000 +0100 +++ Lib/string.py 2005-02-14 10:41:41.000000000 +0100 @@ -145,6 +145,12 @@ raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) + def partial_replace(self, *args, **kwargs): + self.template = self.safe_substitute(*args, **kwargs) + + def partial_substitute(self, *args, **kwargs): + return Template( self.safe_substitute(*args, **kwargs) ) + def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: string.py.partially-resolve-templates.patch URL: From fperez.net at gmail.com Fri Feb 4 18:06:51 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Fri, 04 Feb 2005 16:06:51 -0700 Subject: IPython colors in windows References: <1107487113.732375.110850@c13g2000cwb.googlegroups.com> <36hculF51ho2sU1@individual.net><1107530489.308497.103530@g14g2000cwa.googlegroups.com><36hrjpF4ui8fbU1@individual.net> <36i84qF52ce29U1@individual.net> Message-ID: Fernando Perez wrote: > Hi folks, > > could you please test under windows the 1.9 version of readline? > > http://sourceforge.net/project/showfiles.php?group_id=82407&package_id=84552&release_id=302513 > > This was just put up a moment ago by the developer, let me know if it fixes > these problems. Never mind. He contacted me briefly after I wrote this, with the following info: #################################### I just checked. The new version does not fix that problem. The code as released does not handle backgrounds other than black. Folks should run with a black background for now. #################################### So for now, I'm sorry to say this but under win32, ipython users should stick to dark backgrounds. I'll post a note here when the readline developer has a chance to work on this problem. Regards, f From cjw at sympatico.ca Wed Feb 9 09:25:02 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 09 Feb 2005 09:25:02 -0500 Subject: Definitive documentation on newstyle classes? (WAS: Pickling and inheritance are making me hurt) In-Reply-To: <1107925915.042588.43000@c13g2000cwb.googlegroups.com> References: <1d6cdae305020516467620aa0@mail.gmail.com> <4208FBFD.6000303@sympatico.ca> <1107925915.042588.43000@c13g2000cwb.googlegroups.com> Message-ID: <420A1D3E.5080407@sympatico.ca> Michele Simionato wrote: >>It would be good to have a clear exposition of the pros and cons of >>__new__ usage. > > > It is there mostly because __init__ would not work on immutable types. > OTOH, you probably do not want to use __new__ on mutable types > (once I was caught by this trap, google for "overriding list.__new__" > if you are interested). > > Michele Simionato > Thanks. The use of __new__ for immutable classes is described in: http://www.python.org/2.2.3/descrintro.html This distinction hadn't registered with me before. The Martelli bible doesn't bring this out. It seems to me that __new__ should probably be deprecated for mutable classes. Colin W. From mensanator at aol.com Sat Feb 5 17:40:44 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 5 Feb 2005 14:40:44 -0800 Subject: sos! In-Reply-To: References: <6d2e4eef.0502050342.d8744cb@posting.google.com> Message-ID: <1107643244.510478.261130@o13g2000cwo.googlegroups.com> Dan Perl wrote: > "jordan2856977" wrote in message > news:6d2e4eef.0502050342.d8744cb at posting.google.com... > > hellow everybody! I'm from china. I'm a beginner of python. in china, > > python is not a fashionable language, so it's difficult to find some > > books about python. finally,I find a book named "python how to > > program" wrote by H.M.Deitel . who can tell me where can I find some > > interesting source code about python. otherwise, I will fell boring > > about study! > > The Python Cookbook is a good source of examples that other posters haven't > mentioned yet: http://aspn.activestate.com/ASPN/Cookbook/Python/ > > It is especially good because it contains simple, short recipes that > illustrate a specific use of python and these recipes are organized in > categories. > > Dan Aren't you in the wrong newsgroup? :-) From beliavsky at aol.com Mon Feb 7 23:13:30 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 7 Feb 2005 20:13:30 -0800 Subject: Is Python as capable as Perl for sysadmin work? References: Message-ID: <1107836010.646355.99020@z14g2000cwz.googlegroups.com> John M. Gabriele wrote: > I recently posted this sort of question to the c.l.p.m but > didn't get much of a response. I know a little Perl and a > little Python, but master neither at the moment. > > I see that Python is a general purpose OO programming language > that finds use among some system administrators, but my guess > is that Perl is still more common in that area than Python. > > For sysadmin-related tasks, is Python as useful as Perl, or > does it get clumsy when often dealing with the stuff admins > deal with on a regular basis? I'm a Windows user, not a Unix sysadmin, but I've noticed that Cameron Laird has written several articles on Python for system administration in Unix Review and Sys Admin magazine, for example http://www.unixreview.com/documents/s=9083/sam0401d/ . Reading his articles may help you decide if Python is a good fit for your work. From exogen at gmail.com Sun Feb 13 17:52:25 2005 From: exogen at gmail.com (Brian Beck) Date: Sun, 13 Feb 2005 17:52:25 -0500 Subject: builtin functions for and and or? In-Reply-To: <37a2i0F58gsbsU1@individual.net> References: <37a2i0F58gsbsU1@individual.net> Message-ID: George Sakkis wrote: > You're right, it doesn't short circuit, as most of the examples posted above. Here's one that it > does: > > ... I also looked into taking advantage of itertools' dropwhile, but the all and any recipes included in the itertools documentation do short-circuit and don't require the setup of a try/except/else. -- Brian Beck Adventurer of the First Order From mahs at telcopartners.com Tue Feb 8 14:15:20 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 08 Feb 2005 11:15:20 -0800 Subject: turing machine in an LC In-Reply-To: References: <1107805151.265680.165380@o13g2000cwo.googlegroups.com> <87mzuf9gu8.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Jeremy Bowers wrote: > > That's not a generator expression, that's a generator function. Nobody > contests they can reference earlier states, that's most of their point :-) > Are you sure? I just wrote my examples in functions to label them Here's your example with this method: >>> import itertools as it >>> results = [0] >>> magicGenerator = (i+1 for i,lastresult in it.izip(xrange(5),results)) >>> results.extend(magicGenerator) >>> results [0, 1, 2, 3, 4, 5] >>> > For context, we're trying to build Turing Completeness into Python without > indentation. I bailed out of a Xah Lee thread because people have > probably killed it :-) Didn't see it, but this looked interesting - presumably your point and this is entirely unrelated by now, except in > the vague sense he started with an (I'm sure entirely accidentally) > thought-provoking question. Michael From pipedreamergrey at gmail.com Wed Feb 16 20:38:39 2005 From: pipedreamergrey at gmail.com (pipedreamergrey at gmail.com) Date: 16 Feb 2005 17:38:39 -0800 Subject: PythonCard and Py2Exe In-Reply-To: References: <1108476282.790371.155670@l41g2000cwc.googlegroups.com> <1108484617.908022.280320@l41g2000cwc.googlegroups.com> Message-ID: <1108604319.052270.170430@l41g2000cwc.googlegroups.com> > You should move these 'import ...' statements to your *script* so that > py2exe doesn find them, not to the setup script. > > Thomas Removing import statements only returns this error message before the package compiles: = "custdb", 'setup' is not defined No files are returned. From rnd at onego.ru Mon Feb 21 15:56:50 2005 From: rnd at onego.ru (Roman Suzi) Date: Mon, 21 Feb 2005 23:56:50 +0300 (MSK) Subject: Bug in email package? In-Reply-To: References: Message-ID: On Sun, 20 Feb 2005, Steven Bethard wrote: > Erik Max Francis wrote: >> Roman Suzi wrote: >> >>> I think that if any object (from standard library at least) doesn't support >>> iteration, it should clearly state so. >>> >>> My guess is that 'for' causes the use of 'm[0]', which is (rightfully) an >>> error... >>> >>> Can this behaviour of email be considered a bug? >>> Is there a good case to iterate over something useful in a message >> >> Why would it be a bug if the documentation never stated that the object was >> iterable? > > I think the bug is not that an error is produced, but that the _wrong_ error > is produced. Trying to iterate over something that is not iterable should Well, that was what I meant. > produce a TypeError saying so (not an Attribute error): > > py> class C(object): > ... pass > ... > py> iter(C()) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: iteration over non-sequence > > I've actually seen something like this come up before (I think with > email.Message even...) I say call it a bug and submit a patch. Ok. A bug minute on the next bug day ;-) > It's pretty > easy to fix -- just add an __iter__ method to Message that raises a TypeError. > That makes it clear that Message doesn't intend to support the getitem > protocol -- it just does so accidentally because it provides __getitem__. > > STeVe > Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From rvm_1380 at yahoo.com Sun Feb 6 05:29:06 2005 From: rvm_1380 at yahoo.com (rozita raissi) Date: Sun, 6 Feb 2005 10:29:06 +0000 (GMT) Subject: Download a file from FTP server to local machine Message-ID: <20050206102906.39108.qmail@web60208.mail.yahoo.com> Hello, I'm writing an ftp client script which must run in explorer. My script must be placed on and run from a web server. User can connect through it to a FTP server. If user requests to download a file from FTP server, file is downloaded to web server on which my script is running. How can I transfere downloaded file from web server to client local machine? Regards. --------------------------------- Yahoo! Messenger - Communicate instantly..."Ping" your friends today! Download Messenger Now -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Thu Feb 3 16:31:11 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 03 Feb 2005 14:31:11 -0700 Subject: remove duplicates from list *preserving order* In-Reply-To: <1107464751.891049.45580@c13g2000cwb.googlegroups.com> References: <1107464751.891049.45580@c13g2000cwb.googlegroups.com> Message-ID: Carl Banks wrote: > from itertools import * > [ x for (x,s) in izip(iterable,repeat(set())) > if (x not in s,s.add(x))[0] ] Wow, that's evil! Pretty cool, but for the sake of readers of my code, I think I'll have to opt against it. ;) STeVe From hanche at math.ntnu.no Sat Feb 26 12:58:18 2005 From: hanche at math.ntnu.no (Harald Hanche-Olsen) Date: 26 Feb 2005 18:58:18 +0100 Subject: Whither datetime.date ? Message-ID: I'm confused. I was going to try linkchecker, and it dies with a traceback ending in File "/usr/local/lib/python2.4/calendar.py", line 32, in _localized_month _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)] AttributeError: 'module' object has no attribute 'date' Sure enough, there is no datetime.date, but there is a datetime.Date: Python 2.4 (#2, Feb 19 2005, 20:35:23) [GCC 3.4.2 [FreeBSD] 20040728] on freebsd5 Type "help", "copyright", "credits" or "license" for more information. >>> import datetime >>> dir(datetime) ['Date', 'DateTime', ...] However, the Library Reference clearly states that datetime.date should exist. Granted, it's been a while since I used python in anger, but isn't this what it says? http://www.python.org/doc/2.4/lib/node243.html http://www.python.org/doc/2.4/lib/datetime-date.html Moreover, the datetime.date class is supposed to have a strftime() method. datetime.Date does not. I'm beginning to wonder if the FreeBSD python package is at fault. Or what is really going on here? -- * Harald Hanche-Olsen - Debating gives most of us much more psychological satisfaction than thinking does: but it deprives us of whatever chance there is of getting closer to the truth. -- C.P. Snow From fredrik at pythonware.com Tue Feb 8 09:19:45 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 8 Feb 2005 15:19:45 +0100 Subject: Big development in the GUI realm References: <200502072347.j17NlPnh012281@mail07.syd.optusnet.com.au> <4208C195.1000104@optushome.com.au> Message-ID: Tim Churches wrote: >>except that if *you* set things up so the code is combined when run, *you* are >>copying, distributing, and/or modifying the program in order to mix, include and/or >>combine your work with the GPL:ed work. >> >>if you leave all that to the user, you're clear. >> > Yes, that is what I, and others, have been saying, and doing, all along. Our Mozilla Public > Licensed Python application imports (but contains no code from) a GPLed third-party Python module > at runtime, but we don't distribute that module, we just tell users to obtain it independently and > install it on their systems. does your program work (in any way) without this module? >>(relying on word games is a lousy legal strategy in most parts of the world) >> > (Gee, I thought that word games were the entire basis of much legal endeavour in most parts of the > world. Patent specifications in particular spring to mind.) yeah, but you shouldn't base your entire game on a specific word play. From fortepianissimo at gmail.com Sat Feb 5 17:37:00 2005 From: fortepianissimo at gmail.com (fortepianissimo) Date: 5 Feb 2005 14:37:00 -0800 Subject: Computing class variable on demand? In-Reply-To: References: <1107410898.260491.203090@l41g2000cwc.googlegroups.com> <6eydnSAjiuofW5zfRVn-sw@comcast.com> <1107445682.239962.284660@o13g2000cwo.googlegroups.com> <1107501071.325170.168620@z14g2000cwz.googlegroups.com> Message-ID: <1107643020.261275.207690@z14g2000cwz.googlegroups.com> Thanks Steve - actually my question was simpler than that. I just wanted to use Daniels' recipe of lazy initialization on objects with __slots__: class Lazy(object): def __init__(self, calculate_function): self._calculate = calculate_function def __get__(self, obj, _=None): if obj is None: return self value = self._calculate(obj) setattr(obj, self._calculate.func_name, value) return value class SomeClass(object): __slots__ = 'someprop' @Lazy def someprop(self): print 'Actually calculating value' return 13 o = SomeClass() print o.someprop print o.someprop Running the code above will produce: Actually calculating value Traceback (most recent call last): File "Lazy.py", line 26, in ? print o.someprop File "Lazy.py", line 11, in __get__ setattr(obj, self._calculate.func_name, value) AttributeError: 'SomeClass' object attribute 'someprop' is read-only Removing the __slots__ statement, everything would run normally. Is there any workaround? From kartic.krishnamurthy at gmail.com Fri Feb 4 11:20:38 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 4 Feb 2005 08:20:38 -0800 Subject: Thread in python In-Reply-To: <1107533540.641969.191940@z14g2000cwz.googlegroups.com> References: <1107533540.641969.191940@z14g2000cwz.googlegroups.com> Message-ID: <1107534038.823409.89650@l41g2000cwc.googlegroups.com> ajikoe at gmail.com wrote: > Hello, is any one knows websites which give a python thread tutorial ? > > Sincerely Yours, > Pujo Aji Pujo Aji, I have not come across a tutorial but found this link rather helpful - http://www.faqts.com/knowledge_base/index.phtml/fid/263 - to get started. Also, there are good recipes in ASPN - http://aspn.activestate.com/ASPN/Cookbook/Python?kwd=Threads And last but not least, the chapter on Threads in Python Standard Library by Fredrik Lundh - http://effbot.org/zone/books.htm Thanks, -Kartic From kent37 at tds.net Wed Feb 23 23:51:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Feb 2005 23:51:26 -0500 Subject: Source Encoding GBK/GB2312 In-Reply-To: <1109217736.643721.201240@o13g2000cwo.googlegroups.com> References: <1109217736.643721.201240@o13g2000cwo.googlegroups.com> Message-ID: <421d5a29$1_3@newspeer2.tds.net> steven at lczmsoft.com wrote: > When I specify an source encoding such as: > > # -*- coding: GBK -*- > or > # -*- coding: GB2312 -*- > > as the first line of source, I got the following error: > > SyntaxError: 'unknown encoding: GBK' > > > Does this mean Python does not support GBK/GB2312? What do I do? GB2312 is supported in Python 2.4. GB2312 support can be added to Python 2.3 with the CJKCodecs package: http://cjkpython.i18n.org/ Kent > > - > narke > From dial#####$$NOSPAM##$#$## at gmail.com Thu Feb 24 17:38:33 2005 From: dial#####$$NOSPAM##$#$## at gmail.com (Valentino Volonghi aka Dialtone) Date: Thu, 24 Feb 2005 23:38:33 +0100 Subject: Python and "Ajax technology collaboration" References: <1109193970.029421.213490@l41g2000cwc.googlegroups.com> <1gsgn7j.1sr4el39la6ctN%dial#####$$NOSPAM##$#$##@gmail.com> Message-ID: <1gsigz7.1vc5boq173k51cN%dial#####$$NOSPAM##$#$##@gmail.com> Chris wrote: > Does anyone else have any Nevow examples? Nevow SVN is full of examples ranging from a simple hello world to a complete blog engine with xml-rpc, smtp and web interfaces for adding new posts and an atom feed, or even a live chat or a pastebin or an image uploader and so on. -- Valentino Volonghi aka Dialtone Now Running MacOSX 10.3.8 Blog: http://vvolonghi.blogspot.com http://weever.berlios.de From godoy at ieee.org Fri Feb 11 12:34:35 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Fri, 11 Feb 2005 15:34:35 -0200 Subject: Postgres and SSL References: Message-ID: <1223014.6WjCJWoPXh@jupiter.g2ctech> Greg Lindstrom wrote: > I'm on a Linux box running python 2.3 and would like to connect to a > postgres database via SSL, but have not been able to find a module to do > this (or haven't figured out the syntax). Can anyone help me out? With both psycopg and pypgsql it depends on how your libpq was compiled. If the libraries from your PostgreSQL installation were compiled to support SSL, then you can connect to the server without any problems. Be seeing you, Godoy. From davidf at sjsoft.com Tue Feb 1 02:16:58 2005 From: davidf at sjsoft.com (David Fraser) Date: Tue, 01 Feb 2005 09:16:58 +0200 Subject: [ANN] Spike Asset Manager release 0.13 In-Reply-To: <1107206259.910842.111840@f14g2000cwb.googlegroups.com> References: <1107196878.026930.154270@c13g2000cwb.googlegroups.com> <16894.36152.345508.583247@montanaro.dyndns.org> <1107206259.910842.111840@f14g2000cwb.googlegroups.com> Message-ID: mh wrote: > Fredrik- > > This is a known issue. The tool currently only looks in certain > locations or hints rather then spidering the whole hard drive (which > could take a bit of time). If you have installed in a non-standard > location (or are using a platform or version of software that hasn't > been tested against) the tool won't find the component. > > One way around this is manually enter more "hints" but this doesn't > scale. I'm open to suggestions for handling this in a better way. > > matt > > ps-I assume you are running on windows. Where is python installed on > your machine? > Windows also has package management in the form of Windows Installer, it would be better to use that on windows than simply look in locations... David From guettli at thomas-guettler.de Wed Feb 23 04:45:55 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 23 Feb 2005 10:45:55 +0100 Subject: user interface for python References: <1109131790.140672.209730@l41g2000cwc.googlegroups.com> Message-ID: Am Tue, 22 Feb 2005 20:09:50 -0800 schrieb Raghul: > Hi, > Which of the UI I can used for my program that I can use both in > windows and in Linux. Is it possible for me to use Wxpython for my > program so that it can run on both the windows and linux machine? Will > it be platform independent? Hi, I like pygtk. It should be portable to windows, but I have not tried this yet. Up to now I only used it under linux. Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From bearophileHUGS at lycos.com Sun Feb 20 06:31:33 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 20 Feb 2005 03:31:33 -0800 Subject: exercise: partition a list by equivalence References: <1108683980.894412.14060@z14g2000cwz.googlegroups.com> <1108814276.680736.264380@l41g2000cwc.googlegroups.com> <37pb5jF5fnfivU1@individual.net> <1108890925.941814.45860@g14g2000cwa.googlegroups.com> <1108895373.013257.192310@l41g2000cwc.googlegroups.com> Message-ID: <1108899093.340446.216420@o13g2000cwo.googlegroups.com> John Machin: >Perhaps I'm missing a posting of yours -- what are merge2 and merge4? What is "this random pairs test"? What is xMax (nPairs isn't hard to guess), and how are you generating your input data?< merge2 and this random pairs test comes from the post by Brian Beck. merge4 is the first in my last post. And merge3 isn't included (nor tested) because it uses the original (slow) addArcs. This is the simple test generator taken from his post: xMax = 3000 nPairs = xMax*5 l = [[randint(0,xMax), randint(0,xMax)] for i in xrange(nPairs)] For such high number of nPairs (arcs), the resulting graph usuall has one big connected component, and few tiny debris... To produce a more divided graph, nPairs have to be much smaller, like xMax*1.5. >FWIW, my offering is attached. < I'm sorry, I don't see the attach... (just the different title). John Machin: >Only David's uses stuff that's not in the Python 2.4 off-the-shelf distribution.< Well, using already mede functions and classes is good, it avoids you to reinvent things each time. Some of my versions too use my graph library (for a problem like this I usually don't create stand alone versions like merge6 and merge7). And my original point was adding one graph data structure to the standard Python library :-] I haven't tested the speed of David Eppstein version... Anyway, this is a simplified version of merge6, that uses an indirect graph g, instead of the directed graph, and avoids the use of chain: . from collections import deque . . def merge7(l): . # Undirect graph g creation: . g = {} . for n1,n2 in l: . if n1 not in g: g[n1] = {n2:0} . else: g[n1][n2] = 0 . if n2 not in g: g[n2] = {n1:0} . else: g[n2][n1] = 0 . # Connected components: . result = [] . visited = set() . for root in g.iterkeys(): . if root not in visited: . component = [root] . visited.add(root) . Q = deque() # A queue . Q.append(root) . while Q: . n1 = Q.popleft() . for n2 in g[n1].iterkeys(): . if n2 not in visited: . visited.add(n2) . Q.append(n2) . component.append(n2) . result.append(component) . return result It's a bit shorter and a little faster than merge6, memory used is similar (there is only one dictionary, so there is only one ammortization overhead of the dictionary, but it contains the sum of both arcs, so the ammortization can be twice as big, so... memory used can be the same). (Usually BFS and DFS memory requirements are a little different; this implementation uses BFS, and I think it uses a bit less memory than DFS, but for this problem/test the difference isn't significative.) Bear hugs, Bearophile From xah at xahlee.org Sat Feb 26 07:07:11 2005 From: xah at xahlee.org (Xah Lee) Date: 26 Feb 2005 04:07:11 -0800 Subject: generic equivalence partition In-Reply-To: <1109245733.261643.219420@f14g2000cwb.googlegroups.com> References: <1109245733.261643.219420@f14g2000cwb.googlegroups.com> Message-ID: <1109419631.693212.236890@z14g2000cwz.googlegroups.com> # the following solution is submitted by # Sean Gugler and David Eppstein independently # 20050224. @def parti(aList, equalFunc): @ result = [] @ for i in range(len(aList)): @ for s in result: @ if equalFunc( aList[i], aList[s[0]] ): @ s.append(i) @ break @ else: @ result.append( [i] ) @ return [[x+1 for x in L] for L in result] # add 1 to all numbers @ @--------------- as for my original perl code, i realized it is written to work on a sorted input. Here it is and the translated Python code. # perl sub parti($$) { my @li = @{$_[0]}; my $sameQ = $_[1]; my @tray=(1); my @result; for (my $i=1; $i <= ((scalar @li)-1); $i++) { if (&$sameQ($li[$i-1], $li[$i])) { push @tray, $i+1} else { push @result, [@tray]; @tray=($i+1); } } push @result, [@tray]; return \@result; } @#python @def parti(li,sameQ): @ tray=[1]; @ result=[]; @ @ for i in range(1, len(li) ): @ if sameQ(li[i-1],li[i]): @ tray.append(i+1) @ else: @ result.append(tray) @ tray=[i+1] @ result.append(tray) @ return result @ http://xahlee.org/perl-python/gen_parti_by_equiv.html Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From fredrik at pythonware.com Fri Feb 11 13:25:14 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Feb 2005 19:25:14 +0100 Subject: is there a safe marshaler? References: <420b6936$0$28982$e4fe514c@news.xs4all.nl><420b6e98$0$23018$626a14ce@news.free.fr><420b9135$0$28982$e4fe514c@news.xs4all.nl><3b091a1c.0502110634.5edb1987@posting.google.com> <420cef48$0$28977$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: >> but can't effbot's fast cElementree be used for PYROs XML_PICKLE and would it be safe and fast >> enough? > > ElementTree's not a marshaler. > Or has it object (de)serialization included? nope. building a serialization layer on top of it is pretty trivial, and the result is pretty fast, but nowhere close to C speed. From miki.tebeka at zoran.com Tue Feb 8 06:25:27 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 8 Feb 2005 13:25:27 +0200 Subject: Choosing the right parser for parsing C headers In-Reply-To: <1107861023.254610.14310@g14g2000cwa.googlegroups.com> References: <1107861023.254610.14310@g14g2000cwa.googlegroups.com> Message-ID: <20050208112505.GC2156@zoran.com> Hello Jean, > - ply: > Lex / Yacc for python! Tackle the Beast! Syntax processing looks mini_c is a C compiler written using ply. You can just use it as is. http://people.cs.uchicago.edu/~varmaa/mini_c/ HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From removethis.kartic.krishnamurthy at gmail.com Wed Feb 9 22:08:55 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Thu, 10 Feb 2005 03:08:55 GMT Subject: Help: retrieving e-mail from yahoo pop server. what's wrong? In-Reply-To: References: <1107983472.417329.292750@l41g2000cwc.googlegroups.com> Message-ID: Andre said the following on 2/9/2005 7:28 PM: > Thank, Kartic > > I actually tried doing it with several other accounts, notably mail.com and > netscape.com > When i do it with netscape the dialog goes like the following: > > The username and password are naturally valid, but something else is wrong. > Do you know if Netscape also doesn't allow POP access? Is there a free > e-mail provider who does? Okay..this OT now! Gmail provides pop access. Or you can use fastmail.fm, they hae a free account option with POP3 as well as IMAP access. Before you post any Python code, first try with some email client and then try with Python code. -Kartic From sean_mcilroy at yahoo.com Wed Feb 9 15:07:57 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 9 Feb 2005 12:07:57 -0800 Subject: two questions - no common theme Message-ID: And now for a pair of questions that are completely different: 1) I'd like to be able to bind callbacks to presses of the arrow buttons on the keyboard. How do you say that in Tkinter? 2) The function 'listdir' in os.path returns a list of all the files in the given directory - how do I get hold of a list of its subdirectories? Any help will be greatly appreciated. Peace, STM From someone at someplace.somewhere Mon Feb 7 08:20:20 2005 From: someone at someplace.somewhere (Jonathan Polley) Date: Mon, 07 Feb 2005 13:20:20 GMT Subject: Unable to run IDLE Under Windows References: <060220052259038640%eq_fidget@mac.com> <36ofmlF533252U1@individual.net> Message-ID: <070220050720198940%someone@someplace.somewhere> In article <36ofmlF533252U1 at individual.net>, Marian Aldenh?vel wrote: > Hi, > > > Any ideas as to what might me wrong? > > > TclError: unknown color name "white " > > There is a space after "white" in this error-message. If this string comes > from some per-user configuration that may well explain your problem. > > Ciao, MM Where do I have to go in order to fix it? It follows them from computer to computer... Thanks, Jonathan Polley From andrea.gavana at agip.it Mon Feb 28 11:20:11 2005 From: andrea.gavana at agip.it (andrea.gavana at agip.it) Date: Mon, 28 Feb 2005 17:20:11 +0100 Subject: String Replace Problem Message-ID: Hello Peter And NG, thank you a lot... now I'm blaming myself, how couldn't I see it? I will probably go for the re.sub (if it is not too complicated, I'm not a Python expert and even less expert of RegEx things), if not I'll try your suggestion of sorting the strings by length. Thanks a lot. Andrea. ------------------------------------------------------------------------------------------------------------------------------------------ Message for the recipient only, if received in error, please notify the sender and read http://www.eni.it/disclaimer/ From devries at idolstarastronomer.com Mon Feb 7 13:59:12 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: Mon, 7 Feb 2005 13:59:12 -0500 Subject: New to unix/python. How to install In-Reply-To: References: Message-ID: <20050207185912.GA7455@miyu.cjas.org> On Sun, Feb 06, 2005 at 01:42:22PM -0800, Bobby Owens wrote: > I've muddled through the python code and figured out parts of it. I've > now installed Sun Solaris 10 on a VM ware installation successfully > and can muddle thorough the basics of the o/s. I cant figure out how > to install python. From looking online I've found what I think I need: > > - python-2.3.3-sol9-intel-local > - libgcc-3.3-sol10-intel-local I wouldn't worry about these binary packages. Usually under solaris compiling the source works fine. Download the source from this page: http://www.python.org/download/ It comes as a gzipped tar file. You can unpack it by issuing the command: gunzip -c Python-2.4.tgz | tar xvf - Change into the Python-2.4 directory and run the commands: ./configure make as "root" run the command: make install Python should install into /usr/local. The python interpreter should be /usr/local/bin/python. Since python is written in C, you do not need to use the Gnu C compiler to compile it, ./configure should find an appropriate C compiler, and everything should work fine. Feel free to reply if this series of steps does not work. Good luck, Chris From vijay.nakhawa at gmail.com Wed Feb 2 00:38:15 2005 From: vijay.nakhawa at gmail.com (vijay) Date: 1 Feb 2005 21:38:15 -0800 Subject: how to use python scripts in zope3 Message-ID: <6c466d2d.0502012138.6dcdb8de@posting.google.com> hi Recently i started learning zope3 framework. Unlike in zope2.7 , there is no Script(Python) component in the addlist of zope3. Also by inserting scripts in zpt it gives me error. Somebody help me in using python script in zope3. Thank you. From leszczynscy at nospamyahoo.com Sat Feb 19 12:27:58 2005 From: leszczynscy at nospamyahoo.com (Andy Leszczynski) Date: Sat, 19 Feb 2005 11:27:58 -0600 Subject: wxPython 2.5 - bug in wx.Execute Message-ID: Hi, I need a help with following problem which is blocking me quite seriously. I noted some weird behavior on Windows (Python 2.3, wxPython 2.5). The same code works fine under Linux. When using ?pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process)? to spawn new wxPython based GUI program, the GUI does not pop up. I checked that the process itself is running/alive, the print over the streams get propagated to the parent process, but no GUI. It only happnes for wxPython based programs - for e.g. regural python command line programs it works fine. It is easy to be replicated using wx Demo by opening Process and Events/Process. Then after typing in "python -u demo.py" nothing happens. Please help, it really blocks me. The temporary work around is to use "cmd /e python -u demo.py", but I lose the unbuffered -u effect. Thanks, Andy From jicman at gmail.com Wed Feb 9 12:56:15 2005 From: jicman at gmail.com (jicman) Date: 9 Feb 2005 09:56:15 -0800 Subject: Java Integer.ParseInt translation to python In-Reply-To: <1107950708.037808.211570@l41g2000cwc.googlegroups.com> References: <008d01c507f4$451d9b30$2820790d@stso.xcdg.xerox.com> <372a762405013116263a4e93b7@mail.gmail.com> <1107950708.037808.211570@l41g2000cwc.googlegroups.com> Message-ID: <1107971775.794116.317250@c13g2000cwb.googlegroups.com> John Machin wrote: > jose isaias cabrera wrote: > However some Java code (I can't believe that it was the Java code that > you posted) has printed NINE bytes which bear no relation that I can > see to any of the TWENTY bytes that the posted Java code should have > stowed in retBuf. I know what you're saying, John. That's what is encryptic about this whole thing. The [byte] call in front of any variable will turn the variable value to a "byte". If you look at the code at the java code at the beginning, >>> byte[] retBuf = new byte[inString.length()/2]; this retBuf is an array of bytes. Whatever that means in java. And yes, that is the right output or result. Hmmm, maybe an array of bytes will turn into retBuf[0]+retBuf[0] = the first letter... Hmmmm.... > You claim that "[B at 1616c7" is the right answer -- what is the question? Well, how can I get that exact answer from python? > What is it meant to be? Your routine is called PrepareHash; is it > possible that you are seeing these 9 bytes _after_ hashing? Well, now that you say that, it may be that there is a space there. Hmmmm, let me try that again... > Funny > hashing scheme; they usually give 4, 8, 16, etc bytes, but worth an ask > ... yep, you're right... From nelson at monkey.org Wed Feb 2 18:13:40 2005 From: nelson at monkey.org (Nelson Minar) Date: Wed, 02 Feb 2005 23:13:40 GMT Subject: Where are list methods documented? References: <41ffba7d$0$15879$a1866201@visi.com> Message-ID: You're not the only one with a hard time finding the list documentation. It's even crazier for string docs. If you want to see how to strip strings in Python you have to go to the library docs, then click "sequence types" (betcha don't think of strings as sequences), then scroll to the bottom, then click "String Methods", then scroll to find "strip()". This makes perfect sense if you understand that strings are "mutable sequences". But if you're coming from (say) Perl and are looking for the quick way to work with strings, it's pretty deeply buried. A simple internal link or two would help a lot. Say, something in "built-in functions" which says "see also..." From rlwm.erens at home.nl Thu Feb 17 08:41:12 2005 From: rlwm.erens at home.nl (Roger) Date: 17 Feb 2005 05:41:12 -0800 Subject: Is it possible to use the logging-module in a threadless environment? Message-ID: <5475062c.0502170541.41ec4320@posting.google.com> I'd like to use a program (roundup) that imports the logging.config module on a machine where I could not get the thread and threading modules to compile. How dangerous is it to changing /lib/python2.4/logging/config.py to something like: import dummy_thread as thread, dummy_threading as threading Thanks in advance, Roger Erens From timh at zute.net Mon Feb 7 21:08:44 2005 From: timh at zute.net (Tim Hoffman) Date: Tue, 08 Feb 2005 10:08:44 +0800 Subject: Memory Allocation? In-Reply-To: References: <8GCNd.9880$ya6.9761@trndny01> Message-ID: <42081f2e@news.highway1.com.au> Hi Chris Have a look at http://www.python.org/doc/2.3.4/whatsnew/section-pymalloc.html for a description of what is going on. Basically malloc is used to grab a big chunk of memory, then python objects use bits of it. Rgds Tim Chris S. wrote: > Donn Cave wrote: > >> In article <8GCNd.9880$ya6.9761 at trndny01>, >> "Chris S." wrote: >> >> >>> Is it possible to determine how much memory is allocated by an >>> arbitrary Python object? There doesn't seem to be anything in the >>> docs about this, but considering that Python manages memory >>> allocation, why would such a module be more difficult to design than >>> say, the GC? >> >> >> >> Sorry, I didn't follow that - such a module as what? > > > GC == Garbage Collector (http://docs.python.org/lib/module-gc.html) > >> Along with the kind of complicated internal implementation >> details, you may need to consider the possibility that the >> platform malloc() may reserve more than the allocated amount, >> for its own bookkeeping but also for alignment. It isn't >> a reliable guide by any means, but something like this might >> be at least entertaining - >> >> >>> >>> class A: >> ... def __init__(self, a): >> ... self.a = a >> ... >>> d = map(id, map(A, [0]*32)) >> >>> d.sort() >> >>> k = 0 >> >>> for i in d: >> ... print i - k >> ... k = i >> ... >> This depends on the fact that id(a) returns a's storage >> address. >> >> I get very different results from one platform to another, >> and I'm not sure what they mean, but at a guess, I think >> you will see a fairly small number, like 40 or 48, that >> represents the immediate allocation for the object, and >> then a lot of intervals three or four times larger that >> represent all the memory allocated in the course of creating >> it. It isn't clear that this is all still allocated - >> malloc() doesn't necessarily reuse a freed block right >> away, and in fact the most interesting thing about this >> experiment is how different this part looks on different >> platforms. Of course we're still a bit in the dark as >> to how much memory is really allocated for overhead. >> >> Donn Cave, donn at u.washington.edu > > > Are you referring to Python's general method of memory management? I was > under the impression that the ISO C specification for malloc() dictates > allocation of a fixed amount of memory. free(), not malloc(), handles > deallocation. Am I wrong? Does Python use a custom non-standard > implementation of malloc()? From kent3737 at yahoo.com Fri Feb 4 17:33:17 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Fri, 04 Feb 2005 17:33:17 -0500 Subject: Possible additions to the standard library? (WAS: About standardlibrary improvement) In-Reply-To: References: Message-ID: <4203f56d$1_3@newspeer2.tds.net> Daniel Bickett wrote: > | def reverse( self ): > | """ > | Return a reversed copy of string. > | """ > | string = [ x for x in self.__str__() ] > | string.reverse() > | return ''.join( string ) def reverse(self): return self[::-1] Kent From http Mon Feb 14 18:50:45 2005 From: http (Paul Rubin) Date: 14 Feb 2005 15:50:45 -0800 Subject: Inheritance error in python 2.3.4??? References: <1108422852.332215.165790@o13g2000cwo.googlegroups.com> <1108424593.009391.187930@z14g2000cwz.googlegroups.com> Message-ID: <7xbrambt0q.fsf@ruckus.brouhaha.com> "friedmud at gmail.com" writes: > The problem is that I actually do need them to be private to the > outside world... but not to subclasses. I guess what I actually need > is something like "protected" in C++.... but I don't think I'm going to > get that luxury. The only way to make instance variables really private is to put them in a separate process and use IPC to reach the accessors. The __xyz convention results in deterministic name mangling that other parts of the program can undo if they wish to. From uche.ogbuji at gmail.com Mon Feb 28 22:34:08 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 28 Feb 2005 19:34:08 -0800 Subject: best XSLT processor? In-Reply-To: <1109646196.351284.77630@z14g2000cwz.googlegroups.com> References: <1109646196.351284.77630@z14g2000cwz.googlegroups.com> Message-ID: <1109648048.416434.235840@g14g2000cwa.googlegroups.com> Actually, most of the compliant problems I can remember off-head with respect to Xalan have been regarding EXSLT 1.0, not base XSLT 1.0. Sorry for any misconstruction. --Uche From steve at holdenweb.com Wed Feb 9 12:58:57 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 09 Feb 2005 12:58:57 -0500 Subject: Python and version control In-Reply-To: References: Message-ID: Carl wrote: > Dear friends, > > What is the ultimate version control tool for Python if you are working in a > Windows environment? > > When you work on a Visual C++ project then it's easy, use Visual Source Safe > for your source code! But when it comes to large Python projects and no > universal Python IDE with version control integration is available, > checking in and out files is not as simple. I am a keen user of Emacs, but > version control, which is very simple when you are in a Linux environment, > for example, is not a straightforward in Windows. > > What is the most common adopted approach among Python developers working in > a Windows environment? > > Carl > You can integrate PythonWin and version control if you know the appropriate incantation. Vss used to work fine, but I upgraded and couldn't be bothered to go through the installation steps again. regards Steve From johann at rocholl.net Thu Feb 10 14:37:52 2005 From: johann at rocholl.net (Johann C. Rocholl) Date: Thu, 10 Feb 2005 20:37:52 +0100 Subject: That horrible regexp idiom In-Reply-To: <3e8ca5c805020923107c36cd7f@mail.gmail.com> References: <3e8ca5c805020923107c36cd7f@mail.gmail.com> Message-ID: <20050210193752.GA10075@rocholl.net> Hi, > import re > foo_pattern = re.compile('foo') > > '>>> m = foo_pattern.search(subject) > '>>> if m: > '>>> pass > '>>> else: > '>>> pass I agree that is horrible. This is one of my favorite problems with python syntax. > but it occured to me today, that it is possible to do it in python > without the extra line. > ' > '>>> def xsearch(pattern, subject): > '>>> yield pattern.search(subject) > > '>>> for m in xsearch(foo_pattern, subject): > '>>> pass > '>>> else: > '>>> pass I think I wouldd rather have it this way, based on a suggestion by Diez B. Roggisch recently: import re class matcher: def __init__(self, regex): self.regex = re.compile(regex) def match(self, s): self.m = self.regex.match(s) return not self.m is None def search(self, s): self.m = self.regex.search(s) return not self.m is None def group(self, n = None): if n is None: return self.m.group() return self.m.group(n) m = matcher('(foo)(.*)') if m.match('foobar'): print m.group() if m.search('barfoobaz'): print m.group(2) I think one solution that does not need a wrapper class would be to add the group() method to the match objects from module 're'. IIRC, the obsolete package 'regex' provided this, once upon a time. Cheers, Johann From harlinseritt at yahoo.com Tue Feb 22 08:04:24 2005 From: harlinseritt at yahoo.com (Harlin) Date: 22 Feb 2005 05:04:24 -0800 Subject: Creating Button arrays with different commands using Tkinter Message-ID: <1109077464.543960.282830@o13g2000cwo.googlegroups.com> I have an array of Appnames. Let's say they are 'Monkeys', 'Cats', 'Birds'. I would like create a button array with these: ---Start Code--- # Constructing and displaying buttons for a in Appnames: Button(root, text=a, command=lambda:self.OpenFile(a)).pack() # Somewhere else I have this function defined within the class... def OpenFile(self, AppName): fh = open(AppName+".txt", 'r').read() do something with fh ---End Code--- When I do this, whatever the last value a was is what the each button's command option is. Does anyone know what I can do to differentiate each button so that it has its own separate argument for self.OpenFile? Thanks, Harlin From lbates at syscononline.com Wed Feb 2 11:18:28 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 02 Feb 2005 10:18:28 -0600 Subject: Prepending to traceback In-Reply-To: References: Message-ID: <7JSdndRZRunRYJ3fRVn-sw@comcast.com> Replace system exception hook with your on function that gets called when exception is raised (not fully tested): # # Define a function that is called when system exception happens # def excepthook(self, type, value, tb): # # This function allows the user to redefine what happens if the program # aborts due to an uncaught exception. import traceback # # Prepend your lines to tblines list here # tblines=['PyParsing, line 5, in SomeStatement\n', 'PARSER TEST FOR TESTING MISSING TERM\n'] # # Get traceback lines and append the current session log # tblines.extend(traceback.format_exception(type, value, tb)) map(sys.stdout.writelines, tblines) # Always write exceptions to screen sys.exit(2) # # At top of your main program: # Set the sys.excepthook so I can clean up properly if main program aborts # sys.excepthook=excepthook Larry Bates Stefan Behnel wrote: > Hi! > > I'm writing a parser using pyparsing and I would like to augment the > ParserException tracebacks with information about the actual error line > *in the parsed text*. Pyparsing provides me with everything I need > (parsed line and column), but is there a way to push that information on > the traceback? > > > To make it a bit clearer, tracebacks currently look like this: > > Traceback (most recent call last): > ... > File "/usr/lib/python2.4/site-packages/pyparsing.py", line 456, in parse > loc,tokens = self.parseImpl( instring, loc, doActions ) > File "/usr/lib/python2.4/site-packages/pyparsing.py", line 727, in > parseImpl > raise exc > ParseException: Expected "SOMEOTHERTERM" (146), (5,9) > > > I want them to look like this: > > Traceback (most recent call last): > ... > File "/usr/lib/python2.4/site-packages/pyparsing.py", line 456, in parse > loc,tokens = self.parseImpl( instring, loc, doActions ) > File "/usr/lib/python2.4/site-packages/pyparsing.py", line 727, in > parseImpl > raise exc > PyParsing, line 5, in SomeStatement > PARSER TEST FOR TESTING MISSING TERM > ParseException: Expected "SOMEOTHERTERM" (146), (5,9) > > > where "PARSER TEST FOR TESTING MISSING TERM" is a line parsed by > pyparsing that leads to raising a ParseException. I wouldn't mind too > much not having the original traceback, though I'd prefer it. I remember > having read somewhere that there is a way to embed an exceptions in > another one, that might help. > > How can I alter or create such Tracebacks? > > Thanks, > Stefan From sjmachin at lexicon.net Thu Feb 10 00:55:32 2005 From: sjmachin at lexicon.net (John Machin) Date: 9 Feb 2005 21:55:32 -0800 Subject: negative integer division References: <4208039c$0$28559$8fcfb975@news.wanadoo.fr> Message-ID: mjackson at alumni.caltech.edu (Mark Jackson) wrote in message news:... > > A: 42 > > Q: What multiple of 7 did I add to the critical expression in the Zeller > algorithm so it would remain nonnegative for the next few centuries? What are you calling "the Zeller algorithm", and what is the "critical expression"? There _is_ something called "Zeller's congruence": if m is the month number in an adjusted or computational year (m == 0 => March, m == 11 => Feb), then the number of days in the adjusted year before month m is [Python notation] (13*m + 2) // 5 + m * 28 Alternatively (153*m + 2) // 5 I believe that strictly the term "Zeller's congruence" applies only to the (13*m + 2)//5 part. In any case, all of the above is quite independent of the year, and there is no possibility of going negative. I've no doubt you came across a stuffed-up date-to-days calculation routine and fixed it, but it's a bit unfair to lumber Zeller with the blame. If it was a days-to-date routine, then Zeller is not even standing next to the real target. Cheers, John From zathras at thwackety.com Sat Feb 12 07:51:21 2005 From: zathras at thwackety.com (Michael Sparks) Date: Sat, 12 Feb 2005 12:51:21 +0000 (GMT) Subject: [perl-python] 20050211 generating expression by nested loops In-Reply-To: <1108162972.047914.20780@l41g2000cwc.googlegroups.com> Message-ID: On 11 Feb 2005, Xah Lee wrote: > # this construct uses a irregular syntax to generate a expression > # built by nested loops. Semantically, this expression generation is > # akin to applying a function to a tree. Morons in the computing > # industry and academia like to call this "list comprehension". People who try to change existing terminology in a language by declaring the terminology used by __everyone__ are generally those considered moronic. Xah Lee - I know you have been declared a Troll on many an occasion, and it does seem a fitting declaration based on your behaviour. Consider that all you are achieving is making yourself look foolish to both the established perl community and the established python communities. Your code examples are NOT exemplars for either language or community. By trying to get new users to ignore existing terminology you ARE doing those people a disservice. (If indeed your goal is as stated to try and help new users). Taking 'list comprehension' for example. There is a long standing concept that is decades old (centuries old even?) called "set comprehension". This is taught in schools and says "from this set of things take these values perhaps based on a condition". List comprehension alludes to this and as soon as I saw the syntax and what it was called it was very clear what this "moronic" description meant. Clearly not everyone is in the same boat. However what will they search for? If told it's a "list comprehension", suppose they search for that - what will their #1 search result be? On google, the number 1 result is this: http://docs.python.org/tut/node7.html * This is the python tutorial section that deals with data structures and includes a section on "moronically named" list comprehensions. One can debate whether naming something distinctly and clearly which results in the #1 search result being a tutorial on the structure as being a good or a bad thing. I'll make no judgement here. So by trying to get people to call it something else - do new users get better results ? If you were doing new users a service then the answer should be yes. Is it, and are you doing them a service? Let's try the same thing for "irregular syntax": * http://www.google.com/search?num=100&q=irregular+syntax None of these 100 results contains any reference to list comprehensions. Not so successful. None of the 3 results out of that 100 that do relate to python refer even vaguely to python's list syntax. (2 relate to a scheme programmer finding python hard, and the other relates to Latin) Well, you also incorrectly (or perhaps misleadingly) stated this: * Semantically, this expression generation is akin to applying a function to a tree. If you provide an iterator on the tree (say a tree walker of some kind) then this becomes technically true (__kinda__) , but the common case is iterating over list of somekind. So again, assuming a new user, what might they use as a search term using your description ? Let's try "applying a function to a tree python". (last term to try and ensure it's on topic) Do any of those search results do something as useful as, say, point at a tutorial or documentation page on list comprehensions ? Oddly no. The closest that comes to it is one of your pages, which is taling about Perl & Mathematica. (Removing "python" makes it even further removed from being relevant) Based on seeing your perl and python code I would suggest you go away and improve your idiomatic perl & python code before posting any more of these things. Or at least try to cease attacking people declaring their established terminology as moronic, etc. Posting naive translations (which is what you've been doing) between languages can occasionally be useful to help people get started. However acting as if they are "masterful" translations and/or descriptions when they are not is not helpful in the slightest. It's very saddening to see something posted which new users will read and assume, based on the tone on the post, that it's the _correct_ way of describing things when it clearly is NOT, and will just end up misleading them and sending them down blind alleys. Michael. From fredrik at pythonware.com Mon Feb 14 12:08:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 14 Feb 2005 18:08:59 +0100 Subject: ValueError: invalid literal for int(): 1.0000000000e+00 References: <4210D979.4000709@ribosome.natur.cuni.cz> Message-ID: Martin MOKREJ? wrote: > is this a bug or "feature" that I have to use float() to make int() autoconvert > from it? it's by design, of course. "1.0000000000e+00" is not an integer. if you want to treat a floating point literal as an integer, you have to use an explicit conversion. From me at privacy.net Mon Feb 28 15:50:22 2005 From: me at privacy.net (Dan Sommers) Date: 28 Feb 2005 15:50:22 -0500 Subject: accessor/mutator functions References: <1109315698.002207.245690@g14g2000cwa.googlegroups.com> Message-ID: On 28 Feb 2005 10:30:03 GMT, Nick Craig-Wood wrote: > Actually I would say just access the attribute directly for both get > and set, until it needs to do something special in which case use > property(). > The reason why people fill their code up with boiler plate get/set > methods is to give them the flexibility to change the implementation > without having to change any of the users. In python you just swap > from direct attribute access to using property(). The reason their code is so inflexible is that they've filled their classes with boiler plate get/set methods. Why do users of classes need such access anyway? If my class performs useful functions and returns useful results, no user of my class should care about its attributes. If I "have to" allow access to my attributes in order that my users be happy, then I did something else wrong when I designed the class and its public interface in the first place. I usually aim for this: if users of the public interface of my class can figure out that I changed the implementation, then I've exposed too much. Sure there are exceptions, but that's my basic thought process. Sorry about the rant. Regards, Dan -- Dan Sommers ?? ? ?? ? c? = 1 From gmane-schpam at joefrancia.com Wed Feb 9 12:38:37 2005 From: gmane-schpam at joefrancia.com (Joe Francia) Date: Wed, 09 Feb 2005 12:38:37 -0500 Subject: Python versus Perl ? In-Reply-To: <1107930486.318280.251010@l41g2000cwc.googlegroups.com> References: <1107695949.247611.272800@g14g2000cwa.googlegroups.com> <1107930486.318280.251010@l41g2000cwc.googlegroups.com> Message-ID: Caleb Hattingh wrote: > As you might imagine, I think about this constantly. However, there > are many other issues that make it complicated, such as having to work > in a team where the average guy knows pascal well (we're just a bunch > of chemical engineers), but has never even heard of python. Plus, were > I to go this type of route, I would almost definitely code the binary > modules in Delphi or FreePascal, make a DLL and use ctypes to call it. > I do not know C and have no desire to learn now :) On the other > hand, I know pascal quite well. > > keep well > Caleb > You could always code Python extensions directly in Delphi: http://membres.lycos.fr/marat/delphi/python.htm http://www.atug.com/andypatterns/PythonDelphiLatest.htm Demo09 (look in demodll.dpr & module.pas) in the download tells you how. Peace, Joe From dodoowang at gmail.com Fri Feb 25 08:26:37 2005 From: dodoowang at gmail.com (dodoo) Date: 25 Feb 2005 05:26:37 -0800 Subject: how to use property In-Reply-To: <1109327145.250209.203720@o13g2000cwo.googlegroups.com> References: <1109327145.250209.203720@o13g2000cwo.googlegroups.com> Message-ID: <1109337997.348010.176130@l41g2000cwc.googlegroups.com> try this: self.channel = choice From duncan.booth at invalid.invalid Fri Feb 18 04:27:04 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Feb 2005 09:27:04 GMT Subject: difference between class methods and instance methods References: <1119g2rre5g610c@corp.supernews.com> <37juh3F5d511mU1@individual.net> <1119p2o72976500@corp.supernews.com> Message-ID: John wrote: >>inst = C() >>f1 = inst.foo >>f2 = inst.foo >>f1, f2 >> >> (>, > method C.foo of <__main__.C instance at 0x00B03F58>>) >> > > I just wanted to interject, although those two hex > numbers in the above line are the same, calling > id() on f1 and f2 produces two *different* numbers, > which agrees with the point you made. Yes, note that the numbers are in the repr of C() and are actually id(inst). A common mistake seems to be for people to do: >>> inst = C() >>> id(inst.foo), id(inst.foo) (11803664, 11803664) and conclude that the bound methods are the same. They aren't, but if you just take the id of an object and throw it away then the next object of similar size can [and with the current implementation probably will] be allocated at the same location. From stefan.behnel-n05pAM at web.de Sun Feb 13 12:33:06 2005 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 13 Feb 2005 18:33:06 +0100 Subject: changing __call__ on demand In-Reply-To: References: Message-ID: Michael Hoffman schrieb: > __call__, like __getitem__, and __getattr__ is called on the > class object, not the instance object. So, no, not as far as I > am aware, without using metaclass trickery. The simplest option > IMO is to use another level of indirection as you suggest. Thanks for the quick answer. I didn't know they were class-level methods. Too bad. Guess I'll stick with indirection then. Stefan From http Thu Feb 3 19:20:30 2005 From: http (Paul Rubin) Date: 03 Feb 2005 16:20:30 -0800 Subject: OT: why are LAMP sites slow? Message-ID: <7x8y65kwfl.fsf@ruckus.brouhaha.com> LAMP = Linux/Apache/MySQL/P{ython,erl,HP}. Refers to the general class of database-backed web sites built using those components. This being c.l.py, if you want, you can limit your interest to the case the P stands for Python. I notice that lots of the medium-largish sites (from hobbyist BBS's to sites like Slashdot, Wikipedia, etc.) built using this approach are painfully slow even using seriously powerful server hardware. Yet compared to a really large site like Ebay or Hotmail (to say nothing of Google), the traffic levels on those sites is just chickenfeed. I wonder what the webheads here see as the bottlenecks. Is it the application code? Disk bandwidth at the database side, that could be cured with more ram caches or solid state disks? SQL just inherently slow? I've only worked on one serious site of this type and it was "SAJO" (Solaris Apache Java Oracle) rather than LAMP, but the concepts are the same. I just feel like something bogus has to be going on. I think even sites like Slashdot handle fewer TPS than a 1960's airline reservation that ran on hardware with a fraction of the power of one of today's laptops. How would you go about building such a site? Is LAMP really the right approach? From dave at pythonapocrypha.com Sat Feb 26 01:05:55 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 25 Feb 2005 23:05:55 -0700 Subject: urllib2 meta-refresh In-Reply-To: References: Message-ID: <422011C3.6000304@pythonapocrypha.com> Artificial Life wrote: > urllib2 does not seem to be able to handle META-REFRESH in an html > document. I just get back the html to the page that is supposed to forward > me to the intended page. Right - urllib2 is for working with protocols (like HTTP) to transfer data, whereas META-REFRESH is an application (browser) level "instruction" *in* that data. Compare this to a 302 HTTP response header (a simple redirect) - urllib2 can handle it because it is part of HTTP. > Any way around this? Sure - META-REFRESH is an instruction to the browser, so have your code be the browser: scan the HTML for the tag, extract the URL, and send that new URL off to urllib2. -Dave From jfj at freemail.gr Mon Feb 14 21:14:20 2005 From: jfj at freemail.gr (jfj) Date: Mon, 14 Feb 2005 18:14:20 -0800 Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler In-Reply-To: <4210a434$0$23451$626a14ce@news.free.fr> References: <4210a434$0$23451$626a14ce@news.free.fr> Message-ID: <42115AFC.9040806@freemail.gr> bruno modulix wrote: > Ilias Lazaridis wrote: > >> I'm a newcomer to python: >> >> [EVALUATION] - E01: The Java Failure - May Python Helps? >> http://groups-beta.google.com/group/comp.lang.python/msg/75f0c5c35374f553 >> > > My trollometer's beeping... > When person 'A' calls person 'B' a troll, these are the possibilities: 1. 'A' is indeed a troll 2. 'B' is the troll 3. both 'A' and 'B' are trolls 4. nobody is a troll. they're computer scientists passionate about their ideas and they are trying to convince each other. 5. nobody is a troll and there is no trolling going on. Now, it's rather common to accuse people of trolling these days. The fact that Markus Wankus said that Ilias is a troll does not mean that everybody should reply to him in that tone. This is a one .vs many battle and it sucks. gerald From fuzzyman at gmail.com Wed Feb 23 10:59:31 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 23 Feb 2005 07:59:31 -0800 Subject: user interface for python In-Reply-To: <1109151356.896348.58940@g14g2000cwa.googlegroups.com> References: <1109131790.140672.209730@l41g2000cwc.googlegroups.com> <1109150221.947518.209220@o13g2000cwo.googlegroups.com> <1109151356.896348.58940@g14g2000cwa.googlegroups.com> Message-ID: <1109174371.046089.187450@g14g2000cwa.googlegroups.com> Yeah.. Tkinter is nice. Wzx is just as easy though, but scales better because it's built on wx. Regards, Fuzzy http://www.voidsapce.org.uk/python/index.shtml From aleaxit at yahoo.com Sun Feb 6 04:17:31 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 6 Feb 2005 10:17:31 +0100 Subject: Word for a non-iterator iterable? References: <36lu1cF516qtdU1@individual.net> Message-ID: <1grk4a5.eq5u5q10cmxktN%aleaxit@yahoo.com> Leif K-Brooks wrote: > Is there a word for an iterable object which isn't also an iterator, and > therefor can be iterated over multiple times without being exhausted? > "Sequence" is close, but a non-iterator iterable could technically > provide an __iter__ method without implementing the sequence protocol, > so it's not quite right. Not just ``technically'' -- a dict is a good and very common example of just such a "non-iterator, non-sequence iterable". As you're focusing on "can be iterated over multiple-times", I like "re-iterable"; it centers on what you can DO with the object, rather than quibbling what it ISN'T;-) Alex From francis.girard at free.fr Mon Feb 7 14:58:51 2005 From: francis.girard at free.fr (Francis Girard) Date: Mon, 7 Feb 2005 20:58:51 +0100 Subject: "Collapsing" a list into a list of changes In-Reply-To: <20050207185138.GA20602@grulic.org.ar> References: <200502071907.12169.francis.girard@free.fr> <20050207185138.GA20602@grulic.org.ar> Message-ID: <200502072058.51513.francis.girard@free.fr> Le lundi 7 F?vrier 2005 19:51, John Lenton a ?crit?: > On Mon, Feb 07, 2005 at 07:07:10PM +0100, Francis Girard wrote: > > Zut ! > > > > I'm very sorry that there is no good use case for the "reduce" function > > in Python, like Peter Otten pretends. That's an otherwise very useful > > tool for many use cases. At least on paper. > > > > Python documentation should say "There is no good use case for the reduce > > function in Python and we don't know why we bother you offering it." > > I am guessing you are joking, right? Of course I am joking. I meant the exact contrary. Only wanted to show that Peter did exaggerate. Thank you for citing me with the full context. > I think Peter exaggerates when he > says that "there will be no good use cases for reduce"; it is very > useful, in writing very compact code when it does exactly what you > want (and you have to go through hoops to do it otherwise). It also > can be the fastest way to do something. For example, the fastest way > to get the factorial of a (small enough) number in pure python is > > factorial = lambda n: reduce(operator.mul, range(1, n+1)) Great. Regards Francis Girard From marian at mba-software.de Thu Feb 10 04:01:47 2005 From: marian at mba-software.de (=?ISO-8859-1?Q?Marian_Aldenh=F6vel?=) Date: Thu, 10 Feb 2005 10:01:47 +0100 Subject: pyFMOD writing a callback function in Python Message-ID: <370m88F525p5uU1@individual.net> Hi, I am using the FMOD audio-library with the pyFMOD python bindings. pyFMOD uses ctypes. It is possible to register callback functions with FMOD that are called at certain points in the processing pipeline or when certain events happen. I am expecially interested in the one that fires when a currently playing stream ends. This is what the declaration in pyFMOD looks like: _FSOUND_Stream_SetEndCallback = getattr(fmod,"_FSOUND_Stream_SetEndCallback at 12") _FSOUND_Stream_SetEndCallback.restype = c_byte def FSOUND_Stream_SetEndCallback(stream, callback, userdata): result = _FSOUND_Stream_SetEndCallback(c_int(stream), c_int(callback), c_int(userdata)) if not result: raise fmod_exception() I cannot make it work, however. I tried: def _sound_end_callback(stream,buf,len,userdata): print "_sound_end_callback(): Stream has reached the end." as simplest possible callback function. I am registering it like this: pyFMOD.FSOUND_Stream_SetEndCallback(_currenttrack,_sound_end_callback,0) And this is how my program dies: File "d:\projekte\eclipse\workspace\gettone\gettonesound.py", line 175, in sound_tick pyFMOD.FSOUND_Stream_SetEndCallback(_currenttrack,_sound_end_callback,0) File "c:\programme\Python23\lib\site-packages\pyFMOD.py", line 690, in FSOUND_Stream_SetEndCallback result = _FSOUND_Stream_SetEndCallback(c_int(stream), c_int(callback), c_int(userdata)) TypeError: int expected instead of function instance I am very new to Python and have zero idea what the problem is nor how to solve it. In some of my other languages I would have to explicitly make a function pointer and possibly have to cast that to an int to pass it to SetEndCallback, but that seems very inappropriate in Python... Ciao, MM -- Marian Aldenh?vel, Rosenhain 23, 53123 Bonn. +49 228 624013. http://www.marian-aldenhoevel.de "Wir brauchen keine Opposition, wir sind bereits Demokraten." From Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org Thu Feb 3 19:58:10 2005 From: Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org (Alexander) Date: Fri, 04 Feb 2005 03:58:10 +0300 Subject: dict indexed by lists - ? References: Message-ID: ?????? All! 04 ??????? 2005 ? 02:47, Alexander Zatvornitskiy ? ????? ?????? ? All ?????: AZ> I'am trying to make something like this: AZ> CPT={ ['b0','c0']:1, ['b0','c1']:0, ['b1','c0']:3, ['b1','c1']:1 } Thanks, I fix it - i use lists. AZ> and, later, modifying it like this: AZ> key[2]=up.next_state() replaced with: k=k[:cur_idx-1]+up.next_state()+k[cur_id+1:] AZ> ... AZ> print CPT[key] AZ> Any suggestions? AZ> Alexander, zatv at bk.ru Alexander, zatv at bk.ru From gsakkis at rutgers.edu Sun Feb 20 22:00:18 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sun, 20 Feb 2005 22:00:18 -0500 Subject: How Do I get Know What Attributes/Functions In A Class? References: <1108870842.095282.54200@z14g2000cwz.googlegroups.com> <1108952515.297032.306980@l41g2000cwc.googlegroups.com> Message-ID: <37t168F5ibletU1@individual.net> wrote in message news:1108952515.297032.306980 at l41g2000cwc.googlegroups.com... > Thank you Hans. Could you give me a simple sample of using inspect? > http://www.python.org/doc/current/lib/module-inspect.html George From EP at zomething.com Sun Feb 6 17:29:01 2005 From: EP at zomething.com (EP) Date: Sun, 6 Feb 2005 14:29:01 -0800 Subject: Python versus Perl ? In-Reply-To: <1107695949.247611.272800@g14g2000cwa.googlegroups.com> References: <1107695949.247611.272800@g14g2000cwa.googlegroups.com> Message-ID: <20050206142901.620621043.EP@zomething.com> surfunbear at yahoo.com asked > 3. Perl is installed on our system and a lot of other systems. > You don't have to make sys admins go out of there way to make it > available. It's usualy allready there. I also did a search of job > postings on a popular website. 108 jobs where listed that require > knowledge of Perl, only 17 listed required Python. Becomeing more > familiar with Perl might then be usefull for ones resume ? Python is trivial to install on one's workstation or PC, if it isn't already there. Getting Python on the company's servers can require some IT latitude or buy-in. I've begun to view the availability of Python on company servers as a measure of an IT organization's fitness. Perl was (probably) the right language at the right time at least for cgi work and text processing in the early days of the web, when there was a sudden increase in the need for such work. And Perl "works", especially as you become familiar with it and some of the non-obvious ways it works. Learning Perl is an investment and many folks becomes Perl people - why would you switch from anything you've put that much time into? And so a vast number of people and orgnizations remain in the cave, unwilling to risk going outside, unwilling to believe life could be better out there in the unknown. Congrats for being the rare person who takes a look. (That strange feeling you may get is from something we call "sunshine" and, on balance, I think you'll find it is a very nice thing.) > If Python is better than Perl, I'm curious how really significant > those advantages are ? I'd say the advantages are significant if you develop anything complex, or like to think about the software you develop in clean abstractions. I'd say knowing Python probably does not lead to a higher salary, but that the software engineers attracted to Python tend to be the cream of the crop and are worth more money. [Disclaimer: Python also attracts some who are not cream of the crop software engineers but rather see things - applications, large or small - that ought to be done, and are looking for the most efficient way of getting there. Anyone can write some Python succssfully, but not everyone is capable of contributing to PyPy. Python is a great tool for each.] Recommendation: Python requires little investment. Play in it. Read (briefly) about the aspects that seem interesting. Try writing a small progam in it. There are very very few cases where anyone is going to require you to use Python; it's a personal decision, and the people that use Python do so because they want to, not because someone required them to. cheers/ From cdieterich at geosci.uchicago.edu Fri Feb 4 23:16:47 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Fri, 4 Feb 2005 22:16:47 -0600 Subject: Pickling and inheritance are making me hurt In-Reply-To: <477dd2xhuk2.ln2@news.conpoint.com> Message-ID: On D? hAoine, Feabh 4, 2005, at 15:48 America/Chicago, Kirk Strauser wrote: > I have a module that defines a Search class and a SearchResult class. > I use > these classes by writing other modules that subclass both of them as > needed > to interface with particular search engines. > > My problem is that Search defines a method (called automatically by > __del__) > to save its results between invocations: > > def _saveresults(self): > self._oldresults = self._results > file = open(self._storefile(), 'w') > pickle.dump(self._oldresults, file) > file.close() > > The problem I'm having is the the pickle.dump call is failing whenever > the > objects in "self.data" are instances of derivatives of SearchResult > rather > than instances of SearchResult itself (which is pretty much always the > case): > > Exception pickle.PicklingError: 0xb7f7ad6c> in at > 0xb7ec954c>> ignored > > > Now, if I overload _saveresults inside a subclass of Search, then it > works. > It seems like the problem is that _saveresults is only looking inside > the > same namespace as Search (where it's originally defined), even if it's > actually been inherited by another class in a different module. Is > there a > way around this? It's hard to tell exactly what's going on. I have only suggestions what you could try to verify. There was a thread a few days ago, where it was concluded that garbage collecting happens in alphabetical order. Can't remember which one it was. You could temporarily rename self._result to self.z_result to check that. Here's a gotcha that I had in a similar context. Well, it's logical but somehow unexpected. If you do for example s = Search() s = Search() the calling sequence for the constructor and destructor is __init__() __init__() __del__() Maybe this interferes with pickling your first instance? Hope this helps debugging, Christian From jzgoda at gazeta.usun.pl Mon Feb 21 15:18:24 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 21 Feb 2005 21:18:24 +0100 Subject: PyQt Python Bindings for Qt v3.14 Released In-Reply-To: References: Message-ID: Phil Thompson napisa?(a): > Riverbank Computing is pleased to announce the release of PyQt v3.14 available > from http://www.riverbankcomputing.co.uk/. Classes generated by puyic 3.13 are not compatible with PyQt 3.14 (some method signature incompatibilities). I cann't provide more details, as I regenerated all classes from *.ui files, but this may be reproductible. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From fredrik at pythonware.com Fri Feb 11 16:13:44 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Feb 2005 22:13:44 +0100 Subject: is there a safe marshaler? References: <420b6936$0$28982$e4fe514c@news.xs4all.nl><1108051828.483222.62670@z14g2000cwz.googlegroups.com> <420b9281$0$28982$e4fe514c@news.xs4all.nl> Message-ID: (repost; gmane seems to have eaten my original post) Irmen de Jong wrote: >> I think marshal could be fixed; the only unsafety I'm aware of is that >> it doesn't always act rationally when confronted with incorrect input >> like bad type codes or truncated input. It only receives instances of >> the built-in types and it never executes user code as a result of >> unmarshalling. > > So it is not vulnerable in the way that pickle is? That's a start. > The security warning in the marsal doc then makes it sound worse than > it is... the problem is that the following may or may not reach the "done!" statement, somewhat depending on python version, memory allocator, and what data you pass to dumps. import marshal data = marshal.dumps((1, 2, 3, "hello", 4, 5, 6)) for i in range(len(data), -1, -1): try: print marshal.loads(data[:i]) except EOFError: print "EOFError" except ValueError: print "ValueError" print "done!" (try different data combinations, to see how far you get on your platform...) fixing this should be relatively easy, and should result in a safe unmarshaller (your application will still have to limit the amount of data fed into load/loads, of course). From kartic.krishnamurthy at gmail.com Tue Feb 1 16:21:19 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 1 Feb 2005 13:21:19 -0800 Subject: How do you do arrays In-Reply-To: References: <1107284817.848551.79000@c13g2000cwb.googlegroups.com> Message-ID: <1107292879.436151.47030@c13g2000cwb.googlegroups.com> Tom - I answered your question even before you posted it! You have to use iMatrix.append(k) and NOT iMatrix[index] = k. Also, what do you expect out of: while index < majorlop1: print '- %s %s' % ( iMatrix[index], sep) This loop will never get executed because your previous loop finishes due to the same condition index < majorlop1. I am not sure what book you are using but I don't think it is a very good one. > I would like to set the size of the List/array independent > of having to intialialize it prior to use. You can do the following when you allocate your list. iMatrix = [''] * size # where size is an integer and this will give you a list of size empty elements. If you do this, do not use iMatrix.append(). Use the array notation like you have in you code currently. Thanks -Kartic From mensanator at aol.com Thu Feb 3 19:40:57 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 3 Feb 2005 16:40:57 -0800 Subject: how to generate SQL SELECT pivot table string References: <1107475373.064794.155030@l41g2000cwc.googlegroups.com> Message-ID: <1107477657.906912.54080@z14g2000cwz.googlegroups.com> McBooCzech wrote: > Hallo all, > > I am trying to generate SQL SELECT command which will return pivot > table. The number of column in the pivot table depends on the data > stored in the database. It means I do not know in advance how many > columns the pivot table will have. > > For example I will test the database as following: > SELECT DISTINCT T1.YEAR FROM T1 > > The SELECT command will return: > 2002 > 2003 > 2004 > 2005 > > So I would like to construct following select: > > select T1.WEEK, > SUM (case T1.YEAR when '2002' then T1.PRICE else 0 END) Y_02, > SUM (case T1.YEAR when '2003' then T1.PRICE else 0 END) Y_03, > SUM (case T1.YEAR when '2004' then T1.PRICE else 0 END) Y_04, > SUM (case T1.YEAR when '2005' then T1.PRICE else 0 END) Y_05 > from T1 > group by T1.week > > which will return pivot table with 5 columns: > WEEK, Y_02, Y_03, Y_04, Y_05, > > but if the command "SELECT DISTINCT T1.YEAR FROM T1" returns: > 2003 > 2004 > > I have to construct only following string: > > select T1.WEEK, > SUM (case T1.YEAR when '2003' then T1.PRICE else 0 END) Y_03, > SUM (case T1.YEAR when '2004' then T1.PRICE else 0 END) Y_04, > from T1 > group by T1.week > > which will return pivot table with 3 columns: > WEEK, Y_03, Y_04 > > Can anyone help and give me a hand or just direct me, how to write a > code which will generate SELECT string depending on the data stored in > the database as I described? > > Thanks > > Petr McBooCzech In MS-Access, the appropriate SQL statement is TRANSFORM Sum(T1.price) AS SumOfprice SELECT T1.week FROM T1 GROUP BY T1.week PIVOT T1.year; Note the keywords TRANSFORM and PIVOT. These change an ordinary SELECT query into what Access calls a CROSSTAB query. In such a query, the number of columns is created automatically (subject to the limitation of a maximum of 256 columns). For example, if your T1 table contains: year week price 2002 1 123 2002 10 456 2002 20 254 2002 30 253 2002 40 325 2002 50 111 2003 1 254 2003 10 256 2003 20 854 2003 30 125 2003 40 845 2003 50 562 2004 1 425 2004 10 123 2004 20 212 2004 30 555 2004 40 412 2004 50 852 The query shown will output: week 2002 2003 2004 1 123 254 425 10 456 256 123 20 254 854 212 30 253 125 555 40 325 845 412 50 111 562 852 Now, if you add another year's worth of data, year week price 2005 1 666 2005 10 555 2005 20 444 2005 30 333 2005 40 222 2005 50 111 the query (without any modiification) will now output week 2002 2003 2004 2005 1 123 254 425 666 10 456 256 123 555 20 254 854 212 444 30 253 125 555 333 40 325 845 412 222 50 111 562 852 111 If you had multiple records for each year/week you would, of course, see the aggregate result (in this case, Sum). Watch what happens when I duplicate the 2005 records: week 2002 2003 2004 2005 1 123 254 425 1332 10 456 256 123 1110 20 254 854 212 888 30 253 125 555 666 40 325 845 412 444 50 111 562 852 222 From peter at engcorp.com Sun Feb 27 11:15:22 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 27 Feb 2005 11:15:22 -0500 Subject: PyUnit and multiple test scripts In-Reply-To: References: Message-ID: Calvin Spealman wrote: > I'm trying to find the best way to use PyUnit and organize my test scripts. > What I really want is to separate all my tests into 'test' directories > within each module of my project. The script below will do that. > I want all the files there to define a > 'suite' callable and to then all all those suites from all those test > directories into one big suite and run it all. I'm having trouble with > this. It won't do that. In my own opinion, based on experience, this isn't even a desirable thing for several reasons. For one thing, using that whole "suite" thing seems to be a lot of work for little gain. The default "unittest" stuff will already find all classes that are instances of unittest.TestCase, and will already run all methods in them that begin with the string "test". Furthermore, it's often much better to run different test files using separate processes, mainly to ensure you don't pollute one test's starting conditions by failing to clean up stuff (e.g. terminate all threads) from a previous test. > 1) Is there a very simple way to just take a file path and name, that I > could use to open the source file, and load it as a module object, no > strings attached? > > 2) Is there already a framework around that will do what I need? Try this. It works here (in a more complex version: this was pruned for posting here). Basic conditions: all tests are in subfolders called "test", and all have a filename ending with _unit.py. (This lets me name them based on the module that they are testing.) You can change that pattern in the code. It's possible there are external dependencies on things unique to my environment, but I've tried to catch and remove them all. Note (though it's unrelated to this particular script) that since the tests run in a subfolder of the folder where the code under test resides, you need to do the equivalent of "sys.path.append('..')" in each test file. I accomplish that by having all import my own library module called "testbed", which does this during import time: srcDir = os.path.abspath('..') sys.path.insert(1, srcDir) Anyway, it might give you some ideas. '''test runner''' import os import sys import subprocess import fnmatch def runTest(path): folder, filename = os.path.split(path) cmd = [sys.executable, '-u'] p = subprocess.Popen(cmd + [filename], cwd=folder or '.', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output = [] line = [] while True: c = p.stdout.read(1) if not c: break if not line: sys.stdout.write('--|') sys.stdout.write(c) line.append(c) if c == '\n': output.append(''.join(line)) line = [] return output def findfiles(path, pattern): '''scan all files and folders below path, returning sorted list of those matching pattern''' files = [] match = fnmatch.fnmatch for p, ds, fs in os.walk(path): for f in fs: path = os.path.abspath(os.path.join(p, f)) if match(path, pattern): print path files.append(path) files.sort() return files def run(): pattern='*/tests/*_unit.py' files = findfiles('.', pattern) if not files: print 'no tests found' sys.exit(1) print 'running all tests below %s' % os.path.abspath('.') try: for file in files: if not os.path.exists(file): print 'file not found', file continue print print file output = runTest(file) except KeyboardInterrupt: print 'User aborted test.' if __name__ == '__main__': run() # EOF From aleaxit at yahoo.com Tue Feb 8 03:04:10 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 8 Feb 2005 09:04:10 +0100 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1grifns.14san6f1b076mdN%aleaxit@yahoo.com> <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com> <4208178F.40804@po-box.mcgill.ca> Message-ID: <1grnpna.dwvqwdn50ot0N%aleaxit@yahoo.com> Terry Reedy wrote: > "Brian van den Broek" wrote in message > news:4208178F.40804 at po-box.mcgill.ca... > > Is the right way to understand it in this vicinity: > > In the vicinity, but not quite exact > > >At compile time (by which I mean when the Python bytecode is built) > > Compile time is when the def statement is executed I disagree: compile time is when the compiler is running (for example, the compiler is the component which diagnoses syntax errors, while other errors are diagnosed ``at runtime''). Bytecode is built before def executes -- indeed it's built whether def executes or not. Cfr: >>> def f(wo): ... if wo: ... def g(): pass ... >>> f.func_code.co_consts (None, ", line 3>) the 'def g' hasn't executed (yet?), but the bytecode is built (and stored as the first constantvalue in f, save the ubiquitous None). If the ``if wo: def ...'' construct was in a module being imported, the mechanics would be similar -- although in this case I think you could tell only if a syntax error was present in the def statement (I may be wrong, but offhand I don't think the codeobject is saved in this case). Or, try this one: >>> c = compile('def x(): pass', '', 'exec') >>> c ", line 1> >>> c.co_consts (", line 1>, None) >>> ``compile time'' here is when the 'compile' built-in runs; and we can see the code object ``x'' is already built even though the def has not been executed yet. Alex From donn at drizzle.com Sun Feb 20 00:35:43 2005 From: donn at drizzle.com (Donn Cave) Date: Sun, 20 Feb 2005 05:35:43 -0000 Subject: [Fwd: Re: [Uuu-devel] languages] <-- Why Python References: <1108678805.542584.171930@z14g2000cwz.googlegroups.com> <864qgaisoq.fsf@guru.mired.org> <86vf8qhcql.fsf@guru.mired.org> <86r7jdh5vw.fsf@guru.mired.org> Message-ID: <1108877742.416530@yasure> Quoth Nick Coghlan : [... re Python OS interface vs. language-generic model ] | *Allowing* other languages is one thing, but that shouldn't preclude having a | 'default' language. On other OS's, the default language is some form of shell | scripting (i.e. Unix shell scripts, or Windows batch files). It would be good to | have a real language to fill that role. I don't know what the Windows version is like, but for all the UNIX shell's weaknesses, it's very well suited to its role. The Plan 9 shell (rc) is similar with much improved syntax, and has a distant relative "es" that I think is the closest thing I've ever seen to a 1st class language that works as a shell (though the implementation was only at the proof of concept level.) (I'm not forgetting REXX, it's a fairly respectable effort but not 1st class.) ... | Still, the builtin shell is going to need *some* form of scripting support. An | if that looks like IPython's shell mode, so much the better. | | Anyway, the reason to prefer Python to LISP for something like this, is that | Python reads much more naturally for most people, whereas LISP requires that y | write things 'out of order'. | | Compare out-of-the-box Python: | a = 1 + 2 + 3 + 4 | | And out-of-the-box Lisp: | (setq a (+ 1 2 3 4)) | | Which language has the lower barrier for entry? That should be a fairly | important consideration for a language that is going to sit at the heart of an OS. Well, honestly I think that's stretching it. Your order issue here seems to apply only to operators, and they don't really figure that heavily in the kinds of things we normally do with the OS. The only operator I can think of in "rc" is ^, an odd sort of string multiplication thing, and I can't think of any in the original Bourne shell. Meanwhile, the idea that barriers to entry are built out of things like "+ 1 2 3 4" vs. "1 + 2 + 3 + 4" is really quite open to question. 10 years ago when BeOS was a little hotter than it is today, there were a couple enthusiasts pushing Python as an official language. A few of the people following BeOS at that point had come from a strong Amiga background, and I remember one of them arguing vehemently against Python because its arcane, complicated syntax was totally unsuited to casual use. Compared to, say, REXX. Now, we Python users know very well that's not true, Python's as clear as could be. But theoretically, if you wanted to talk about order issues, for example ... is it really easier to understand when a language sometimes expresses a function f over x and y this way f(x, y) sometimes this way (+ is a function, really) x f y and sometimes this way x.f(y) ? I don't know, I'm just thinking that while Python's notation might be just fine for people who've gotten here the way most of us have, it's not obvious from this that it's just fine 4 everyone. Donn Cave, donn at u.washington.edu From skip at pobox.com Tue Feb 1 22:11:32 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 1 Feb 2005 21:11:32 -0600 Subject: Next step after pychecker In-Reply-To: <200502012113.26393.francis.girard@free.fr> References: <41ff0308$0$6503$636a15ce@news.free.fr> <369mivF4ubv6mU1@individual.net> <200502012113.26393.francis.girard@free.fr> Message-ID: <16896.17636.292712.594184@montanaro.dyndns.org> Francis> "Every well-formed expression of the language can be assigned a Francis> type that can be deduced from the constituents of the Francis> expression alone." Bird and Wadler, Introduction to Functional Francis> Programming, 1988 Francis> This is certainly not the case for Python since one and the Francis> same variable can have different types depending upon the Francis> execution context. Example : Francis> 1- if a is None: Francis> 2- b = 1 Francis> 3- else: Francis> 4- b = "Phew" Francis> 5- b = b + 1 Francis> One cannot statically determine the type of b by examining the Francis> line 5- alone. Do you have an example using a correct code fragment? It makes no sense to infer types in code that would clearly raise runtime errors: >>> "Phew" + 1 Traceback (most recent call last): File "", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects Also, note that the type assigned to an expression may be nothing more than "object". Clearly that wouldn't be very helpful when trying to write an optimizing compiler, but it is a valid type. Skip From fredrik at pythonware.com Fri Feb 11 14:58:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 11 Feb 2005 20:58:39 +0100 Subject: check if object is number References: Message-ID: Steven Bethard wrote: > Is there a good way to determine if an object is a numeric type? Generally, I avoid type-checks in > favor of try/except blocks, but I'm not sure what to do in this case: > > def f(i): > ... > if x < i: > ... > > The problem is, no error will be thrown if 'i' is, say, a string: > > py> 1 < 'a' > True > py> 10000000000 < 'a' > True > > But for my code, passing a string is bad, so I'd like to provide an appropriate error. assert operator.isNumberType(i) (but make sure you read the warning in the docs: http://docs.python.org/lib/module-operator.html ) From nospam at me.invalid Sun Feb 27 11:34:25 2005 From: nospam at me.invalid (anthonyberet) Date: Sun, 27 Feb 2005 16:34:25 +0000 Subject: TKinter Message-ID: <38eb4lF5nldh7U1@individual.net> So, is it pronounced 'Tee-Kinter', or 'Tee-Kay-Inter'? I don't want to appear as a dork down the pub. From fuzzyman at gmail.com Fri Feb 4 10:21:29 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 Feb 2005 07:21:29 -0800 Subject: IPython colors in windows In-Reply-To: <36hculF51ho2sU1@individual.net> References: <1107487113.732375.110850@c13g2000cwb.googlegroups.com> <36hculF51ho2sU1@individual.net> Message-ID: <1107530489.308497.103530@g14g2000cwa.googlegroups.com> Are you really using the readline module from newcenturycomputers ? I've got a feeling that's broken and you need to use the Gary Bishop one with IPython.... Sorry if this is spurious... (restricted internet access, so I can't check for you... but the correct one is linked to from the IPython site). Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml Claudio Grondi wrote: > Hi, > > I have watched this thread hoping to get an > hint on my problem, but it seems I didn't. > > My problem is, that the background of part of > the error messages is always black > (e.g. after typing In [1]: sdfsdf) > and my monitor failes to show the red, green > texts on black background clearly enough > to see it (I can read it after selection, which > inverts the colors). > I have tried to play with PyColorize.py, > LightBGColors = ColorScheme( > 'LightBG',{ > token.NUMBER : Colors.Cyan, > token.OP : Colors.Blue, > token.STRING : Colors.Blue, > tokenize.COMMENT : Colors.Red, > token.NAME : Colors.White, # Colors.Black, > token.ERRORTOKEN : Colors.Red, > > _KEYWORD : Colors.Green, > _TEXT : Colors.Blue, > > 'normal' : Colors.White # Colors.Normal # color off (usu. > Colors.Normal) > } > but without success. > How can I get rid of the black background > "--------------------------------------------------------------------------- > " > "exceptions.NameError" Traceback (most > recent call last) > in with quotation marks marked areas? > Where is the color of the background of this > areas defined? > The color scheme seems to handle only the > text colors, not the background. > > Claudio > > "Ashot" schrieb im Newsbeitrag > news:opsln54fpwej1m1c at ashot... > > yea, I've done that. It must be something subtle, as the colors and tab > > completion works. > > On Thu, 03 Feb 2005 20:31:37 -0800, DogWalker > wrote: > > > > > "Ashot" said: > > > > > >> On 3 Feb 2005 19:18:33 -0800, James wrote: > > >> > > >>> > > >>> Ashot wrote: > > >>>> I am using IPython in windows and the LightBG setting doesn't > > >>> correctly > > >>>> because the background of the text is black even if the console > > >>> background > > >>>> is white. Anyone know whats going on? Thanks. > > >>>> > > >>>> -- > > >>>> ============================== > > >>>> Ashot Petrosian > > >>>> University of Texas at Austin, Computer Sciences > > >>>> (views expressed are solely my own) > > >>>> ============================== > > >>> > > >>> Did you try installing readline for windows? > > >>> http://newcenturycomputers.net/projects/readline.html > > >>> > > >> > > >> yea I've installed that and ctypes. The color and tab completion work, > > >> its just that colored get displayed with black background, it almost > > >> works > > >> so its very frustrating.. > > >> > > > > > > Did you try the following (from the manual)?: > > > > > > Input/Output prompts and exception tracebacks > > > > > > > > > You can test whether the colored prompts and tracebacks work on your > > > system interactively by typing '%colors Linux' at the prompt (use > > > '%colors LightBG' if your terminal has a light background). If the input > > > prompt shows garbage like: > > > [0;32mIn [[1;32m1[0;32m]: [0;00m > > > instead of (in color) something like: > > > In [1]: > > > this means that your terminal doesn't properly handle color escape > > > sequences. You can go to a 'no color' mode by typing '%colors NoColor'. > > > > > > > > > You can try using a different terminal emulator program. To > > > permanently set your color preferences, edit the file > > > $HOME/.ipython/ipythonrc and set the colors option to the desired value. > > > > > > > > -- > > ============================== > > Ashot Petrosian > > University of Texas at Austin, Computer Sciences > > (views expressed are solely my own) > > ============================== From deetsNOSPAM at web.de Tue Feb 8 10:01:15 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 08 Feb 2005 16:01:15 +0100 Subject: Loop in list. References: <1107874174.445345.41230@c13g2000cwb.googlegroups.com> Message-ID: <36s2b2F53f67pU1@individual.net> Jim wrote: > Where did this type of structure come from: > > mat = ['a' for i in range(3)] ? > > This will produce a list of three elements but > I don't see reference for it in any of the books. Its called a list-comprehension. And as I don't know what books you mean, I can't say if its covered there or not. -- Regards, Diez B. Roggisch From test1dellboy3 at yahoo.co.uk Thu Feb 3 16:59:19 2005 From: test1dellboy3 at yahoo.co.uk (test1dellboy3 at yahoo.co.uk) Date: 3 Feb 2005 13:59:19 -0800 Subject: python-mode tab completion problem Message-ID: <1107467959.821309.102850@z14g2000cwz.googlegroups.com> Hi, I am exploring python-mode on emacs. When I open foo.py in emacs and hit C-!, it starts the python interpreter in another window. Next, I execute - import rlcompleter, readline readline.parse_and_bind('tab: complete') Now I will test the completion by trying to complete sys.v (which could be sys.version or sys.version_info). It works find when I run the python interpreter from a terminal, by in python-mode, I get - import sys sys.v [tab][enter] '2.3.4 (#2, Jan 5 2005, 08:24:51) \n[GCC 3.3.5 (Debian 1:3.3.5-5)]' sys.v [tab][tab][enter] '2.3.4 (#2, Jan 5 2005, 08:24:51) \n[GCC 3.3.5 (Debian 1:3.3.5-5)]' sys.v [tab][tab][[tab][enter] sys.version sys.version_info '2.3.4 (#2, Jan 5 2005, 08:24:51) \n[GCC 3.3.5 (Debian 1:3.3.5-5)]' I see that it is doing the completion, but it doesn't show me the choices before I hit enter, instead it moves the cursor one tab stop to the right. Any ideas? Thanks in advance From t-meyer at ihug.co.nz Tue Feb 22 20:50:27 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Wed, 23 Feb 2005 14:50:27 +1300 Subject: Dealing with config files what's the options In-Reply-To: Message-ID: > How are the expert pythoneers dealing with config files? [...] You can just "import ConfigParser", or look at the various alternatives: =Tony.Meyer From jinty at web.de Sat Feb 26 21:31:54 2005 From: jinty at web.de (Brian Sutherland) Date: Sun, 27 Feb 2005 03:31:54 +0100 Subject: Making a calendar In-Reply-To: <422071d5$0$22691$ba624c82@nntp04.dk.telia.net> References: <422071d5$0$22691$ba624c82@nntp04.dk.telia.net> Message-ID: <20050227023154.GA15400@minipas> On Sat, Feb 26, 2005 at 01:57:20PM +0100, Pete..... wrote: > I'm trying to make a calendar for my webpage, python and html is the only > programming languages that I know, is it possible to make such a calendar > with pythong code and some html. > > The Idea is that when I click the link calendar on my webpage, then the user > will be linked to the calendar. > > The calendar should show one month at the time, and the user should be able > to browse to the other month. > > I will make a script that puts events and such into a db ( I know how to do > this) > > Then I need a script that puts the events from the db into the calendar, if > every day in the calendar has a value id that part will not be hard. All this and more (perhaps overkill): http://www.schooltool.org/schoolbell -- Brian Sutherland It's 10 minutes, 5 if you walk fast. From http Sun Feb 20 10:09:31 2005 From: http (Paul Rubin) Date: 20 Feb 2005 07:09:31 -0800 Subject: BaseHTTPServer threading using SocketServer.ThreadingMixIn References: <1108910973.117326.206390@f14g2000cwb.googlegroups.com> Message-ID: <7x1xbbw9n8.fsf@ruckus.brouhaha.com> "Tortelini" writes: > I am making custom web server using HTTPServer and want to be able to > access it simultaneously from different computers. To achieve > multithreading, I have been experimenting with ThreadingMixIn from > SocketServer, but it doesn't seem to work, One common error is to define your class as something like: class myServer(HTTPServer, ThreadingMixin): ... You have to put ThreadingMixin first, since it overrides methods of TCPServer: class myServer(ThreadingMixin, HTTPServer): ... From jerf at jerf.org Thu Feb 3 18:34:51 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 03 Feb 2005 18:34:51 -0500 Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xy8e5jagh.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 03 Feb 2005 19:00:30 -0800, Paul Rubin wrote: > Hmm, I'm not familiar with Nevow. Twisted is pretty neat, though > confusing. I don't see how to scale it to multiple servers though. Same way you'd scale any webserver, load balancing in hardware, store all user state in a database, and tell the load balancer to try to "persist" a user's connection to a machine, so Twisted doesn't even have to go back to the server then? I'm going to assume you know about this if you deal with large websites professionally, so I'm curious as to why this is inadequate for your needs? (If it's too detailed, no answer requested then, but if it's fast to explain I'm intrigued.) From rmb25612 at yahoo.com Mon Feb 21 11:56:16 2005 From: rmb25612 at yahoo.com (rmb25612 at yahoo.com) Date: 21 Feb 2005 08:56:16 -0800 Subject: IDLE Problem: win98\Python2.4 In-Reply-To: <22eSd.1969$MY6.1483@newsread1.news.pas.earthlink.net> References: <22eSd.1969$MY6.1483@newsread1.news.pas.earthlink.net> Message-ID: <1109004976.267201.200950@z14g2000cwz.googlegroups.com> kim kubik wrote: > This sure seems like it would have been > brought up but I checked Google Groups > (the dejanews replacement) and saw > nothing: I installed Python2.4 in Win98 > and IDLE doesn't work (neither does the > online manual even tho a 3.6KB Python24.chm > is there, but that's a story for another > day) - that is, clicking on the IDLE icon > in the Start menu just gives a brief hourglass > cursor and then nothing . . . Are you also running Ruby? The Ruby bundle for MS Windows has caused problems with it's TCL package conflicting with Python's. Search comp.lang.python on Google Groups for: Ruby TCL From apocalypznow at gmail.com Tue Feb 8 04:39:17 2005 From: apocalypznow at gmail.com (apocalypznow) Date: Tue, 08 Feb 2005 01:39:17 -0800 Subject: re-entrancy question Message-ID: I have a program that instantiates some objects and runs a main loop. Before the main loop starts, I create a thread that listens to TCP connections on a port. If any connections are made, and depending on the data, I call methods on some of those objects. I am worried that calling methods on objects from outside the main loop, but that are also operated on in the main loop, could cause problems. My questions: 1) is this safe? 2) what kind of problems could occur? 3) how do I safely handle this? From enleverlesO.OmcO at OmclaveauO.com Tue Feb 8 19:12:28 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Wed, 9 Feb 2005 01:12:28 +0100 Subject: PHP Embedded In Python References: <1107814685.908990.58410@z14g2000cwz.googlegroups.com> Message-ID: <42095579$0$28560$8fcfb975@news.wanadoo.fr> And : http://lesuisse.net/pyphp-0.1.tgz ? @-salutations -- Michel Claveau From briancolfer at comcast.net Thu Feb 10 04:14:25 2005 From: briancolfer at comcast.net (Brian Colfer) Date: Thu, 10 Feb 2005 01:14:25 -0800 Subject: How to quit a Tkinter application Message-ID: <001001c50f50$ede56000$0202a8c0@sisley> If I set up a menu item to Exit and use root.quit the application quits but I get a thread terminated abnormaly error. BTW I'm using Pmw to create the menu and items. ================================ primary email: BrianColfer at comcast.net blog: http://briancolferblog.blogspot.com/ Mobile: (415) 613-3669 -------------- next part -------------- An HTML attachment was scrubbed... URL: From gsakkis at rutgers.edu Sat Feb 5 21:24:41 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sat, 5 Feb 2005 21:24:41 -0500 Subject: Swig-friendly distutils.command.build_ext Message-ID: <36ldetF52d8abU1@individual.net> I'm using a custom extension of the build_ext distutils 'command' that integrates better with SWIG. Specifically, it: 1. Adds '-I' (include) swig option for each directory containing a source file in the given Extension. 2. Determines whether to add the '-c++" option by checking the source file extensions (even if the 'swig_cpp' and 'swig_opts' do not explicitly specify that it is a c++ wrapper). 3. Builds the swig-generated high-level python module (currently only the low level .dll/.so is built). If these changes are generally useful, I think they (c|sh)ould make it into the next release of distutils. George From mefjr75 at hotmail.com Fri Feb 4 00:03:49 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 3 Feb 2005 21:03:49 -0800 Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xy8e5jagh.fsf@ruckus.brouhaha.com> Message-ID: <1107490165.178237.169730@f14g2000cwb.googlegroups.com> Paul Rubin wrote: > Yes, good point about html tables, though I'm concerned primarily > about server response. (It's off-topic, but how do you use CSS to get > the effect of tables?) To emulate a table you use the div and span tag. (really you can do just about anything with div and span) Div is a block level tag and span isn't. You can also group them together and nest them. div and span have little meaning but the can be styled. In the CSS declaration we create styles and then just use them later as needed. Try to always focus on layout first and actual style later. (CSS is all about seperation of concerns) You will find the verbosity of CSS is not as annoying as you might think it might be, it is quite easy to learn and well worth the effort. Ok here is a bad example ( do a search on Google for CSS tables ). ( this was torn out of a webapp I am working on ) .
.
. Archive . Entry Date . .
.
. %s . %s . %s .
.
.         posted by: %s . . text . %s . .
.
And here is some of the CSS ( these are classes the dot in front of the name tells you that, when combined with div or span just about anything is possible. ) . .panel { . border: solid thin #666677; . margin: 2em 4em 2em 4em;} . .leftspaces { . letter-spacing:.5em; . text-decoration:none; . color:#EEEEff;} . .rightspaces { . letter-spacing:.5em; . position: absolute; . right: 5em; . text-decoration: none; . color:#EEEEff;} . . .archivehead { . text-indent:.5em; . background-color:#333333;} . .archivelite { . color:#777777; . text-indent:.5em; . background-color:#222222;} . .archivedark { . color:#777777; text-indent:.5em; . background-color:#111111;} . .archivelite a{ . color:#BBBBDD; . text-decortation:none; . background-color:#222222;} . .archivedark a{ . color:#BBBBDD; . text-decortation:none; . background-color:#111111;} hth, M.E.Farmer From grante at visi.com Thu Feb 17 16:10:02 2005 From: grante at visi.com (Grant Edwards) Date: 17 Feb 2005 21:10:02 GMT Subject: How to wrap a class's methods? References: <4214f167$0$44618$a1866201@visi.com> Message-ID: <4215082a$0$46531$a1866201@visi.com> On 2005-02-17, Mathias Waack wrote: > How about using a delegator: > > class Wrapper: > funcs = ("login", "list", "search") > def __init__(self, classobj): > self.__wrapped = classobj() > def __getattr__(self, attr): > if attr in Wrapper.funcs: > def f(*args): > f1 = getattr(self.__wrapped, attr) > s,r = f1(args) > if s != 'OK': raise NotOk((s,r)) > return r > return f > # raise some exception here > imap = Wrapper(imaplib.IMAP4_SSL) > > If you wrap all methods you can ignore the if-test. I'm not, and the other methods should behave "normally": class Wrapper: funcs = ("login", "list", "search") def __init__(self, classobj): self.__wrapped = classobj() def __getattr__(self, attr): if attr in Wrapper.funcs: def f(*args): f1 = getattr(self.__wrapped, attr) s,r = f1(args) if s != 'OK': raise NotOk((s,r)) return r else: f = getattr(self.__wrapped, attr) return f > PS: note that we're wrapping the instance's methods, not the class's > methods! You're right. -- Grant Edwards grante Yow! "THE LITTLE PINK at FLESH SISTERS," I saw them visi.com at th' FLUROESCENT BULB MAKERS CONVENTION... From richie at entrian.com Thu Feb 3 07:58:16 2005 From: richie at entrian.com (Richie Hindle) Date: Thu, 03 Feb 2005 12:58:16 +0000 Subject: IDLE history, Python IDE, and Interactive Python with Vim In-Reply-To: <0%oMd.102684$Jk5.10686@lakeread01> References: <0%oMd.102684$Jk5.10686@lakeread01> Message-ID: [Steve] > The history is required to be available in a chunk, to copy and paste > into a file. I see, sorry, I didn't catch that the first time round. (In PyCrust you can use Alt+LeftDrag to copy a rectangular selection - you'll still need to remove any output, but at least you can get rid of the >>> prompts in one go.) -- Richie Hindle richie at entrian.com From martin.sand.christensen at gmail.com Thu Feb 17 11:23:22 2005 From: martin.sand.christensen at gmail.com (Martin Christensen) Date: Thu, 17 Feb 2005 17:23:22 +0100 Subject: Getting milliseconds in Python References: <1108565135.167562.196830@z14g2000cwz.googlegroups.com> <37h5epF5ck38lU2@individual.net> <1108571009.698970.152020@z14g2000cwz.googlegroups.com> Message-ID: <87d5uzyx39.fsf@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >>>>> "Brian" == Brian Beck writes: Brian> Despite a millisecond being a thousandth of a second [...] A math teacher! A math teacher! My kingdom for a math teacher! Martin - -- Homepage: http://www.cs.auc.dk/~factotum/ GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.5 (GNU/Linux) Comment: Using Mailcrypt+GnuPG iEYEARECAAYFAkIUxPkACgkQYu1fMmOQldXH3QCdGcw3grK/R17kfakMBhxU1Io/ 4ukAoJl+gysL9q/6j1G8LYPZz7NawEV+ =1CNL -----END PGP SIGNATURE----- From tbunce at mac.com Tue Feb 1 13:52:45 2005 From: tbunce at mac.com (Thomas Bunce) Date: Tue, 01 Feb 2005 10:52:45 -0800 Subject: How do you do arrays Message-ID: I am new at Pyton and I am learning from book not classes so please forgive my being slow The below does not work I get an Error of File "Matrix[index] = k NameError: name 'iMatrix' is not defined" while index < majorlop1: index = index + 1 k = random.choice(listvalues) + 1 iMatrix[index] = k The book statement of array(typecode, initializer) does not make sence to me how it henerates ore relaes to the org name for the array. Thank You Tom From almad at include.cz Mon Feb 7 12:47:58 2005 From: almad at include.cz (Almad) Date: Mon, 07 Feb 2005 18:47:58 +0100 Subject: Python on WWW - beginners question: what to choose? References: Message-ID: Dan Perl wrote: > Have you looked at these links? > http://www.python.org/pycon/papers/framework/web.html > Dan Thank You, I haven't found this one...exactly what I was looking for. -- Lukas "Almad" Linhart [:: http://www.almad.net/ ::] [:: The stars are constantly shining, but often we do not see them until the dark hours. ::] [:: PGP/GNUPg key: http://www.almad.net/download/pubkey.asc ::] From jacek.generowicz at cern.ch Tue Feb 1 05:59:31 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 01 Feb 2005 11:59:31 +0100 Subject: Next step after pychecker References: <41ff0308$0$6503$636a15ce@news.free.fr> <7xis5cq5bj.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Philippe Fremy writes: > > I would like to develop a tool that goes one step further than > > pychecker to ensure python program validity. The idea would be to get > > close to what people get on ocaml: a static verification of all types > > of the program, without any kind of variable declaration. This would > > definitely brings a lot of power to python. > > You know, I've always thought that ML-style type inference is an > impressive technical feat, but why is it so important to not use > declarations? This is an aspect I've never really understood. You gain something akin to duck typing, though in a formalized way (type classes). The code works for any types which provide the features which are used in the code, without regard for the specific type. You gain generic programming. You also gain not having to clutter your code with all the type declarations. And you gain not having to decide what types you will use too early on in development. From bvande at po-box.mcgill.ca Tue Feb 22 05:04:36 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 22 Feb 2005 05:04:36 -0500 Subject: NOOB coding help.... In-Reply-To: <03f8baafb2634534c398d3ddcc476158@localhost.talkaboutprogramming.com> References: <69012ed09e48920e1e80e311bca1659c@localhost.talkaboutprogramming.com> <03f8baafb2634534c398d3ddcc476158@localhost.talkaboutprogramming.com> Message-ID: <421B03B4.30306@po-box.mcgill.ca> Igorati said unto the world upon 2005-02-22 03:51: > #This program will ask for a user to imput numbers. The numbers will then > be calculated > #to find the statistical mean, mode, and median. Finallly the user will be > asked > #if he would like to print out the answers. > numbers = [ ] > print 'Enter numbers to add to the list. (Enter 0 to quit.)' > def getint(): > return int(raw_input('Number? ')) > > numbers = sorted(iter(getint, 0)) > > numbers > [2, 3, 5, 7] > def variable_median(x): > > return sorted(x)[len(x)//2] > def variable_mode(x): > > counts = {} > for item in x: > counts[x] = counts.get(x, 0) + 1 > > return sorted(counts, key=counts.__getitem__, reverse=True)[0] > > > > s = variableMean(numbers) > y = variableMedian(numbers) > t = variableMode (numbers) > > import pickle > pickle.dump((s, y, t), file('avg.pickle', 'w')) > > > print 'Thank you! Would you like to see the results after calculating' > print 'The mode, median, and mean? (Please enter Yes or No)' > print 'Please enter Yes or No:' > > > if raw_input == yes: > > f = open("avg.py","r") > avg.py = f.read() > print 'The Mean average is:', mean > print 'The Median is:', meadian > print 'The Mode is:', mode > > > I got the error: > > Traceback (most recent call last): > File "C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py", line 9, in ? > numbers = sorted(iter(getint, 0)) > File "C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py", line 7, in > getint > return int(raw_input('Number? ')) > TypeError: 'str' object is not callable > > and this one for my if statement: > > Traceback (most recent call last): > File "C:\Python24\Lib\New Folder\Wade_StoddardSLP3-2.py", line 39, in ? > if raw_input == Yes: > NameError: name 'Yes' is not defined > > I cannot understand how I can define yes so that when they type yes the > data is printed out. Also if they type no how do I make the program do > nothing. Or is that just infered. Hi, have you tried examining the objects you are trying to put together to see why they might not fit? For instance, look what happens when you run this, entering 42 at the prompt: ri = raw_input('Gimme! ') print type(ri) print type(int(ri)) print ri == 42 print ri == '42' name_not_defined_in_this_code Does looking at the output of that help? Best, Brian vdB From miki.tebeka at zoran.com Thu Feb 3 03:31:46 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 3 Feb 2005 10:31:46 +0200 Subject: Finding user's home dir In-Reply-To: <5i9rtc.rq31.ln@orion.homeinvalid> References: <5i9rtc.rq31.ln@orion.homeinvalid> Message-ID: <20050203083122.GM2416@zoran.com> Hello Nemesis, > Hi all, I'm trying to write a multiplatform function that tries to > return the actual user home directory. > ... What's wrong with: from user import home which does about what your code does. Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From kartic.krishnamurthy at gmail.com Wed Feb 9 16:11:12 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 9 Feb 2005 13:11:12 -0800 Subject: Help: retrieving e-mail from yahoo pop server. what's wrong? In-Reply-To: References: Message-ID: <1107983472.417329.292750@l41g2000cwc.googlegroups.com> Andre, Do you have a premium Yahoo account? Only premium users can access Yahoo mail via POP3. If you are a premium account holder and it still is not working, print out your password to see if you typed the correct password. Have you tried accessing your Yahoo from an email client? Does that work? Thanks, -Kartic From simoninusa2001 at yahoo.co.uk Wed Feb 9 23:47:38 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 9 Feb 2005 20:47:38 -0800 Subject: PyQt and Python 2.4 - also WinXP LnF? References: <1108003471.242829.297030@o13g2000cwo.googlegroups.com> Message-ID: <1108010858.887829.240990@z14g2000cwz.googlegroups.com> Yeah I had a look at the Qt Free/Win project, but I think it offers me less than the current official 3.12 from BlackAdder, which is only $80 without the hassle of following those convoluted build instructions (I did try yesterday). As far as XMMS/Gtk goes, it's a remote client for XMMS, designed to be run across a network, so it doesn't really matter about using the same toolkit. Plus all the problems with XMMS seem to lie with Gtk1 (whenever it crashes, the errors always come from Gtk!) I was looking at the Gtk2 fork XMMS2, which seems to provide network control like the InetCtrl plugin for XMMS1, but I'm still not keen on Gtk as it looks so weird outside of Linux. From follower at gmail.com Tue Feb 15 02:09:03 2005 From: follower at gmail.com (Follower) Date: 14 Feb 2005 23:09:03 -0800 Subject: gui scripting References: <1108381881.828494.98340@c13g2000cwb.googlegroups.com> Message-ID: <3c18c08f.0502142309.3e52fdbe@posting.google.com> > >Second phase will have this done on a Windows platform... but that is > >second priority ... --Phil. From flupke at nonexistingdomain.com Thu Feb 10 10:33:55 2005 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 10 Feb 2005 15:33:55 GMT Subject: python equivalent to access reports Message-ID: Hi, a lot of applications here a made with access. Tables, forms, reports and the like. Now i rather use Python to do this but i'm not sure how to proceed. I can use wxPython for a gui via wxGlade for rapid testing and design (forms), MySQL as db (tables) but the report part is what's bothering me. The only semi easy way that i see is by making html files with the results in and then opening a browser to display the result. But this would lack nice printing as there is no way to cleanly start a new page. Any other ideas? Thanks, Benedict From steve at holdenweb.com Fri Feb 25 08:43:36 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 25 Feb 2005 07:43:36 -0600 Subject: xhtml-print parser In-Reply-To: References: <1109333074.548547.171090@f14g2000cwb.googlegroups.com> Message-ID: Michael Hoffman wrote: > p.nagarajkumar at gmail.com wrote: > >> my question is i have parsed the xhtml data stream using c > > > That's not a question. And this is a language for discussing > Python, not C. > Whoa, there! Ease off that trigger-finger, pardner ... >> i need to diplay the content present in the command prompt as the data >> present in the webpage as links how it can be done? > Looks like a question to me ... > > http://www.catb.org/~esr/faqs/smart-questions.html Consider that the OP might want to pass the C parser output to a Python web-content generator, which would make a deal of sense. regards Steve From martinnitram at excite.com Mon Feb 7 20:48:39 2005 From: martinnitram at excite.com (martinnitram at excite.com) Date: 7 Feb 2005 17:48:39 -0800 Subject: check socket alive Message-ID: <1107827319.700424.180790@f14g2000cwb.googlegroups.com> Dear all, following are some piece of my code (mainly create a socket connection to server and loop to receive data): # function to create and return socket def connect(): server_config = ('192.168.1.50', 3333); sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect() except socket.error: print "Failed to connect" return 0 return sock # function to receive data def recv_for_sock(sock): sock.settimeout(25) while 1: if sock is None: return 1 try: recv_data = sock.recv(65535) if recv_data: .... # do something except socket.timeout: print "Socket Timeout" time.sleep (10) pass except socket.error: print "Socket Error" time.sleep (10) pass # main function if __name__ == '__main__': sock = connect() if sock: errorno = recv_for_sock(sock) ... # other stuffs else: print "Cannot create connection" ... my question is, when the socket (create a main function) is disconnected by server (netstat status show close_wait), in "recv_for_sock" function, it can catch the timeout exception at first time. After then, the program will looping/hang within the "recv_for_sock" function (actually is the socket.recv function) and causing CPU usage to 99%. So, how to detect the socket connection is closed at this case? I tried to use exception/check socket is None but no help. Thank for helping. From irmen.NOSPAM at xs4all.nl Thu Feb 10 09:01:25 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 10 Feb 2005 15:01:25 +0100 Subject: is there a safe marshaler? Message-ID: <420b6936$0$28982$e4fe514c@news.xs4all.nl> Pickle and marshal are not safe. They can do harmful things if fed maliciously constructed data. That is a pity, because marshal is fast. I need a fast and safe (secure) marshaler. Is xdrlib the only option? I would expect that it is fast and safe because it (the xdr spec) has been around for so long. Or are there better options (perhaps 3rd party libraries)? Thanks Irmen. From claird at lairds.us Mon Feb 14 23:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 15 Feb 2005 04:08:04 GMT Subject: [EVALUATION] - E02 - Support for MinGW Open Source Compiler References: Message-ID: In article , Tim Peters wrote: >[Ilias Lazaridis] >... . . . >That leaves volunteers, or a company that wants what you want enough >to pay for it on their own (which has happened, but not often -- I >don't think it's happened since Zope Corp funded development of the >datetime module). . . . 'Depending how you categorize things, there have been a few others since then--IBM, for example, has paid non-IBM people for Python stuff IBM open-sourced. Well, maybe more than a few, now that I think about it. From bkc at Murkworks.com Mon Feb 14 18:24:36 2005 From: bkc at Murkworks.com (Brad Clements) Date: Mon, 14 Feb 2005 18:24:36 -0500 Subject: Python UPS / FedEx Shipping Module References: <4210BAF7.9030106@mediapulse.com> Message-ID: _ "Gabriel Cooper" wrote in message news:4210BAF7.9030106 at mediapulse.com... > > >Are the modules just accessing the published apis for their webservices? > Yes, they use the free API's that have always been freely available. > They're just *Impossible* to find on either of UPS's OR FedEx's > websites. It took me no less than an hour and likely more just to find > the documentation pages on each site. As for putting them up on the web, > I should be able to get them up by the end of the week. > If you downloaded the documentation from UPS, please re-check your license agreement for the documentation before posting the code. You might be in violation of some terms and conditions. I say might, I do not know for certain and am not hinting that you are violating anything. I've been tracking through UPS for 4 years using their old crappy interface, and a newer one, and now we've moved to the XML version. All of their documents come with a click - through license agreement that probably restricts you in some way. I haven't read them too closely, since I'm under contract I say "yes" on behalf of my client. ;-) -- Novell DeveloperNet Sysop #5 From cpl.19.ghum at spamgourmet.com Wed Feb 9 16:13:07 2005 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Wed, 9 Feb 2005 21:13:07 +0000 (UTC) Subject: overwriting method in baseclass References: Message-ID: marc, >> So HOW can SVN be of any use for THIS prob? > > Take a look at the Subversion documentation (the "book") and search > for `Vendor branches`. > [...] > The section deals specifically with the situation how to manage 3rd > party source code with subversion which you want to update from time > to time and even apply some modifications. thank you very much for pointing this out! I did not even dare to hope to find sth. of this kind with a rcs for MY software. So I did not even start searching. Thank you, Harald From serpent17 at gmail.com Sat Feb 19 16:57:33 2005 From: serpent17 at gmail.com (serpent17 at gmail.com) Date: 19 Feb 2005 13:57:33 -0800 Subject: controlling a qbasic program on a windows98 or example of rs-232 commanded through python Message-ID: <1108850253.479488.78650@l41g2000cwc.googlegroups.com> Hello, Can python be installed on a win98 system ? if so, how do I control a qbasic program from python ? the qbasic program controls input to an RS-232 so I am enclined to follow the win98 system + qbasic route in order to be quick, or I guess the question could be, can I control a device through rs-232 from a newer version of windows using python (actually for the last part of the question I know this is feasible, but I 'd like to see an example, any pointers ?) Thanks for any insight, Jake. From aleaxit at yahoo.com Thu Feb 10 03:59:41 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 10 Feb 2005 09:59:41 +0100 Subject: Vectors in Visual Python References: <1107944975.498403.225950@f14g2000cwb.googlegroups.com> <1grqqa2.1cnkkbv1l5mrrxN%aleaxit@yahoo.com> Message-ID: <1grrgt7.rje1681dh98itN%aleaxit@yahoo.com> Arthur wrote: > thinking that the visciousness with wihich you were attacking someone > suggesting a proposal for an optional feature - even if an iill > adivised proposal for and ill advised optional feature (I frankly > don't care much about that part of the discussion one way or another) While in my case it's essentially ALL that I care about in this discussion: the technical aspects of Python. > - was unwarranted, and more importantly *unwise* for someone in a If, like you, I didn't care about the technical aspects of Python, it sure would be unwise to get upset -- I could let the language go to hell in a handbasket, as long as I made sure I looked good myself. Caring deeply and passionately about something greater than oneself, particularly something which may seem dry and abstract to those who don't care a whit for it, might no doubt be deemed intrinsically unwise -- and yet, there is much to be said for such passion. Without the ability to get passionate and inflamed, we might perhaps be wiser, but we'd be Vulcans, not humans. Moreover, unless some of us felt such passion for certain technical issues, you guys who don't care would not get the benefits of the time and energy we freely devote to them -- so it's unwise, even from a strictly selfish viewpoint, to try to turn us firebrands into such coolly calculating Vulcans. > postion of community leadership - considering past, recent, and > undoubtedly future issues that have and will arise. > > What don't *you* understand about that?? Could you _really_ believe, considering the many years of consistent history of my posts on this group, that by reviving the issue you could get *any* other effect but fanning the flames all over again? THAT is what I don't understand: whether you're doing that _deliberately_, or out of almost-unbelievable levels of cluelessness. > We all have are own kinds of stupidities, it seems to me. This is no doubt the case. For example, many of us instinctively brake and swerve when a small animal jumps into the road in front of the car they're driving, seriously endangering themselves and the passengers thereby. If we were presented the issue in a context giving us time to reflect and react rationally -- "To how much danger to life and limb would you subject yourself, your wife, and your children, to increase the likelihood of survival for some stupid cat who can't wait to cross the road?" -- we'd probably react quite differently. And yet, while it IS objectively stupid to behave that way, it _is_ one of the stupidities that make us human. A _deliberate_ and consistent preference can be disagreed with, but it's pretty pointless to call it "stupid" or "unwise"; there is just no accounting for tastes. If you _prefer_ the flame about declarations to continue for its own sake (or because you believe it makes you look good, whatever), while not caring about its contents, I may consider that evil and hateful, but it's neither intelligent nor stupid _per se_. If your preferences are otherwise, and yet your behavior is easily seen to be such as to have that effect, then THIS is indeed very stupid. Alex From fperez.net at gmail.com Fri Feb 4 02:18:21 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Fri, 04 Feb 2005 00:18:21 -0700 Subject: exporting mesh from image data References: Message-ID: John Hunter wrote: > > I am trying to generate a mesh for a finite volume solver (gambit, > fluent) from 3D image data (CT, MRI). To generate the fluent msh > file, you need not only a list of vertices and polygons, much like > what is available in the vtk file format, but also the volume elements > in the mesh that the polygons abut. Eg for a given triangle in the > mesh, you would have a line like [...] I hope you posted this on the VTK list with a CC to Prabhu as well... The hopes of a positive reply there are, I suspect, a fair bit higher. The scipy list would be a good idea, too. I don't have an answer, but I recall seeing something about a finite volume solver implemented in python recently. Interestingly, a quick googling on those terms turned this up: http://math.nist.gov/mcsd/Seminars/2005/2005-03-01-wheeler.html Note the March 1 Boulder meeting :) (the coordinated times suggest a videoconference of sorts). I'll most likely attend the talk, let me know if you still don't have a solution by then and I can try to talk to Wheeler (if he's physically here instead of in Gaithesburg). For all we know, their code might provide an implementation, have a look (I'd be quite interested in your opinion if you've already looked at it). Cheers, f From jelleferinga at gmail.com Tue Feb 1 13:07:07 2005 From: jelleferinga at gmail.com (jelle) Date: 1 Feb 2005 10:07:07 -0800 Subject: pythonic equivalent of Mathematica's FixedPoint function In-Reply-To: References: <1107273234.276714.272890@z14g2000cwz.googlegroups.com> Message-ID: <1107281227.147853.144520@c13g2000cwb.googlegroups.com> Ah, i see, that clears up the monetary context. Thank you for your FixedPoint example. Can i help myself out by mentioning that the most simple things are always most difficult ;-) Thanks, Jelle. From bvande at po-box.mcgill.ca Thu Feb 24 12:07:47 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu, 24 Feb 2005 12:07:47 -0500 Subject: Selective HTML doc generation In-Reply-To: <1109238843.901331.224580@g14g2000cwa.googlegroups.com> References: <1109169752.819253.202930@o13g2000cwo.googlegroups.com> <1109238843.901331.224580@g14g2000cwa.googlegroups.com> Message-ID: <421E09E3.8010701@po-box.mcgill.ca> Graham Ashton said unto the world upon 2005-02-24 04:54: > Thanks Brian, much appreciated. Looks quite straightforward. > > Graham > Hi Graham, glad it helped -- I think this marks the first time I've given a useful answer to a non-trivial question on comp.lang.python. :-) G: > Hi. I'm looking for a documentation generation tool (such as pydoc, > epydoc, happydoc, etc.) that will allow me to filter what it includes > in it's output. > > I only want the reader to know about classes and methods in my package > if if the classes have docstrings. B: Pointed Graham to to the visiblename function of pydoc.py, where I recently made a small change to get it to display `private' methods, and hypothesized that would be where he'd want to start in order to modify pydoc to meet his needs. Before I responded, I tried for a bit to write the code to filter for only those objects with docstrings like you wanted. I'm fairly new to programming and wasn't able to work out exactly what code is needed. (My skill level is such that it isn't quite so straight-forward to me :-) Would you be willing to post what you did to make it work? I think I'd learn something, having bounced off when making a (gentle) push on the problem. Best, Brian vdB From tmj at SPAMLESSjarmania.com Sun Feb 27 13:55:13 2005 From: tmj at SPAMLESSjarmania.com (Tim Jarman) Date: Sun, 27 Feb 2005 18:55:13 +0000 Subject: Need help running external program References: Message-ID: <38ejcfF5lu11pU1@individual.net> Rigga wrote: > Pink wrote: > >> Rigga wrote: >> >>> Hi, >>> >>> I am running the line of code below from a shell script and it works >>> fine, however I am at a total loss on how i can run it from within a >>> Python script as every option I have tried fails and it appears to be >>> down to the escaping of certain characters. >>> >>> wget -q www.anywebpage.com -O - | tr '\r' '\n' | tr \' \" | sed -n >>> 's/.*url="\([^"]*\)".*/\1/p' >> If your problem is getting a python string without worrying about how to >> escape the escape sequences, try: >> >> r"""wget -q www.anywebpage.com -O - | tr '\r' '\n' | tr \' \" | sed -n >> 's/.*url="\([^"]*\)".*/\1/p'""" >> >> You should be able to pass this directly to a popen() function. > > Hi, > > Thanks for replying however I have just tried that and it does not seem to > work, it doesnt return any results (i take it the r was a typo) > > Thanks > > RiGGa No, the r was the point - it's there to tell Python not to do any escaping on the string. Try it again with the r and see what happens. -- Website: www DOT jarmania FULLSTOP com From usenet_spam at janc.invalid Fri Feb 4 06:33:27 2005 From: usenet_spam at janc.invalid (JanC) Date: Fri, 04 Feb 2005 11:33:27 GMT Subject: OT: why are LAMP sites slow? References: <7x8y65kwfl.fsf@ruckus.brouhaha.com> <7xy8e5jagh.fsf@ruckus.brouhaha.com> <1107490052.542546.285950@c13g2000cwb.googlegroups.com> <7xekfwc19i.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schreef: > I don't know that the browser necessarily renders that faster than it > renders a table, Simple tables aren't slow, but tables-in-tables-in-tables-in-tables-in- tables are. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From steven.bethard at gmail.com Fri Feb 11 18:26:02 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 11 Feb 2005 16:26:02 -0700 Subject: pre-check for string-to-number conversion In-Reply-To: <1108163692.700703.183870@o13g2000cwo.googlegroups.com> References: <1108163692.700703.183870@o13g2000cwo.googlegroups.com> Message-ID: 18k11tm001 at sneakemail.com wrote: > I am reading an ASCII data file and converting some of the strings to > integers or floats. However, some of the data is corrupted and the > conversion doesn't work. I know that I can us exceptions, but they > don't seem like the cleanest and simplest solution to me. You should reconsider this thought. It's quite clean and fast: for s in get_ASCII_strings_from_data_file(): try: f = float(s) except ValueError: do_whatever_you_need_to_do_for_invalid_data() > I would like to simply perform a pre-check before I do the > conversion, but I can't figure out how to do it. Again, this is the less Pythonic approach, but one option would be to use regular expressions: matcher = re.compile(r'[\d.]+') for s in get_ASCII_strings_from_data_file(): if matcher.match(s): f = float(s) else: do_whatever_you_need_to_do_for_invalid_data() but note that this won't except valid floats like '1e10'. You'll also note that this is actually less concise than the exception based approach. Steve From noah at noah.org Fri Feb 18 20:58:31 2005 From: noah at noah.org (noah at noah.org) Date: 18 Feb 2005 17:58:31 -0800 Subject: Can I get message filename from a Maildir mailbox stream? Message-ID: <1108778311.300124.56920@f14g2000cwb.googlegroups.com> Is there a way to figure out what filename an email object points to in a qmail style Maildir directory? Hmmm... I don't think so, but I'm hoping I wrong. I instantiated a Maildir mailbox and I'm iterating through the messages. When I find a special message I want to move it or delete it or something. Yours, Noah From roy at panix.com Sun Feb 6 09:56:59 2005 From: roy at panix.com (Roy Smith) Date: Sun, 06 Feb 2005 09:56:59 -0500 Subject: Python versus Perl ? References: <1107695949.247611.272800@g14g2000cwa.googlegroups.com> Message-ID: surfunbear at yahoo.com wrote: > I've read some posts on Perl versus Python and studied a bit of my > Python book. > > I'm a software engineer, familiar with C++ objected oriented > development, but have been using Perl because it is great for pattern > matching, text processing, and automated testing. Our company is really > fixated on risk managnemt and the only way I can do enough testing > without working overtime (which some people have ended up doing) is by > automating my testing. That's what got me started on Perl. Automated testing is essential in almost any software project, and not just to make sure you don't have to work overtime. > I've read that many people prefer Python and that it is better than > Perl. However, I want to ask a few other questions. Keep in mind that this is a somewhat biased audience to ask a question like that. For the most part, c.l.p. is inhabited by rabid Pythonistas :-) > 1. Perl seems to have alot of packaged utilities available through > CPAN, the comprehensive perl network. There is no doubt that there's a lot of stuff on CPAN, and the architecture of the repository makes it relatively easy to find what you want and get it running. On the other hand, there are a lot of add-on modules for Python too. You mention DBI; Python's version of that is the DB-API, and there are quite a few modules that implement it (http://www.python.org/topics/database/modules.html). > Perl also has excellent pattern matching compared to > sed, not sure about how Python measures up, > but this seems to make perl ideally suited to text processing. As far as regular espressions themselves, Python supports exactly the same regex syntax that Perl does. The packaging is a little different; instead of being built-in to the language, it's a module you import and use in an object-oriented way. > 2. Python is apparantly better at object oriented. Perl has some kind > of name spacing, I have used that in a limited way. Does Perl use a > cheap and less than optimal Object oriented approach? Python's OO support was designed-in from the ground up. Perl's is an ugly wart held on with duct tape. > That was what someone at work said, he advocates Python. > Is it likely that Perl will improve it's object oriented features > in the next few years ? There is a "Perl 6" project going on, which I imagine will have some major changes to the language, but you'll have to ask the Perl people about that. > 3. Perl is installed on our system and alot of other systems. > You don't have to make sys admins go out of there way to make it > available. It's usualy allready there. Python now comes standard with a lot of operating systems, but it is certainly true that if there is one lingua franca in the computer world (and certainly the Unix world), Perl is it. If your prime motivation is portability, that might be the feature which tips the balance in favor of Perl. > I also did a search of job > postings on a popular website. 108 jobs where listed that require > knowledge of Perl, only 17 listed required Python. Becomeing more > familiar with Perl might then be usefull for ones resume? There is no doubt that most employers expect you to know Perl. Even if it's not on the job spec, there's enough Perl out there in the world that it really is worth knowing. If your career goal is sysadmin rather than programming, then I'd say Perl is absolutely essential to know. > If Python is better than Perl, I'm curious how really significant > those advantages are? Well, now we're back to that biased audience stuff again. My answer is that of course it's better. The biggest advantage of Python is that it has a clean syntax with designed-in support of OOP. Perl's basic syntax is a jumble of stuff stolen from shell, awk, sed, and grep, with some vague OO ideas glommed onto it. The heavy reliance on punctuation makes it almost impossible to read. My suggestion is to learn Python, then make up your own mind. Grab one of the tutorials available on-line and spend an afternoon getting the basics down. Next step, pick a small real-life project and invest a couple of days doing it in Python. By then, you should have a better idea of whether it's worth investing some more time to get deeper into it. One you know C++, Perl, and Python, you'll have exposure to a pretty broad range of programming paradigms. But, don't stop there. If your goal is to be a professional programmer, keep learning languages. Learn some because they'll provide a paycheck, learn others because they'll expose you to different ideas. In today's world, I'd put Java, SQL, VB, and C# in the "paycheck" group. I'd put Lisp, Smalltalk, and Postscript in the "personal improvement" group. Things like Python, Tcl, and Ruby fall somewhere in-between; they're interesting because they explore different corners of the "how to design a programming language" universe, but they also have a reasonable chance of being a skill which will keep the paychecks flowing. From skip at mojam.com Wed Feb 2 13:45:35 2005 From: skip at mojam.com (Skip Montanaro) Date: Wed, 2 Feb 2005 12:45:35 -0600 Subject: Python Code Auditing Tool In-Reply-To: References: <7xhdkvbjab.fsf@ruckus.brouhaha.com> Message-ID: <16897.8143.800947.266849@montanaro.dyndns.org> >> 246 ValueError >> 227 aetools.Error >> 216 Error >> 124 TypeError >> 101 error >> 75 RuntimeError >> 53 IOError >> 36 NotImplementedError >> 36 ImportError >> 36 EOFError >> 31 SyntaxError >> 23 KeyError >> 23 AttributeError >> 22 DistutilsPlatformError >> 21 UnicodeError Roy> It's kind of interesting (scarry?) that in roughly 20% of the cases Roy> nothing more specific than Error is raised. Not really. You might have code in a module named mod like this: class Error(Exception): pass then later: def foo(...): ... blah blah blah ... if condition: raise Error, "hey dummy!" The caller might look like: import mod ... try: mod.foo() except mod.Error, msg: print msg That said, the tendency for many newer modules seems to be to discriminate exceptions based on type (look at urllib2 for example) while older modules tended to have just a single exception they raised (look at ftplib). I suspect that has something to do with whether the module was originally written before or after Python introduced class exceptions. Skip From peter at somewhere.com Mon Feb 14 04:11:14 2005 From: peter at somewhere.com (Peter Maas) Date: Mon, 14 Feb 2005 10:11:14 +0100 Subject: For American numbers In-Reply-To: References: <420e7376$1@nntp0.pdx.net> <420fb4e6$0$16575$9b622d9e@news.freenet.de> Message-ID: <37b8dfF5anl9bU1@individual.net> Dave Brueck schrieb: > Multiple definitions aside, "kilo" and "mega" are far too entrenched - > even if I could manage to say "kibibyte" with a straight face, I'd get > nothing but blank stares in return. This kibi-mebi thing will probably fail because very few can manage to say "kibibyte" with a straight face :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From rparnes at megalink.net Wed Feb 9 17:58:11 2005 From: rparnes at megalink.net (Bob Parnes) Date: Wed, 09 Feb 2005 22:58:11 -0000 Subject: User Identification References: Message-ID: On Tue, 08 Feb 2005 12:29:48 -0000, Bob Parnes wrote: > I have a python program on a server of an all-linux network. It needs to > record the user name running it. Is there a way for the program to extract > the name from the system without a separate log-in dialog? > > Bob Parnes Thanks very much. Had not realized there were so many possibilities. Bob Parnes -- Bob Parnes rparnes at megalink.net From tjreedy at udel.edu Mon Feb 14 23:19:28 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Feb 2005 23:19:28 -0500 Subject: Iterator / Iteratable confusion References: <420a5c1e$0$21630$a1866201@visi.com><200502131848.03655.francis.girard@free.fr> <200502131958.27410.francis.girard@free.fr> Message-ID: "Michael Spencer" wrote in message news:cuooip$1pd$1 at sea.gmane.org... > Terry Reedy wrote: >> iter(iterator) is iterator is part of the iterater protocol > But, notwithstanding the docs, it is not essential that > iter(iterator) is iterator If a program depends on that invariant, then it is essential for that program. Leaving such programs aside, I interpret this and your example together as saying three things: 1. "There is more than one possible definition of 'iterator'." Yes. Python could have defined many things differently. But I think it important to have a clear definition of iterator (and other things) so one can reason about program behavior. 2. "It is not essential to not do something wasteful as long as it is otherwise inconsequential." Usually true, but I don't see this as clarifying the relationship between iterables and iterators in Python. (I am assuming that your example is only meant to illustrate possibilities rather than usefulness.) 3. "You can substitute a copy of an object that is never mutated for the object itself." True, as long as you do not look at the id. But in practice, change of state is essential to the function of nearly all iterators. For mutated objects, one has to add the proviso that the copy is current and the substitution total, so that there are no references left to the original. But again, this has nothing in particular to do with iteration. > >>> class A(object): > ... def __iter__(self): > ... return AnIterator() > ... > >>> class AnIterator(object): # an iterator that copies itself By the narrower definition of iterator that I used, this is not an iterator. Also, the replacement is only a copy if the instance has not been mutated. Is your broader definition limited to return of initialized copies or would it allow other things also? > ... def next(self): > ... return "Something" > ... def __iter__(self): > ... return AnIterator() The second def statement is equivalent (except for identity) to __iter__ = A.__iter__ To illustrate the point about mutation with a simple toy example: a = A() a.doc = 'My iterator' b = iter(a) b is not a copy of a as it is, but only as it was initially. Terry J. Reedy From kent3737 at yahoo.com Sat Feb 5 21:12:29 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Sat, 05 Feb 2005 21:12:29 -0500 Subject: changing local namespace of a function In-Reply-To: References: <4204400C.5060608@iinet.net.au> Message-ID: <42057a48$1_2@newspeer2.tds.net> Bo Peng wrote: >> Exec is slow since compiling the string and calls to globals() use a >> lot of time. The last one is most elegant but __getattr__ and >> __setattr__ are costly. The 'evil hack' solution is good since >> accessing x and y takes no additional time. > > > Previous comparison was not completely fair since I could pre-compile > fun2 and I used indirect __setattr__. Here is the new one: > >>> # solution two: use exec > ... def makeFunction(funcStr, name): > ... code = compile(funcStr, name, 'exec') > ... def f(d): > ... exec code in d > ... return f > ... > >>> def fun2(d): > ... myfun = makeFunction('z = x + y', 'myfun') > ... for i in xrange(0,N): > ... myfun(d) > ... del d['__builtins__'] You are still including the compile overhead in fun2. If you want to see how fast the compiled code is you should take the definition of myfun out of fun2: myfun = makeFunction('z = x + y', 'myfun') def fun2(d): for i in xrange(0,N): myfun(d) del d['__builtins__'] Kent From jfj at freemail.gr Mon Feb 7 02:41:05 2005 From: jfj at freemail.gr (jfj) Date: Sun, 06 Feb 2005 23:41:05 -0800 Subject: Confused with methods In-Reply-To: References: Message-ID: <42071B91.5050901@freemail.gr> Diez B. Roggisch wrote: > If things worked as you wanted it to, that would mean that passing a bound > method as argument to a class and storing it there to an instance variable > that would "eat up" the arguments - surely not the desired behaviour. Could you please give an example of this ? If you mean: class A: def f(x): print x class B: pass a=A() B.f = a.f b=B() b.f() #surprise: it works!! then that is equally "weird" as my case. In fact is seems more appropriate to use a.f.im_func in this case to "convert the bound method to an unbound one". Maybe this happens more often though? Thanks, G. From roman.yakovenko at gmail.com Tue Feb 8 07:43:26 2005 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 8 Feb 2005 14:43:26 +0200 Subject: Choosing the right parser for parsing C headers In-Reply-To: References: <1107861023.254610.14310@g14g2000cwa.googlegroups.com> <1107865641.937691.282930@g14g2000cwa.googlegroups.com> Message-ID: <7465b61705020804432e738790@mail.gmail.com> try http://sourceforge.net/projects/pygccxml There are a few examples and nice ( for me ) documentation. Roman On Tue, 8 Feb 2005 13:35:57 +0100, Fredrik Lundh wrote: > Jean de Largentaye wrote: > > > GCC-XML looks like a very interesting alternative, as Python includes > > tools to parse XML. > > The mini-C compiler looks like a step in the right direction for me. > > I'm going to look into that. > > I'm not comfortable with C++ yet, and am not sure how I'd use Pyste. > > to clarify, Pyste is a Python tool that uses GCCXML to generate bindings; it might > not be something that you can use out of the box for your project, but it's definitely > something you should study, and perhaps borrow implementation ideas from. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From jdhunter at ace.bsd.uchicago.edu Thu Feb 3 12:27:02 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 03 Feb 2005 11:27:02 -0600 Subject: exporting mesh from image data Message-ID: I am trying to generate a mesh for a finite volume solver (gambit, fluent) from 3D image data (CT, MRI). To generate the fluent msh file, you need not only a list of vertices and polygons, much like what is available in the vtk file format, but also the volume elements in the mesh that the polygons abut. Eg for a given triangle in the mesh, you would have a line like 3 3 2 1 11 0 which is numfaces vert0 vert1 vert2 vol1 vol2 where vol1 and vol2 are indices that indicate the volume in the mesh that the triangle belongs to (vol2 is 0 for triangles on the surface). The specific problem at hand involves building a mesh for ventricles in the brain. I have no trouble building the isosurface that surrounds the ventricles using the marching cubes and connectivity filters in VTK, but now need to be able to generate a mesh over the interior and assign volumes to faces. Does such capability exist in VTK? and if so I would be thankful for pointers to class docs or examples. Are there other algorithms in the world of python 3D libraries that can provide 3D meshes for 2D surface isocontours, assigning volume elements from the mesh to the surfaces that surround the volume. Thanks! JDH From skip at pobox.com Fri Feb 11 13:00:58 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 11 Feb 2005 12:00:58 -0600 Subject: is there a safe marshaler? In-Reply-To: <3b091a1c.0502110634.5edb1987@posting.google.com> References: <420b6936$0$28982$e4fe514c@news.xs4all.nl> <420b6e98$0$23018$626a14ce@news.free.fr> <420b9135$0$28982$e4fe514c@news.xs4all.nl> <3b091a1c.0502110634.5edb1987@posting.google.com> Message-ID: <16908.62170.778888.249227@montanaro.dyndns.org> Carl> but can't effbot's fast cElementree be used for PYROs XML_PICKLE Carl> and would it be safe and fast enough? It's not clear to me that if marshal is unsafe how XML could be safe. In this context they are both just serializations of basic Python data structures. Skip From martin.sand.christensen at gmail.com Thu Feb 17 11:49:53 2005 From: martin.sand.christensen at gmail.com (Martin Christensen) Date: Thu, 17 Feb 2005 17:49:53 +0100 Subject: Getting milliseconds in Python References: <1108565135.167562.196830@z14g2000cwz.googlegroups.com> <37h5epF5ck38lU2@individual.net> <1108571009.698970.152020@z14g2000cwz.googlegroups.com> <87d5uzyx39.fsf@gmail.com> Message-ID: <871xbfyvv2.fsf@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >>>>> "Brian" == Brian Beck writes: Brian> Man, this is the hottest topic on c.l.py since that Lazaridis Brian> guy... ... which was really the point of my joke, even if it did belly flop somewhat. This whole discussions brought to mind a cartoon where a group of doctors were performing open heart surgery. One of them says, "Okay, how many of us believe that the heart has _four_ chambers?," and a few of the others raise their hands. I intended it as a 'let's call in the professors to determine if 2+2=4', but, well... :-) Martin - -- Homepage: http://www.cs.auc.dk/~factotum/ GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.5 (GNU/Linux) Comment: Using Mailcrypt+GnuPG iEYEARECAAYFAkIUyzAACgkQYu1fMmOQldWVdACdHLxtUi4TtFCl0ZW6wf65Hu9M ioMAoMWAHrkS5lhQw5V0cJXVO1nk76MO =6MXl -----END PGP SIGNATURE----- From alexander.dietz at mpi-hd.mpg.de Wed Feb 2 16:27:49 2005 From: alexander.dietz at mpi-hd.mpg.de (alex) Date: 2 Feb 2005 13:27:49 -0800 Subject: Basic file operation questions Message-ID: <1107379669.870799.256030@g14g2000cwa.googlegroups.com> Hi, I am a beginner with python and here is my first question: How can I read the contents of a file using a loop or something? I open the file with file=open(filename, 'r') and what to do then? Can I use something like for xxx in file: .... Thanks for help Alex From zerok at zerokspot.com Tue Feb 22 13:36:38 2005 From: zerok at zerokspot.com (Horst Gutmann) Date: Tue, 22 Feb 2005 19:36:38 +0100 Subject: Problem with minidom and special chars in HTML In-Reply-To: References: <421b5b8c$1@news.uni-klu.ac.at> Message-ID: <421b7b67$1@news.uni-klu.ac.at> Fredrik Lundh wrote: > umm. doesn't that doctype point to an SGML DTD? even if minidom did fetch > external DTD's (I don't think it does), it would probably choke on that DTD. > > running your documents through "tidy -asxml -numeric" before parsing them as > XML might be a good idea... > > http://tidy.sourceforge.net/ (command-line binaries, library) > http://utidylib.berlios.de/ (python bindings) > > > > > Thanks, but the problem is, that I can't use the numeric representations of these special chars. I will probably simply play find&replace before feeding the document into minidom and change the output back afterwards :-) MfG, Horst From marian at mba-software.de Wed Feb 2 05:56:44 2005 From: marian at mba-software.de (=?ISO-8859-1?Q?Marian_Aldenh=F6vel?=) Date: Wed, 02 Feb 2005 11:56:44 +0100 Subject: Printing Filenames with non-Ascii-Characters In-Reply-To: <42009f9b$0$238$edfadb0f@dread12.news.tele.dk> References: <36a3ikF4uk8r0U1@individual.net> <36bka5F4vp17cU1@individual.net> <42009f9b$0$238$edfadb0f@dread12.news.tele.dk> Message-ID: <36bpvmF4vri6jU1@individual.net> Hi, > Have you set the coding cookie in your file? Yes. I set it to Utf-8 as that's what I use for all my development. > Try adding this as the first or second line. > > # -*- coding: cp850 -*- > > Python will then know how your file is encoded That is relevant to the encoding of source-files, right? How does it affect printing to standard out? If it would I would expect UTF-8 data on my console. That would be fine, it can encode everything and as I have written in another posting in my case garbled data is better than termination of my program. But it uses 'ascii', at least if I can believe the error message it gave. Ciao, MM -- Marian Aldenh?vel, Rosenhain 23, 53123 Bonn. +49 228 624013. http://www.marian-aldenhoevel.de "There is a procedure to follow in these cases, and if followed it can pretty well guarantee a generous measure of success, success here defined as survival with major extremities remaining attached." From roy at panix.com Tue Feb 1 09:47:04 2005 From: roy at panix.com (Roy Smith) Date: Tue, 01 Feb 2005 09:47:04 -0500 Subject: PyCon signature advertising References: Message-ID: In article , "Mike C. Fletcher" wrote: > Steve Holden wrote: > ... > > > I appreciate that not everyone has control over their .sig, > > ... > > Take control of your sigs, my sisters and brothers! Viva la > Revolution! Follow the Steve into the heat and light of PyCon. You can > achieve enlightenment if only you go to the District on the Eastern Edge > of the new continents when the spring arrives. It is only there that > all will be revealed. It is only there that you shall find peace. > > Joy to the Python world! > Mike And the smallest child asked: Why is this language different from all other languages?. In all other languages, we are driven to declare our variables in a static manner, as surely as the compiler compels us to know their types ahead of time, and be forced to invoke the power of the reinterpret_cast whenever we need to deviate from the straight path laid out for us. Why do we not in this language? In all other languages, we may indent as we please, depending on the twin angels of the curly-brace and the semicolon to discern the true meaning from the meanderings of our code across the pages of our printouts. Why do we indent with tabs as rigidly as the rows of corn in our fields in this language? In all other languages, we omit explicit references to self, trusting to context to determine the scope of our variables. Why in this language do we speak our own name with overbearing monotony each time we refer to an instance variable? In all other languages, we are forced to choose between object orientation and procedural code and bear the burden of our choice all through the long days of the project lifecycle. Why in this language are we free to mix paradigms, even to the point of using functional programming constructs only whenever they seem cool and useful without fear of retribution from the methodology police? Then the smallest child was silent, and the old man began to speak. From rbt at athop1.ath.vt.edu Fri Feb 4 14:43:30 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Fri, 04 Feb 2005 14:43:30 -0500 Subject: string issue In-Reply-To: <36QMd.103084$Jk5.36127@lakeread01> References: <36QMd.103084$Jk5.36127@lakeread01> Message-ID: Steve Holden wrote: > rbt wrote: > >> Either I'm crazy and I'm missing the obvious here or there is >> something wrong with this code. Element 5 of this list says it doesn't >> contain the string 255, when that's *ALL* it contains... why would it >> think that??? >> >> import time >> >> ips = ['255.255.255.255', '128.173.120.79', '198.82.247.98', >> '127.0.0.1', '255.0.0.0', '255', '128.173.255.34'] >> >> for ip in ips: >> if '255' in ip: >> try: >> print "Removing", ip >> ips.remove(ip) >> except Exception, e: >> print e >> >> print ips >> time.sleep(5) >> >> Someone tell me I'm going crazy ;) > > > You are modifying the list as you iterate over it. Instead, iterate over > a copy by using: > > for ip in ips[:]: > ... > > regards > Steve Very neat. That's a trick that everyone should know about. I vote it goes in Dr. Dobbs newsletter. From fperez.net at gmail.com Fri Feb 4 20:27:04 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Fri, 04 Feb 2005 18:27:04 -0700 Subject: IPython colors in windows References: <1107487113.732375.110850@c13g2000cwb.googlegroups.com> <36hculF51ho2sU1@individual.net><1107530489.308497.103530@g14g2000cwa.googlegroups.com><36hrjpF4ui8fbU1@individual.net> <36i84qF52ce29U1@individual.net> Message-ID: Ashot wrote: > whoa, that was quick, looks like it works for me. Thanks a lot! > It would be nice to be able to set the colors in the prefs file, although > its possible to edit the pyColorize file as Claudio mentioned. Yes, I haven't implemented user-definable color schemes. Not impossible, but not a priority at the moment (much bigger fish to fry). Sorry 'bout that (patches welcome, though). Regards, f From reinhold-birkenfeld-nospam at wolke7.net Mon Feb 7 14:41:36 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 07 Feb 2005 20:41:36 +0100 Subject: python code with indention In-Reply-To: <1107805151.265680.165380@o13g2000cwo.googlegroups.com> References: <1107805151.265680.165380@o13g2000cwo.googlegroups.com> Message-ID: <36pujcF55i71cU1@individual.net> Xah Lee wrote: > is it possible to write python code without any indentation? Yes. Reinhold From db3l at fitlinxx.com Wed Feb 23 10:52:53 2005 From: db3l at fitlinxx.com (David Bolen) Date: 23 Feb 2005 10:52:53 -0500 Subject: print and str subclass with tab in value Message-ID: I ran into this strange behavior when noticing some missing spaces in some debugging output. It seems that somewhere in the print processing, there is special handling for string contents that isn't affected by changing how a string is represented when printed (overriding __str__). For example, given a class like: class mystr(str): def __new__(cls, value): return str.__new__(cls, value) def __str__(self): return 'Test' you get the following behavior >>> x = strtest.mystr('foo') >>> print x,1 Test 1 >>> print repr(x),1 'foo' 1 >>> x = strtest.mystr('foo\t') >>> print x,1 Test1 >>> print repr(x),1 'foo\t' 1 Note the lack of a space if the string value ends in a tab, even if that tab has nothing to do with the printed representation of a string. It looks like it's part of basic string output since with a plain old string literal the tab gets output (I've replaced the literal tab with [TAB] in the output below) but no following string. >>> x = 'testing\t' >>> print x,1 testing[TAB]1 >>> x = str('testing\t') >>> print x,1 testing[TAB]1 so I'm guessing it's part of some optimization of tab handling in print output, although a quick perusal of the Python source didn't have anything jump out at me. It seems to me that this is probably a buglet since I would expect print and its softspace handling to depend on what was actually written and not internal values - has anyone else ever run into this. -- David From ncoghlan at iinet.net.au Mon Feb 7 07:34:54 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 07 Feb 2005 22:34:54 +1000 Subject: empty classes as c structs? In-Reply-To: <9rmdnVR1lr-LYJvfRVn-gg@comcast.com> References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <1gric2n.17myhon1hfrc6gN%aleaxit@yahoo.com> <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> <9rmdnVR1lr-LYJvfRVn-gg@comcast.com> Message-ID: <4207606E.4040806@iinet.net.au> Steven Bethard wrote: > It was because these seem like two separate cases that I wanted two > different functions for them (__init__ and, say, dictview)... The other issue is that a namespace *is* a mutable object, so the default behaviour should be to make a copy (yeah, I know, I'm contradicting myself - I only just thought of this issue). So an alternate constructor is definitely the way to go. I think Michael's implementation also fell into a trap whereby 'E' couldn't be used as an attribute name. The version below tries to avoid this (using magic-style naming for the other args in the methods which accept keyword dictionaries). To limit the special casing in update, I've switched to only using __dict__ for the specific case of instances of namespace (otherwise the semantics are too hard to explain). This is to allow easy copying of an existing namespace - for anything else, invoking vars() is easy enough. And I was reading Carlos's page on MetaTemplate, so I threw in an extra class "record" which inherits from namespace and allows complex data structures to be defined via class syntax (see the record.__init__ docstring for details). That bit's entirely optional, but I thought it was neat. Finally, I've just used normal names for the functions. I think the issue of function shadowing is best handled by recommending that all of the functions be called using the class explicitly - this works just as well for instance methods as it does for class or static methods. Cheers, Nick. +++++++++++++++++++++++++++++++++++++++++++++ from types import ClassType class namespace(object): """ namespace([namespace|dict]) => object namespace objects provide attribute access to their __dict__ Complement of vars: vars(object) => object.__dict__ Non-magic methods should generally be invoked via the class to avoid inadvertent shadowing by instance attributes Using attribute names that look like magic attributes is not prohibited but can lead to surprising behaviour. In general, operations on namespace equate to the operations on namespace.__dict__ """ def __init__(__self__, __orig__ = None, **__kwds__): """__init__([namespace|dict], **kwds) -> None""" type(__self__).update(__self__, __orig__, **__kwds__) @classmethod def view(cls, orig): """namespace.view(dict) -> namespace Creates a namespace that is a view of the original dictionary. Allows modification of an existing dictionary via namespace syntax""" new = cls() new.__dict__ = orig return new def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self.__dict__)) # Recommend calling non-magic methods via class form to # avoid problems with inadvertent attribute shadowing def _checked_update(self, other): try: self.__dict__.update(other) except (TypeError): raise TypeError("Namespace update requires mapping " "keyed with valid Python identifiers") def update(__self__, __other__ = None, **__kwds__): """type(self).update(self, [namespace|dict], **kwds) -> None equivalent to self.__dict__.update""" # Handle direct updates if __other__ is not None: if isinstance(__other__, namespace): type(__self__)._checked_update(__self__, __other__.__dict__) else: type(__self__)._checked_update(__self__, __other__) # Handle keyword updates if __kwds__ is not None: type(__self__)._checked_update(__self__, __kwds__) class record(namespace): def __init__(self, definition=None): """record([definition]) -> record Constructs a namespace based on the given class definition Nested classes are created as sub-records Fields starting with an underscore are ignored If definition is not given, uses current class This is handy with subclasses Using subclasses this way has the advantage that the created records are also instances of the subclass. For example: Py> from ns import namespace, record Py> class Record: ... a = 1 ... b = "" ... class SubRecord: ... c = 3 ... Py> x = record(Record) Py> x record({'a': 1, 'b': '', 'SubRecord': record({'c': 3})}) Py> class Record2(record): ... a = 1 ... b = "" ... class SubRecord2(record): ... c =3 ... Py> x = Record2() Py> x Record2({'a': 1, 'b': '', 'SubRecord2': SubRecord2({'c': 3})}) """ cls = type(self) if definition is None: definition = cls cls.update_from_definition(self, definition) def update_from_definition(self, definition): """type(self).update_from_definition(self, definition) -> None Updates the namespace based on the given class definition Nested classes are created as sub-records Fields starting with an underscore are ignored""" try: for field, default in definition.__dict__.iteritems(): if field.startswith("_"): continue if (isinstance(default, (type, ClassType)) and issubclass(default, record)): # It's a record, so make it an instance of itself self.__dict__[field] = default() else: try: # If we can make a record of it, do so self.__dict__[field] = record(default) except TypeError: # Throw it in a standard field self.__dict__[field] = default except AttributeError: raise TypeError("Namespace definition must have __dict__ attribute") -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From simoninusa2001 at yahoo.co.uk Thu Feb 17 12:18:10 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 17 Feb 2005 09:18:10 -0800 Subject: Pausing a program - poll/sleep/threads? In-Reply-To: <1108659761.226825.178390@f14g2000cwb.googlegroups.com> References: <1108625477.222091.34680@l41g2000cwc.googlegroups.com> <7xekffr5ts.fsf@ruckus.brouhaha.com> <1108642815.203982.140210@g14g2000cwa.googlegroups.com> <1108659761.226825.178390@f14g2000cwb.googlegroups.com> Message-ID: <1108660690.941659.209430@g14g2000cwa.googlegroups.com> Damn! signal is not supported on Windows. time.sleep() doesn't work, as I suspected:: def info(self): sleep(5) self.info() Basically causes the function to pause, then call itself again, all in the foreground :-( I'm thinking some sort of thread timer is the way to go, but really don't understand threads.... From sdementen at hotmail.com Tue Feb 1 06:47:34 2005 From: sdementen at hotmail.com (Sebastien de Menten) Date: 1 Feb 2005 03:47:34 -0800 Subject: python ScriptControl error in Excel while running fine in python Message-ID: <8dad5312.0502010347.48fdd947@posting.google.com> I am trying to use ScriptControl under Excel (Windows XP) with the code: Global sc As New MSScriptControl.ScriptControl Public Function os_getcwd() sc.Language = "python" sc.ExecuteStatement ("import os") os_getcwd = sc.Eval("os.getcwd()") End Function When setting the language to python I have the error "A script engine for the specified language..." On the other side, under python, the translated code: import win32com.client sc=win32com.client.Dispatch("ScriptControl") sc.Language = "python" sc.ExecuteStatement ("import os") print sc.Eval("os.getcwd()") works without any problem ! So, is it possible that a different set of permissions for languages available in ScriptControl is used when executed from Excel or from python ? Is it possible to ask the available languages to ScriptControl ? Well, in fact I am totally puzzled by this behaviour so any help is welcome :-) Sebastien PS: could you reply to my email address as I do not read regularly c.l.p. ? thanks From mark at freelance-developer.com Wed Feb 2 17:06:22 2005 From: mark at freelance-developer.com (Mark Nenadov) Date: Wed, 02 Feb 2005 17:06:22 -0500 Subject: Getting a module's byte code, how? References: <42014e25$0$28975$e4fe514c@news.xs4all.nl> Message-ID: On Wed, 02 Feb 2005 23:03:17 +0100, Irmen de Jong wrote: > What would be the best way, if any, to obtain > the bytecode for a given loaded module? > > I can get the source: > import inspect > import os > src = inspect.getsource(os) > > but there is no ispect.getbytecode() ;-) > > --Irmen The inspect API documentation says that code objects have "co_code", which is a string of raw compiled bytecode. Hope that helps! - - Mark Nenadov Python Byte Solutions http://www.pythonbyte.com/ From rschroev_nospam_ml at fastmail.fm Sun Feb 27 04:39:49 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 27 Feb 2005 09:39:49 GMT Subject: lambda strangeness?? In-Reply-To: References: Message-ID: Alan Gauld wrote: > I was playing with lambdas and list compregensions and came > across this unexpected behaviour: > > >>>>adds = [lambda y: (y + n) for n in range(10)] >>>>adds[0](0) > > 9 > >>>>for n in range(5): print adds[n](42) > > ... > 42 > 43 > 44 > 45 > 46 > >>>>adds[0](0) > > 4 > > Can anyone explain the different answers I'm getting? > FWIW the behaviour I expected was what seems to happen inside > the for loop... It seems to somehow be related to the > last value in the range(), am I somehow picking that up as y? > If so why? You're picking it up not as y but as n, since n in the lambda is evaluated when you call the lambde, not when you define it. Or is that just a coincidence? And why did it work > inside the for loop? In the loop you are giving n exactly the values you intended it to have inside the lambda. Check what happens when you use a different loop variable: >>> for i in range(5): print adds[i](0) 9 9 9 9 9 I guess you could something like this instead: >>> adds=[] >>> for n in range(10): def f(y, n=n): return y+n adds.append(f) >>> adds[0](0) 0 >>> adds[0](5) 5 >>> adds[9](5) 14 -- "Codito ergo sum" Roel Schroeven From mwm at mired.org Thu Feb 17 20:12:43 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 17 Feb 2005 19:12:43 -0600 Subject: os.walk() References: Message-ID: <86zmy2hdro.fsf@guru.mired.org> rbt writes: > Could someone demonstrate the correct/proper way to use os.walk() to > skip certain files and folders while walking a specified path? I've > read the module docs and googled to no avail and posted here about > other os.walk issues, but I think I need to back up to the basics or > find another tool as this isn't going anywhere fast... I've tried this: > > for root, dirs, files in os.walk(path, topdown=True): > > file_skip_list = ['file1', 'file2'] > dir_skip_list = ['dir1', 'dir2'] > > for f in files: > if f in file_skip_list > files.remove(f) > > for d in dirs: > if d in dir_skip_list: > dirs.remove(d) > > NOW, ANALYZE THE FILES > > And This: > > files = [f for f in files if f not in file_skip_list] > dirs = [d for d in dirs if dir not in dir_skip_list] > > NOW, ANAYLZE THE FILES > > The problem I run into is that some of the files and dirs are not > removed while others are. I can be more specific and give exact > examples if needed. On WinXP, 'pagefile.sys' is always removed, while > 'UsrClass.dat' is *never* removed, etc. As other have pointed out, the problem you are running into is that you are modifying the list while looping over it. You can fix this by creating copies of the list. No one has presented the LC version yet: for rl, dl, fl in os.walk(path, topdown=True): file_skip_list = ('file1', 'file2') #* dir_skip_list = ('dir1', 'dir2') files = [f for f in fl if not f in file_skip_list] dirs = [d for d in dl if not d in dir_skip_list] # Analyze files and dirs If you're using 2.4, you might consider using generators instead of LC's to avoid creating the second copy of the list: files = (f for f in fl if not f in file_skip_list) dirs = (d for d in dl if not d in dir_skip_list) http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From john.abel at pa.press.net Fri Feb 18 09:27:49 2005 From: john.abel at pa.press.net (John Abel) Date: Fri, 18 Feb 2005 14:27:49 +0000 Subject: Annoying Socket Problem Message-ID: <4215FB65.6090406@pa.press.net> I'm hoping this is something simple, and someone can point me in the right direction here. I have a class based on SocketServer (ThreadingTCPServer), and I've used makefile on the socket so I use the "for in " routine. My client sends it a small amount of data. However, both programs appear to hang once the data has been sent, obviously something to do with flushing. I'd appreciate any pointers. Regards J Server Class: class _DBSocketHandler( SocketServer.BaseRequestHandler ): xmlStart = re.compile( "XML-START" ) xmlEnd = re.compile( "XML-END" ) def handle( self ): print "Accepted Connection From", self.client_address socketIn = self.request.makefile( 'r' ) socketOut = self.request.makefile( 'wb' ) remoteDoc = None for dataIn in socketIn: if self.xmlEnd.match( dataIn ): remoteDoc.close() break if self.xmlStart.match( dataIn ): print "Receiving XML" remoteDoc = StringIO() continue if remoteDoc is not None: remoteDoc.write( dataIn ) socketOut.write( "Got Yer XML File, Thanks" ) Client Code: def connect( self ): self.socketCon.connect( ( self.dbServer, self.dbPort ) ) testFile = StringIO.StringIO( testXML ) self.socketCon.send( "XML-START" ) for xmlSQL in testFile: self.socketCon.send( xmlSQL ) testFile.close() self.socketCon.send( "XML-END" ) self.socketCon.send( "" ) time.sleep(10) while True: dataRec = self.socketCon.recv( 8192 ) if not dataRec: break self.socketCon.close() From fredrik at pythonware.com Fri Feb 18 14:03:49 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 18 Feb 2005 20:03:49 +0100 Subject: Probably over my head... Trying to get Font Names References: Message-ID: "Samantha" wrote: >I am attempting to extract the Font Names from the installed windows fonts. I am having a heck of a >time getting these rather than the file names. Examples can be seen by going to Control Panel > >Fonts here's one way to do it (using Tkinter): >>> import Tkinter, tkFont >>> tk = Tkinter.Tk() >>> tkFont.families() ('System', 'Terminal', 'Fixedsys', 'Roman', 'Script', 'Modern', 'Small Fonts', 'MS Serif', ...) here's another way (using PIL): import os from PIL import ImageFont fontdir = os.path.join(os.environ["windir"], "fonts") for fontfile in os.listdir(fontdir): try: font = ImageFont.truetype(os.path.join(fontdir, fontfile), 1) except IOError: pass else: print font.font.family, font.font.style (this prints a list of family/style combinations). You can get PIL from http://www.pythonware.com/products/pil/ (1.1.4) http://effbot.org/downloads/#pil (1.1.5 betas) From pf_moore at yahoo.co.uk Mon Feb 21 12:33:34 2005 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Mon, 21 Feb 2005 17:33:34 +0000 Subject: Unittest - testing properties (read-only attributes) References: Message-ID: Peter Hansen writes: > Roy Smith wrote: >> You want something like >> self.assertRaises(AttributeError, lambda: self.combat.value = 1) > > Or, combining the two responses and avoiding the lambda: > > self.assertRaises(AttributeError, setattr, self.combat, 'value', 1) > > Hmm... this might be a case where the lambda form is actually the > more readable one... Thanks, I hadn't thought of setattr. I was bitten by the "assignment is a statement, so can't be used in a lambda" issue, as well :-) Paul. -- It was a machine, and as such only understood one thing. Being clobbered with big hammers was something it could relate to. -- Tom Holt From almondb at gmail.com Wed Feb 9 05:50:50 2005 From: almondb at gmail.com (Brian) Date: 9 Feb 2005 02:50:50 -0800 Subject: Success using Python .NET with py2exe? In-Reply-To: <1107938006.074283.159590@c13g2000cwb.googlegroups.com> References: <1107938006.074283.159590@c13g2000cwb.googlegroups.com> Message-ID: <1107946250.292983.254030@l41g2000cwc.googlegroups.com> I haven't spent any time recently with it, but I seem to recall having more success using cx_Freeze for packaging than with py2exe (when using Python.NET). In the time since I then, I suspect all of the packagers have gotten more sophisticated, and you might have more options. A good place for questions like these is the Python.NET list: http://mail.python.org/mailman/listinfo/pythondotnet From jdadson at yahoo.com Wed Feb 9 16:57:15 2005 From: jdadson at yahoo.com (Jive Dadson) Date: Wed, 09 Feb 2005 21:57:15 GMT Subject: Name of type of object References: <4209A52C.A1C40311@yahoo.com> <36uo36F54okd6U1@individual.net> Message-ID: <420A8774.638D88E8@yahoo.com> I don't think I've quite got it. The application I'm writing has some similarities to an interactive shell. Like an interactive shell, it executes arbitrary code that it receives from an input stream. When it gets an exception, it should create an informative message, regardless of the type of exception. The traceback routine does that, somehow, some way, but I've tried to read that code and figure out how and I don't get it. The best I have so far is, class Exec_thread(BG_thread): """ Execute a line of code in the global namespace. """ def _process(s): """ Process one instruction """ try: exec s.product in globals() except (Exception), e: handle_error( typename(e)+ ": " + str(e) ) But that works only if the exception happens to be derived from Exception. How do I handle the general case? From snacktime at gmail.com Mon Feb 14 20:04:10 2005 From: snacktime at gmail.com (snacktime) Date: Mon, 14 Feb 2005 17:04:10 -0800 Subject: regular expression question Message-ID: <1f060c4c050214170425021677@mail.gmail.com> The primary question is how do I perform a match when the regular expression contains string variables? For example, in the following code I want to match a line that starts with STX, then has any number of characters, then ends with STX. Example 2 I'm pretty sure works as I expect, but I'm not sure about Example 1, and I'm pretty sure about example 3. import re from curses.ascii import STX,ETX,FS STX = chr(STX) ETX = chr(ETX) FS = chr(FS) data = STX + "ONE" + FS + "TWO" + FS + "THREE" + ETX match = STX + '(.*)' + ETX # Example 1 # This appears to work, but I'm not sure if the '+' is being used in the regular expression, or if it's just joining STX, '(.*)', and ETX. if re.search(STX + '(.*)' + ETX,data): print "Matches" # Example 2 # This also appears to work if re.search(match,data): print "Matches" # Example 3 # Doesn't work, as STX and ETX are evaluated as the literal strings 'STX' and 'ETX' if re.search('STX(.*)ETX', data): print "Matches" Chris From Chris48224 at yahoo.com Fri Feb 11 18:37:04 2005 From: Chris48224 at yahoo.com (Chris48224 at yahoo.com) Date: 11 Feb 2005 15:37:04 -0800 Subject: A REAL money maker. IT WORKS!!!! Message-ID: <1108165024.726009.289520@g14g2000cwa.googlegroups.com> Try this out, it works!!!! Turn $10 into $10,000 with PayPal, easy and quick. PLEASE TAKE A MOMENT TO READ THIS INFORMATION. THIS REALLY WORKS!!! " I WAS SHOCKED WHEN I SAW HOW MUCH MONEY CAME FLOODING INTO MY PAYPAL ACCOUNT." -Mark 2004 Dear Friend, This is a new program, as you will see. It can be for the U.S. Canada, S.E Asia or the U.K. This is a fantastic opportunity. Try it for yourself!! EVERYTHING DONE ONLINE! With just $10 or ?5 and a PayPal PREMIER or BUSINESS account, you could make $$Thousands$$ in 2 SIMPLE STEPS! GUARANTEED - you will have $10,000 in two weeks. Only $10, a PayPal PREMIER or BUSINESS account and 30 minutes are all that is needed to get this going. If you want to make a few thousand dollars real quick, then PLEASE take a moment to read and understand the MLM program I'm sharing with you. No it's not what you think. YOU DON?T have to send $10 to five or six people to buy a report, receipt or get on their mailing list. Nor will you need to invest more money. You will be able to complete it in LESS THAN 30 MINUTES and you will NEVER FORGET THE DAY YOU FIRST VIEWED THIS ONLINE. If you're already running a home business, you can easily do this one along with it. If not, this is the FASTEST and EASIEST way to earn serious money online that you've ever seen so far in the history of the Internet! This program works no matter what country you are in, or what currency you use. It doesn't matter how old or how young you are. And you certainly won't need any special knowledge or talent. You won't need to run a website, or make phone calls, or make photocopies, or send out letters through the mail, or pay for advertising, etc. The only things you will need are: * an email address * A Premier or Business PayPal account with at least $10 deposited in it * 30 minutes of your time ONLY 2 SIMPLE AND EASY STEPS! ! If you are doing other programs, by all means stay with them. The more the merrier, BUT PLEASE READ ON!! First of all, there are only TWO POSITIONS, not realistic and much, MUCH FASTER. Because it is so easy, the response rate for this program is VERY HIGH and VERY FAST, and you will receive your reward in FOURTEEN DAYS. That's only TWO WEEKS! Not one or two months. Just in time for next months BILLS. TRUE STORY -- Grace Kelly tells how she ran this gifting summation four times last year. The first time, she received $6,000 in cash in two weeks and then $14,000 in cash the next three times. THIS CAN AND WILL WORK FOR YOU! HERE ARE THE DETAILS: Post this letter in 50 message boards, chat rooms, or newsgroup. You don't need to post 200 like other programs or email 100 people just to get started. Even if you are already in a program like the "send twenty dollars to six people", CONTINUE IT and stay with it, THOSE DO PAY OUT, but do yourself a favor, DO THIS ONE TODAY as well, RIGHT NOW!!! It is simple and takes a very small investment, only $10 and a PayPal PREMIER or BUSINESS account. IT WORKS AND IS DONE IN 2 SIMPLE AND EASY STEPS! ! This program WILL PAY FASTER before the other programs you are working on even trickle in!! Follow the simple instructions and in two weeks, you should have $10,000 because most PEOPLE WILL RESPOND due to the LOW ONE TIME INVESTMENT, SPEED AND HIGH PROFIT POTENTIAL, PLUS, since its done ALL ONLINE, there is no time-wasted mailing out letters and such!!! We are not even figuring a 50% response! So let's all keep it going and help each other in these tough times. We all owe money to bill collectors, and creditors. But, with this, if people take the time to help each other, the good fortune will follow. SO, Take the measly minutes this SIMPLE and REWARDING program offers and give the gift that gives back TODAY!!! HERE?S WHAT YOU NEED TO DO: STEP 1 Ok, if you're not already a PayPal user, the very first thing you need to do is use the PayPal link below and SIGN UP. It takes just two minutes! Here's the URL. Just click on the PayPal link below: https://www.paypal.com/cgi-bin/webscr?cmd=_registration-run Be sure to use this link so you can sign up for a free PREMIER or BUSINESS account. You'll need to have a PREMIER or BUSINESS account (and not a PERSONAL account) otherwise you won't be able to receive credit card payments from other people. STEP 2 It is an undeniable law of the universe that we must first give in order to receive. So the first thing to do when you have your Premier/Business PayPal account is to IMMEDIATELY send a $10 payment from your PayPal account to the person at POSITION #1, if... Your birthday is BETWEEN JAN 1 THRU JUNE 30, OR, if... -- your birthday is BETWEEN JULY 1 THRU DEC 31, send the gift to the person at POSITION # 2. Along with a note saying: "HERE IS A $10 GIFT FOR YOU." Be certain to add this note, as this is what KEEPS THIS PROGRAM LEGAL. Instructions on how to send a payment are under "SEND MONEY" at the PayPal Site. It's so Easy!!! When you send your $10 payment to the first address in the list, do it with a great big smile on your face because "as you sow, so shall you reap!" When this program is continued, as it should be, EVERYONE PROFITS!! DON?T BE AFRAID to send gifts to strangers. It will come back to you ten folds. A person can give you up to $10,000 per year and you don't have to report it to the IRS! Here are the current positions: * POSITION#1 --- chris48224 at yahoo.com * POSITION#2 --- executioner_2k at yahoo.com (sorry the emails don't show up correctly on these Google posts in @ format, change them to ___ at ___. ___) After you have transferred a $10 payment to the email address, something very eerie happens. It gives you an indescribable, overwhelming sense of certainty, belief and conviction in the system. You've just proved to yourself that, because you have done it, there must be a great number of other people ready to do exactly the same. Thus you have now seen for yourself, first hand, that this business actually works! REMOVE the email address you are replacing (the one you sent $10 to), and REPLACE it with your own email address. REMEMBER: Use the same EMAIL ADDRESS that is used with YOUR PayPal account!!! Paste your newly typed email address over the old one and then post to 50 Message Boards, Chat Rooms, or Newsgroups. DON?T MULL OVER IT, JUST 30MIN OF YOUR TIME, THAT?S IT THERE IS NO MORE TO DO!! ACT FAST AND GET THE GIFT. HONESTLY AND INTEGRITY MAKE THIS PLAN WORK!! DO TO OTHERS, AS YOU WOULD HAVE THEM DO TO YOU. YOUR NAME COULD CYCLE FOR A LONG TIME! ! THIS MAKES IT THE GIFT THAT KEEPS ON GIVING. This is excellent seed money to start or expand a business, buy you dream home, car, and pay off whatever bills you may have. Good luck and God Bless. Play fairly. Good fortune will follow. WHY THIS PROGRAM WORKS: !! HONESTY AND INTEGRITY!! Straight to the point, the reason this program is SO SUCCESSFUL is because when you follow these instructions EXACTLY = GIVE A $10 GIFT and POST this in 50 different message boards, there are only TWO outcomes. (1) A person's birthday will fall on the same half as yours, therefore, YOU GET THE $10... OR, (2) a persons birthday will fall on the other half of the timeline, therefore, YOU STAY IN YOUR POSITION and get posted in 50 other MESSAGE BOARDS, etc. BOTTOMLINE: Either you get the $10 or your name gets passed on for other people to give YOU $10 or pass YOUR name on to other people that will. It makes you think though, the more you POST YOUR OWN POSTS, the BETTER the results!!! 4 FACTORS THAT MAKE THIS PROGRAM SO SUCCESSFUL... * EXTREMELY FAST RESPONSE * EXTREMELY HIGH RESPONSE RATE * UNLIMITED PROFIT POTENTIAL * QUICK, SIMPLE AND CHEAP TO GET STARTED So there it is. You now have the knowledge that will enable you to make over $10,000 within the next two weeks. The only thing that can hold you back now is a lack of faith or a lack of self-belief. However, any doubts you may currently have will disappear within a few days of putting this plan into practice. Trust me on this! You certainly won't regret it. SOME NOTES FROM PAYPAL WHICH YOU MAY FIND USEFUL: PayPal lets you pay anyone with an email address and is the world's Number 1 online payment service. PayPal is accepted on over 3 million eBay auctions as well as a countless number of online shops. You can also use PayPal to pay your friends - for example, it's a convenient way to split the phone bill with your room-mate, send cash to your kids in college, or send cash to someone in another country. Better yet, you can also earn a referral bonus of up to $100 each time someone signs up for a PayPal account using your referral URL! When you send money through PayPal, you can fund your payments with your credit card or checking account. You won't have to worry about your privacy, because PayPal keeps your accounting information safe and secure. Making a purchase with PayPal is far more secure than mailing a check or giving your credit card number to a stranger. That's why over 9 MILLION people from around the world use PayPal to move money. Signing up for a PayPal account is free, easy, and it takes only a couple of minutes. Thank you, and good luck in your ventures P.S. Does this sound too good? Well maybe to some skeptics it is. But it actually works, and is worth the 30 minutes of your time now. So, just make a nice cup of tea and get started on it now. After all, you can't lose, but you stand to gain more in the next few weeks than many people earn in a year. From deetsNOSPAM at web.de Mon Feb 21 10:16:13 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 21 Feb 2005 16:16:13 +0100 Subject: lambda closure question References: <1108798951.128843.79810@f14g2000cwb.googlegroups.com> <1108802613.284686.200170@o13g2000cwo.googlegroups.com> <37u4dpF5cboqvU1@individual.net> <7xsm3qc700.fsf@ruckus.brouhaha.com> Message-ID: <37uc7rF5igk7fU1@individual.net> Paul Rubin wrote: > "Diez B. Roggisch" writes: >> It's not only that way in python, but in java too. So it seems that there >> is a fundamental principle behind it: In a language that allows >> sideeffects, these will actually happen. > > Can you even have nested functions in Java? Algol-60 did things the > way you'd expect, i.e. you can modify the outer variable from the > inner scope. Not nested functions, but closures in anonymous inner classes - which can reference only final variables, thus creating the same effect as the scoping rules of python. -- Regards, Diez B. Roggisch From paul at boddie.org.uk Tue Feb 22 10:00:27 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 22 Feb 2005 07:00:27 -0800 Subject: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux & Windows XP References: Message-ID: <5339b60d.0502220700.3ec7ae56@posting.google.com> Mike Dee wrote in message news:... > A very very basic UTF-8 question that's driving me nuts: > > If I have this in the beginning of my Python script in Linux: > > #!/usr/bin/env python > # -*- coding: UTF-8 -*- > > should I - or should I not - be able to use non-ASCII characters > in strings For string literals, with the "coding" declaration, Python will accept that the bytes sitting in your source file inside the string literal didn't get there by accident - ie. that you meant to put the bytes [0xC3, 0xA6, 0xC3, 0xB8, 0xC3, 0xA5] into a string when you entered "???" in a UTF-8-enabled text editor. (Apologies if you don't see the three Scandinavian characters properly there in your preferred newsreader.) For Unicode literals (eg. u"???" in that same UTF-8-enabled text editor), Python will not only accept the above but also use the "coding" declaration to produce a Unicode object which unambiguously represents the sequence of characters - ie. something that can be used/processed to expose the intended characters in your program at run-time without any confusion about which characters are being represented. > and in Tk GUI button labels and GUI window titles and in > raw_input data without Python returning wrong case in manipulated > strings and/or gibberished characters in Tk GUI title? This is the challenging part. Having just experimented with using both string literals and Unicode literals with Tkinter on a Fedora Core 3 system, with a program edited in a UTF-8 environment and with a ubiquitous UTF-8-based locale, it's actually possible to write non-ASCII characters into those literals and to get Tkinter to display them as I intended, but I've struck lucky with that particular combination - a not entirely unintended consequence of the Red Hat people going all out for UTF-8 everywhere (see below for more on that). Consider this snippet (with that "coding" declaration at the top): button1["text"] = "???" button2["text"] = u"???" In an environment with UTF-8-enabled editors, my program running in a UTF-8 locale, and with Tk supporting treating things as UTF-8 (I would imagine), I see what I intended. But what if I choose to edit my program in an editor employing a different encoding? Let's say I enter the program in an editor employing the mac-iceland encoding, even declaring it in the "coding" declaration at the top of the file. Running the program now yields a very strange label for the first button, but a correct label for the second one. What happens is that with a non-UTF-8 source file, running in a UTF-8 locale with the same Tk as before, the text for the first button consists of a sequence of bytes that Tk then interprets incorrectly (probably as ISO-8859-1 as a sort of failsafe mode when it doesn't think the text is encoded using UTF-8), whereas the text for the second button is encoded from the unambiguous Unicode representation and is not misunderstood by Tk. Now, one might argue that I should change the locale to suit the encoding of the text file, but it soon becomes very impractical to take this approach. Besides, I don't think mac-iceland (an admittedly bizarre example) forms part of a supported locale on the system I have access to. > With non-ASCII characters I mean ( ISO-8859-1 ??) stuff like the > German / Swedish / Finnish / etc "umlauted" letter A (= a diaresis; > that is an 'A' with two dots above it, or an O with two dots above.) > > In Linux in the Tk(?) GUI of my 'program' I get an uppercase "A" > with a tilde above - followed by a general currency symbol ['spider']. > That is, two wrong characters where a small umlauted letter "a" > should be. That sort of demonstrates that the bytes used to represent your character are produced by a UTF-8 encoding of that character. Sadly, Tk then chooses to interpret them as ISO-8859-1, I guess. One thing to verify is whether Tk is aware of anything other than ISO-8859-1 on your system; another thing is to use Unicode objects and literal to at least avoid the guessing games. > But in Windows XP exactly the *same* code (The initiating "#!/usr/bin > /env python" and all..) works just fine in the Tk GUI - non-ascii > characters showing just as they should. (The code in both cases is > without any u' prefixes in strings.) It's pretty much a rule with internationalised applications in Python that Unicode is the way to go, even if it seems hard at first. This means that you should use Unicode literals in your programs should the need arise - I can't say it does very often in my case. > I have UTF-8 set as the encoding of my Suse 9.2 / KDE localization, I > have saved my 'source code' in UTF-8 format and I have tried to read > *a lot* of information about Unicode and I have heard it said many > times that Python handles unicode very well -- so why can it be so > bl**dy difficult to get an umlauted (two-dotted) letter a to be > properly handled by Python 2.3? In Windows I have Python 2.4 - but the > following case-insanity applies for Windows-Python as well: Python does handle Unicode pretty well, but it's getting the data in and out of Python, combined with other components and their means of presenting/representing that data which is usually the problem. > For example, if I do this in my Linux konsole (no difference whether it > be in KDE Konsole window or the non-gui one via CTRL-ALT-F2): > > >>>aoumlautxyz="12xyz" # number 1 = umlauted a, number 2 = uml o > >>>print aoumlautxyz.(upper) > > then the resulting string is NOT all upper case - it is a lowercase > umlauted a, then a lowercase umlauted o then uppercase XYZ In this case, you're using normal strings which are effectively locale-dependent byte strings. I guess that what happens is that the byte sequence gets passed to the system's string processing routines which then fail to convert the non-ASCII characters to upper case according to their understanding of what the bytes actually mean in terms of being characters. I'll accept that consoles can be pretty nasty in exposing the right encoding to Python (search for "setlocale" in the comp.lang.python archives) and that without some trickery you won't get decent results. However, by employing Unicode objects and explicitly identifying the encoding of the input, you should get the results you are looking for: aoumlautxyz=unicode("??xyz", "utf-8") This assumes that UTF-8 really is the encoding of the input. [...] > One can hardly expect the users to type characters like unicode('\xc3\ > xa4\xc3\xb6\xc3\xbc', 'utf-8')u'\xe4\xf6\xfc' u"???".encode('utf-8') or > whatnot, and encode & decode to and fro till the cows come home just to > get a letter or two in their name to show up correctly. With a "coding" declaration and Unicode literals, you won't even need to use the unicode constructor. Again, I must confess that much of the data I work with doesn't originate in the program code itself, so I rarely need to even think of this issue. > It's a shame that the Linux Cookbook, Learning Python 2nd ed, Absolute > beginners guide to Python, Running Linux, Linux in a Nutshell, Suse 9.2 > Pro manuals and the online documentation I have bumped into with Google > (like in unicode.org or python.org or even the Python Programming Faq > 1.3.9 / Unicode error) do not contain enough - or simple enough - > information for a Python/Linux newbie to get 'it'. One side-effect of the "big push" to UTF-8 amongst the Linux distribution vendors/maintainers is the evasion of issues such as filesystem encodings and "real" Unicode at the system level. In Python, when you have a Unicode object, you are dealing with idealised sequences of characters, whereas in many system and library APIs out there you either get back a sequence of anonymous bytes or a sequence of UTF-8 bytes that people are pretending is Unicode, right up until the point where someone recompiles the software to use UTF-16 instead, thus causing havoc. Anyone who has needed to expose filesystems created by Linux distributions before the UTF-8 "big push" to later distributions can attest to the fact that the "see no evil" brass monkey is wearing a T-shirt with "UTF-8" written on it. Paul From ramen at lackingtalent.com Thu Feb 3 11:06:08 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Thu, 03 Feb 2005 16:06:08 -0000 Subject: Nested scopes and class variables References: Message-ID: Thanks, Nick and Alex, for the nice, detailed explanations. My understanding of Python bytecode is not deep enough to comment at this time. ;) -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. "talking about music is like dancing about architecture." From quentel.pierre at wanadoo.fr Fri Feb 4 23:51:10 2005 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Sat, 05 Feb 2005 05:51:10 +0100 Subject: how to send an int over a socket In-Reply-To: References: Message-ID: <420450c6$0$19414$8fcfb975@news.wanadoo.fr> Use string formatting : msglen = '%16s' %len(testmessage) will return a 16-byte string, beginning with spaces. Send it over your connection and use int() to get the message length Pierre From tjreedy at udel.edu Sun Feb 13 17:58:24 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 13 Feb 2005 17:58:24 -0500 Subject: Iterator / Iteratable confusion References: <420a5c1e$0$21630$a1866201@visi.com><200502131848.03655.francis.girard@free.fr> <200502131958.27410.francis.girard@free.fr> Message-ID: "Francis Girard" wrote in message news:200502131958.27410.francis.girard at free.fr... > An ""iteratable"" class is a class supporting the __iter__ method which > should > return an ""iterator"" instance, that is, an instance of a class > supporting > the "next" method. Not quite right, see below. > An iteratable, strictly speaking, doesn't have to support the "next" > method An iterable with a next method is, usually, an iterator. > an "iterator" doesn't have to support the "__iter__" method Yes it does. iter(iterator) is iterator is part of the iterater protocol for the very reason you noticed... >(but this breaks the iteration protocol as we will later see). Iterators are a subgroup of iterables. Being able to say iter(it) without having to worry about whether 'it' is just an iterable or already an iterator is one of the nice features of the new iteration design. Terry J. Reedy From doodle4 at gmail.com Mon Feb 14 18:21:50 2005 From: doodle4 at gmail.com (doodle4 at gmail.com) Date: 14 Feb 2005 15:21:50 -0800 Subject: Multidimensional arrays - howto? Message-ID: <1108423310.463006.318320@f14g2000cwb.googlegroups.com> Hello all, I am trying to convert some C code into python. Since i am new to python, i would like to know how to deal with multidimensional arrays? Thanks, -Joe Here's a snippet of what i am trying to convert: # define table0 15 # define table1 20 unsigned int Table[table0][table1] if(Table[table0][table1] != 0) { Table[table0][table1]-- } From vesko8 at yahoo.com Fri Feb 18 15:55:13 2005 From: vesko8 at yahoo.com (john14) Date: Fri, 18 Feb 2005 15:55:13 -0500 Subject: xmlrpc.server.work() does not seem to handle multiple requests Message-ID: <018be98bd7f75da932445488d3263748@localhost.talkaboutprogramming.com> Hi, I have an xmlrpc server. I using the python package xmlrpc. Here is what I am doing: s = xmlrpc.server() s.addMethods(method_hash) s.bindAndListen(PORT) while 1: try: s.work() except: e = sys.exc_info() The problem is that when I send multiple requests they are queued and processed one after the other. Is there some other method that will allow me to process multiple request at the same time? Thank You From rkern at ucsd.edu Wed Feb 2 22:04:46 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 02 Feb 2005 19:04:46 -0800 Subject: Reinstall python 2.3 on OSX 10.3.5? In-Reply-To: <1107388080.703032.116150@g14g2000cwa.googlegroups.com> References: <1107388080.703032.116150@g14g2000cwa.googlegroups.com> Message-ID: moa at extrapolation.com wrote: > Hi there > > I started a very long and roundabout process of attempting to install > python 2.3.4 along side my apple-installed 2.3 system. To make a long > story short, I have completely confabulated my environment ( i deleted > the 2.3 binaries and so forth from the system in an attempt to start > things fresh), and now I cannot figure out how to reinstall the base > 2.3 Apple python distribution. > Can somebody please point me in the right direction? Borrow Guido's time machine and prevent your former self from doing that. OS X depends on it's python being there untouched. They also have compiled stuff that does not exist in the standard Python distribution. Back up your data and reinstall the OS. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From maxime_phan at hotmail.com Wed Feb 9 23:08:59 2005 From: maxime_phan at hotmail.com (maxime) Date: 9 Feb 2005 20:08:59 -0800 Subject: pygame and music Message-ID: <4cc9a89e.0502092008.249582ac@posting.google.com> Hi, I try to develop a game in python and pygame. In my game I play a music (.mid with pygame.mixer.music) but sometime I need to accelerate it but I don't see how to do that with pygame. Is it possible? If not, do you know an other python music lib that do that? Thanks a lot From fredrik at pythonware.com Wed Feb 9 15:39:21 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 9 Feb 2005 21:39:21 +0100 Subject: two questions - no common theme References: Message-ID: Sean McIlroy wrote: > 1) I'd like to be able to bind callbacks to presses of the arrow > buttons on the keyboard. How do you say that in Tkinter? , , , http://effbot.org/books/tkinterbook/events-and-bindings.htm For an ordinary 102-key PC-style keyboard, the special keys are Cancel (the Break key), BackSpace, Tab, Return(the Enter key), Shift_L (any Shift key), Control_L (any Control key), Alt_L (any Alt key), Pause, Caps_Lock, Escape, Prior (Page Up), Next (Page Down), End, Home, Left, Up, Right, Down, Print, Insert, Delete, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Num_Lock, and Scroll_Lock. > 2) The function 'listdir' in os.path returns a list of all the files > in the given directory - how do I get hold of a list of its > subdirectories? listdir returns files and directories; use os.path.isdir(path) to check if path is a directory: for name in os.listdir(path): p = os.path.join(path, name) if os.path.isdir(p): ... From tzot at sil-tec.gr Thu Feb 17 08:56:11 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 17 Feb 2005 15:56:11 +0200 Subject: Why Tk treat F10, F11, F12 diferently from F1...F9? References: <5175a81c05021216415204de93@mail.gmail.com> <20050213014425.GB24076@unpythonic.net> Message-ID: <8j89119f988ptskat69shtire8r2ha9mr0@4ax.com> On Sun, 13 Feb 2005 00:10:35 -0200, rumours say that "Gabriel B." might have written: [snip: F10 in Motif activates the menu bar] >i'm on windowsXP (what makes the F10 biding by "default" even more >weird). Well, for now using the keysym_num will be more safe since i'm >still getting they correct. It's not weird, it's the same in Windows as far as I remember (windows 3.0). F10 is the same as depressing Alt. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From gabriel.barros at gmail.com Tue Feb 8 09:20:41 2005 From: gabriel.barros at gmail.com (Gabriel B.) Date: Tue, 8 Feb 2005 12:20:41 -0200 Subject: Big development in the GUI realm In-Reply-To: <4207D64F.2000709@optushome.com.au> References: <1107795145.049239.73450@l41g2000cwc.googlegroups.com> <5ocf01hmspufk3iusvm35p6hj4mes5heke@4ax.com> <4207D64F.2000709@optushome.com.au> Message-ID: <5175a81c05020806207f9f77ce@mail.gmail.com> > >>Considering the fact that the Qt DLL exist by themselves, that the > >>version used is the one provided by Qt, and that the EXE uses a > >>standard, open way to communicate with it, the above does seem to say > >>this use would be valid. > >> > >> > > > > http://www.gnu.org/licenses/gpl-faq.html#MereAggregation > > > > "/.../ If modules are designed to run linked together in a shared address > > space, that almost surely means combining them into one program. > > > > By contrast, pipes, sockets and command-line arguments are > > communication mechanisms normally used between two separate > > programs. So when they are used for communication, the modules > > normally are separate programs. But if the semantics of the > > communication are intimate enough, exchanging complex internal > > data structures, that too could be a basis to consider the two parts > > as combined into a larger program." > > > > This is odd. They claim it's a GPL'ed version, but it's a trolltech license that forces you to release your code under gpl even tought their's not! I'm not against a company getting it's share with their product. that's what motivated them in the first place. but DONT LIE! don't call it gpl when it's not. Gpl make it very explicity it deals with the program as a whole, in the meaning of a executable code. What they're trying to achive here is that, by adding this paragraph, they will cover the "dll use" under the gpl. By that cover-all definition they came up, i can't use Internet Explorer to see a site hosted with a gpl'ed server! i can't even use a BSD program to grep a file! anyway... it will only mater when people with money cares. I already have 3 choices. From aleaxit at yahoo.com Sun Feb 6 15:36:06 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 6 Feb 2005 21:36:06 +0100 Subject: empty classes as c structs? References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <1gric2n.17myhon1hfrc6gN%aleaxit@yahoo.com> Message-ID: <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> Steven Bethard wrote: > Hmm... interesting. This isn't the main intended use of > Bunch/Struct/whatever, but it does seem like a useful thing to have... > I wonder if it would be worth having, say, a staticmethod of Bunch that > produced such a view, e.g.: > > class Bunch(object): > ... > @staticmethod > def view(data): > result = Bunch() > result.__dict__ = data > return result > > Then you could write your code as something like: > > gbls = Bunch.view(globals()) > > I'm probably gonna need more feedback though from people though to know > if this is a commonly desired use case... Reasonably so, is my guess. Witness the dict.fromkeys classmethod -- it gives you, on dict creation, the same kind of nice syntax sugar that wrapping a dict in a bunch gives you for further getting and setting (and with similar constraints: all keys must be identifiers and not happen to clash with reserved words). I think this ``view'' or however you call it should be a classmethod too, for the same reason -- let someone handily subclass Bunch and still get this creational pattern w/o extra work. Maybe a good factoring could be something like: class Bunch(object): def __init__(self, *a, **k): self.__dict__.update(*a, **k) def getDict(self): return self.__dict__ def setDict(self, adict): self.__dict__ = adict theDict = property(getDict, setDict, None, "direct access to the instance dictionary" ) @classmethod def wrapDict(cls, adict, *a, **k): result = cls.__new__(cls, *a, **k) result.setDict(adict) cls.__init__(result, *a, **k) return result I'm thinking of use cases where a subclass of Bunch might override setDict (to do something else in addition to Bunch.setDict, e.g. maintain some auxiliary data structure for example) -- structuring wrapDict as a classmethod in a ``Template Method'' DP might minimize the amount of work, and the intrusiveness, needed for the purpose. (I don't have a real-life use case for such a subclass, but it seems to cost but little to provide for it as a possibility anyway). [[given the way property works, one would need extra indirectness in getDict and setDict -- structuring THEM as Template Methods, too -- to fully support such a subclass; but that's a well-known general issue with property, and the cost of the extra indirection -- mostly in terms of complication -- should probably not be borne here, it seems to me]] Alex From tzot at sil-tec.gr Thu Feb 10 11:18:36 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 10 Feb 2005 18:18:36 +0200 Subject: goto, cls, wait commands References: <1ixbe7q69lob3.1npuu3z54gx8z.dlg@40tude.net> Message-ID: On Thu, 10 Feb 2005 16:59:04 +0100, rumours say that BOOGIEMAN might have written: Best advice: try to forget QBasic, and try again reading the tutorial. That, if your post is serious. If it isn't, keep reading my reply :) >I've just finished reading Python turtorial for non-programmers >and I haven't found there anything about some usefull commands I used in >QBasic. First of all, what's Python command equivalent to QBasic's "goto" ? goto for python: http://entrian.com/goto/index.html Please ignore the line in bold red. >Secondly, how do I clear screen (cls) from text and other content ? Python clears after itself, so you don't need to. If you insist though, .>> import os .>> os.system('cls') That on a windows "console". If on IDLE, try closing the window and reopening it. >And last, how do I put program to wait certain amount of seconds ? >If I remeber correctly I used to type "Wait 10" and QBasic waits >10 seconds before proceeding to next command. (A serious answer for a change) Waiting is time related. So import time and call the time.sleep function. Try entering help at a Python prompt. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From pipedreamergrey at gmail.com Tue Feb 22 15:46:19 2005 From: pipedreamergrey at gmail.com (PipedreamerGrey) Date: 22 Feb 2005 12:46:19 -0800 Subject: PythonCard and Py2Exe Message-ID: <1109105179.230092.202750@g14g2000cwa.googlegroups.com> I'm trying to create a standalone version (.exe) of PythonCard's Custdb sample using Py2Exe version 0.5.0. Everytime I attempt to compile the program, I get an error during compilation. This is the exact code I'm using in the setup file: from distutils.core import setup import py2exe setup( name = "custdb", console = ["custdb.py"], data_files = [ (".", ["custdb.ini", "custdb.de.rsrc.py", "custdb.rsrc.py", "customerdata.csv"]) ] ) This is the error message I get when I run custdb.exe: Traceback (most recent call last): File "custdb.py", line 202, in ? app = model.Application(CustDbStack) File "PythonCard\model.pyc", line 337, in __init__ File "PythonCard\resource.pyc", line 48, in getResource File "PythonCard\resource.pyc", line 86, in __init__ File "PythonCard\resource.pyc", line 91, in __init__ File "PythonCard\resource.pyc", line 91, in __init__ File "PythonCard\resource.pyc", line 96, in __init__ File "PythonCard\resource.pyc", line 139, in enforceSpec File "PythonCard\resource.pyc", line 30, in loadComponentModule ImportError: cannot import module 'radiogroup When I add "radiogroup" to the imports at the top of custdb.py, I get this error message: Traceback (most recent call last): File "custdb.py", line 18, in ? ImportError: cannot import name radiogroup This is line 18 in Custdb.py: from PythonCard import dialog, model, radiogroup From gmachlev at cisco.com Sun Feb 13 08:44:53 2005 From: gmachlev at cisco.com (Guy Machlev (gmachlev)) Date: Sun, 13 Feb 2005 14:44:53 +0100 Subject: Probel with socket "recv" function on Win2000 Message-ID: <8C22373EA650AF40928EEA0C188D62D201810286@xmb-ams-338.emea.cisco.com> Hi, I have a problem with the socket recv() function while using it on win-2000, the problem accrue while receiving data from socket in a constant format (e.g. 1Byte then 4Bytes and then number of bytes according to the previous 4Bytes number), this receiving action "fail" after a bout ~120Kbytes of data the, actually the phenomena that accrue after reading this amount of data is a kind of data skipping which mean that the next recv is reading data start from ~121Kbytes I am losing data between the 120 and 121, this phenomena is consistently happened exactly at the same data point. I have tried to run the same script on Linux and there it went perfect. anyone has any idea way it happened ? thanks Guy. -------------- next part -------------- An HTML attachment was scrubbed... URL: From apardon at forel.vub.ac.be Mon Feb 7 08:00:32 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 Feb 2005 13:00:32 GMT Subject: variable declaration References: <4202A022.3050209@netscape.net> Message-ID: Op 2005-02-05, Nick Coghlan schreef : > [ ... ] > > With a rebinding operator, the intent of the last line can be made explicit: > > def collapse(iterable): > it = iter(iterable) > lastitem = it.next() > yield lastitem > for item in it: > if item != lastitem: > yield item > lastitem .= item > > (Note that doing this *will* slow the code down, though, since it has to check > for the existence of the name before rebinding it) I think that most of the time it won't slow down the code as the checking will have been done during the compilation phase. It may even speed up code like this, because the compilation phase will have established that it is a rebinding and so code for testing whether a new variable is created or not is not necessarry here. -- Antoon Pardon From knight at baldmt.com Sun Feb 13 10:49:16 2005 From: knight at baldmt.com (knight at baldmt.com) Date: 13 Feb 2005 07:49:16 -0800 Subject: SCons build tool speed References: Message-ID: <1108309756.236396.201830@o13g2000cwo.googlegroups.com> Hi Peter-- > > How does the speed of the Scons build tool compare with > > Ant? Right now with out Ant builds take around an hour. Hoping > > to speed that up. > > Don't tools like Scons, Ant, and for that matter "make" just > execute other programs? So that 99% of the time is consumed > external to the Scons, Ant, or make process itself? Why > do you think the speed of the build tool is of any significance > compared to the time for things like compilers and linkers > to execute? You're right that build times are dominated by the external commands when rebuilds occur. If nothing needs to be rebuilt, though, the wall-clock time is obviously dominated by how long it takes for the build tool to decide that. A build tool that doesn't decide whether or not targets are up-to-date *and* dispatch the commnds to rebuild them reasonably quickly and efficiently doesn't do a good job of serving its users. --SK From mefjr75 at hotmail.com Thu Feb 3 23:39:45 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 3 Feb 2005 20:39:45 -0800 Subject: advice needed for simple python web app In-Reply-To: <5cqdnZX-cZ9ca5_fRVn-3Q@rogers.com> References: <5cqdnZX-cZ9ca5_fRVn-3Q@rogers.com> Message-ID: <1107491985.187092.268580@o13g2000cwo.googlegroups.com> I am no web expert but have recently used cherrypy to 'webify' a script. It is very easy to get going and has its own server or can be run behind Apache. The only real problem I see is that the docs are still a little lite for the new 2.0 series ,but they do have a newsgroup where the author still answers questions. Cherrypy2 is fairly logical and most of it is covered in the examples on there website. I can not speak for the other packages,have not used them yet ;) hth, M.E.Farmer From jan.dries at dcube-resource.be Fri Feb 4 18:50:34 2005 From: jan.dries at dcube-resource.be (Jan Dries) Date: Sat, 05 Feb 2005 00:50:34 +0100 Subject: [EVALUATION] - E01: The Java Failure - May Python Helps? In-Reply-To: References: Message-ID: <42040A4A.7060403@dcube-resource.be> Fredrik Lundh wrote: > Markus Wankus wrote: > >>Google his name - he has been banned from Netbeans and Eclipse (and Hibernate, and others...) for >>good reason. Can you imagine how much of a Troll you need to be to *actually* get "banned" from >>the newsgroups of open source projects such as those? > > have Pythoneers ever "banned" anyone from a public forum? it's not like > we haven't seen trolls and crackpots before, you know. Well, we don't have to ban them because we have the PSU eliminate them alltogether. So much more efficient. Or do you think it's a coincidence we've never seen or heard Timothy "autocoding" Rue again? Be afraid, Xah, be very afraid. Regards, Jan From http Wed Feb 16 09:37:09 2005 From: http (Paul Rubin) Date: 16 Feb 2005 06:37:09 -0800 Subject: low-end persistence strategies? References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <37h194F50j4pkU1@individual.net> <7xfyzwehq7.fsf@ruckus.brouhaha.com> <37h2keF5a2ijjU1@individual.net> Message-ID: <7xwtt8a7vu.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > > I think it's way too heavyweight for what I'm envisioning, but I > > haven't used it yet. I'm less concerned about object persistence > > (just saving strings is good enough) than finding the simplest > > possible approach to dealing with concurrent update attempts. > > And that's exactly where zodb comes into play. It has full ACID support. > Opening a zodb is a matter of three lines of code - not to be compared to > rdbms'ses. The issue with using an rdbms is not with the small amount of code needed to connect to it and query it, but in the overhead of installing the huge piece of software (the rdbms) itself, and keeping the rdbms server running all the time so the infrequently used app can connect to it. ZODB is also a big piece of software to install. Is it at least 100% Python with no C modules required? Does it need a separate server process? If it needs either C modules or a separate server, it really can't be called a low-end strategy. From aahz at pythoncraft.com Sat Feb 12 19:13:17 2005 From: aahz at pythoncraft.com (Aahz) Date: 12 Feb 2005 19:13:17 -0500 Subject: Kill GIL (was Re: multi threading in multi processor (computer)) References: <1107961698.225373.247440@l41g2000cwc.googlegroups.com> <1107964587.818199.223980@g14g2000cwa.googlegroups.com> <7xr7jlwieq.fsf@ruckus.brouhaha.com> Message-ID: In article <7xr7jlwieq.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >The day is coming when even cheap computers have multiple cpu's. >See hyperthreading and the coming multi-core P4's, and the finally >announced Cell processor. > >Conclusion: the GIL must die. It's not clear to what extent these processors will perform well with shared memory space. One of the things I remember most about Bruce Eckel's discussions of Java and threading is just how broken Java's threading model is in certain respects when it comes to CPU caches failing to maintain cache coherency. It's always going to be true that getting fully scaled performance will require more CPUs with non-shared memory -- that's going to mean IPC with multiple processes instead of threads. Don't get me wrong -- I'm probably one of the bigger boosters of threads. But it bugs me when people think that getting rid of the GIL will be the Holy Grail of Python performance. No way. No how. No time. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "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." --GvR From jamesthiele.usenet at gmail.com Thu Feb 24 13:57:58 2005 From: jamesthiele.usenet at gmail.com (jamesthiele.usenet at gmail.com) Date: 24 Feb 2005 10:57:58 -0800 Subject: Mapping operator tokens to special methods Message-ID: <1109271478.871224.272750@g14g2000cwa.googlegroups.com> I was starting to write a dictionary to map operator strings to their equivalent special methods such as: { '+' : 'add', '&' : 'and_' } The idea is to build a simple interactive calculator. and was wondering if there is already something like this builtin? Or is there a better way to do what I want? From bvande at po-box.mcgill.ca Tue Feb 8 11:55:07 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 08 Feb 2005 11:55:07 -0500 Subject: variable declaration In-Reply-To: <4208178F.40804@po-box.mcgill.ca> References: <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com> <4208178F.40804@po-box.mcgill.ca> Message-ID: <4208EEEB.3050207@po-box.mcgill.ca> Brian van den Broek said unto the world upon 2005-02-07 20:36: > Steve Holden said unto the world upon 2005-02-07 17:51: >> The reason global is a wart can clearly be seen in the following example: >> >> >>> x = 3 >> >>> def f(tf, v): >> ... if tf: >> ... global x >> ... x = v >> ... >> >>> f(0, 5) >> >>> x >> 5 >> >>> > Hi, > > Steve's example makes my brain hurt. :-) > > I'd appreciate it if someone could tell me if I am understanding the > example correctly. (My grasp of the terminology and issues at play is a > bit shaky.) > Thanks for any confirmation of my understanding / rectification of same. > Best, > > Brian vdB Thanks to everyone whose contributed to this sub-thread! I've learned a lot. :-) And, for posterity, some one wrote me off-list to correct my claim that in if False: # thousands of lines of code here the thousands of lines "would never get executed". Simplifying their example, they pointed out: >>> False = 'evil trickery' >>> if False: ... print 'Surprise!' ... Surprise! >>> Which leads me naturally to the differences between 'if False:' and 'if ):' that Duncan Booth pointed to. (Where'd I put the Tylenol.) Thanks again to all, Brian vdB From bvdeenen at xs-four-all.nl.invalid Wed Feb 23 13:57:34 2005 From: bvdeenen at xs-four-all.nl.invalid (Bart van Deenen) Date: Wed, 23 Feb 2005 19:57:34 +0100 Subject: Don't understand global variables between modules References: <4219ba1f$0$162$e4fe514c@dreader14.news.xs4all.nl> Message-ID: <1gsgcp8.rstw901izkwb0N%bvdeenen@xs-four-all.nl.invalid> Hi thanks for the answer. Coming from C and C++ this behaviour wasn't really obvious to me. I still love Python though :-) Most elegant language I've ever seen. Bart From noahspurrier at gmail.com Tue Feb 22 18:59:52 2005 From: noahspurrier at gmail.com (Noah) Date: 22 Feb 2005 15:59:52 -0800 Subject: Can I get message filename from a Maildir mailbox stream? In-Reply-To: References: <1108778311.300124.56920@f14g2000cwb.googlegroups.com> Message-ID: <1109116792.529974.308840@f14g2000cwb.googlegroups.com> This didn't work. I'm using the standard Python 2.3.4 library mailbox.Maildir. I got an error that message instance has no attribute 'fp'. I ended up not using mailbox.Maildir at all. It occured to me that since Maildir style mailboxes is just a collection of files that it was simpler to write a generator that walked the directory using os.listdir. def Maildir_messages (path): d = os.listdir(path) for filename in d: fin = file (os.path.join(path, filename)) yield (email.message_from_file(fin), filename) fin.close() for msg, msg_filename in Maildir_messages ("/home/noah/Maildir/new"): print msg_filename print msg['Subject'] Yours, Noah From v451v at yahoo.com Thu Feb 3 16:22:58 2005 From: v451v at yahoo.com (Jorl Shefner) Date: Thu, 03 Feb 2005 16:22:58 -0500 Subject: Reinstall python 2.3 on OSX 10.3.5? References: Message-ID: <36fj01F508ugpU1@individual.net> In article , Robert Kern wrote: > Christian Dieterich wrote: > > On D? C?adaoin, Feabh 2, 2005, at 17:48 America/Chicago, > > moa at extrapolation.com wrote: > > > >> Hi there > >> > >> I started a very long and roundabout process of attempting to install > >> python 2.3.4 along side my apple-installed 2.3 system. To make a long > >> story short, I have completely confabulated my environment ( i deleted > >> the 2.3 binaries and so forth from the system in an attempt to start > >> things fresh), and now I cannot figure out how to reinstall the base > >> 2.3 Apple python distribution. > >> Can somebody please point me in the right direction? > > > > > > You could use > > fink install python > > which makes you a Python installation under /sw. > > But that doesn't solve his problem, which is to restore the > Apple-supplied Python that he deleted. I use a version of 2.3.4 on my Os X system that I installed myself without any apparent loss of functionality. What extra advantages is the Apple installed version supposed to provide? J.S. From quentel.pierre at wanadoo.fr Fri Feb 18 01:32:17 2005 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Fri, 18 Feb 2005 07:32:17 +0100 Subject: low-end persistence strategies? In-Reply-To: <7xr7jezxlh.fsf@ruckus.brouhaha.com> References: <7xll9pus7o.fsf_-_@ruckus.brouhaha.com> <4214f9ba$0$832$8fcfb975@news.wanadoo.fr> <7xr7jezxlh.fsf@ruckus.brouhaha.com> Message-ID: <42158bf1$0$6624$8fcfb975@news.wanadoo.fr> If a dozen people click the url in the next day, several of > them will probably in the first minute or so after the email goes out. > So two simultaneous clicks isn't implausible. > More generally, I don't like writing code with bugs even if the bugs > have fairly low chance of causing trouble. So I'm looking for the > easiest way to do this kind of thing without bugs. Even if the 12 requests occur in the same 5 minutes, the time needed for a read or write operation on a small base of any kind (flat file, dbm, shelve, etc) is so small that the probability of concurrence is very close to zero If you still want to avoid it, you'll have to pay some price. The most simple and portable is a client/server mode, as suggested for KirbyBase for instance. Yes, you have to run the server 24 hours a day, but you're already running the web server 24/7 anyway From francis.girard at free.fr Sun Feb 13 13:58:27 2005 From: francis.girard at free.fr (Francis Girard) Date: Sun, 13 Feb 2005 19:58:27 +0100 Subject: Iterator / Iteratable confusion In-Reply-To: <200502131848.03655.francis.girard@free.fr> References: <420a5c1e$0$21630$a1866201@visi.com> <200502131848.03655.francis.girard@free.fr> Message-ID: <200502131958.27410.francis.girard@free.fr> Hi, I wrote simple dummy examples to teach to myself iterators and generators. I think that the iteration protocol brings a very neat confusion between the iterator and what it iterates upon (i.e. the iteratable). This is outlined in "example 3" in my dummy examples. What are your feelings about it ? Regards Francis Girard ==== BEGINNING OF EXAMPLES ==== from itertools import tee, imap, izip, islice import sys import traceback sEx1Doc = \ """ ================================================================================ Example 1: ================================================================================ An ""iteratable"" class is a class supporting the __iter__ method which should return an ""iterator"" instance, that is, an instance of a class supporting the "next" method. An iteratable, strictly speaking, doesn't have to support the "next" method and an "iterator" doesn't have to support the "__iter__" method (but this breaks the iteration protocol as we will later see). The ""for ... in ..."" construct now expect an iteratable instance in its second argument place. It first invoke its __iter__ method and then repeatedly invoke the ""next"" method on the object returned by ""__iter__"" until the ""StopIteration"" exception is raised. The designing goal is to cleanly separate a container class with the way we iterate over its internal elements. """ class Ex1_IteratableContClass: def __init__(self): print "Ex1_IteratableContClass.__init__" self._vn = range(0,10) def elAt(self, nIdx): print "Ex1_IteratableContClass.elAt" return self._vn[nIdx] def __iter__(self): print "Ex1_IteratableContClass.__iter__" return Ex1_IteratorContClass(self) class Ex1_IteratorContClass: def __init__(self, cont): print "Ex1_IteratorContClass.__init__" self._cont = cont self._nIdx = -1 def next(self): print "Ex1_IteratorContClass.next" self._nIdx += 1 try: return self._cont.elAt(self._nIdx) except IndexError: raise StopIteration print print sEx1Doc print for n in Ex1_IteratableContClass(): print n, sys.stdout.flush() sEx2Doc = \ """ ================================================================================ Example 2: ================================================================================ Let's say that we want to give two ways to iterate over the elements of our example container class. The default way is to iterate in direct order and we want to add the possibility to iterate in reverse order. We simply add another ""iterator"" class. We do not want to modify the container class as, precisely, the goal is to decouple the container from iteration. """ class Ex2_IteratableContClass: def __init__(self): print "Ex2_IteratableContClass.__init__" self._vn = range(0,10) def elAt(self, nIdx): print "Ex2_IteratableContClass.elAt" return self._vn[nIdx] def __iter__(self): print "Ex2_IteratableContClass.__iter__" return Ex1_IteratorContClass(self) class Ex2_RevIteratorContClass: def __init__(self, cont): print "Ex2_RevIteratorContClass.__init__" self._cont = cont self._nIdx = 0 def next(self): print "Ex2_RevIteratorContClass.next" self._nIdx -= 1 try: return self._cont.elAt(self._nIdx) except IndexError: raise StopIteration print print sEx2Doc print print "Default iteration works as before" print for n in Ex2_IteratableContClass(): print n, sys.stdout.flush() print print "But reverse iterator fails with an error : " print cont = Ex2_IteratableContClass() try: for n in Ex2_RevIteratorContClass(cont): print n, sys.stdout.flush() except: traceback.print_exc() sEx3Doc = \ """ ================================================================================ Example 3. ================================================================================ The previous example fails with the "iteration over non sequence" error because the "Ex2_RevIteratorContClass" iterator class doesn't support the __iter__ method. We therefore have to supply one, even at the price of only returning ""self"". I think this is ugly because it baffles the distinction between iterators and iteratables and we artificially have to add an ""__iter__"" method to the iterator itself, which should return ... well, an iterator, which it already is ! I presume that the rationale behind this is to keep the feature that the second argument place of the ""for ... in ..."" should be filled by a container (i.e. an iteratable), not an iterator. Another way that Python might have done this without breaking existing code is to make the ""for ... in ..."" construct invoke the __iter__ method if it exists, otherwise, directly call the ""next"" method on the supplied object. But this is only a minor quirk as the decoupling of the iterator from the iteratable is nonetheless achieved at the (small) price of adding an "almost" useless method. So here it is. """ class Ex3_RevIteratorContClass: def __init__(self, cont): print "Ex3_RevIteratorContClass.__init__" self._cont = cont self._nIdx = 0 def __iter__(self): print "Ex3_RevIteratorContClass.__iter__" return self ## zut ! def next(self): print "Ex3_RevIteratorContClass.next" self._nIdx -= 1 try: return self._cont.elAt(self._nIdx) except IndexError: raise StopIteration print print sEx3Doc print cont = Ex2_IteratableContClass() for n in Ex3_RevIteratorContClass(cont): print n, sys.stdout.flush() sEx4Doc = \ """ ================================================================================ Example 4. ================================================================================ Since version 2.2, a new built-in function is offered that simply takes an iteratable as argument and returns an iterator by calling its "__iter__". As long as only iteratables/iterators are involved, this is no big deal as ""iter(anIteratable)"" is strictly equivalent to ""anIteratable.__iter__()"". The real advantage in using this function is that is also accepts containers supporting the sequence protocol (the __getitem__() method with integer arguments starting at 0). The ""iter"" methods also returns an iterator for this case. We can therefore write a function accepting a container as argument that, with the same code, can either support the iteration protocol or the sequence protocol. """ class Ex4_IteratableContClass: def __init__(self): print "Ex4_IteratableContClass.__init__" self._vn = range(0,10) def elAt(self, nIdx): print "Ex4_IteratableContClass.elAt" return self._vn[nIdx] def __iter__(self): print "Ex4_IteratableContClass.__iter__" return Ex4_IteratorContClass(self) class Ex4_IteratorContClass: def __init__(self, cont): print "Ex4_IteratorContClass.__init__" self._cont = cont self._nIdx = -1 def __iter__(self): print "Ex4_RevIteratorContClass.__iter__" return self ## zut ! def next(self): print "Ex4_IteratorContClass.next" self._nIdx += 1 try: return self._cont.elAt(self._nIdx) except IndexError: raise StopIteration class Ex4_SequenceContClass: def __init__(self): print "Ex4_SequenceContClass.__init__" self._vn = range(0,10) def elAt(self, nIdx): print "Ex4_SequenceContClass.elAt" return self._vn[nIdx] def __getitem__(self, key): print "Ex4_IteratableContClass.__getitem__" return self.elAt(key) def Ex4_FuncPrintContainerEl(cont): for n in iter(cont): print n, sys.stdout.flush() print print sEx4Doc print print print "Applying Ex4_FuncPrintContainerEl to an iteratable container" print Ex4_FuncPrintContainerEl(Ex4_IteratableContClass()) print print "Applying Ex4_FuncPrintContainerEl to a sequence container" print Ex4_FuncPrintContainerEl(Ex4_SequenceContClass()) sEx5Doc = \ """ ================================================================================ Example 5. ================================================================================ Introducing Generators The "generator" term itself is frequently used with two different meanings. It is sometimes used to mean "generator function" and sometimes to mean "generator-iterator". The PEP255 and python mailing list are the two only places where I could read something that clearly distinguishes the two notions. A generator-function can be first seen as only a notational artefact to generate an iterator. The generated iterator is called a generator-iterator and it is, by its intimate nature, both an iterator and an iteratable. (This might very well be another reason why the iteration protocol baffles the distinction betweeen iterators and iteratables.) Typically (but not necessarily), the generator-iterator is such that the elements do not pre-exist but are "generated" as needed while iteration is going on. Here is an example of a generator-function and the equivalent iterator class. The function ""Ex5_GenList"" can be seen as just a notational shortcut to the equivalent Ex5_GenListIteratorClass class. """ def Ex5_GenList(): print "Enters Ex5_GenList" i = 0 while i < 10: print "Ex5_GenList yields -- Equivalent to have a it.next() return" yield i i += 1 print "Ex5_GenList exits, equivalent to : raise StopIteration" class Ex5_GenListIteratorClass: def __init__(self): print "Ex5_GenListIteratorClass.__init__" self._i = 0 def __iter__(self): print "Ex5_GenListIteratorClass.__iter__" return self def next(self): print "Ex5_GenListIteratorClass.next" nReturn = self._i if nReturn > 9: print "Ex5_GenListIteratorClass.next raises the StopIteration exception" raise StopIteration self._i += 1 return nReturn print print sEx5Doc print print "The type of Ex5_GenList() is : %s" % type(Ex5_GenList()) print "Although it is really meant generator-iterator" print "As you can see, calling Ex5_GenList() didn't enter the function since our" print "trace \"Enters Ex5_GenList\" had not been printed." print "It only produced the generator-iterator." print print "for n in Ex5_GenList(): gives:" print for n in Ex5_GenList(): print n, sys.stdout.flush() print print "The type of Ex5_GenList is : %s" % type(Ex5_GenList) print "Although it is really meant generator-function" print print "for n in Ex5_GenList: gives:" print try: for n in Ex5_GenList: print n, sys.stdout.flush() except: traceback.print_exc() print print "The type of Ex5_GenList().__iter__() is : %s" % type(Ex5_GenList().__iter__()) print print "for n in Ex5_GenList().__iter__(): gives:" print for n in Ex5_GenList().__iter__(): print n, sys.stdout.flush() print print "it = Ex5_GenList()" print "for n in it(): gives:" print it = Ex5_GenList() try: for n in it(): print n, sys.stdout.flush() except: traceback.print_exc() print "The iterator produced by Ex5_GenList() is obviously not itself callable" print print "for n in Ex5_GenListIteratorClass(): gives:" print for n in Ex5_GenListIteratorClass(): print n, sys.stdout.flush() sEx6Doc = \ """ ================================================================================ Example 6 ================================================================================ After having distinguished iteratable from iterator and generator-function from generator-iterator, and having seen how generator-iterator makes iterable and iterator undistinguishables, we are now ready for some real work. There is now a real vocabulary problem in the Python community but I think that it is now clear enough. Our first pseudo-real-world example is to produce the Fibonacci sequence using a simple generator. The Ex6_Fibonacci() is a bit special as it never stops. This is one way to implement something similar to infinite lists in python. """ def Ex6_Fibonacci(): a = 1 b = 1 yield a yield b while True: bb = a + b a = b b = bb yield bb print print sEx6Doc print it = Ex6_Fibonacci() for i in xrange(0,10): print it.next() sEx7Doc = \ """ ================================================================================ Example 7 ================================================================================ A beautiful algorithm to produce the fibonacci sequence goes by noticing that : fib(i) = 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, ... fib(i+1) = 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, ... fib(i)+fib(i+1) = 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, ... Generators now enable us to ""run after our tail"". We will exploit the Fibonacci sequence property shown above by defining a function that produces and returns a "list" while the production algorithm supposes the list as having been already produced by recursively calling itself. In order to be able to do this, we need to initiate the processus by explicitly giving the first values. We also need that the list must be produced "lazily" ; i.e. the values must be produced only as needed ... well needed to produce the next element in the ""list"" in our case. Here is a first try that will almost work. """ ## Without the traces: ## ## def Ex7_Fibonacci(): ## yield 1 ## yield 1 ## itTail = Ex7_Fibonacci() ## itTail.next() # Skip the first one ## for n in (head + tail for (head, tail) in izip(Ex7_Fibonacci(), itTail)): ## yield n N_STACK_DEPTH = 0 def Ex7_Fibonacci(): global N_STACK_DEPTH N_STACK_DEPTH += 1 nStackDepth = N_STACK_DEPTH print "[%d] Entering Ex7_Fibonacci" % nStackDepth print "[%d] Yielding 1" % nStackDepth yield 1 print "[%d] Yielding 1" % nStackDepth yield 1 itTail = Ex7_Fibonacci() itTail.next() # Skip the first one for n in (head + tail for (head, tail) in izip(Ex7_Fibonacci(), itTail)): print "[%d] Yielding %d" % (nStackDepth, n) yield n print print sEx7Doc print print list(islice(Ex7_Fibonacci(), 5)) sEx8Doc = \ """ ================================================================================ Example 8 ================================================================================ Running after your tail with itertools.tee Example 7 shows that although the idea is beautiful, the implementation is very inefficient. To work efficiently, the beginning of the list must not be recomputed over and over again. This is ensured in most FP languages as a built-in feature. In python, we have to explicitly maintain a list of already computed results and abandon genuine recursivity. The "tee" function does just what we want. It internally keeps a generated result for as long as it has not been "consumed" from all of the duplicated iterators, whereupon it is deleted. You can therefore print the Fibonacci sequence during hours without increasing memory usage, or very little. The beauty of it is that recursive running after their tail FP algorithms are quite straightforwardly expressed with this Python idiom. """ def Ex8_Fibonacci(): print "Entering Ex8_Fibonacci" def _Ex8_Fibonacci(): print "Entering _Ex8_Fibonacci" yield 1 yield 1 fibTail.next() # Skip the first one for n in (head + tail for (head, tail) in izip(fibHead, fibTail)): yield n fibHead, fibTail, fibRes = tee(_Ex8_Fibonacci(), 3) return fibRes print print sEx8Doc print print list(islice(Ex8_Fibonacci(), 5)) From apardon at forel.vub.ac.be Mon Feb 21 07:41:20 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 21 Feb 2005 12:41:20 GMT Subject: lambda closure question References: <1108798951.128843.79810@f14g2000cwb.googlegroups.com> <1108802613.284686.200170@o13g2000cwo.googlegroups.com> Message-ID: Op 2005-02-21, jfj schreef : > Antoon Pardon wrote: >> Op 2005-02-19, jfj schreef : >> >>>once foo() returns there is no way to modify 'x'! >>>It becomes a kind of constant. >> >> >> In this particular case yes. But not in general, what about >> this: >> >> >>>>>def F(): >> >> ... l = [] >> ... def pop(): >> ... return l.pop() >> ... def push(e): >> ... l.append(e) >> ... return pop, push >> ... >> > > Others will point this out, but if I'm fast enough... > > This does not change the object referenced by l. > It calls methods of it and because it is mutable the containts > of the list are modified. > 'l' is a list at address, 0xXXXX and that can never change once > F() has returned. I'm sorry but in my understanding of english mutating an object is changing or modifying it. Yes it is stil the same list but that list was not unmodified. But I'll get back at what seems you actually wanted to say: That there is no way to rebind 'x' or in my case 'l' and with that I have to agree although I personnaly find that a lack in python -- Antoon Pardon From mefjr75 at hotmail.com Mon Feb 7 00:10:30 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 6 Feb 2005 21:10:30 -0800 Subject: pygame.mixer.music not playing In-Reply-To: <36o9dvF53a94mU1@individual.net> References: <36mb0iF54udklU1@individual.net> <1107700800.258876.298010@z14g2000cwz.googlegroups.com> <36mvjkF54gvnrU1@individual.net> <1107748705.808825.319270@f14g2000cwb.googlegroups.com> <36o9dvF53a94mU1@individual.net> Message-ID: <1107753030.904833.179800@z14g2000cwz.googlegroups.com> Just curious what is not suitable about FMOD ? It seems to be exactly what you are looking for. Cross platform, free, great sound, python bindings, no compiler needed. M.E.Farmer From alec at thened.net Thu Feb 10 12:47:24 2005 From: alec at thened.net (Alec Berryman) Date: Thu, 10 Feb 2005 12:47:24 -0500 Subject: [N00B] What's %? In-Reply-To: <614c778e.0502100938.6665cb52@posting.google.com> References: <614c778e.0502100938.6665cb52@posting.google.com> Message-ID: <20050210174724.GC3416@thened.net> administrata on 2005-02-10 09:38:41 -0800: > Hi! it's been about a week learning python! > I've read 'python programming for the absolute begginer' > I don't understand about % like... > > 107 % 4 = 3 > 7 % 3 = 1 > > I'm confused with division :/ It's not division; the division operator is '/'. It's the mod function, which returns the remainder - for example, 7 divided by 3 is 2 remainder 1, so 7 % 3 returns 1. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From vze4rx4y at verizon.net Sat Feb 12 19:15:39 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 13 Feb 2005 00:15:39 GMT Subject: [PATCH] Re: frozenset() without arguments should return a singleton References: <001701c51145$410e50c0$deae958d@oemcomputer> Message-ID: > > It is not quite correct to say that this is what all immutables do: > > > >.>>>x = 500 > >.>>>y = 600 - 100 > >.>>>x is y > > False > > I know. The same is true for concateneted strings, etc. But whenever an > immutable object is created directly ('by hand'), it holds. It also holds, > btw, for tuple() - as opposed to (). That is an implementation detail, not guaranteed by the language (i.e. not necessarily true in future versions, in Jython, or other implementations). It is just an optimization that made sense for tuples but not necessarily for other immutables. > I actually use frozensets whenever I know that my set is going to be immutable > (I thought that was what they were meant for). That is a reasonable use. I like it because it is explicit about your intent. Guido, on the other hand, would probably object because it is akin to saying that () should be passed for an empty list in situations where the list is expected not to mutate. > And similar to the usage of tuples as replacements for empty lists, I > definitely pass a frozenset whenever I need a dummy set-like object. > If I know that frozenset() is not constant, I may end up with keeping a dummy > reference around somewhere that is passed instead of a 'new' frozenset(). That solution is reasonable and portable: emptyset = frozenset() f('abc', emptyset) g('def', emtpyset) h(1, 2, emtpyset, True) . . . I also find it be more readable than: f('abc', frozenset()) g('def', frozenset()) h(1, 2, emtpyset, frozenset()) FWIW, the latter form entails three failed lookups into the local scope and three successful lookups in the __builtin__ scope. Since the former can store emptyset as a local variable, it can be accessed with no lookups at all. Also, the latter forms incur extra trips around the eval-loop and call-function overhead. IOW, yoursavings = time_to_allocate_an_emtpy_set - builtin_lookup_time - eval_loop_and_call_overhead - extra_time_building_non_emtpy_sets. I suspect the net savings to be near zilch. > Also, I don't know what else needs to be changed and what a difference that > makes. But if the added code is reasonably limited, I'd vote for it. Will think about it for a while. I'm not terribly opposed to the idea. I just find the case for it to be somewhat weak. Also, I'm not sure it warrants the effort, the code clutter, or introducing issues like having a semantic difference between the result of frozenset() and the result of frozenset([]). Raymond Hettinger From PDunce at somewhere.invalid Mon Feb 7 02:22:35 2005 From: PDunce at somewhere.invalid (Python Dunce) Date: 07 Feb 2005 07:22:35 GMT Subject: Dumb glob question Message-ID: I've run into an issue with glob and matching filenames with brackets '[]' in them. The problem comes when I'm using part of such a filename as the path I'm passing to glob. Here's a trimmed down dumb example. Let's say I have a directory with the following files in it. foo.par2 foo.vol0+1.par2 foo.vol1+1.par2 zzz [foo].par2 zzz [foo].vol0+1.par2 zzz [foo].vol1+1.par2 While processing one of the files I want to do certain things in batch so I've been using glob as a means to get all of the files in a set. The following code will print the filenames for parity volumes in each set while working with the base checksum, unless there are brackets in the name. #re2 = re.compile(r'vol', re.IGNORECASE) #for nuke in glob.glob('*.par2'): # if not re2.search(nuke): # list = glob.glob(nuke[:-5]+'*vol*') # for name in list: print os.path.join(os.getcwd(),name) I'm sure there is something obvious I'm missing. I figured I could use something like re.escape on the trimmed filename for matching but that hasn't worked either. Using win32api.FindFiles instead of glob works but I'd obviously rather do it the _right_ way and have it work properly in *nix too. From Serge.Orlov at gmail.com Thu Feb 10 11:47:29 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 10 Feb 2005 08:47:29 -0800 Subject: sre is broken in SuSE 9.2 References: <1108036791.098550.306310@g14g2000cwa.googlegroups.com> Message-ID: <1108054048.998825.64300@o13g2000cwo.googlegroups.com> Denis S. Otkidach wrote: > On 10 Feb 2005 03:59:51 -0800 > "Serge Orlov" wrote: > > > > On all platfroms \w matches all unicode letters when used with flag > > > re.UNICODE, but this doesn't work on SuSE 9.2: > [...] > > I can get the same results on RedHat's python 2.2.3 if I pass re.L > > option, it looks like this option is implicitly set in Suse. > > Looks like you are right: > > >>> import re > >>> re.compile(ur'\w+', re.U).match(u'\xe4') > >>> from locale import * > >>> setlocale(LC_ALL, 'de_DE') > 'de_DE' > >>> re.compile(ur'\w+', re.U).match(u'\xe4') > <_sre.SRE_Match object at 0x40375560> > > But I see nothing related to implicit re.L option in their patches > and the sources themselves are the same as on other platforms. I'd > prefer to find the source of problem. I found that print u'\xc4'.isalpha() import locale print locale.getlocale() produces different results on Suse (python 2.3.3) False (None, None) and RedHat (python 2.2.3) 1 (None, None) Serge. From gabriel.barros at gmail.com Tue Feb 8 20:12:13 2005 From: gabriel.barros at gmail.com (Gabriel B.) Date: Tue, 8 Feb 2005 23:12:13 -0200 Subject: tcl/tk naming scheme vs python's Message-ID: <5175a81c0502081712437d3fb0@mail.gmail.com> I got my self writting nested objects to hold Tk references, then i realizes that i was working in python and not tcl, so i switched to flat vars... and in no time i was using more then 7 words separated by captalization in the names... i was able to rethink my scheme to use 5... no less. i'm i exagerating or do you people also comes to this some times? The other choice i think i had was to use semantic names instead of semantic and hierarchical ones. Gabriel PS: i resisted the force of make an example using ButtonSpamSpamSpamSpamSpamEggsSpam From steven.bethard at gmail.com Mon Feb 21 13:44:36 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 21 Feb 2005 11:44:36 -0700 Subject: combining several lambda equations In-Reply-To: References: <2ae25c6b.0502180224.3d6164a7@posting.google.com> Message-ID: Antoon Pardon wrote: > So and if I have code like this: > > f = lamda x:x > for g in some_iter: > f = compose(g,f) > > Do you still think that one should use a named function in this case? Yes. If you really don't like taking two lines, Python still allows you to write this as: def f(x): return x for g in some_iter: f = compose(g, f) On the other hand, if you really love FP enough to write this kind of code, shouldn't you be using reduce istead? ;) I'm horrible with reduce, but something like: def identity(x): return x f = reduce(compose, some_iter, identity) or if you want to use lambda (note that my complaint about making an named function with the anonymous function syntax doesn't apply here): f = reduce(compose, some_iter, lambda x: x) Not sure if the order of composition is right here, but you get the idea. STeVe From xah at xahlee.org Tue Feb 15 07:59:30 2005 From: xah at xahlee.org (Xah Lee) Date: 15 Feb 2005 04:59:30 -0800 Subject: problem: reducing comparison In-Reply-To: <1108471704.220626.27530@g14g2000cwa.googlegroups.com> References: <1108450348.253772.158120@z14g2000cwz.googlegroups.com> <1108471704.220626.27530@g14g2000cwa.googlegroups.com> Message-ID: <1108472370.722794.85170@z14g2000cwz.googlegroups.com> my Python coding is not experienced. In this case, is ps.pop("%d,%d"%(j[1],k[1]),0) out of ordinary? if i have long paragraphs of documentation for a function, do i still just attach it below the fun def? Xah Xah Lee wrote: > here are the answers: > > ?Python code. > ? > ?def reduce(pairings, pair): > ? ps=pairings.copy(); j=pair; > ? ps.pop("%d,%d"%(j[0],j[1]),0) > ? for k in pairings.itervalues(): > ? if (k[0]==j[0]): > ? if (j[1] < k[1]): > ? ps.pop("%d,%d"%(j[1],k[1]),0) > ? else: > ? ps.pop("%d,%d"%(k[1],j[1]),0) > ? if (k[1]==j[0]): > ? if (k[0] < j[1]): > ? ps.pop("%d,%d"%(k[0],j[1]),0) > ? else: > ? ps.pop("%d,%d"%(j[1],k[0]),0) > ? return ps > ? > > In imperative languages such as Perl and Python and Java, in general it > is not safe to delete elements when looping thru a list-like entity. > (it screws up the iteration) One must make a copy first, and work with > the copy. > > Note also that in Python there's already a function called reduce. (it > is equivalent to Mathematica's Fold.) In Python, looks like user can > over-ride default functions. > > This post is archived at > http://xahlee.org/perl-python/pairing_reduce.html > Possible errata or addenda will appear there. > > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html From M.Waack at gmx.de Tue Feb 15 11:58:00 2005 From: M.Waack at gmx.de (Mathias Waack) Date: Tue, 15 Feb 2005 17:58:00 +0100 Subject: 64 bit Python References: <1cd7e2-qu7.ln1@valpo.de> Message-ID: Mike C. Fletcher wrote: > Mathias Waack wrote: > ... > >>My python script allocates a bunch of strings each of 1024 >>characters and writes it in a cStringIO. And it fails after writing >>512K of strings. Don't know how python restricts the heap size - >>but I'm fairly sure its not a restriction of the OS. >> >> > Does cStringIO require contiguous blocks of memory? I'm wondering > if maybe there's something going on where you just can't allocate > more than > a GB of contiguous space? That was the problem. I've used cStringIO to reduce the overhead by the python memory management. But now I know - that was a bad idea in this case. > What happens if you just store the > strings in > a list (or use StringIO instead of cStringIO)? It consumed 10 GB really fast, another GB really slow, some hundred MB much slower and then it died;) Mathias From tom at dtsam.com Tue Feb 1 13:04:29 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Tue, 1 Feb 2005 12:04:29 -0600 Subject: The next Xah-lee post contest References: <20050130114008.797088857.whereU@now.com> <1107137465.973491.42050@f14g2000cwb.googlegroups.com> <1107277633.959477.302860@f14g2000cwb.googlegroups.com> Message-ID: "Luis M. Gonzalez" wrote in message news:1107277633.959477.302860 at f14g2000cwb.googlegroups.com... > > Have you visited his website? > I kind of like this guy... it's like he has a few bugs in his brain, > but other parts are surprisingly interesting. I kind of like him too. I hope he manages to find a babe! As human conditions go, normalcy is *highly* overrated.. Thomas Bartkus From bill.mill at gmail.com Fri Feb 11 14:31:35 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 11 Feb 2005 14:31:35 -0500 Subject: check if object is number In-Reply-To: References: Message-ID: <797fe3d40502111131bbd7f38@mail.gmail.com> On Fri, 11 Feb 2005 12:11:44 -0700, Steven Bethard wrote: > Is there a good way to determine if an object is a numeric type? > Generally, I avoid type-checks in favor of try/except blocks, but I'm > not sure what to do in this case: > > def f(i): > ... > if x < i: > ... > > The problem is, no error will be thrown if 'i' is, say, a string: > > py> 1 < 'a' > True > py> 10000000000 < 'a' > True > > But for my code, passing a string is bad, so I'd like to provide an > appropriate error. How about: if type(variable) == type(1): print "is an integer" else: print "please input an integer" > > I thought about calling int() on the value, but this will also allow > some strings (e.g. '1'). I guess this isn't horrible, but it seems > somewhat suboptimal... > > Ideas? > > Steve > -- > http://mail.python.org/mailman/listinfo/python-list > From michael.bierenfeld at web.de Tue Feb 22 05:06:52 2005 From: michael.bierenfeld at web.de (michael) Date: 22 Feb 2005 02:06:52 -0800 Subject: Memory Based File Objects Message-ID: Hi there, I am using the Python Image package to do some Image conversion. I have a "pgm" Image and this must be converted to a "1" Bits / Sample Tiff Image. There for I am using Image.save ("lala.tiff"). *hm* A Tiff Image opt. consists of several pages so I am thinking about using the pytiff package as well. The existing code is like that parser = ImageFile.Parser () parser.feed (imagecontent) image = parser.close () # Now we have the Image image = image.convert ("1") # reduce to 1 Bits per sample image.save ("lala.tif") # Store as Tiff After everey File has been processed I am using the "tiffcp" command to append all the files to a single tiff-file containing each image as a separate page. eg. "tiffcp fileone.tiff filetwo.tiff filethree.tiff allinone.tiff" Performance is an issue here and therefore I am evaluating the pytiff package. Cause this package can reduce to "1" Bits per Sample and append to tifffiles. So the code would be like this image.save (fileobject, format="tif") tifffile = pytiff.TiffFileReader (fileobject) # do some stuff allinone = pytiff.TiffFileWriter ("allinone.tiff") allinone.append (fifffile) Of course I dont wanna write the "in between" File to disk with image.save () I do wann to to use a memory file object. The Image Documentation says that file object just has to implement seek, tell and write. Does anybody have an example how to do that or maybe a snipplet for an "In Memory" File Object with an unknown size. Kind Regards Michael From caleb1 at telkomsa.net Sun Feb 6 23:34:32 2005 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Sun, 06 Feb 2005 23:34:32 -0500 Subject: loops -> list/generator comprehensions References: <1107718117.221204.80410@l41g2000cwc.googlegroups.com> <4qCdnXI11-vhGJvfRVn-vQ@comcast.com> Message-ID: Sure Steve Lemme see ... (indentation changed so comments associate with correct bits) > Out of curiosity, do you find: > > filenames = [os.path.join(dirpath, filename) # This is cool for dirpath, _, filenames in os.walk('.') # This is getting tricky, whats the '_' for? Which thing goes where again in a comprehension? for filename in filenames] # The hierarchy has nailed me by this point. I will have to start over... Yes, yes I do find it more difficult to read. Maybe I just don't know python as well as I should (certainly not as well as others here!). I guess it is just familiarity. A single comprehension is ok, nesting them gets tricky, and 3 times is a strike for me. I will practise :) keep well Caleb From cam.ac.uk at mh391.invalid Mon Feb 28 06:09:55 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 28 Feb 2005 11:09:55 +0000 Subject: Explicit or general importing of namespaces? In-Reply-To: <38gc2tF5o34sbU1@individual.net> References: <1109588238.491145.52060@l41g2000cwc.googlegroups.com> <38gc2tF5o34sbU1@individual.net> Message-ID: Diez B. Roggisch wrote: >[Harlin Seritt]: >>Is there really a major performance difference between doing the > > No. Actually, if you are using a name in another module repeatedly in an inner loop, it can make a big difference if you have to lookup the name in the module repeatedly. In that case, just explicitly import the name you want to use repeatedly: from Tkinter import Label, otherfunction, othervariable Of course, you are not likely to see this use case when you're doing UI programming. But don't do "from Tkinter import *" for the reasons Diez has identified in the FAQ. -- Michael Hoffman From dontwant at spam.com Sat Feb 5 22:45:05 2005 From: dontwant at spam.com (Courageous) Date: Sat, 05 Feb 2005 19:45:05 -0800 Subject: [EVALUATION] - E01: The Java Failure - May Python Helps? References: Message-ID: >Well, we don't have to ban them because we have the PSU eliminate them >alltogether. So much more efficient. Or do you think it's a coincidence >we've never seen or heard Timothy "autocoding" Rue again? Foolish, man! You said his name! It's almost like you said C'thul'hu, ... you ... ah.... no, no, NO! N'YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH *insert ripping and splashing sounds* From fperez.net at gmail.com Thu Feb 3 18:10:40 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 03 Feb 2005 16:10:40 -0700 Subject: python-mode tab completion problem References: <1107467959.821309.102850@z14g2000cwz.googlegroups.com> <16898.42642.530502.108487@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > > test1dellboy3> I am exploring python-mode on emacs. When I open foo.py > test1dellboy3> in emacs and hit C-!, it starts the python interpreter in > test1dellboy3> another window. Next, I execute - > > ... > > That's not really intended to be used as an interactive session with all > sorts of bells and whistles. Or he can use ipython, which with the special ipython.el companion file and a recent (CVS) python-mode, will give him true tab completion (with options listed in an emacs *completions* buffer) for all objects. With ipython's %pdb active, it will also open up the source at any uncaught exception, at the line of the exception. Very handy for debugging. Regards, f ps. All this fanciness is thanks to the sustained efforts of A. Schmolck and P. Ramachandran, I'm just happy to use them (I can't code a line of elisp). From Scott.Daniels at Acm.Org Mon Feb 14 15:14:45 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 14 Feb 2005 12:14:45 -0800 Subject: For American numbers In-Reply-To: References: <420e7376$1@nntp0.pdx.net> Message-ID: <421102d6$1@nntp0.pdx.net> Neil Benn wrote: > Scott David Daniels wrote: >> Kind of fun exercise (no good for British English). > what's American about it? If anything, it's more French than American ;-) Well, actually this started with scaling integers, and I was worried about a billion / billionth (and up / down). In mid-task I switched to ISO prefix without bothering to update my mental state. So I warned about a problem that a former version of this code had. As I hit send, I realized my stupidity, but figured I was better off not wasting more bandwidth (which I now have done). If I had it to do over again, I'd have made the default unit something like meters -- again non-British, and it avoids the issue of 1024 / 1000 altogether. grinning-stupidly, Scott David Daniels Scott.Daniels at Acm.Org From eric_brunel at despammed.com Wed Feb 9 07:10:59 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 09 Feb 2005 13:10:59 +0100 Subject: tkinter menu bar problem References: Message-ID: On Wed, 09 Feb 2005 11:35:40 GMT, John Pote wrote: > I have a menu bar in a top level window as follows [snip code] > > Q1 Cannot find a way of changing the menu bars background colour. When > colour options are accepted they seem to be ignored. Is this a native > look > and feel characteristic of write once run anywhere, not yet implemented > or > possibly a bug. Even if the tk man pages [1] don't mention it, it would not be surprising if the background option for menu items did not work on Windows, since many things seem to be "hardcoded" on this platform. I tested the following code on Linux; it works without problem and has the expected behaviour: >>> from Tkinter import * >>> root = Tk() >>> mb = Menu(root) >>> root.configure(menu=mb) >>> m = Menu(mb) >>> mb.add_cascade(label='Menu', menu=m) >>> m.add_command(label='Quit', command=root.quit, background='red') If it is what you did and if it doesn't work on Windows, it is likely that the background option for menu items is not supported for this platform... > Q2 Some of the menu options in the config menu will not always be > available > depending on program state. How can individual items in such a menu be > turned to faint gey to indicate their unavailability. Also a tick mark > against an item would be useful to show the currently selected option. Is > this possible? To "grey out" a menu item: parentMenu.entryconfigure(itemIndex, state=DISABLED) To have menu items with a check-mark, use the add_checkbutton or add_radiobutton methods on the parent menu. Their use is similar to the Checkbutton and Radiobutton classes. See [1] for all available options. [1] http://www.tcl.tk/man/tcl8.4/TkCmd/menu.htm - Eric Brunel - From steven.bethard at gmail.com Fri Feb 11 17:44:45 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 11 Feb 2005 15:44:45 -0700 Subject: check if object is number In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Steven Bethard wrote: >> Is there a good way to determine if an object is a numeric type? > > assert operator.isNumberType(i) Interesting, thanks! If I read the source right, PyNumber_Check (which operator.isNumberType is an alias for) basically just returns True if the object's type has a __int__ or __float__ method defined: int PyNumber_Check(PyObject *o) { return o && o->ob_type->tp_as_number && (o->ob_type->tp_as_number->nb_int || o->ob_type->tp_as_number->nb_float); } Did I read that right? Steve From merman at o2online.de Fri Feb 11 09:48:55 2005 From: merman at o2online.de (TK) Date: Fri, 11 Feb 2005 15:48:55 +0100 Subject: Install MySQLdb on Mac OS X (10.3) In-Reply-To: References: <420bf2f4$0$16553$9b622d9e@news.freenet.de> Message-ID: <420cc58a$0$27570$9b622d9e@news.freenet.de> Skip Montanaro wrote: > TK> I can't install MySQLdb on Mac OS X (Ver. 10.3) properly. Here's my > TK> environment: > > TK> 1. MySQL-python-1.0.0 > > ... > > Try a more recent version of mysql-python. I think 1.1.7 is the latest. > > Skip Hi Skip, > Try a more recent version of mysql-python. I think 1.1.7 is the latest. It now works with MySQL-python-1.2.0 And I have to set: export PATH=$PATH:/usr/local/mysql-standard-4.1.9-apple-darwin7.7.0-powerpc/bin Thanks for the hint. o-o Thomas From rkern at ucsd.edu Fri Feb 18 16:14:43 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 18 Feb 2005 13:14:43 -0800 Subject: Python, Matlab and AI question In-Reply-To: References: Message-ID: Alexander Schmolck wrote: > Actually, I've written a highlevel matlab-python bridge (based on bugfixed and > slightly extended version of the original pymat) which is quite up-to-date; by > and large it makes using matlab from python as easy as if matlab were just > some python library: Fantastic! I've added a link to the Scipy Wiki: http://www.scipy.org/wikis/topical_software/TopicalSoftware -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From samantha7395 at hotmail.com Thu Feb 17 21:43:22 2005 From: samantha7395 at hotmail.com (Samantha) Date: Thu, 17 Feb 2005 18:43:22 -0800 Subject: Probably over my head... Trying to get Font Names References: Message-ID: <8oydnSIY04Xby4jfRVn-iA@adelphia.com> Thanks Mike. I must have not installed the ttfquery and font tools correctly. I get an error. This error: Traceback (most recent call last): File "C:\Python24\Lib\font-getter.py", line 1, in -toplevel- from ttfquery import _scriptregistry File "C:\Python24\Lib\site-packages\ttfquery\_scriptregistry.py", line 1, in -toplevel- from ttfquery import ttffiles File "C:\Python24\Lib\site-packages\ttfquery\ttffiles.py", line 10, in -toplevel- from ttfquery import describe, findsystem File "C:\Python24\Lib\site-packages\ttfquery\describe.py", line 2, in -toplevel- from fontTools import ttLib ImportError: No module named fontTools Like I said I think I am way in over my short head. S "Mike C. Fletcher" wrote in message news:mailman.2786.1108689703.22381.python-list at python.org... > If you don't have a GUI library to use, TTFQuery+Fonttools will retrieve > this information: > > from ttfquery import _scriptregistry > fonts = _scriptregistry.registry.fonts.keys() > fonts.sort() > for name in fonts: > print name > > if you do have a GUI, your GUI library will almost certainly have a > mechanism to retrieve the list of fonts. With wxPython, for instance, > it's called wxFontEnumerator. If you just want the user to choose a font, > most GUI libraries already have controls/dialogues that can handle it. > > TTFQuery is going out, reading the .ttf fonts with Fonttools and storing > their metadata in an index for faster access, whereas your GUI library > will be using a simple API call to retrieve the metadata. That means > TTFQuery is going to be heavier, but it can, for instance, also give you > information about fonts not installed on the system. > > HTH, > Mike > > TTFQuery: > http://ttfquery.sourceforge.net/ > > > Samantha wrote: > >>I am attempting to extract the Font Names from the installed windows >>fonts. I am having a heck of a time getting these rather than the file >>names. Examples can be seen by going to Control Panel > Fonts >> >>Any help or direction is appreciated. >>S > ________________________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://www.vrplumber.com > http://blog.vrplumber.com > PyCon is coming... > From kent37 at tds.net Fri Feb 25 21:13:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Feb 2005 21:13:43 -0500 Subject: Converting HTML to ASCII In-Reply-To: References: Message-ID: <421fd82a$1_1@newspeer2.tds.net> gf gf wrote: > Hi. I'm looking for a Python lib to convert HTML to > ASCII. You might find these threads on comp.lang.python interesting: http://tinyurl.com/5zmpn http://tinyurl.com/6mxmb Kent From ncoghlan at iinet.net.au Thu Feb 3 06:17:15 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 03 Feb 2005 21:17:15 +1000 Subject: new style exception handleing In-Reply-To: References: <2LydnVuDKZ32iZzfRVn-qg@powergate.ca> Message-ID: <4202083B.9000503@iinet.net.au> Ola Natvig wrote: > Peter Hansen wrote: >> I can't actually think of a reason to need to base an >> exception on a new-style class, but perhaps you have a >> good one... > > It's quite simple to bypass the problem, it was more the reason I was > wondering about too. Basically because fixing it without killing backward compatibility with string exceptions is hard :) Doesn't mean people aren't trying though (Google the python-dev archives, as well as the python-list ones). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From apardon at forel.vub.ac.be Thu Feb 10 04:23:13 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Feb 2005 09:23:13 GMT Subject: variable declaration References: <1griqnv.7iuvul8vpt6N%aleaxit@yahoo.com> <4208178F.40804@po-box.mcgill.ca> Message-ID: Op 2005-02-08, Fredrik Lundh schreef : > Peter Otten wrote: > >>> executed. the compiler handles "global" and "from __future__", everything >>> else is done at runtime. >> >> and __debug__, too, it seems: > > you left out the "python -O" line. > >>>>> __debug__ >> False >>>>> def f(): >> ... if __debug__: >> ... global x >> ... x = 42 >> ... >>>>> f() >>>>> x >> Traceback (most recent call last): >> File "", line 1, in ? >> NameError: name 'x' is not defined > > yup, but unlike the two others, that's a CPython -O implementation issue. > (I'd say bug, in this case). > > neither standard CPython (without -O) nor Jython behave this way. > If people here are so against declarations, how do they feel about statements that don't seem like declarations but have a declarative effect anyway? Because that is what assignment statements in python essentially are. If assignments wouldn't have a declarative effect then code like the following should work: x = 42 def f(): if False: x = 20 return x f() If the x = 20 would be a pure executing statement, then how come its presence has an effect on the return statement even when it isn't executed. And we can play the same trick here. calling python -O and feeding it this program but with the False replaced by __debug__ will make this "work". So having come to the conclusion that some statements have a declarative effect, I would prefer to have the declaration and the assignment be seperated in two different statements. That would make the declaration explicit instead of being implicit now and explicit is better than implicit. Of course the other solution, simply removing the declarative effect from assignments, could work too and might even be preferable but I fear it would produce strange behaviour. -- Antoon Pardon From john at grulic.org.ar Tue Feb 1 11:03:43 2005 From: john at grulic.org.ar (John Lenton) Date: Tue, 1 Feb 2005 13:03:43 -0300 Subject: Remove HTML tags (except anchor tag) from a string using regular expressions In-Reply-To: <41FF7013.7030309@zp-solutions.com> References: <41FF7013.7030309@zp-solutions.com> Message-ID: <20050201160343.GD5205@grulic.org.ar> On Tue, Feb 01, 2005 at 01:03:31PM +0100, Nico Grubert wrote: > Hello, > > I want to remove all html tags from a string "content" except ...>xxx. > > My script reads like this: > > ### > import re > content = re.sub('<([^!>]([^>]|\n)*)>', '', content) > ### > > It works fine. It removes all html tags from "content". > Unfortunately, this also removes xxx occurancies. > Any idea, how to modify this to remove all html tags except xxx? not sure what the outer parenthesis are there for, i.e. afaics <([^!>]([^>]|\n)*)> is the same as <[^!>](?:[^>]|\n)*> for doing a re.sub; the grouping parentheses are only needed if you actually need the groups later on. Try this: <(?!(?:a\s|/a|!))[^>]*> -- John Lenton (john at grulic.org.ar) -- Random fortune: Slurm, n.: The slime that accumulates on the underside of a soap bar when it sits in the dish too long. -- Rich Hall, "Sniglets" -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From aleaxit at yahoo.com Wed Feb 9 08:14:25 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 9 Feb 2005 14:14:25 +0100 Subject: empty classes as c structs? References: <7rSdne7BcbDeV57fRVn-jg@comcast.com> <1gric2n.17myhon1hfrc6gN%aleaxit@yahoo.com> <1grkz2q.16dobcz12zdvcnN%aleaxit@yahoo.com> <9rmdnVR1lr-LYJvfRVn-gg@comcast.com> <4207606E.4040806@iinet.net.au> <1grnyld.1t8l5kw1nr5aqsN%aleaxit@yahoo.com> Message-ID: <1grpz9z.tycvyx1jrdzeiN%aleaxit@yahoo.com> Nick Coghlan wrote: > Alex Martelli wrote: > > One thing I'd like to see in namespaces is _chaining_ -- keeping each > > namespace separate but having lookups proceed along the chain. (The > > best semantics for _bindings_ as opposed to lookups isn't clear though). > > Hmm, so if it doesn't find it in the current namespace, it looks in the > parent? Yep. > For bindings, you could just go with standard Python semantics - normal > name binding always happens in the innermost scope, so binding a name in a > namespace should happen in the directly referenced namespace. Then you can > shadow names from outer scopes, and later regain access to them using > 'del'. ...which you can't do in "standard Python semantics" - if a name is local, it's local throughout. You can't do that with a namespace object, which is why I think the best semantics for bindings in that case isn't all that clear. Alex From behnel_ml at gkec.informatik.tu-darmstadt.de Wed Feb 9 10:48:32 2005 From: behnel_ml at gkec.informatik.tu-darmstadt.de (Stefan Behnel) Date: Wed, 09 Feb 2005 16:48:32 +0100 Subject: probably weird or stupid newbie dictionary question In-Reply-To: <1107962661.011759.30100@f14g2000cwb.googlegroups.com> References: <1107962661.011759.30100@f14g2000cwb.googlegroups.com> Message-ID: hawkmoon269 schrieb: > some other languages' hash table (Perl's, for instance). But FMU a > dictionary's keys are *themselves* hashed so that a hash table exists > that maps hashed key values to keys in the dictionary. I guess you're mixing up the terms "hashing" and "storing in a hash-table". When we hash a dictionary key >>> a = hash(key) then we retrieve a value that is used to refer to the value that we want to store. Ok? :) 1>>> mydict = {} 2>>> mydict['mykey'] = 'somevalue' 3>>> mydict['mykey'] 'somevalue' What happened, was: 1) mydict becomes a dictionary 2a) mydict hashed the key 'mykey' and got an integer value. Strings know how to calculate a hash value for themselves, that value is retrieved via a call to hash('mykey') 2b) mydict then stored the value 'myvalue' at a location that the hashed key refers to (don't care how that is done) 3) mydict hashes the key 'mykey' and retrieves an integer. It looks at the location that that int refers to and finds the value 'somevalue' that was previously stored there. It returns that value. A bit clearer now? Stefan From kbk at shore.net Tue Feb 22 23:19:55 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Tue, 22 Feb 2005 23:19:55 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200502230419.j1N4Jthi005718@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 308 open (+10) / 2755 closed ( +1) / 3063 total (+11) Bugs : 838 open (+15) / 4834 closed ( +5) / 5672 total (+20) RFE : 168 open ( +0) / 148 closed ( +4) / 316 total ( +4) New / Reopened Patches ______________________ do not add directory of sys.argv[0] into sys.path (2004-05-02) http://python.org/sf/946373 reopened by wrobell isapi.samples.advanced.py fix (2005-02-17) http://python.org/sf/1126187 opened by Philippe Kirsanov more __contains__ tests (2005-02-17) http://python.org/sf/1141428 opened by Jim Jewett Fix to allow urllib2 digest auth to talk to livejournal.com (2005-02-18) http://python.org/sf/1143695 opened by Benno Rice Add IEEE Float support to wave.py (2005-02-19) http://python.org/sf/1144504 opened by Ben Schwartz cgitb: make more usable for 'binary-only' sw (new patch) (2005-02-19) http://python.org/sf/1144549 opened by Reinhold Birkenfeld allow UNIX mmap size to default to current file size (new) (2005-02-19) http://python.org/sf/1144555 opened by Reinhold Birkenfeld Make OpenerDirector instances pickle-able (2005-02-20) http://python.org/sf/1144636 opened by John J Lee webbrowser.Netscape.open bug fix (2005-02-20) http://python.org/sf/1144816 opened by Pernici Mario Replace store/load pair with a single new opcode (2005-02-20) http://python.org/sf/1144842 opened by Raymond Hettinger Remove some invariant conditions and assert in ceval (2005-02-20) http://python.org/sf/1145039 opened by Neal Norwitz Patches Closed ______________ date.strptime and time.strptime as well (2005-02-04) http://python.org/sf/1116362 closed by josh-sf New / Reopened Bugs ___________________ attempting to use urllib2 on some URLs fails starting on 2.4 (2005-02-16) http://python.org/sf/1123695 opened by Stephan Sokolow descrintro describes __new__ and __init__ behavior wrong (2005-02-15) http://python.org/sf/1123716 opened by Steven Bethard gensuitemodule.processfile fails (2005-02-16) http://python.org/sf/1123727 opened by Jurjen N.E. Bos PyDateTime_FromDateAndTime documented as PyDate_FromDateAndT (2005-02-16) CLOSED http://python.org/sf/1124278 opened by smilechaser Function's __name__ no longer accessible in restricted mode (2005-02-16) CLOSED http://python.org/sf/1124295 opened by Tres Seaver Python24.dll crashes, EXAMPLE ATTACHED (2005-02-12) CLOSED http://python.org/sf/1121201 reopened by complex IDLE line wrapping (2005-02-16) CLOSED http://python.org/sf/1124503 opened by Chris Rebert test_os fails on 2.4 (2005-02-17) CLOSED http://python.org/sf/1124513 reopened by doerwalter test_os fails on 2.4 (2005-02-16) CLOSED http://python.org/sf/1124513 opened by Brett Cannon test_subprocess is far too slow (2005-02-17) http://python.org/sf/1124637 opened by Michael Hudson Math mode not well handled in \documentclass{howto} (2005-02-17) http://python.org/sf/1124692 opened by Daniele Varrazzo GetStdHandle in interactive GUI (2005-02-17) http://python.org/sf/1124861 opened by davids subprocess.py Errors with IDLE (2005-02-17) http://python.org/sf/1126208 opened by Kurt B. Kaiser subprocesss module retains older license header (2005-02-17) http://python.org/sf/1138653 opened by Tres Seaver Python syntax is not so XML friendly! (2005-02-18) CLOSED http://python.org/sf/1143855 opened by Colbert Philippe inspect.getsource() breakage in 2.4 (2005-02-18) http://python.org/sf/1143895 opened by Armin Rigo future warning in commets (2005-02-18) http://python.org/sf/1144057 opened by Grzegorz Makarewicz reload() is broken for C extension objects (2005-02-19) http://python.org/sf/1144263 opened by Matthew G. Knepley htmllib quote parse error within a