From andre.roberge at gmail.com Fri Jan 21 20:01:00 2005 From: andre.roberge at gmail.com (=?UTF-8?B?QW5kcsOpIFJvYmVyZ2U=?=) Date: Fri, 21 Jan 2005 21:01:00 -0400 Subject: finding name of instances created In-Reply-To: <1106353764.19065.89.camel@bucket.localnet> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> Message-ID: Craig Ringer wrote: > On Fri, 2005-01-21 at 16:13 -0800, Andr? wrote: > >>Short version of what I am looking for: >> >>Given a class "public_class" which is instantiated a few times e.g. >> >>a = public_class() >>b = public_class() >>c = public_class() >> >>I would like to find out the name of the instances so that I could >>create a list of them e.g. >>['a', 'b', 'c'] [snip] > > > I'm not really able to grasp what you're trying to do (but others > might). It wouldn't hurt if you could post a description of what you're > actually trying to achieve - /why/ you want this - as that can often be > very helpful both in understanding what you're thinking and in > suggesting a suitable approach or alternative. > Ok, here it goes... I am designing a "learning environment" for Python. (See rur-ple.sourceforge.org for details of a *very early, still buggy* relase). I have a "world" in which a "robot" can accomplish four built-in instructions: move(), turn_left(), pick_beeper(), put_beeper(). turn_left() corresponds to a 90 degree left turn. One can define a function to simulate a 90 degree right turn as follows: def turn_right(): turn_left() turn_left() turn_left() and call it as a built-in instruction thereafter. By giving more and more complicated tasks for the robot to accomplish, one can learn various programming concepts using python syntax: def (as above), while, if, else, elif, ...... I have all of that working well so far (not on sourceforge yet). Next, I want to introduce the concept of classes and objects, again using python's syntax. Behind the scene, I have something like: robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') } and have mapped move() to correspond to robot_dict['robot'].move() (which does lots of stuff behind the scene.) I have tested robot_dict[] with more than one robot (each with its own unique name) and am now at the point where I would like to have the ability to interpret something like: alex = CreateRobot() anna = CreateRobot() alex.move() anna.move() etc. Since I want the user to learn Python's syntax, I don't want to require him/her to write alex = CreateRobot(name = 'alex') to then be able to do alex.move() I have tried various things at the interpreter, found that to a class 'a', I could see the instance 'b' created in locals(): 'a': , 'b': <__main__.a object at 0x011515D0> which tells me that there must be a way to catch b's name as it is created, and do what I want to do. Does this clarify what I am trying to do and why? Andr? From http Sat Jan 22 19:04:46 2005 From: http (Paul Rubin) Date: 22 Jan 2005 16:04:46 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> Message-ID: <7xhdl9huxt.fsf@ruckus.brouhaha.com> "A.M. Kuchling" writes: > It was discussed in this thread: > http://mail.python.org/pipermail/python-dev/2003-April/034959.html In that thread, you wrote: > Rubin wanted to come up with a nice interface for the module, and > has posted some notes toward it. I have an existing implementation > that's 2212 lines of code; I like the interface, but opinions may > vary. :) Does that mean you have a 2212-line C implementation of the interface that I proposed? Do you plan to release it? BTW, I just looked at the other messages in that thread and I realize that I've looked at them before, and that's where I saw the concern about importing crypto into some countries including Holland. Again, I think the reasoning is bizarre. I'm sure there are tons of Firefox users in Holland, and Firefox definitely contains an SSL stack that doesn't have to be downloaded separately. From r.roelofsen at tuxed.de Tue Jan 4 19:50:43 2005 From: r.roelofsen at tuxed.de (Roman Roelofsen) Date: Wed, 5 Jan 2005 01:50:43 +0100 Subject: coding conventions, PEP vs. practice Message-ID: <200501050150.43556.r.roelofsen@tuxed.de> Dear python-list, while looking for some coding conventions for python programs, i found the PEP8 at http://www.python.org/peps/pep-0008.html. It defines the rules very well and leaves no space for interpretations. I guess thats a good thing :-) But when i started playing a bit with python and frameworks like Zope, Webworks, etc., i noticed, that a lot frameworks are using a different convention for methodnames. These frameworks are using "mixedCase" but PEP8 suggests "lower_case_with_underscores" except "in contexts where that's already the prevailing style" which is not the case here IMHO. So, are there any specific reasons for breaking the rules here? I think consistent conventions are very important. Being a Java developer in the last couple of years, i learned how practical it can be to have only one naming style. Best regards, Roman From duncan.booth at invalid.invalid Fri Jan 28 10:30:43 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Jan 2005 15:30:43 GMT Subject: a sequence question References: Message-ID: Chris Wright wrote: > 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 > ... Try this: l = [1, 2, 3, 4] for a, b in zip(*[iter(l)]*2): print a, b zip(*[iter(seq)]*N) will group by N (but if there are any odd items at the end it will ignore them). map(None, *[iter(seq)]*N) will group by N padding the last item with None if it needs to. From davorss at gmail.com Tue Jan 25 18:01:23 2005 From: davorss at gmail.com (Davor) Date: 25 Jan 2005 15:01:23 -0800 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <1106694083.199064.240680@f14g2000cwb.googlegroups.com> Thanks, I do not hate OO - I just do not need it for the project size I'm dealing with - and the project will eventually become open-source and have additional developers - so I would prefer that we all stick to "simple procedural" stuff rather than having to deal with a developer that will be convincing me that his 50 layers inheritance hierarchy is good since it exists in some weird pattern that he saw somewhere on some Java design patterns discussion board :-) and other "proper" OO design issues... Once I opted for C++ in a very small project and believed everyone will stick with C subset + better type checking offered through C++ - but I simply could not manage to keep them off using OO stuff which was just making program more complicated than it should have been. (note, I am not an experienced developer, nor the others I'll be working with (even though some think they are:-)), so I prefer preemptively dealing with issue of everyone showing off their OO design skills) Davor From gosselit at norwich.edu Tue Jan 11 18:40:36 2005 From: gosselit at norwich.edu (Tim Gosselin) Date: Tue, 11 Jan 2005 23:40:36 +0000 Subject: Detecting shutdown of remote socket endpoint. Message-ID: <1105504107.d645f57ce935d6cb8e82567c0be1e97e@onlynews> I am writing a tcp tunnel but cannot find a way of detecting when a socket shuts down its read end without writing to the socket. For testing the write end of the remote endpoint I just do a: if not sock.recv(buffsize) I cannot write to the socket and check if send returns 0 though, because that involves sending data out of the which may not have come in yet. When I try polling the socket with: r, w, e=select([],[sock],[], 0) w returns with the socket still writable, even if the other end was closed. #For example: s=socket() s.bind(('localhost', 5000)) s.listen(5) s2, addr=s.accept() #then create a socket to connect, s=socket() s.connect(('localhost', 5000)) #then I close the server side, s2.close() #or s2.shutdown(0) #and poll s to see if it's still writable, r, w, e=select([],[s],[], 0) #this returns that the socket is writable! and i can even write to it, s.send('test') #succeeds #but the second write finally throws an exception. Is there any other way to check if a the remote endpoint on a socket has shutdown its read end? Is it difficult to implement a sock.is_shutdown(1) with some additional c code? From dbickett at gmail.com Sun Jan 23 10:57:25 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 23 Jan 2005 10:57:25 -0500 Subject: how to write a tutorial In-Reply-To: <1106472508.591411.40140@c13g2000cwb.googlegroups.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: <1d6cdae3050123075756536a66@mail.gmail.com> > Most texts in computing are written by authors to defend and showcase > their existence against their peers. When you aren't busy `showcasing' your ignorance, this is *all* i see in everything you write. > In a tutorial, nobody cares how > the language compared to x y and z, or what technicality is it all > about, or some humorous snippet of history only funny to the author > himself. You couldn't be farther from the truth. To preface a document by illustrating it's similarities to other languages is to better prepare a reader who may have experience in those languages. As for the snippet of history, few people desire to live life as cynical as you do, and one would hope even fewer take their own opinion and assume it applies to their peers, as you have just done. > Particularly for texts in a tutorial context, you want to write it as > simple as possible covering the most useful basic functionalities and > concepts, and self-contained. Not showcasing your knowledge of history > of languages or your linguistic lineage byways. You of all people are the least qualified to say this, as you are the most guilty of such a crime. > For example this chapter 9 on Objects, it is not difficult to write it > without making a show of lingoes. One simply write what is of Python, > without thinking about relation to xyz languages or the "computer > science" establishment and their ways of thinkings of namespaces and > scopes and dynamic and statics and inheritances ... fucking bags of > shit. Then please be so kind as to give us all a pleasant surprise, and take the place of the productive reformer rather than the angsty criticizer. Your vision as to the errors in the tutorial is *clearly* less clouded than ours, so only *you* are in the position to write the proper replacement. Daniel Bickett From foo at bar.com Sun Jan 23 01:06:35 2005 From: foo at bar.com (Steve Menard) Date: Sun, 23 Jan 2005 01:06:35 -0500 Subject: JPype and classpath (Was Re: embedding jython in CPython... ) In-Reply-To: <1106446384.384110.25150@z14g2000cwz.googlegroups.com> References: <1106446384.384110.25150@z14g2000cwz.googlegroups.com> Message-ID: > While we are on topic, I am having some trouble understanding JPype > classpath. How do I init the JVM with the folder in which the Python > program is located included in the classpath? > > I tried > t = JPackage('.').test > > That did not work. > > My environment variable includes current folder in the classpath > > I tried passing it as an argument to startJVM. Didn't help. > > I think my main use is going to be using CPython with a few Java custom > classes and if anyone has a snippet on this it would really help me. > Thanks > That's easy. First realise that "." denotes the current working directory, not the "directory where the python program is located". Second, JPackage uses Java package names. So, assuming you java classes are properly stord in a directory called "classes" at the same level as your python script (see how java looks up classes on the filesystem for what "properly" means), here is a snippet that will do what you wanted : #============================================================== import os, os.path, jpype root = os.path.abspath(os.path.dirname(__file__)) jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.class.path=%s%sclasses" % (root, os.sep)) #============================================================== Or alternately, if the Java classes you want to use ar in JAR files, in a lib directory at the same level as your python script : #============================================================== import os, os.path, jpype root = os.path.abspath(os.path.dirname(__file__)) jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s%slib" % (root, os.sep)) #============================================================== The magic in the above script is the __file__ variable, which stores the absolute path to the currently executing Python script. If you have both situation (you classes in the classes directory and some JARS containing stuff that they uses) you can combine the above : #============================================================== import os, os.path, jpype root = os.path.abspath(os.path.dirname(__file__)) jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.class.path=%s%sclasses" % (root, os.sep), "-Djava.ext.dirs=%s%slib" % (root, os.sep)) #============================================================== Hopefully this will help. -- Steve Menard -------------------- Maintainer of http://jpype.sourceforge.net From bokr at oz.net Thu Jan 13 01:26:08 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 06:26:08 GMT Subject: why are people still using classic classes? References: <7x6522gegg.fsf@ruckus.brouhaha.com> Message-ID: <41e612dc.719526364@news.oz.net> On 12 Jan 2005 20:06:39 -0800, Paul Rubin wrote: >Simon Wittber writes: >> > Is there a reason NOT to use them? If a classic class works fine, what >> > incentive is there to switch to new style classes? >> >> Perhaps classic classes will eventually disappear? > >It just means that the formerly "classic" syntax will define a >new-style class. Try to write code that works either way. > >It would be nice if a __future__ directive were added right now (if >it's not there already) that processes all class definitions as >new-style. Otherwise there's no easy way to test for compatibility. UIAM, it's not so bad: >>> class C: pass ... >>> type(C) >>> class D(object): pass ... >>> type(D) >>> __metaclass__ = type >>> class E: pass ... >>> type(E) So I guess you can put __metaclass__ = type where you would have done the __future__ thing. If you want to do a special metaclass thing (even using a proper class ;-), you can override the global __metaclass__ >>> def MC(*a): print a; return type(*a) ... >>> class F: ... __metaclass__ = MC ... pass ... ('F', (), {'__module__': '__main__', '__metaclass__': }) Regards, Bengt Richter From gurpreet.sachdeva at gmail.com Thu Jan 20 08:23:06 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Thu, 20 Jan 2005 18:53:06 +0530 Subject: Problem in importing MySQLdb Message-ID: I am using Mysql version 5.0.2-alpha on RedHat 9.0 (python2.2) When I try to import MySQldb I get: Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/site-packages/MySQLdb/__init__.py", line 27, in ? import _mysql ImportError: /usr/lib/libmysqlclient.so.10: symbol errno, version GLIBC_2.0 not defined in file libc.so.6 with link time reference Is there any problem in library files?? Do I need to install anything I have installed MySQL-shared-3.23.54a-1.i386.rpm, MySQL-devel-5.0.2-0.i386.rpm, MySQL-client-5.0.2-0.i386.rpm, MySQL-server-5.0.2-0.i386.rpm Please help, Garry From ianb at colorstudy.com Fri Jan 7 16:52:27 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Fri, 07 Jan 2005 15:52:27 -0600 Subject: Exception report library In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3398134@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3398134@exchange.hqamor.amorhq.net> Message-ID: <41DF049B.2070003@colorstudy.com> Robert Brewer wrote: >>I've been using one of several systems to catch unexpected exceptions >>and log them (e.g., write to a file, display on web page, email me, >>etc). But many are built into a particular system, or have an >>interesting but incomplete set of features. E.g., many web >>frameworks have exception reporters (and the stdlib includes cgitb), >>but I want to handle non-web exceptions in the same way as exceptions >>from web requests, and that's not generally easy. > > ... > >>I feel like there must be something out there, since every Python >>programmer has to deal with this sort of thing to some degree...? > > > I feel that way, too, but haven't found it. I broke my webapp framework > out of my ORM late last year, and quickly realized how small the core > framework really is (22k, versus 250k for the web bits). Features like > the logging handler could be provided as separate modules, rather than > built into the Application object, and I've been meaning to get around > to that. If we could put our many heads together, I think this would be > doable for the stdlib. I'm not optimistic about a good exception handler in the standard library; development slows down a lot at that point, and it's not a reasonable candidate until it is designed and used (in part because of that slowdown -- if it's not mature, it is a diservice to the project to calcify the interface with such strong backward compatibility requirements). But anyway, hopefully multiple people/frameworks/projects could use such a library, done well, as a start. > Here are the pieces of the framework, by the way, which might also > benefit from some standardization (I was thinking about them all at > once): > > 1. Thread-safe application state > 2. Logging (+ exception handling) > 3. Configuration data (reading from various sources) > 4. Registry of Workers for getting things done on a schedule, > possibly recurring > 5. Registry of startup/shutdown functions > 6. Registry of active user interfaces > > I think the first three are all good candidates for a standard. If we > had a standard, thread-safe Application object, the rest could be > registerable plugins for that. You'd basically register callbacks for > app.startup and .shutdown methods to iterate over. Hmm... I'm confused by these bits. Are you talking about libraries for other parts of a web framework, besides exception handling? If so, you might want to look into WSGI and then discuss these things on the web-sig list (WSGI as a starting point; it doesn't specifically relate to many of these ideas, but provides a context in which to develop them). Some of these have been discussed there, like logging, configuration, and perhaps aspects of the registration you are thinking about. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From dalke at dalkescientific.com Sat Jan 8 20:30:15 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sun, 09 Jan 2005 01:30:15 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin: > Lately there are people trying to program PC's to > simulate the Lisp hardware and to get the Lisp Machine software > released (now that the commercial market for it has long since dried > up). However, both of those projects have a ways to go. There's a video of someone demoing how to use a Lisp Machine at http://lemonodor.com/archives/000103.html Andrew dalke at dalkescientific.com From bjourne at gmail.com Thu Jan 13 14:14:39 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 13 Jan 2005 20:14:39 +0100 Subject: Refactoring; arbitrary expression in lists In-Reply-To: References: Message-ID: <740c3aec05011311141ce10b8e@mail.gmail.com> > # do other non-extension-related tests here > if basename.find( "Makefile" ) != -1: > return "text/x-makefile" I believe this can be nicelier written as: if "Makefile" in basename: -- mvh Bj?rn From stephane.bronsart at bea.be Fri Jan 28 05:02:38 2005 From: stephane.bronsart at bea.be (StepH) Date: Fri, 28 Jan 2005 11:02:38 +0100 Subject: How to test that an exception is raised ? Message-ID: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> Hi, I've this module : from optparse import OptionParser import re _version = "P1" def writeVar(f, line): """Output a line in .xml format in the file f.""" f.write('\t\n') name = line.split()[0] adr = line.split()[3] f.write('\t\t' + name + '\n') f.write('\t\t' + adr + '\n') f.write('\t\n') def mps2xml(mps,verbose): """Convert '.mps' to '.xml'.""" try: f = open(mps) f.close() xmlfile = mps + ".xml" f = open(xmlfile, "w+") f.write('\n') f.writelines('\n') pat = re.compile(".*Var.*g.*0x00.*") lines = list(open(mps)) nbScan = nbFound = 0 for line in lines: nbScan = nbScan + 1 if pat.match(line): writeVar(f, line) nbFound = nbFound + 1 f.writelines('\n') f.close() if verbose: print "Output to file %s..." % xmlfile print "Lines scanned:", nbScan print "Lines found:", nbFound except: if verbose: print "FileError" if __name__ == "__main__": usage = "usage: %prog [options] filename" parser = OptionParser(usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose") parser.add_option("-q", "--quiet", action="store_false", dest="verbose") (options, args) = parser.parse_args() if len(args) != 1: parser.error("incorrect number of arguments") exit(1) if options.verbose: print "mps2xml -", _version mps2xml(args[0],options.verbose) And this "unittest" module : import mps2xml import os import unittest class Tests(unittest.TestCase): def setUp(self): self.mps = "test.mps" def tearDown(self): pass def test_badFile(self): """Check that an exception is raised if a bad filename is passed to mps2xml""" self.assertRaises((IOError),mps2xml.mps2xml, "thisfiledoesntexists", False) def test_writeVar_Output(self): """Check the output of the 'writeVar' method""" line = " irM1slotnoisePPtmp Var. g 0x0002F6" file = open("testWriteVar.xml","w+") mps2xml.writeVar(file, line) file.close() outputlines = list(open("testWriteVar.xml")) goodlines = list(open("testWriteVar.xml.good")) self.assertEquals(outputlines, goodlines, 'bad output format') def test_mps2xml_Creation(self): """Check if test.mps.xml is created""" mps2xml.mps2xml(self.mps, False) self.assert_(os.path.exists(self.mps + ".xml"), 'test.mps.xml not created') if __name__ == '__main__': unittest.main() But i've prob with the 1st test : test_badFile. When I run the test, unittest say that no error is Raised. But when I run the mps2xml module with a bad file as arg., the exception is well Raised. What i'm doing wrong ? It is because the exception in catched in the mps2xml module ? Thanks for your helps. StepH. From peter at engcorp.com Wed Jan 12 11:01:20 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Jan 2005 11:01:20 -0500 Subject: 2 versions of python on 1 machine In-Reply-To: <4446BD725249914A801A2C8ED5BFA4CADE2D59@cernne02.cern.ch> References: <4446BD725249914A801A2C8ED5BFA4CADE2D59@cernne02.cern.ch> Message-ID: flupke wrote: > I searched with Google and on this newsgroups and i didn't find any info > regarding this. If there is more info, please redirect me to that info. [snip] The above looks like a glitch or accidental repost of the post that started this thread: http://groups.google.ca/groups?threadm=YLedndIVKMWwhn3cRVn-rA%40powergate.ca (Was it just on my server or did others get this strange repost?) -Peter From john at grulic.org.ar Thu Jan 13 19:14:53 2005 From: john at grulic.org.ar (John Lenton) Date: Thu, 13 Jan 2005 21:14:53 -0300 Subject: how to control the mouse pointer with python? In-Reply-To: <1105650438.311153.167410@f14g2000cwb.googlegroups.com> References: <1105650438.311153.167410@f14g2000cwb.googlegroups.com> Message-ID: <20050114001453.GC3727@grulic.org.ar> On Thu, Jan 13, 2005 at 01:07:18PM -0800, oglycans at yahoo.com wrote: > Hi. > Anybody know a way to control the mouse pointer > (move it around and click on things) using python? in X11, you could use Xlib to do so. In debian unstable, that's "apt-get install python-xlib{,-doc}", and start reading. -- John Lenton (john at grulic.org.ar) -- Random fortune: Obviously I was either onto something, or on something. -- Larry Wall on the creation of Perl -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From f.geiger at vol.at Thu Jan 13 01:50:18 2005 From: f.geiger at vol.at (F. GEIGER) Date: Thu, 13 Jan 2005 07:50:18 +0100 Subject: java 5 could like python? References: Message-ID: "vegetax" schrieb im Newsbeitrag news:mailman.568.1105544231.22381.python-list at python.org... > I was a java developer one year ago ,before i moved to python i realy liked > it at the beggining, but i got very disapointed lately since my > previus two python proyects where relatively big,and python didnt feel > well suited for the task. > > The reasons are mainly due to the standard library,the language > performance was aceptable, but the library, in my opinion has several grave > issues: > > -No naming convention. The speech of "it fits in my head" is no longer valid > when i use a lot of functionality,modules,classes in a large proyect. > > For example if i remember a function i want ie:get attribute, i dont > remember if the module implementer coded it as > getAttribute,GetAttribute,get_attribute, then i have to go and check the > doc, every time,which is a waste of time. Too many getters indicate bad design. But, ok, that's not the point here. I ask myself all the time, how people can dev software in *any* language w/o an IDE offering Intellisense (besides a decent clas browser, of course). You simply type "myObj.get" and the IDE looks the proper names up for you. Then you choose the right one and you are done with. WingIDE is such an IDE, and Kommodo too, I think. HTH Franz GEIGER From mahs at telcopartners.com Sat Jan 22 17:06:22 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sat, 22 Jan 2005 14:06:22 -0800 Subject: What YAML engine do you use? In-Reply-To: <7xoefhtavd.fsf@ruckus.brouhaha.com> References: <35a6tpF4gmat2U1@individual.net> <35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> <7xoefhtavd.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > YAML looks to me to be completely insane, even compared to Python > lists. I think it would be great if the Python library exposed an > interface for parsing constant list and dict expressions, e.g.: > > [1, 2, 'Joe Smith', 8237972883334L, # comment > {'Favorite fruits': ['apple', 'banana', 'pear']}, # another comment > 'xyzzy', [3, 5, [3.14159, 2.71828, []]]] > > I don't see what YAML accomplishes that something like the above wouldn't. > > Note that all the values in the above have to be constant literals. > Don't suggest using eval. That would be a huge security hole. Not hard at all, thanks to compiler.ast: >>> import compiler ... >>> class AbstractVisitor(object): ... def __init__(self): ... self._cache = {} # dispatch table ... ... def visit(self, node,**kw): ... cls = node.__class__ ... meth = self._cache.setdefault(cls, ... getattr(self,'visit'+cls.__name__,self.default)) ... return meth(node, **kw) ... ... def default(self, node, **kw): ... for child in node.getChildNodes(): ... return self.visit(child, **kw) ... >>> class ConstEval(AbstractVisitor): ... def visitConst(self, node, **kw): ... return node.value ... ... def visitName(self,node, **kw): ... raise NameError, "Names are not resolved" ... ... def visitDict(self,node,**kw): ... return dict([(self.visit(k),self.visit(v)) for k,v in node.items]) ... ... def visitTuple(self,node, **kw): ... return tuple(self.visit(i) for i in node.nodes) ... ... def visitList(self,node, **kw): ... return [self.visit(i) for i in node.nodes] ... >>> ast = compiler.parse(source,"eval") >>> walker = ConstEval() >>> walker.visit(ast) [1, 2, 'Joe Smith', 8237972883334L, {'Favorite fruits': ['apple', 'banana', 'pear']}, 'xyzzy', [3, 5, [3.1415899999999999, 2.71828, []]]] Add sugar to taste Regards Michael From tim at zeos.net Tue Jan 25 03:45:21 2005 From: tim at zeos.net (Timothy Babytch) Date: Tue, 25 Jan 2005 10:45:21 +0200 Subject: ANN: LJ pyGTK clien Zapys-0.3 released Message-ID: Usable simple app for posting messages to LiveJournal. Easy extandable. Main feature: character substitution. I mean (tm) to ?, (c) to ?, quote to matching pairs and so on. The list can be easily extended with your own regexps. submit on Ctrl+Enter. Edit/delete last entry. screenshot: http://img.lj.com.ua/ilishin/zapys-3.png download: http://firefox.org.ua/misc/zapys-0.3.tar.bz2 From emschwar at fc.hp.com Wed Jan 26 20:19:49 2005 From: emschwar at fc.hp.com (Eric Schwartz) Date: Wed, 26 Jan 2005 18:19:49 -0700 Subject: [perl-python] 20050126 find replace strings in file References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> Message-ID: To follow up on Jurgen Exner's critique, I present Xah Lee's version, and then my rewritten version. "Xah Lee" writes: > if (scalar @ARGV != 4) {die "Wrong arg! Unix BNF: $0 > \n"} > $stext=$ARGV[0]; > $rtext=$ARGV[1]; > $infile = $ARGV[2]; > $outfile = $ARGV[3]; > open(F1, "<$infile") or die "Perl fucked up. Reason: $!"; > open(F2, ">$outfile") or die "Perl fucked up. Reason: $!"; > while ($line = ) { > chomp($line); > $line =~ s/$stext/$rtext/g; > print F2 "$line\n"; > } > close(F1) or die "Perl fucked up. Reason: $!"; > close(F2) or die "Perl fucked up. Reason: $!"; #!/usr/bin/perl use warnings; use strict; if (@ARGV != 4) { die "Wrong arg! Unix BNF: $0 " } my ($stext, $rtext, $infile, $outfile) = @ARGV; open my $infh, '<', $infile or die "Error opening input file [$infile]: $!"; open my $outfh, '>', $outfile or die "Error opening output file [$outfile]: $!"; while(<$infh>) { s/$stext/$rtext/g; print { $outfh } $_; } close($infh) or die "Error closing input file [$infile]: $!"; close($outfh) or die "Error closing output file [$outfile]: $!"; My version takes up more lines, but I don't count whitespace-- whitespace is not expensive, and when used properly adds greatly to the readability of your program. I've set followups to the only appropriate group for Mr. Lee's postings. -=Eric -- Come to think of it, there are already a million monkeys on a million typewriters, and Usenet is NOTHING like Shakespeare. -- Blair Houghton. From ramen at lackingtalent.com Tue Jan 18 12:53:43 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 18 Jan 2005 10:53:43 -0700 Subject: One-Shot Property? In-Reply-To: <20050118115456510-0500@braeburn.themorgue.org> References: <20050118115456510-0500@braeburn.themorgue.org> Message-ID: <%2cHd.21965$ql2.16363@okepread04> Kevin Smith wrote: > I have many cases in my code where I use a property for calculating a > value on-demand. Quite a few of these only need to be called once. > After that the value is always the same. In these properties, I set a > variable in the instance as a cached value and return that value on > subsequent calls. It would be nice if there was a descriptor that would > do this automatically. Actually, what would be really nice is if I > could replace the property altogether and put the calculated value in > its place after the first call, but the property itself prevents me from > doing that. Is this possible? I was going to recommend taking a look at the "memoize" example on the Python wiki, but it seems to be missing at the moment. In any case, here's the URL: http://www.python.org/moin/PythonDecoratorLibrary There are also a few examples on the Cookbook, like this one: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325205 It shouldn't be too difficult to adapt this technique so that it can be used to create properties. I wouldn't bother replacing the property with an attribute unless you have a specific reason to do so (performance, perhaps). HTH, Dave From fredrik at pythonware.com Sun Jan 23 08:15:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 14:15:59 +0100 Subject: compile python to binary References: Message-ID: "sam" wrote: > I have seen some software written in python and delivered as binary form. > > How does these binary code get generated by python compiler? see section 6.1.2 in the tutorial: http://docs.python.org/tut/node8.html From donn at u.washington.edu Tue Jan 11 16:33:57 2005 From: donn at u.washington.edu (Donn Cave) Date: Tue, 11 Jan 2005 13:33:57 -0800 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <10u5fu3o7v4h9e3@corp.supernews.com> <10u8e65lju3atbd@corp.supernews.com> Message-ID: In article <10u8e65lju3atbd at corp.supernews.com>, Jeff Shannon wrote: ... > From the sounds of it, you may have the opposite experience with > reading map/lambda vs. reading list comps, though, so we could go back > and forth on this all week without convincing the other. :) I'm with him. List incomprehensions do not parse well in my eyes. I am reduced to guessing what they mean by a kind of process of elimination. map is simply a function, so it doesn't pose any extra reading problem, and while lambda is awkward it isn't syntactically all that novel. Donn Cave, donn at u.washington.edu From jaydonnell at gmail.com Fri Jan 21 20:19:49 2005 From: jaydonnell at gmail.com (Jay donnell) Date: 21 Jan 2005 17:19:49 -0800 Subject: why am I getting a segmentation fault? In-Reply-To: <1106351339.457714.214940@f14g2000cwb.googlegroups.com> References: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> <1106351339.457714.214940@f14g2000cwb.googlegroups.com> Message-ID: <1106356789.748649.259090@f14g2000cwb.googlegroups.com> >### Have you looked in your database to see if the >script has actually >updated item.goodImage? Do you have a test plan? Thank you for the help. Sorry for the messy code. I was under time constraints. I had class, and I was rushing to get this working before class. I should waited a day and read over it before I asked. Sorry again. From cbfalconer at yahoo.com Fri Jan 21 11:30:55 2005 From: cbfalconer at yahoo.com (CBFalconer) Date: Fri, 21 Jan 2005 16:30:55 GMT Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: <41F12912.3748FFB7@yahoo.com> Xah Lee wrote: > > i've started to read python tutorial recently. > http://python.org/doc/2.3.4/tut/tut.html > > Here are some quick critique: This has absolutely nothing to do with c.l.c, nor most of the cross-posted groups. F'ups set. Why did you do such a foul cross-posting in the first place. -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson From reinhold-birkenfeld-nospam at wolke7.net Mon Jan 17 14:03:16 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 17 Jan 2005 20:03:16 +0100 Subject: Assigning to self In-Reply-To: References: Message-ID: <352gfkF4gq9a2U1@individual.net> Frans Englich wrote: > Hello, > > I am having trouble with throwing class instances around. Perhaps I'm > approaching my goals with the wrong solution, but here's nevertheless a > stripped down example which demonstrates my scenario: > > #------------------------------------------------------------------------------------------ > > class foo: > tests = {} > def __init__( self, id ): > > try: > me = self.__class__.tests[ id ] > > except KeyError: > print "Did not exist, initializing myself.." > self.attr = "exists" > self.__class__.tests[ id ] = self > > else: > print "Already exists! Re-using existing instance" > self = me > > print "Me", self.attr + "!" # line 18 > > def yo(self): > return self.attr # line 21 As 'self' is a method parameter, changing it only affects the current function. When __init__ is called, the instance is already created, so you can't change it. What you are looking for is a class factory (is this term correct?), here is a sample implementation (using 2.4 decorators): class foo: tests = {} @classmethod def get_test(cls, id): if cls.tests.has_key(id): return cls.tests[id] else: inst = cls() inst.attr = "exists" cls.tests[id] = inst return inst def yo(self): return self.attr Here you define get_test as a classmethod, that is, it does not receive the instance as first argument, but the class. It can be called from the class (foo.get_test) or an instance (foo().get_test). An alternative might be to override __new__, but I'm sure someone other will suggest this. Reinhold From francis.girard at free.fr Tue Jan 25 16:11:41 2005 From: francis.girard at free.fr (Francis Girard) Date: Tue, 25 Jan 2005 22:11:41 +0100 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: <1106624803.825442.73870@f14g2000cwb.googlegroups.com> Message-ID: <200501252211.43386.francis.girard@free.fr> Hi, I'm really not sure but there might be some way to embed Java Script within Jython. Or to run Jython from inside Java much like the jEdit editor. You then have Python to make some glue code between the C++ core and the Java Script. Java Script must be secure since it runs in browsers everywhere from my worst sex web sites ! I'm not really sure why the original poster want to use Python, I think it's to make the glue between C++ and the scripting engine. Nor am I really sure why java runs inside my browser ... Francis Girard FRANCE Le mardi 25 Janvier 2005 18:08, Cameron Laird a ?crit?: > In article <1106624803.825442.73870 at f14g2000cwb.googlegroups.com>, > Carl Banks wrote: > . > . > . > > >> Python, or Perl, or TCL, or Ruby, or PHP, > > > >Not PHP. PHP is one of the better (meaning less terrible) examples of > >what happens when you do this sort of thing, which is not saying a lot. > >PHP was originally not much more than a template engine with some > >crude operations and decision-making ability. Only its restricted > >problem domain has saved it from the junkheap where it belongs. > > > >TCL isn't that great in this regard, either, as it makes a lot of > >common operations that ought to be very simple terribly unweildy. > > . > . > . > I've lost track of the antecedent by the time of our arrival at > "this regard". I want to make it clear that, while Tcl certainly > is different from C and its imitators, and, in particular, insists > that arithmetic be expressed more verbosely than in most languages, > the cause is quite distinct from the imperfections perceived in > PHP. PHP is certainly an instance of "scope creep" in its semantics. > Tcl was designed from the beginning, though, and has budged little in > over a decade in its fundamentals; Tcl simply doesn't bother to "make > a lot of common operations ..." concise. From tim.golden at viacom-outdoor.co.uk Wed Jan 12 10:50:31 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 12 Jan 2005 15:50:31 -0000 Subject: Excel module for Python Message-ID: <9A28C052FF32734DACB0A288A35339910359B1@vogbs009.gb.vo.local> [Simon Brunning] [sam ] wrote: | > No, I don't use MS windows. I need to generate Excel file | by printing | > data to it, just like Perl module Spreadsheet::WriteExcel. | | If you need to write out formulae, formratting, that kind of thing, | then I think you'll need to write a 'real' Excel file. I don't have a | clue how to do that - sorry. I think http://sourceforge.net/projects/pyxlwriter/ will do it; haven't used it myself, mind you. You need to know that the magic search term is "BIFF" which is -- for some reason -- the name of the Excel file format. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From fredrik at pythonware.com Mon Jan 24 11:21:24 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 17:21:24 +0100 Subject: Python 2.1 - 2.4 differences References: Message-ID: "BOOGIEMAN" wrote: >I found some e-book about Python 2.1, I want to print it but just to check > first if sintax of Python 2.1 is same as 2.4 ? almost everything that works under 2.1 works under 2.4. the opposite isn't always true, though. for more information on new stuff, see: http://www.python.org/doc/2.2.3/whatsnew/ http://www.python.org/doc/2.3.4/whatsnew/ http://www.python.org/doc/2.4/whatsnew/whatsnew24.html and http://effbot.org/zone/librarybook-py21.htm http://effbot.org/zone/librarybook-py22.htm http://effbot.org/zone/librarybook-py23.htm From jacek.generowicz at cern.ch Mon Jan 10 11:45:25 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Jan 2005 17:45:25 +0100 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> Message-ID: "Anna" writes: > Jacek Generowicz wrote: > > "Anna" writes: > > > > > With class and def, I at least have a *name* to start with - class > > > Square pretty obviously is going to have something to do with > > > geometric shapes, I would hope (or maybe with boring people...). > > > > Or maybe with multiplying something by itself. Or maybe the author > > made some changes in his program, and forgot to rename the class > > sensibly, and the class' functionality has nothing to do with squares > > of any sort any more. Or maybe he felt the name "Square" was very > > appropriate for something else in his program and inadvertently gave > > the same name to two different entities thereby clobbering the one > > whose use was intended at this point. > > Idjits abound. ;-) Yup ... which is one reason why lambda is so useful. Everything there is to know about it is right in front of your eyes. There is no chance that some idjit changed the meaning of lambda, or the code which appears within it (unless that refers to some external names, of course). > > So, IIUC, you consider > > > > def add_one(x): > > return x+1 > > > > map(add_one, seq) > > > > to be clearer than > > > > map(lambda x:x+1, seq) > > Completely, totally, and unambiguously: Curious. It's very much the other way around for me. > the version with the defined function is immediately clear to me; > the version with the lambda is decipherable, but requires > deciphering (even at 2nd and 3rd glance). But first, wouldn't > something like: > > [x+1 for x in seq] > > be even clearer? I'm glad you mentioned that. My next question was going to be something along the lines of what you think of the equivalent list comprehension, which is spectacularly devoid of any names to give you any hints whatsoever. As to whether it is clearer. That depends. I would venture to suggest that, given a pool of laboratory rats with no previous exposure to Python, more of them would understand the map-lambda than the list comprehension. There are no words in the list comprehension at all (besides the common "seq"): it's all syntax. Even if "map" and "lambda" ring no bells by association with anything you might have learned outside of Python, they sure are a lot easier to look up in the documentation. > Given an example more complex (which you must admit, lambdas usually > are) Well, they can't be _that_ much more complex in Python :-) But I'll grant you, they are often more complex that the one above. > - the name of the function is something my brain can hold on to to > represent the group of operations; where with the lambda, I need to > mentally go through each operation each time I try to read it. And the > more complex f is, the harder time I have holding it all in my head > while I figure out how to get from the beginning value x to the ending > value f(x). lambda is an O(N*N) problem for my brain. Fair enough. If I understand the code just by looking at it, then I prefer to see it inline. If its meaning isn't obvious immediately, then I'd go for the named function too. But I still value the ability to inline-define the function while developing ... even if the inline function will be outlined in the final product. But, how do you feel about the individual lines of code in the body of a multi-line function? They don't have individual names. > I could see someone more mathematically-minded being happier with > lambda. It's not, after all, the word "lambda" itself; Aaah ... you did suggest (upthread) that it was the word itself which gave you problems ... which is what piqued my interest. From invalidemail at aerojockey.com Fri Jan 21 12:57:24 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 21 Jan 2005 09:57:24 -0800 Subject: Funny Python error messages In-Reply-To: References: <1106315907.551660.276380@c13g2000cwb.googlegroups.com> Message-ID: <1106330244.724582.226020@z14g2000cwz.googlegroups.com> Peter Hansen wrote: > Will Stuyvesant wrote: > > Perhaps this will even be a useful thread, to brighten the > > life of the brave people doing the hard work of providing us > > with error messages. > > > > My first one (i'm learning, i'm learning) is > > > > TypeError: 'callable-iterator' object is not callable > > > > # >>> it = iter(lambda:0, 0) > > # >>> it() > > # TypeError: 'callable-iterator' object is not callable > > Given that the supposed humour depends on the *name* of > the object, which is "callable-iterator", I'd say it's > probably not hard to come up with lots of "funny" error > messages this way. The mildly amusing nature of this error message is due to Will's finding a name, "callable-iterator" (where callable is a name, not a description), appearing in a different context from where it was coined that causes us to parse it differently (where callable is a description, not a name), and accidentally stating an absurdity. I'd say it's actually a nice bit of subtlety. -- CARL BANKS From noreply at python.org Tue Jan 18 07:38:33 2005 From: noreply at python.org (Mail Administrator) Date: Tue, 18 Jan 2005 13:38:33 +0100 Subject: MDaemon Warning - virus found: Returned mail: Data format error Message-ID: <20050118123933.971AB1E4003@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 ---------------------------------------------------------------------- instruction.zip I-Worm.Mydoom.m Removed ********************************************************************** Your message was undeliverable due to the following reason: Your message was not delivered because the destination server 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 8 days: Mail server 169.58.69.124 is not responding. The following recipients did not receive this message: Please reply to postmaster at python.org if you feel this message to be in error. From Scott.Daniels at Acm.Org Wed Jan 12 10:04:38 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 12 Jan 2005 07:04:38 -0800 Subject: Help Optimizing Word Search In-Reply-To: <7xacrfl78y.fsf@ruckus.brouhaha.com> References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> <7xacrfl78y.fsf@ruckus.brouhaha.com> Message-ID: <41e53998$1@nntp0.pdx.net> Paul Rubin wrote: > "Case Nelson" writes: > >>Basically, the program needs to take in a random list of no more than >>10 letters, and find all possible mutations that match a word in my >>dictionary (80k words). However a wildcard letter '?' is also an >>acceptable character which increases the worst case time significantly. > > > For that size pattern and dictionary, simply compiling the pattern to > a regexp, joining the dictionary together into one big string ("abc > def ghijk..."), and matching the regexp against the big string, may > well be faster than using some fancy algorithm coded completely in > python. If these queries happen often, build a dictionary of sorted letters to lists-of-words. The setup will be slow, but use of such a secondary dictionary should be quite fast, with relatively easy dealing with ?s by iterations. --Scott David Daniels Scott.Daniels at Acm.Org From stephen.thorne at gmail.com Thu Jan 13 04:26:54 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 19:26:54 +1000 Subject: newbie q In-Reply-To: <34mku4F4c8bdkU1@individual.net> References: <34mgq0F4dq4buU1@individual.net> <34mku4F4c8bdkU1@individual.net> Message-ID: <3e8ca5c8050113012633ac6155@mail.gmail.com> On Thu, 13 Jan 2005 17:05:39 +1000, Egor Bolonev wrote: > > "Stephen Thorne" ???????/???????? ? ???????? > ?????????: news:mailman.611.1105598828.22381.python-list at python.org... > On Thu, 13 Jan 2005 15:55:10 +1000, Egor Bolonev wrote: > > how to get rid of 'for' operator in the code? > > > > import os, os.path > > > > def _test(): > > src = 'C:\\Documents and Settings\\????\\My Documents\\My Music\\' > > > > for i in [x for x in os.listdir(src) if > > os.path.isfile(os.path.join(src, > > x)) and len(x.split('.')) > 1 and x.split('.')[-1].lower() == 'm3u']: > > os.remove(os.path.join(src, i)) > > > > if __name__ == '__main__': > > _test() > > import glob > for x in glob.glob("*.m3u"): > os.remove(x) > > i want to wipe out 'for x in []: f(x)' using map, lambda, reduce, filter and > List > Comprehensions [x for x in []] > just don't get how to add string to all elements of list Here's a few ways, map(os.remove, glob.glob("*.m3u")) [os.remove(x) for x in glob.glob("*.m3u")] [os.remove(x) for x in os.listdir(src) if os.path.isfile(os.path.join(src, x)) and len(x.split('.')) > 1 and x.split('.')[-1].lower() == 'm3u'] def myfilter(x): return os.path.isfile(os.path.join(src, x)) and len(x.split('.')) > 1 and x.split('.')[-1].lower() == 'm3u' map(os.remove, filter(myfilter, os.listdir(src))) Regards, Stephen Thorne. From bulba at bulba.com Tue Jan 4 12:55:43 2005 From: bulba at bulba.com (Bulba!) Date: Tue, 04 Jan 2005 18:55:43 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <86ekh3qv1o.fsf@guru.mired.org> Message-ID: <03mlt0di3rcntvu7rlrk9k2m9bq8435bs5@4ax.com> On Sun, 02 Jan 2005 17:18:43 -0600, Mike Meyer wrote: >> This "free software" (not so much OSS) notion "but you can >> hire programmers to fix it" doesn't really happen in practice, >> at least not frequently: because this company/guy remains >> ALONE with this technology, the costs are unacceptable. > >Yes, but fixing python software - even sloppily written python >software - is pretty easy. I regularly see contracts to add a feature >to or fix a bug in some bit of OSS Python. That's remarkable, first time I see smth like this - out of curiosity, could you say a word where was that? -- Real world is perfectly indifferent to lies that are the foundation of leftist "thinking". From enleverlesO.OmcO at OmclaveauO.com Fri Jan 28 08:25:34 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Fri, 28 Jan 2005 14:25:34 +0100 Subject: How to post news articles with NNTPlib References: <1106911698.786860.109450@z14g2000cwz.googlegroups.com> Message-ID: <41fa577c$0$25809$8fcfb975@news.wanadoo.fr> Hi ! nntplib.NNTP(newsserver,port,user,passe) -- Michel Claveau From tchur at optushome.com.au Mon Jan 31 16:15:08 2005 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 01 Feb 2005 08:15:08 +1100 Subject: python and gpl In-Reply-To: References: Message-ID: <41FE9FDC.4080808@optushome.com.au> John Hunter wrote: >I have a question about what it takes to trigger GPL restrictions in >python code which conditionally uses a GPL library. > >Here is the context of my question. matplotlib, which I develop, is a >plotting module which is distributed under a PSF compatible license, >and hence we avoid using GPLd code so as to not trigger the GPL >requirements. matplotlib has rigid segregation between the front end >(plotting commands, figure objects, etc) and backends (gtk, wx, ps, >svg, etc). The backend is chosen dynamically at runtime -- eg the >same python script could trigger the import gtk, wx, or ps, depending >an some rc settings or command line opts. > >The question is: does shipping a backend which imports a module that >links with GPL code make some or all of the library GPL. > We sought formal legal advice on this issue from a lawyer with expertise in open source licensing - in our case, our application which is licensed under a (very slightly) modifided version of the Mozilla Public License v1.1 imports a GPLed Python module (RPy) which wraps a GPLed library (R). The answer was that the GPL does not apply to combination of code at run-time. Specifically, Section 0., Para 1 (assuming zero-based paragraph numbering...) says: "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,..." Furthermore, Section 2 para 1 says: "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. ..." and Section 2 para 3 says: "In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License." On the basis of these clauses, the legal advice to us was that merely including "import rpy" and making calls to RPy-wrapped R functions does not invoke the provisions of the GPL because these calls only relate to run-time linking, which is not covered by the GPL. However, combining GPLed source code or static linking would invoke the GPL provisions. Additionally, we were advised to (re-)distribute any GPLed components required by our application in clearly separate packages i.e as separate tarballs or zip files, and not to bind them together in an omnibus distribution or installation file. However, putting them on the same CD-ROM or other media is fine. Note that the formal advice was specific to Australian law, and did mention some Australian case law regarding fair use under the Copyright Act with respect to making API calls - that relates to our application making API calls to the GPLed library which is imported at runtime. The opinion was that we were on safe ground here, but you might want to investigate this aspect wrt copyright laws in other countries. My understanding is that most copyright law provides for "fair use" which may cover use of parts of an API to a GPLed library (as distinct from complete incorporation of the entire API into another application - which would invoke the GPL). IANAL, and the above constitutes mangled paraphrasing of carefully worded formal legal advice, the scope of which was restricted to Australian law. However, the sections of the GPL quoted above are pretty unambiguous. The other, informal advice, was to ignore the FAQs and other opinions on the FSF web site regarding intepretation of the GPL - it's only the license text which counts. Tim C From invalidemail at aerojockey.com Sat Jan 8 19:25:50 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 8 Jan 2005 16:25:50 -0800 Subject: python3: 'where' keyword In-Reply-To: <7xk6qnzd3d.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> Message-ID: <1105230350.861683.265970@c13g2000cwb.googlegroups.com> Paul Rubin wrote: > "Carl Banks" writes: > > You misunderstand. BTW, Peter, I guess I should have said "I misunderstand, but it can be legal if you consider it part of the statements", since it appears the author did intend it to be part of an expression. > > There "where" is not part of the expression but the > > statement. The above example would be a modified print statement, a > > print...where statement, if you will. Under this suggestion, there > > would be modified versions of various simple statements. > > You mean I can't say > > # compute sqrt(2) + sqrt(3) > x = (sqrt(a) where: > a = 2.) \ > + sqrt (a) where: > a = 3. > > Hmmm. What would be the advantage of that over this? . x = sqrt(a) + sqrt(b) where: . a = 2.0 . b = 3.0 Where would making "where" part of an expression rather than part of the statement help? Can you think of a place? ("That it makes Python more like LISP" is not a good enough answer for me, BTW. But feel free to try. :) -- CARL BANKS From bokr at oz.net Fri Jan 21 20:29:09 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 22 Jan 2005 01:29:09 GMT Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> Message-ID: <41f1a3e6.1477492061@news.oz.net> On Fri, 21 Jan 2005 12:04:10 -0600, "A.M. Kuchling" wrote: >On Fri, 21 Jan 2005 18:30:47 +0100, > rm wrote: >> Nowadays, people are trying to create binary XML, XML databases, >> graphics in XML (btw, I'm quite impressed by SVG), you have XSLT, you >> have XSL-FO, ... . > >Which is an argument in favor of XML -- it's where the activity is, so it's >quite likely you'll encounter the need to know XML. Few projects use YAML, >so the chance of having to know its syntactic details is small. > I thought XML was a good idea, but IMO requiring quotes around even integer attribute values was an unfortunate decision. I don't buy their rationale of keeping parsing simple -- as if extracting a string with no embedded space from between an equal sign and terminating white space were that much harder than extracting the same delimited by double quotes. The result is cluttering SVG with needless cruft around numerical graphics parameters. OTOH, I think the HTML XML spec is very readable, and nicely designed. At least the version 1.0 spec I snagged from W3C a long time ago. ... I see the third edition at http://www.w3.org/TR/REC-xml/ is differently styled, (I guess new style sheets) but still pretty readable (glancing at it now). Regards, Bengt Richter From friedmud at gmail.com Mon Jan 31 13:13:00 2005 From: friedmud at gmail.com (friedmud at gmail.com) Date: 31 Jan 2005 10:13:00 -0800 Subject: Relocatable binary installs.... Message-ID: <1107195180.462949.222980@z14g2000cwz.googlegroups.com> Hello all, I'm currently working on a software package that is going to be distributed in binary form (with accompanying source) for lot of different unixes (Linux, AIX, HP-UX and others). Parts of the package are written in Python... so we are going to want to distribute our own version of python. Right now we are just distributing the Python tarball and building it at install time. This works ok, but we are running into some problems on some machines with weird default installs (DEC Alphas in particular).... some of them won't build all the python modules we want (although our in house machines will). What I want to do is compile python statically into binaries and then plop them wherever our customers choose to do an install (we will provide the source tarballs on a cd as well). The problem we are running into is that when we do this python continues to think it's still installed where it was initially compiled and not where it has been placed (which causes some problems with traceback and some other functions). Is there a way to make a relocateable python binary... that is... a python installation that won't care where it is on the machine... and won't care if it gets put somewhere else besides / ? Sorry for the long winded post... just want to make sure you understand my problem. Thanks in advance for any help! Derek From forestiero at qwest.net Tue Jan 11 23:04:20 2005 From: forestiero at qwest.net (DogWalker) Date: Tue, 11 Jan 2005 20:04:20 -0800 Subject: Python.org, Website of Satan In-Reply-To: <1105500724.648914.213880@z14g2000cwz.googlegroups.com> References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <1105500724.648914.213880@z14g2000cwz.googlegroups.com> Message-ID: <20050112040212.8028.64816@linux.local> "Luis M. Gonzalez" said: >humblythegreat... at usa.com wrote: >> python.org = 194.109.137.226 >> >> 194 + 109 + 137 + 226 = 666 >> >> What is this website with such a demonic name and IP address? What >> evils are the programmers who use this language up to? >You dared to unveil our secret. >Now we'll have to kill you... > But is 194.109.137.226 the only one? What other sites are in league with the python? From josh at yucs.org Tue Jan 11 12:33:35 2005 From: josh at yucs.org (josh at yucs.org) Date: Tue, 11 Jan 2005 12:33:35 -0500 Subject: why not datetime.strptime() ? In-Reply-To: <16867.59681.423983.244528@montanaro.dyndns.org> References: <20050111021152.GA20127@yucs.org> <16867.59681.423983.244528@montanaro.dyndns.org> Message-ID: <20050111173335.GB26246@yucs.org> On Tue, Jan 11, 2005 at 08:56:33AM -0600, Skip Montanaro wrote: > * The seventh item returned from time.strptime() is the day of the week. > You're passing it into the microsecond arg of the datetime constructor Thanks! > and ignoring the timezone info (ninth item returned from > time.strptime(), eighth arg to the datetime constructor). > This is intentional. time.strptime() doesn't expose the timezone (only the daylight savings flag), so i'd have to duplicate its logic in order to distinguish between local time and utc. Since it's easy to explicitly call somedatetime.replace(tzinfo=sometzinfo), having strptime() always create "naive" datetimes seemed most sensible. > * It would be nice if the import happened only once and was cached: > > static PyObject *time_module; > ... > if (time_module == NULL && > (time_module = PyImport_ImportModule("time")) == NULL) > return NULL; > obj = PyObject_CallMethod(time_module, ...); The datetime is full of these calls. Would it make sense to make this a separate patch? (Or maybe the PyImport_ImportModule could implement such a cache :) ?) -------------- next part -------------- *** Modules/datetimemodule.c.orig 2003-10-20 10:34:46.000000000 -0400 --- Modules/datetimemodule.c 2005-01-11 12:19:36.839337336 -0500 *************** *** 3774,3779 **** --- 3774,3819 ---- return result; } + /* Return new datetime from time.strptime(). */ + static PyObject * + datetime_strptime(PyObject *cls, PyObject *args) + { + PyObject *result = NULL, *obj, *module; + const char *string, *format; + + if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format)) + return NULL; + + if ((module = PyImport_ImportModule("time")) == NULL) + return NULL; + obj = PyObject_CallMethod(module, "strptime", "ss", string, format); + Py_DECREF(module); + + if (obj != NULL) { + int i, good_timetuple = 1; + long int ia[6]; + if (PySequence_Check(obj) && PySequence_Size(obj) >= 6) + for (i=0; i < 6; i++) { + PyObject *p = PySequence_GetItem(obj, i); + if (PyInt_Check(p)) + ia[i] = PyInt_AsLong(p); + else + good_timetuple = 0; + Py_DECREF(p); + } + else + good_timetuple = 0; + if (good_timetuple) + result = PyObject_CallFunction(cls, "iiiiii", + ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]); + else + PyErr_SetString(PyExc_ValueError, + "unexpected value from time.strptime"); + Py_DECREF(obj); + } + return result; + } + /* Return new datetime from date/datetime and time arguments. */ static PyObject * datetime_combine(PyObject *cls, PyObject *args, PyObject *kw) *************** *** 4385,4390 **** --- 4425,4435 ---- PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " "(like time.time()).")}, + {"strptime", (PyCFunction)datetime_strptime, + METH_VARARGS | METH_CLASS, + PyDoc_STR("strptime -> new datetime parsed from a string" + "(like time.strptime()).")}, + {"combine", (PyCFunction)datetime_combine, METH_VARARGS | METH_KEYWORDS | METH_CLASS, PyDoc_STR("date, time -> datetime with same date and time fields")}, *** Doc/lib/libdatetime.tex.orig 2003-09-06 01:36:56.000000000 -0400 --- Doc/lib/libdatetime.tex 2005-01-11 12:02:30.000000000 -0500 *************** *** 624,629 **** --- 624,636 ---- ignored. \end{methoddesc} + \begin{methoddesc}{strptime}{date_string, format} + Return the date corresponding to date_string, parsed according + to format. This is equivalent to \code{datetime(*(time.strptime( + date_string, format)[0:6]))}. \exception{ValueError} is raised if + \code{time.strptime()} returns a value which isn't a timetuple. + \end{methoddesc} + Class attributes: \begin{memberdesc}{min} *** Lib/test/test_datetime.py.orig 2005-01-11 11:56:36.000000000 -0500 --- Lib/test/test_datetime.py 2005-01-11 12:28:30.268243816 -0500 *************** *** 1351,1356 **** --- 1351,1365 ---- # Else try again a few times. self.failUnless(abs(from_timestamp - from_now) <= tolerance) + def test_strptime(self): + import time + + string = '2004-12-01' + format = '%Y-%m-%d' + expected = self.theclass(*(time.strptime(string, format)[0:6])) + got = self.theclass.strptime(string, format) + self.assertEqual(expected, got) + def test_more_timetuple(self): # This tests fields beyond those tested by the TestDate.test_timetuple. t = self.theclass(2004, 12, 31, 6, 22, 33) From gurpreet.sachdeva at gmail.com Thu Jan 6 02:47:11 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Thu, 6 Jan 2005 13:17:11 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: <2b7d8b42050105232546083758@mail.gmail.com> References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> <003801c4f3b9$af17fa20$0800a8c0@vishnu> <2b7d8b42050105232546083758@mail.gmail.com> Message-ID: On Thu, 6 Jan 2005 12:55:22 +0530, Binu K S wrote: >>>The file's current position moves as you write into it. I concure and have figured out the solution BUT while reading from the file from the position where the file handler is, should return "Null/Blank/Anything in this world" BUT should not write into the file... The information written was that in the Buffer of the handler... Does that mean reading a file will actually release the buffer by throwing the contents in the file??? Please Comment... >>>You normally wouldn't read from the file that you are writing into. May be applicable in handling logs... Regards, Garry From wittempj at hotmail.com Mon Jan 17 11:07:04 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 08:07:04 -0800 Subject: pychecker - sets.Set need to be overridden In-Reply-To: References: Message-ID: <1105978024.706237.304360@c13g2000cwb.googlegroups.com> mport sets class Foo: def __init__(self): self.x = sets.Set() x = Foo() print x, getattr(x, 'x') gives for me: <__main__.Foo instance at 0x00C578A0> Set([]) on 2.4. on WinXP. What environment do you run in? From mahs at telcopartners.com Tue Jan 25 15:05:53 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 25 Jan 2005 12:05:53 -0800 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: Message-ID: Steven Bethard wrote: > > I wish there was a way to, say, exec something with no builtins and > with import disabled, so you would have to specify all the available > bindings, e.g.: > > exec user_code in dict(ClassA=ClassA, ClassB=ClassB) > > but I suspect that even this wouldn't really solve the problem, > because you can do things like: > > py> class ClassA(object): > ... pass > ... > py> object, = ClassA.__bases__ > py> object > > py> int = object.__subclasses__()[2] > py> int > > > so you can retrieve a lot of the builtins. I don't know how to > retrieve __import__ this way, but as soon as you figure that out, you > can then do pretty much anything you want to. > > Steve Steve Safe eval recipe posted to cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 Couldn't safe exec be programmed similarly? 'import' and 'from' are syntax, so trivially avoided Likewise, function calls are easily intercepted As you say, attribute access to core functions appears to present the challenge. It is easy to intercept attribute access, harder to know what's safe. If there were a known set of 'dangerous' objects e.g., sys, file, os etc... then these could be checked by identity against any attribute returned Of course, execution would be painfully slow, due to double - interpretation. Michael From fumanchu at amor.org Thu Jan 20 11:46:26 2005 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 20 Jan 2005 08:46:26 -0800 Subject: QOTW from Ryan Tomayko Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339822D@exchange.hqamor.amorhq.net> http://naeblis.cx/rtomayko/2005/01/20/getters-setters-fuxors "...Many people coming to Python can't believe no one uses IDEs. The automatic assumption is that Python is for old grey beards who are comfortable with vi and Emacs and refuse to accept breakthroughs in programming productivity like IDEs. Then they write a little Python code and realize that an IDE would just get in their way." FuManChu From bokr at oz.net Sat Jan 22 08:32:37 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 22 Jan 2005 13:32:37 GMT Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> <10v39ald6em3u6f@corp.supernews.com> Message-ID: <41f24e9a.1521192118@news.oz.net> On Fri, 21 Jan 2005 17:04:11 -0800, Jeff Shannon wrote: >TB wrote: > >> Hi, >> >> Is there an elegant way to assign to a list from a list of unknown >> size? For example, how could you do something like: >> >> >>>>> a, b, c = (line.split(':')) >> >> if line could have less than three fields? > >(Note that you're actually assigning to a group of local variables, >via tuple unpacking, not assigning to a list...) > >One could also do something like this: > > >>> l = "a:b:c".split(':') > >>> a, b, c, d, e = l + ([None] * (5 - len(l))) > >>> print (a, b, c, d, e) >('a', 'b', 'c', None, None) > >>> Or >>> a, b, c, d, e = ('a:b:c'.split(':')+[None]*4)[:5] >>> print (a, b, c, d, e) ('a', 'b', 'c', None, None) You could even be profligate and use *5 in place of that *4, if that makes an easier idiom ;-) Works if there's too many too: >>> a, b = ('a:b:c'.split(':')+[None]*2)[:2] >>> print (a, b) ('a', 'b') > >Personally, though, I can't help but think that, if you're not certain >how many fields are in a string, then splitting it into independent >variables (rather than, say, a list or dict) *cannot* be an elegant >solution. If the fields deserve independent names, then they must >have a definite (and distinct) meaning; if they have a distinct >meaning (as opposed to being a series of similar items, in which case >you should keep them in a list), then which field is it that's >missing? Are you sure it's *always* the last fields? This feels to >me like the wrong solution to any problem. > >Hm, speaking of fields makes me think of classes. > > >>> class LineObj: >... def __init__(self, a=None, b=None, c=None, d=None, e=None): >... self.a = a >... self.b = b >... self.c = c >... self.d = d >... self.e = e >... > >>> l = "a:b:c".split(':') > >>> o = LineObj(*l) > >>> o.__dict__ >{'a': 'a', 'c': 'c', 'b': 'b', 'e': None, 'd': None} > >>> > >This is a bit more likely to be meaningful, in that there's almost >certainly some logical connection between the fields of the line >you're splitting and keeping them as a class demonstrates that >connection, but it still seems a bit smelly to me. > That gives me an idea: >>> def foo(a=None, b=None, c=None, d=None, e=None, *ignore): ... return a, b, c, d, e ... >>> a, b, c, d, e = foo(*'a:b:c'.split(':')) >>> print (a, b, c, d, e) ('a', 'b', 'c', None, None) But then, might as well do: >>> def bar(nreq, *args): ... if nreq <= len(args): return args[:nreq] ... return args+ (nreq-len(args))*(None,) ... >>> a, b, c, d, e = bar(5, *'a:b:c'.split(':')) >>> print (a, b, c, d, e) ('a', 'b', 'c', None, None) >>> a, b = bar(2, *'a:b:c'.split(':')) >>> print (a, b) ('a', 'b') >>> a, b, c = bar(3, *'a:b:c'.split(':')) >>> print (a, b, c) ('a', 'b', 'c') But usually, I would like n + tail, where I know n is a safe bet, e.g., >>> def ntail(n, *args): ... return args[:n]+(args[n:],) ... >>> a, b, t = ntail(2, *'a:b:c:d:e'.split(':')) >>> print (a, b, t) ('a', 'b', ('c', 'd', 'e')) >>> a, b, t = ntail(2, *'a:b'.split(':')) >>> print (a, b, t) ('a', 'b', ()) People have asked to be able to spell that as a, b, *t = 'a:b:c:d:e'.split(':') Regards, Bengt Richter From gsakkis at rutgers.edu Mon Jan 24 11:47:24 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Mon, 24 Jan 2005 11:47:24 -0500 Subject: Tuple slices Message-ID: <35kn4mF4o44ufU1@individual.net> Why does slicing a tuple returns a new tuple instead of a view of the existing one, given that tuples are immutable ? I ended up writing a custom ImmutableSequence class that does this, but I wonder why it is not implemented for tuples. George From craig at postnewspapers.com.au Sat Jan 1 05:51:20 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 01 Jan 2005 18:51:20 +0800 Subject: exposing C array to python namespace: NumPy and array module. In-Reply-To: References: Message-ID: <1104576679.24895.41.camel@rasputin.localnet> On Sat, 2005-01-01 at 08:18, Bo Peng wrote: > Python's array module is built-in, easy to use, but *without* a > FromLenAndData function! Even the buffer interface provides only 'get > buffer' but no 'set buffer' functions. Could anyone tell me how I can > create an array object from existing data? Python has no array objects in the core language, only lists. The distinction is important when discussing numarray etc, because Python lists and NumPy etc arrays are very different. While you can build a Python list from a subsection of your C array, changes made in Python won't be pushed back to the C array it was created from. If this is OK, you can probably build the list using just a for loop - I'm not sure if there are any more efficient methods for variable length lists. If the Python user needs to be able to change the underlying array, I'd probably drop the use of the built-in list class entirely and write my own class that looks like a list (and smells like a list, and tastes like a list - lucky we didn't step in it!). It can be pretty simple, providing as few of the list protocol methods as: __getitem__ (a PyList_GetItem equivalent) __setitem__ (a PyList_SetItem equivalent) and preferably: __len__ __iter__ or as much of the list protocol as documented on the Python/C API page as you need. I'd probably implement the class in Python, and have my extension module provide a couple of simple functions to the underlying C array. These could be considered private to your list class. That'd make writing things like the __iter__ method much nicer, while still letting you implement __len__, __getitem__, __setitem__, etc in C. For example, I might write: class CArray(object): def __init__(self, ...): ... def __getitem__(self, index): _carray_getitem(self, index) def __len__(self): _carray_len(self, index) def __iter__(self): # build and return an interator using Python ... If you want to write part of your extension module in Python and part in C, there are two main ways to do it. The usual way is to write a 'wrapper' in Python that imports the C parts, wraps them where necessary or just pushes them into its own namespace, etc. The less common way is to import __builtins__ and __main__ into your C extension module's namespace then PyRun_String() python code in it to set things up. I find this approach MUCH more useful when embedding Python in an app and I only want to write small bits of my module in Python. The other alternative is to code your class entirely in C, implementing all the __methods__ as C functions. Unattractive as far as I'm concerned, but then I find constructing classes using Python's C API irritating and less clear than it could be. Here's the code -- hideously reformatted to avoid wrapping in the mail - in my initmodule() function that I use to set up the module so that Python code can execute in its namespace. You can ignore the const_cast<> stuff, chances are your compiler will ignore the const problems. ---- // 'd' is the dictionary of the extension module, as obtained // with PyModule_GetDict(module) PyObject* builtinModule = PyImport_ImportModuleEx( const_cast("__builtin__"), d, d, Py_BuildValue(const_cast("[]")) ); if (builtinModule == NULL) { // Error handling will not be shown; it'll depend on your module anyway. } PyDict_SetItemString(d, const_cast("__builtin__"), builtinModule); PyObject* exceptionsModule = PyImport_ImportModuleEx( const_cast("exceptions"), d, d, Py_BuildValue(const_cast("[]")) ); if (exceptionsModule == NULL) {} PyDict_SetItemString(d, const_cast("exceptions"), exceptionsModule); // We can now run Python code in the module's namespace. For // example (untested), as my real examples wouldn't do you any // good, they're too bound to the internal API of my module: QString python_code = ""; python_code += "def sample_function():\n"; python_code += " print \"See, it worked\"\n"; // My app sets sysdefaultencoding to utf-8, hence: char* python_code_cstring = python_code.utf8(); // Note that we pass our module dictionary as both // locals and globals. This makes the code effectively // run "in" the extension module, as if it was being // run during loading of a Python module after an // 'import' statement. PyObject* result = PyRun_String(python_code_cstring, Py_file_input, d,d); if (result == NULL) { qDebug("Python code to declare sample_function failed!"); PyErr_Print(); // also clears the exception } // Because 'result' may be NULL, not a PyObject*, we must call PyXDECREF not Py_DECREF Py_XDECREF(result); -- Ugh - I'd forgotten how ugly C code limited to 80 cols and without syntax highlighting really was. Especially when the reformatting is done as badly as I've done it. I hope you can make some sense out of that, anyway. Note that once the setup is done you can run as many python code snippets as you want, for declaring variables, functions, classes, etc. In my case, its easier to execute snippets as shown above than it is to worry about the module search path and wrapping things using a Python module. If you're doing substantial amounts of Python coding for your module, you'll almost certainly be better off writing a Python module that uses your C module internally (see PIL for a good example of this). -- Craig Ringer From wittempj at hotmail.com Mon Jan 17 12:19:47 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 09:19:47 -0800 Subject: How to prevent the script from stopping before it should In-Reply-To: <1105981979.853318.269300@c13g2000cwb.googlegroups.com> References: <1105981979.853318.269300@c13g2000cwb.googlegroups.com> Message-ID: <1105982387.852448.298900@c13g2000cwb.googlegroups.com> #import urllib, sys #pages = ['http://www.python.org', 'http://xxx'] #for i in pages: # try: # u = urllib.urlopen(i) # print u.geturl() # except Exception, e: # print >> sys.stderr, '%s: %s' % (e.__class__.__name__, e) will print an error if a page fails opening, rest opens fine From steven.bethard at gmail.com Mon Jan 10 01:12:58 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 09 Jan 2005 23:12:58 -0700 Subject: Python3: on removing map, reduce, filter In-Reply-To: <1105314195.310792.163170@c13g2000cwb.googlegroups.com> References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> <1105314195.310792.163170@c13g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > Steven Bethard wrote: >> Note that list comprehensions are also C-implemented, AFAIK. > > Rather strange meaning attached to "C-implemented". The implementation > generates the code that would have been generated had you written out > the loop yourself, with a speed boost (compared with the fastest DIY > approach) from using a special-purpose opcode LIST_APPEND. See below. Fair enough. ;) So you basically replace the SETUP_LOOP, CALL_FUNCTION, POP_TOP and POP_BLOCK with a DUP_TOP and a LIST_APPEND. Steve From quentel.pierre at wanadoo.fr Sat Jan 8 05:22:19 2005 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Sat, 08 Jan 2005 11:22:19 +0100 Subject: Another look at language comparisons Message-ID: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> http://khason.biz/blog/2004/12/why-microsoft-can-blow-off-with-c.html From mesteve_bpleaseremovethis at hotmail.com Sun Jan 2 12:26:02 2005 From: mesteve_bpleaseremovethis at hotmail.com (StvB) Date: Sun, 02 Jan 2005 17:26:02 GMT Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <1104657909.340055.283710@z14g2000cwz.googlegroups.com> <1104668455.691428.12670@c13g2000cwb.googlegroups.com> Message-ID: you did this with pygame!!?? "Erik Bethke" wrote in message news:1104668455.691428.12670 at c13g2000cwb.googlegroups.com... > somehow lost my j's: > > www.erikbethke.com/Python/screenshot02.jpg > www.erikbethke.com/Python/screenshot03.jpg > www.erikbethke.com/Python/screenshot04.jpg > www.erikbethke.com/Python/screenshot05.jpg > From quentel.pierre at wanadoo.fr Sat Jan 22 03:31:04 2005 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Sat, 22 Jan 2005 09:31:04 +0100 Subject: Comments in configuration files Message-ID: <41f20f4a$0$6599$8fcfb975@news.wanadoo.fr> Bonjour, I am developing an application and I have a configuration file with a lot of comments to help the application users understand what the options mean I would like it to be editable, through a web browser or a GUI application. With ConfigParser I can read the configuration file and edit the options, but when I write the result all the comments are lost Are there modules that work on the same kind of ini files (for the needs of my application, I prefer this format to XML or YAML) and don't remove the comments ? TIA, Pierre From martin at v.loewis.de Sun Jan 16 04:41:40 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 16 Jan 2005 10:41:40 +0100 Subject: deleting from tarfile In-Reply-To: References: Message-ID: <41EA36D4.6090409@v.loewis.de> Mark McEahern wrote: > It doesn't appear so. A workaround, of course, is to create a new file > with the subset of files from the old file: That is actually the *only* way to do that. tarfiles cannot be "sparse", in the sense that parts of the file can be marked as deleted. So in order to delete a file, you have to copy the entire tarfile, and skip the file you want to delete - whether you do this yourself, or whether tarfile.py does it for you. Regards, Martin From jcarlson at uci.edu Sat Jan 22 15:40:18 2005 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 22 Jan 2005 12:40:18 -0800 Subject: IDLE Problem in Windows XP In-Reply-To: <41F03130.4080709@cc.gatech.edu> References: <41F03130.4080709@cc.gatech.edu> Message-ID: <20050122123747.F647.JCARLSON@uci.edu> Branden Smith wrote: > > Hi, > > I am a teaching assistant for an introductory course at Georgia Tech > which uses Python, and I have a student who has been unable to start > IDLE on her Windows XP Home Edition machine. Clicking on the shortcut > (or the program executable) causes the hourglass to appear momentarily > (and the process to momentarily appear in the process monitor), but > nothing happens thereafter. ... > Does anyone have any ideas as to what might cause this problem? It shows > up with both Python 2.4 and 2.3. Version 2.2 works as it should. It is probably the socket issue. To get past the socket issue, according to the idle docs: Running without a subprocess: If IDLE is started with the -n command line switch it will run in a single process and will not create the subprocess which runs the RPC Python execution server. This can be useful if Python cannot create the subprocess or the RPC socket interface on your platform. However, in this mode user code is not isolated from IDLE itself. Also, the environment is not restarted when Run/Run Module (F5) is selected. If your code has been modified, you must reload() the affected modules and re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible. That is, have the student modify the shortcut to pass a '-n' argument (without the quotes) to the command. If it works, great, if it doesn't, a traceback would be helpful. - Josiah From irmen at -nospam-remove-this-xs4all.nl Mon Jan 3 18:39:41 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 04 Jan 2005 00:39:41 +0100 Subject: How to access database? In-Reply-To: References: Message-ID: <41d9d7bd$0$6219$e4fe514c@news.xs4all.nl> Florian Lindner wrote: > AFAIK python has a generic API for database access which adapters are > supposed to implement. How can I found API documentation on the API? http://www.python.org/topics/database/ --Irmen From mike.kreiner at gmail.com Tue Jan 25 00:45:07 2005 From: mike.kreiner at gmail.com (mike kreiner) Date: 24 Jan 2005 21:45:07 -0800 Subject: scipy.signal.convolve2d() clips off part of my image Message-ID: <1106631907.600618.324390@c13g2000cwb.googlegroups.com> I'm using the convolve2d(image, mask) function from scipy to blur an image. The image I'm using is 512 by 384. When I display the image that convolve2d returns, the the left-most square of pixels (388 by 388) turn out fine, blurred and everything, however the right side of the image is all black. I've uploaded the practice image to: http://tinypic.com/1g3iox The output image is: http://tinypic.com/1g3iv9 here's what I entered at the intereactive window: >>> import scipy >>> img = scipy.imread("c:\\practice.jpg",flatten=True) >>> img.shape (384, 512) >>> mask = (1.0/115)*scipy.array([[2,4,5,4,2],[4,9,12,9,4],[5,12,15,12,5],[4,9,12,9,4],[2,4,5,4,2]]) >>> blurredImg = scipy.signal.convolve2d(img, mask) >>> scipy.imsave("c:\\blurred.jpg",blurredImg) Also, I noticed that the shape attribute is (384, 512), even though windows and my image editor say the image is 512 by 384. Could this have something to do with the reason convolve2d() only works right on the left-most 388 by 388 pixels? Thanks for any help. -Mike Kreiner From fredrik at pythonware.com Sun Jan 23 14:10:27 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 20:10:27 +0100 Subject: on the way to find pi! References: <20050123184955.25121.qmail@web61005.mail.yahoo.com> Message-ID: Ali Polatel wrote: > write the code type str(pi(5)) and see what I mean it helps if you post the code you want help with in your first post, so people don't have to guess. the pi function doesn't return anything, it prints the value to stdout (that's what the stdout.write things are doing). if a function doesn't return anything, Python automagically inserts a "return None", which explains the "None" you're seeing (well, it prints 3.1415None after your modification, so you probably did something else to get "3.1415'None'"). if you want the digits, you have to change the stdout.write calls to something else. say: def pi(n=-1): output = "" printed_decimal = False r = f((1,0,1,1)) while n != 0: if len(r) == 5: output += str(r[4]) if not printed_decimal: output += '.' printed_decimal = True n -= 1 r = f(r[:4]) return output (this returns a string. to convert it to a Python float, use float(pi(x)). if x is large enough, that gives you the same thing as math.pi). From http Tue Jan 4 19:46:36 2005 From: http (Paul Rubin) Date: 04 Jan 2005 16:46:36 -0800 Subject: Embedding a restricted python interpreter References: Message-ID: <7xacrohfdf.fsf@ruckus.brouhaha.com> Rolf Magnus writes: > I would like to embed a python interpreter within a program, but since that > program would be able to automatically download scripts from the internet, > I'd like to run those in a restricted environment, which basically means > that I want to allow only a specific set of modules to be used by the > scripts, so that it wouldn't be possible for them to remove files from the > hard drive, kill processes or do other nasty stuff. > Is there any way to do that with the standard python interpreter? Don't count on it. From philippecmartin at sbcglobal.net Tue Jan 18 05:45:28 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Tue, 18 Jan 2005 11:45:28 +0100 Subject: Tkinter in thread hangs on windows but not on Linux Message-ID: <1106045128.6665.9.camel@localhost> Hi, I need to pop-up in a "modless" manner some windows from an existing Tkinter loop. The following code works OK under Linux: the second window opens, shows the information, and quits cleanly when destroyed. However, under windows, I get the second window without the content (so I hang in run I guess), and both the thread and the calling process hang. Any clue ? Thanks Philippe #******************************************************************************* class SC_DOCS(threading.Thread): __m_smg = None __m_title = None def __init__(self,p_msg,p_title): threading.Thread.__init__(self) self.__m_msg = p_msg self.__m_title = p_title #******************************************************************************* def run (self): l_r = Tk() l_r.title(self.__m_title) l_f = Frame(l_r) l_f.pack(side=TOP, expand=YES, fill=BOTH) l_st = ScrolledText(l_f) l_st.pack(side=TOP, expand=YES, fill=BOTH) l_st.insert(END,self.__m_msg) l_r.mainloop() . . . l_d = SC_DOCS('A MESSAGE', 'A TITLE') l_d.start() . . . -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From phr at localhost.localdomain Thu Jan 27 10:48:20 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Thu, 27 Jan 2005 15:48:20 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: Skip Montanaro writes: > phr> It is not a whizbang module. It is a stripped-down, basic > phr> implementation of a well-accepted set of standards that are being > phr> used in thousands of other applications in other languages. > > Then there should be a library already out there already. All you > should need to do is wrap it (manually, with SWIG, whatever). I'm currently using something wrapped with SWIG, but my understanding is that core modules are not supposed to depend on SWIG. So a core module will likely use some existing primitives wrapped by hand. That is what I've offered to do, along with providing a somewhat more Pythonic interface (though still a straightforward one) than directly wrapping a C library intended for use from C applications. > phr> There is demand for it. Look at how this thread started: some > phr> crypto user noticed that rotor was gone and wanted to know what to > phr> do instead. > > Yes, and putting rotor back would be the wrong thing to do. Correct. The right thing is to replace rotor with something reasonable that follows standards. > phr> The issue of whether there's enough desire for a crypto module to > phr> warrant including one in the stdlib was decided a long time ago. > phr> The proof of that somebody decided to accept the rotor module into > phr> the distro. > > No, rotor was added in Python's early days (July 1992). Times have changed. I don't see that. There's surely even more demand for crypto now than there was in 1992. > As long as we are discussing cryptography, what's wrong with m2crypto? > > http://sandbox.rulemaker.net/ngps/m2/ It's a good package but it's pretty heavyweight. It depends on both SWIG and OpenSSL. I think it's still under development--there's an occasional flurry of messages about it on python-crypto, but I haven't been following it closely. I'd have a hard time making a case for accepting it into the core given the difficulty I'm having making the case for something as simple as a block cipher wrapper. m2crypto+OpenSSL is at least 100 times as much code as the module I've proposed. I think the Python lib should someday have its own pure-Python SSL/TLS implementation sort of like the one Java has. But if m2crypto went into the lib, I'd use it. > Why not incorporate it into the standard distribution? I don't have the authority to incorporate anything into the standard distribution. All I can do is offer to contribute stuff that I write, and let the distro maintainers decide whether to incorporate it. I don't have the authority to offer m2crypto, since I'm not the author. Only the authors can do that. They haven't done so, as far as I know. > Or, what about Andrew Kuchling's crypto toolkit? > > http://www.amk.ca/python/code/crypto.html This is perhaps more suitable than m2crypto but as far as I know, Andrew hasn't offered to contribute it. Whatever his reasons are, I have to respect them. I think it has more stuff than a core crypto module really needs (e.g. numerous semi-obsolete algorithms that aren't in widespread use so aren't needed for interoperability) but the extra stuff doesn't really get in the way. If it were in the core, it would completely fulfill my desires and I would be transported with ecstacy. But I've never seen any indication that it's headed there. > I believe both have been around awhile. If crypto-in-the-core is > really what's needed why not see if one of them is ready to go? I don't think m2crypto is the answer, though maybe I'm wrong. And if Andrew's package is the answer, he would have submitted it already. > phr> Have you ever used a crypto library in a serious way? > > Nope, never directly. Don't make this about me. I'm interested in the > Python development process and how you'd like to turn it on its head. Either you're the one turning the actual process on its head, or else it's already on its head and needs to be turned rightside up. Either way, the existing process has certainly been a total failure so far at producing good crypto support in the lib. > phr> It's already the category king, because there are precisely zero > phr> other entrants in the category. > > See my above references. Note, I don't use crypto at all, yet I was aware > of both of these (no Googling required). The authors have not offered to contribute them, so they're not in the category. The category consists of crypto modules that have actually been offered. As I keep saying, I'd love it if someone else offered one. I'm not eager for this headache. I just saw that somebody really ought to do it, and nobody was doing it, so I decided I was elected. > My guess would be they are substantially more mature than your > proposed module. This may sound a little strange, since my module is not yet written, but if we take maturity to mean lower future maintenance needs, then I wouldn't say m2crypto is precisely more mature. m2crypto uses SWIG and is intimately connected to an immensely complex package (OpenSSL) anpd has to track new OpenSSL and SWIG releases. OpenSSL has all kinds of OS dependencies, has high performance math subsystems written in assembly code for various different cpu's, etc. So my guess is that m2crypto has a longer development curve and will always need significant amounts of maintenance. My module is more like a basic portable math library that computes square roots, cosines, etc. and is OS and CPU independent. Once written and tested, it's intended to be pretty solid and not need much attention. Andrew's package is along the same lines as mine, except Andrew's is already done, so Andrew's is definitely more mature. I like to think that my module's API incorporates some lessons from Andrew's and improves on it, but that's not that important in practice. > phr> I read those as saying that no crypto module will be > phr> considered for inclusion whether or not it's the category > phr> king, because any such module might conflict with crypto > phr> regulations in some countries. > > That may be a problem, sure. I'm not sure how the discussion here changes > that. That's just life as we know it. It doesn't change it. However, it does change my level of interest in writing a module, as is reasonable since the only important characteristics of my module that are different from existing ones is that mine is designed specifically to be suitable for the core and has been offered for distribution in the core. Outside the core, the existing modules work ok so I use them. > Why in the heck is inclusion in the standard library a requirement > for you to write this thing? There's no other reason to write it. Outside the stdlib, there are other modules that are already useable, like the ones you mentioned, so I use those. > If it's useful to you, write it and get on with your life. It's not worth doing unless it's intended for the stdlib. How many times do I have to explain this? > phr> Tell me again how rotor got into the distribution. > > Python's user community was probably a few hundred people. Guido > likely had no thoughts of world domination with the little language that > could. Times have changed. If Python is aiming for world domination, it needs to be able to compete with Java in security features. Java ships with the whole JSSE system and a much fancier low level crypto architecture than the one we've been discussing. So I think the Python folks should figure out how to incorporate crypto without getting crushed under the iron boot (or at least the wooden shoe) of the Dutch government or whatever it is that they're worried about. > You seem think there was a PEP process and distutils and Wikis. I > suspect some of the algorithms one might include in a robust crypto > toolkit today weren't even invented in 1992. AES wasn't invented then. DES became a US federal standard around 1977. > So throw away the rotor crutch and put your money where your mouth is. If you mean write yet another crypto module knowing ahead of time that it won't go into the stdlib, that would be more like throwing my money down the drain. From john at grulic.org.ar Tue Jan 18 13:33:10 2005 From: john at grulic.org.ar (John Lenton) Date: Tue, 18 Jan 2005 15:33:10 -0300 Subject: One-Shot Property? In-Reply-To: <20050118115456510-0500@braeburn.themorgue.org> References: <20050118115456510-0500@braeburn.themorgue.org> Message-ID: <20050118183245.GA13370@grulic.org.ar> On Tue, Jan 18, 2005 at 04:54:56PM +0000, Kevin Smith wrote: > > I have many cases in my code where I use a property for calculating a > value on-demand. Quite a few of these only need to be called once. > After that the value is always the same. In these properties, I set a > variable in the instance as a cached value and return that value on > subsequent calls. It would be nice if there was a descriptor that would > do this automatically. Actually, what would be really nice is if I > could replace the property altogether and put the calculated value in > its place after the first call, but the property itself prevents me from > doing that. Is this possible? consider this: 1 >>> class C: 2 ... x = property(str) 3 ... 4 >>> c = C() 5 >>> c.x 6 '<__main__.C instance at 0x4008d92c>' 7 >>> setattr(c, 'x', c.x) 8 >>> c.x 9 '<__main__.C instance at 0x4008d92c>' 10 >>> C.x 11 12 >>> c.x = 2 13 >>> in line 5 you see that the x property so defined works. In line 7 you remove it, replacing it with the computed value of the property. Line 9 shows that it worked, line 11 shows that it didn't break the class, and line 13 (through the absence of an exception) shows that it no longer is 'special' (as it shouldn't be). -- John Lenton (john at grulic.org.ar) -- Random fortune: You can tune a piano, but you can't tuna fish. You can tune a filesystem, but you can't tuna fish. -- from the tunefs(8) man page -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From xah at xahlee.org Fri Jan 14 22:34:41 2005 From: xah at xahlee.org (Xah Lee) Date: 14 Jan 2005 19:34:41 -0800 Subject: [perl-python] 20050114 if statement Message-ID: <1105760081.771782.140700@f14g2000cwb.googlegroups.com> . # here's an example of if statement in python. . . x=-1 . if x<0: . print 'neg' . elif x==0: . print 'zero' . elif x==1: . print 'one' . else: . print 'other' . . # the elif can be omitted. . ------------------------------ . # here's an example of if statement in perl . . $x=31; . if ($x<0) { . print 'neg' . } elsif ($x==0) { . print 'zero' . } elsif ($x==1) { . print 'one' . } else { . print 'other' . } . . . --------------------------- . . Note: this post is from the Perl-Python a-day mailing list at . http://groups.yahoo.com/group/perl-python/ . to subscribe, send an email to perl-python-subscribe at yahoogroups.com . if you are reading it on a web page, program examples may not run . because html conversion often breaks the code. . . Xah . xah at xahlee.org . http://xahlee.org/PageTwo_dir/more.html From klapotec at chello.at Wed Jan 5 01:44:30 2005 From: klapotec at chello.at (Christopher Koppler) Date: Wed, 05 Jan 2005 06:44:30 GMT Subject: % operation References: Message-ID: On Wed, 05 Jan 2005 15:36:30 +0900, Daewon YOON wrote: > ==== > Python 1.5.2 (#1, Jul 5 2001, 03:02:19) [GCC 2.96 20000731 (Red Hat > Linux 7.1 2 on linux-i386 > Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam > >>> x=9 > >>> y=4 > >>> x%y > 1 > >>> for z in range(44): > ... z%9 > File "", line 2 > z%9 > ^ > SyntaxError: invalid syntax > > ==== > What's wrong with the above operation and how can I get the correct > modulo result with Python? There's nothing wrong with the operation, but it looks like you forgot to indent your loop body (which the interactive shell doesn't automagically do for you): >>> for z in range(44): ... z%9 ... [result snipped] -- Christopher raise OutofSigError From daniel at bowettsolutions.com Wed Jan 26 03:27:34 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Wed, 26 Jan 2005 08:27:34 +0000 Subject: MySQLdb In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Tue, 25 Jan 2005 20:43:54 +0000, Daniel Bowett > declaimed the following in > comp.lang.python: > > >>As a test I have written a script that executes 3000 insert statements >>on a table. The table contains 10 fields with a mix of text and numbers >>- its a product table for a website eg UPC, ProductName, Price etc. >> > > How many indices? > > >>The problem I have is that it takes just over two minuted to execute the >>3000 insert statements which seems really slow! I am running it on a > > > I recall reading that, for some RDBMs, when doing such batch > inserts, they recommend turning off the indices at the start, do the > inserts, then reactivate the indices -- apparently it is faster to > rebuild an index after the data has been inserted, then to continually > update the index. > UPC is my only index - its a varchar with 20 characters. I am only opening the connection once, then doing 3000 execute statements in a for loop. I do have two "TEXT" fields in the table which contain the long and short description. The average length of the long description is about 167 characters, the longest is 1800 characters. Is this whats making it slow? From asbach at ient.rwth-aachen.de Wed Jan 12 16:34:53 2005 From: asbach at ient.rwth-aachen.de (Mark Asbach) Date: Wed, 12 Jan 2005 22:34:53 +0100 Subject: GTK libs don't get events when wrapped for Python Message-ID: <1gqaqim.5ba4rn159bm4gN%asbach@ient.rwth-aachen.de> Hi list, I've got a crazy problem: an application fully written C and using a third-party library that itself uses GTK to draw some GUI widgets works as expected. But if I wrap the lib with SWIG and use it in Python, everythings works but the GUI parts. In fact, it looks like the library doesn't get events / messages from the window manager or these events have a significant delay. For example, I want to open a window and draw an image into it. This means two library calls. The first one should draw the window (but it only does when calling it from a C-only binary), the second one should resize the window and draw the image, but when called from python just draws the window. Occasionally, resize and in rare circumstances drawing of the image occur on subsequent calls of the library. Really strange and I don't have a clue where to look for a remedy. Is there anybody who could help me, please? FYI: the library used is Intel's OpenCV / HighGui, OS is debian/Sarge, python2.3 Thanks in advance, Mark -- Dipl.-Ing. Mark Asbach Tel +49 (0)241 80-27677 Institute of Communications Engineering RWTH Aachen University, Germany http://www.ient.rwth-aachen.de From bokr at oz.net Thu Jan 20 01:51:18 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 20 Jan 2005 06:51:18 GMT Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> <7xacr4ewjk.fsf@ruckus.brouhaha.com> Message-ID: <41ef4a7a.1323588509@news.oz.net> On 19 Jan 2005 17:09:19 -0800, Paul Rubin wrote: >Robin Becker writes: >> > Presumably he is talking about crypo-export rules. In the past strong >> > cryptography has been treated as munitions, and as such exporting it >> > (especially from the USA) could have got you into very serious >> > trouble. >> >> well since rotor is a german (1930's) invention it is a bit late for >> Amricans (Hollywood notwithstanding) to be worried about its export > >1. I think the concern was not about exporting from the US, but rather >importing into some countries that restrict the use of crypto. But >the cat is out of the bag on that one too. Just about every web >browser includes an SSL stack and those browsers are in use >everywhere. Isn't the SSL dependent on OS or at least shared lib support? Wasn't there a default 40-bit version that was ok (weak), but you had to declare yourself US resident to download 128-bit support? I dimly recall encountering this sort of thing installing Netscape a long time ago, I think. Is 128 just standard now? And now that 128 is wobbly(?), will the same thing be replayed with the ante upped? > >2. It's irrelevant for the purpose of export rules how old an >invention is or where it was invented. I don't know where machine >guns were invented, but they're at least 100 years old and you can't >export those without a license either. My gripe with the crypto rules >are not about the age or nationality of crypto rotor machines (rotor >is not a clone of the Enigma by the way; it just operates on related >principles) but rather on the control of information in general. I can easily conceive of information that I'd rather not see publicized without severe access controls. But in general I do believe in open sharing of free information as the most productive for everyone. >Exporting a machine gun is much different from publishing a >description of one. Software is just a precise type of description. Yeah, but ... ;-) Regards, Bengt Richter From grig.gheorghiu at gmail.com Mon Jan 10 13:42:22 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 10 Jan 2005 10:42:22 -0800 Subject: Importing Problem on Windows References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> Message-ID: <1105382542.552797.125200@c13g2000cwb.googlegroups.com> What version of Python are you running on Linux vs. Windows? From richie at entrian.com Tue Jan 25 05:03:02 2005 From: richie at entrian.com (Richie Hindle) Date: Tue, 25 Jan 2005 10:03:02 +0000 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <1f7befae05012411376821bb92@mail.gmail.com> References: <41F427EB.3000200@rogers.com> <1f7befae0501231720428ca3c@mail.gmail.com> <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> <1f7befae05012411376821bb92@mail.gmail.com> Message-ID: [Tim] > there's no 100% guarantee that a __del__ method will ever get called Can anyone point me to any definitive documentation on why this is the case? I was under the impression that __del__ would always be called: 1. for objects not in cycles and with no references 2. for objects whose only references are from cycles which themselves have no external references and no __del__methods, assuming that garbage collection runs. > __del__ methods (weakref callbacks too, for that matter) triggered > while Python is tearing itself down at exit may suffer bizarre > exceptions (due to trying to use facilities in partially-torn down > modules, including the module the __del__ method appears in). Good point. > In general, __del__ is a user-visible method like any other, and user > code may call it explicitly. For that reason, it's safest to write > __del__ methods in library objects such that they can be invoked > multiple times gracefully. Another good point - thanks. -- Richie Hindle richie at entrian.com From dmerrillq at usaq.netq Sat Jan 8 15:56:21 2005 From: dmerrillq at usaq.netq (Dave Merrill) Date: Sat, 8 Jan 2005 15:56:21 -0500 Subject: Installing IPython on win2k References: Message-ID: <4JqdnUwQgOFr1X3cRVn-gg@rcn.net> Fernando replied to a similar post of mine on the IPython list, and had a suggestion that for some unknown reason, worked. Or rather, what's unknown is why normal setup failed. For the benefit of anyone else who has this issue, I unzipped the files into C:\Program Files\ipython-0.6.6 ...then opened a DOS window, and did the following two cmds: cd C:\Program Files\ipython-0.6.6 "C:\Program Files\Python23\python.exe" setup.py install Tons of DOS cmds spat out, the shortcut was created, and launching it brought up the config wizard, then ipython. I'd really love it if ipython could be invoked in the current debugger context in PyDev under Eclipse. Is there any way to do that? Thanks again, Dave Merrill From fredrik at pythonware.com Sun Jan 23 17:52:29 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 23:52:29 +0100 Subject: Set parity of a string References: <1f060c4c050123140310e6f887@mail.gmail.com> Message-ID: "snacktime" wrote: > Is there a module that sets the parity of a string? I have an > application that needs to communicate with a host using even parity > So what I need is before sending the message, convert it from space to > even parity. And when I get the response I need to convert that from > even to space parity. umm. shouldn't the communication library do this for you? From bulba at bulba.com Wed Jan 5 21:27:25 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 03:27:25 +0100 Subject: No typical loops, and other crazy ideas Message-ID: OK. I have reworked this program (below) to use just the data manipulation capabilities of Python (training was largely the motivation). I've tried to manipulate the data just in Python and not in typical loops. One thing that may not be entirely crazy in this, IMHO, is the attempt to use built-in capabilities of the language as much as possible instead of doing it "manually". Anyway, Python is the only language I've seen (apart from functional languages probably, but I have yet to get unconventional enough to wet my feet there) where it is possible. Still, it was not as easy as I wish it were: I've had to use 3 types of data structures (dictionaries, sets, lists) and arguably 6 "stages" (marked in comments below) to get it done. And it still dies when the source terms are not unique. And I haven't figured out the way of producing a list of dictionaries that would have this particular key as unique across all the dictionaries in this list. [Also, for some reason the advice by another poster, to use: oldl=list(orig) instead of: oldl=[x for x in orig] ..somehow didn't work. The first instruction has produced only empty lists.] #---------Code follows----------- import sys import csv from sets import Set as set class excelpoldialect(csv.Dialect): delimiter=';' doublequote=True lineterminator='\r\n' quotechar='"' quoting=0 skipinitialspace=False epdialect=excelpoldialect() csv.register_dialect('excelpol',epdialect) try: ofile=open(sys.argv[1],'rb') except IOError: print "Old file %s could not be opened" % (sys.argv[1]) sys.exit(1) try: tfile=open(sys.argv[2],'rb') except IOError: print "New file %s could not be opened" % (sys.argv[2]) sys.exit(1) titles=csv.reader(ofile, dialect='excelpol').next() orig=csv.DictReader(ofile, titles, dialect='excelpol') transl=csv.DictReader(tfile, titles, dialect='excelpol') cfile=open('cmpfile.csv','wb') titles.append('New') titles.append('RowChanged') cm=csv.DictWriter(cfile,titles, dialect='excelpol') cm.writerow(dict(zip(titles,titles))) print titles print "-------------" # 1. creating lists of old & new translations #oldl=list(orig) #newl=list(orig) oldl=[x for x in orig] newl=[x for x in transl] # oldl is a list of dictionaries like: # [{'Polish': 'Zarzadzanie', 'TermID': '5', 'English': 'Administration'}, # {'Polish': 'Zarzadzanie systemem', 'TermID': '4', 'English': 'System Administration'}, # {'Polish': 'Testowanie', 'TermID': '5', 'English': 'Testing'}] # 2. creation of intersection of sets of old and new English strings to find the common source strings oldeng=set([item['English'] for item in oldl]) neweng=set([item['English'] for item in newl]) matcheng = list(oldeng & neweng) # 3. eliminating items not containing the common source strings oldl=[x for x in oldl if x['English'] in matcheng] newl=[x for x in newl if x['English'] in matcheng] # 4. sorting lists oldl.sort(lambda a, b: cmp(a['English'], b['English'])) newl.sort(lambda a, b: cmp(a['English'], b['English'])) # 5. defining comparison function def matchpol(old,new): retval={'TermID': old['TermID'], 'English': old['English'], 'Polish': old['Polish'], 'New': new['Polish'], 'RowChanged': ''} if old['Polish'] != new['Polish']: retval['RowChanged']='CHANGED' return retval # 6. Constructing list of target dictionaries chglist=map(matchpol, oldl, newl) # 7. Writing to a target file cm.writerows(chglist) # the end.. cfile.close() ofile.close() tfile.close() -- It's a man's life in a Python Programming Association. From alipolatel at yahoo.com Sat Jan 29 19:23:29 2005 From: alipolatel at yahoo.com (Ali Polatel) Date: Sat, 29 Jan 2005 16:23:29 -0800 (PST) Subject: Proxy Message-ID: <20050130002329.4200.qmail@web61003.mail.yahoo.com> is it possible to connect to somewhere through a proxy while using sockets module of Python to connect? If yes can you show me some basic examples? regards --------------------------------- Do you Yahoo!? Yahoo! Search presents - Jib Jab's 'Second Term' -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Sun Jan 23 18:29:55 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 24 Jan 2005 00:29:55 +0100 Subject: Alternative Ways to install Python 2.4? In-Reply-To: References: Message-ID: <41F43373.4020003@v.loewis.de> Michael Goettsche wrote: > I convinced my CS teacher to use Python in school. We currently have 2.2 > installed on a Windows 2000 Terminal server. I asked the system administrator > to upgrade to Python 2.4, but he didn't succeed in doing it. He used the > microsoft installer package, which according to him crashed when starting. > So my question is if there's an alternative way to install it(must be easy). > Would it be an option to remove 2.2 first and then try to install 2.4 again? That would be an option, but I doubt it helps. Please have a look at http://www.python.org/2.4/bugs.html Most likely, you need to upgrade Visual Basic on that machine. Of course, without a precise error description, it is hard to tell. Regards, Martin From sjmachin at lexicon.net Mon Jan 3 14:30:23 2005 From: sjmachin at lexicon.net (John Machin) Date: 3 Jan 2005 11:30:23 -0800 Subject: Py2exe and extension issues References: <1104763249.008031.100100@f14g2000cwb.googlegroups.com> Message-ID: <1104780623.038891.25810@z14g2000cwz.googlegroups.com> kdahlhaus at yahoo.com wrote: > Is anyone aware of issues with Py2exe and extensions compiled with > cygwin/mingw for Python 2.3? I have an extension that wraps access to > some C DLLs. The generated executable always segfaults at startup, > although things work fine when running through the normal python > interpreter. I had a guess that perhaps the issue stems from my > extension being compiled with cygwin and py2exe compiled with Visual > C++? Some questions: 1. Did it work before (e.g. with Python 2.2, or an earlier version of py2exe), or has it never worked? 2. Where at start-up does it "segfault"? Doesn't the "Dr Watson" log file tell you anything? You may need to sprinkle prints and printfs around your code. 3. Those C DLLs: supplied by whom -- you or an nth party? compiled with which compiler? 4. Which version(s) of which Windows are you using? Some hints: 1. Ask on the py2exe mailing list. 2. Your guess may be correct. The usual cause of such a problem is getting a run-time-library resource on one side of the chasm and trying to use it on the other side. When the resource is a pointer to a data structure whose contents are not defined by some standard, anything can go wrong, and usually does. Examples: (a) malloc() on one side and free() on the other (b) fopen() on one side and fanything() on the other. However I would expect these problems to show up under normal interpreter use. 3. Using py2exe instead of python may merely be exposing a bug in your code caused by e.g. an uninitialised variable. (-: When you say "things work fine" in normal interpreter mode, where does this lie in the continuum between "it ran regression tests and volume tests happily all night" and "I fired it up and it didn't fall over"? :-) HTH, John From removethis.kartic.krishnamurthy at gmail.com Mon Jan 31 20:38:19 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Tue, 01 Feb 2005 01:38:19 GMT Subject: "Mail receiver server" In-Reply-To: <41feb541$0$27942$636a15ce@news.free.fr> References: <41feaff2$0$2068$626a14ce@news.free.fr> <41feb541$0$27942$636a15ce@news.free.fr> Message-ID: manatlan said the following on 1/31/2005 5:46 PM: > > I like the idea, but how to connect the virtual smtp and a python script ? > > but ... There should be a way to be python only ... because i don't want > to be very complex, i just want to get the subject of the email, to run > some commands (and perhaps get a attachment file) ... but that's all > i am pretty sure that a recipe exists ... that a man has already done > that ! > But i don't know what to query on google ... Hi, What you are trying to do is what is called a mail filter. So google for python mail filter and see what you get. With this setup, lets say Computer B sends an email to user controluser on Computer A , the email is actually passed off to a script (in your case python script) to process the incoming email, instead of actually delivering the email to the user's inbox on "A". I don't have the faintest the idea how you would do this on IIS's virtual SMTP server; there is probably a setup user panel. In any case, on UNIXish systems, there are a few ways of doing it of which one way is to setup a user in a file called /etc/aliases and put an entry like this: controluser: | /usr/local/bin/mailprocessor.py which tells the SMTP server to pass off the email to script after the | (pipe) when controluser gets an email. So, see if the SMTP control panel provides you with some such feature. If IIS does not, my suggestion to you will be to install Cygwin from cygwin.com and use the Exim Mail transfer agent available with Cygwin (You will have to choose that when installing Cygwin, it is not automatically installed) or please google for Windows SMTP Server and see if something piques your interest. Now, coming to the Python related part. Your SMTP server will invoke your script by sending the incoming email data on your script's sysin. So, from python you will do... #!/usr/local/bin/python import sys, email, os em = email.message_from_file(sys.stdin) # Read message from Std Input subject = em.get('Subject') # Get the subject from em object if subject.startswith('reboot'): os.system('shutdown -r') # reboot the Server For more information, please read the email module in the Python Module Docs. Hope that will help you get started! Thanks, --Kartic From jlrodilla at gmail.com Sun Jan 30 14:19:30 2005 From: jlrodilla at gmail.com (jlrodilla at gmail.com) Date: 30 Jan 2005 11:19:30 -0800 Subject: search engine Message-ID: <1107112770.301449.49070@c13g2000cwb.googlegroups.com> hi all, i?m doing a search engine using python for the spider and php to make a web for the search. The Database i have choosen is postgreSQL. Do you think it is a good choosen? Any suggestion? if anybody in interested in colaborate please send an e-mail to jlrodilla at gmail.com In a few weeks i will upload all the code to one domain and so i can be able to send you information about this project. The idea is to build a search engine like "google", but my/our search engine only look for tech pages, i also wants that users can select if they want to search a web, faqs/howto, manuals/tutorials... Thanks. From fuzzyman at gmail.com Thu Jan 27 07:38:39 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 27 Jan 2005 04:38:39 -0800 Subject: Please suggest on the book to follow In-Reply-To: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> Message-ID: <1106829519.540737.164210@z14g2000cwz.googlegroups.com> We've only just had Python 2.4. Based on previous experience that means it will be about 18 months before python 2.5..... I learned to program from 'Programming Python'. Particularly the stuff on Tkinter is very helpful. I don't think you'll have much to 'unlearn', although obviously there is stuff it doesn't cover (like new style classes). Regards, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From __peter__ at web.de Mon Jan 17 16:04:41 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Jan 2005 22:04:41 +0100 Subject: Assigning to self References: <200501172055.33962.frans.englich@telia.com> Message-ID: Frans Englich wrote: >> > >>> class Foo(object): >> > >> > ... cache = {} >> > ... def __new__(cls, id): >> > ... try: >> > ... return cls.cache[id] >> > ... except KeyError: >> > ... pass >> > ... cls.cache[id] = result = object.__new__(cls, id) >> > ... return result >> > ... def __init__(self, id): >> > ... self.id = id >> > ... def __repr__(self): >> > ... return "Foo(id=%r)" % self.id >> > ... >> >> I'm not sure, but I think this code misses one thing: that __init__ is >> called each time __new__ returns it, as per the docs Peter posted. > > Ahem, John I ment :) You are right -- just put the initialization into the __new__() method, then. Peter From rkern at ucsd.edu Thu Jan 6 00:37:10 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 05 Jan 2005 21:37:10 -0800 Subject: Python evolution: Unease In-Reply-To: <41dcc35a$0$3872$afc38c87@news.optusnet.com.au> References: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> <41dcc35a$0$3872$afc38c87@news.optusnet.com.au> Message-ID: Mike Thompson wrote: > Alex Martelli wrote: > >> Carlos Ribeiro wrote: >> ... >> >>>> - IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than >>>> Pythonwin? >>> >>> >>> I would like to seee Eric3, with some polish & opensourced on Win >>> (which means solving the Qt licensing problem). Perhaps someone could >>> convince Trolltech to release a special Qt Win version just for it >>> (Eric3). Eclipse is also an interesting approach. >> >> >> >> I love eric3, but if you're an eclipse fan, look at enthought's >> "envisage" IDE -- it seems to me that it has superb promise. >> > > I've tried both the SciPy and Enthought WWW sites and I can't find much > on "Envisage". At SciPy.org there is one set of powerpoint slides on it > but nothing more. > > Is it available for download somewhere? Alex is, I think, jumping the gun a bit. Envisage isn't quite ready for prime time as your day to day IDE. It might be useful to you right now as a platform to build a dynamic GUI application (Envisage's intended use) if you are willing to get your hands dirty and help us build Envisage. Hence, it is not being advertised widely. But Alex is right; Envisage does hold a lot of promise. -- 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 ola.natvig at infosense.no Tue Jan 18 09:16:04 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Tue, 18 Jan 2005 15:16:04 +0100 Subject: generator expressions: performance anomaly? In-Reply-To: <354jhnF4gk8l6U1@individual.net> References: <377Hd.77904$Jk5.30235@lakeread01> <354gj7F4etgn8U1@individual.net> <354h9gF4fgsqgU1@individual.net> <354jhnF4gk8l6U1@individual.net> Message-ID: > > What makes the leftmost expression different from the iterable returning > expression inside the for? The same arguments apply there. > It's not different, but it's a requirement that the iterable returns the same data every time. I know that anyone can type range = fancyRange and make this return a random number of random items. But if that happens the expression cannot be transformed into a static list / tuple. Thats obvious. From ncoghlan at iinet.net.au Wed Jan 19 05:34:56 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 19 Jan 2005 20:34:56 +1000 Subject: Dictionary keys (again) (was Re: lambda) In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: <41EE37D0.70108@iinet.net.au> Antoon Pardon wrote: > A rule of thumb is context sensitive. If circumstances change, > so do the rules of thumb. Principles have a broader field > of application. > > IMO there is nothing principally wrong with using a mutable object > as a dictionary key. But avoiding doing so is a good rule of > thumb if you have a python-like implementation of a dictionary. For a 'mutable key' to make sense, the following: lst = [] dct = {l: "Hi!"} print dct[[]] print dct[lst] lst.append(1) print dct[[1]] print dct[lst] Should print: Hi Hi Hi Hi That's completely impractical though - for any sane implementation, at least one of the above print statements will throw a KeyError. Your example of a 'safe_dict' that copies mutable keys means that the final print statement is the one that fails. My suggestion of an "identity_dict" means that both of the same-value based lookups would fail. Notice that both of these approaches take a mutable key and make it immutable (either by holding the sole reference to a copy, or retrieving an immutable property of the mutable object). There's also your solution of "I promise not to mutate the key while it is in the dictionary". Workable, but opens the door to some entertaining bug hunts when the promise is broken. Which solution is the best default behaviour? Well, the Zen of Python states "In the face of ambiguity, refuse the temptation to guess". So that's the policy the builtin dict follows - it doesn't try to guess when to make a copy, or whether or not to use identity based semantics in the face of mutability. Instead, it raises an exception at key entry time, asking the programmer to clarify their intent. The principle is *certainly* that hash tables should contain immutable keys. Your own 'safe_dict' example implicitly concedes this point by making copies 'when required'. 'When required' for what? When required to preserve immutability, perhaps? In short, sane hash tables require immutable keys, and how mutable keys acquire the requisite immutability is going to be application dependent. Provision of a safe_dict or identity_dict would merely allow a programmer to state their intent at the time the container is created, rather than having to state it whenever keys are generated or referenced. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steve at holdenweb.com Mon Jan 31 13:55:34 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 13:55:34 -0500 Subject: Relocatable binary installs.... In-Reply-To: References: <1107195180.462949.222980@z14g2000cwz.googlegroups.com> Message-ID: <41FE7F26.1090209@holdenweb.com> Fredrik Lundh wrote: > friedmud at gmail.com wrote: > > >>Is there a way to make a relocateable python binary... that is... a >>python installation that won't care where it is on the machine... and >>won't care if it gets put somewhere else besides / ? > > > the standard CPython interpreter is 100% "relocatable". If you think > it isn't, you have to be a bit more specific. > Is it possible that you are using "relocatable" in the standard sense of "code can be located anywhere in physical memory", where the OP is using the same term to mean "can live anywhere in the filestore"? I suspect the problem the OP is seeing is because the --prefix configuration parameter will cause an interpreter to look in a specific place for standard libraries. Clearly if you "relocate" the libraries to another directory entirely then an interpreter without any further nouse (and no symbolic links to help it) is going to crap out badly. But I could be wrong. always-prepared-to-at-least-admit-the-possibility-ly y'rs - 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 http Sat Jan 22 07:32:30 2005 From: http (Paul Rubin) Date: 22 Jan 2005 04:32:30 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> Message-ID: <7xu0p9lk4h.fsf@ruckus.brouhaha.com> Dave Benjamin writes: > Can we get a show of hands for all of those who have written or are > currently maintaining code that uses the leaky listcomp "feature"? It's really irrelevant whether anyone is using a feature or not. If the feature is documented as being available, it means that removing it is an incompatible change that can break existing code which currently conforms to the spec. If the "feature" is described as the bug that it is, anything that relies on it is nonconformant. I do remember seeing some cute tricks (i.e. capable of becoming idioms) that depend on the leakage. From xah at xahlee.org Mon Jan 17 12:45:01 2005 From: xah at xahlee.org (Xah Lee) Date: 17 Jan 2005 09:45:01 -0800 Subject: [perl-python] 20050117, filter, map In-Reply-To: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: <1105983901.353590.83310@c13g2000cwb.googlegroups.com> erratum: the Mathematica Apply should've been Select. ... Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From godoy at ieee.org Wed Jan 19 12:17:55 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Wed, 19 Jan 2005 15:17:55 -0200 Subject: Accessing MDB files on Windows References: <1635068.ZTfiooUzB4@strongwill.g2ctech> <4262806.PViGKJWPeZ@strongwill.g2ctech> <57wHd.80954$Jk5.41342@lakeread01> Message-ID: <1116749.2eGh3JeIRy@strongwill.g2ctech> Steve Holden, Quarta 19 Janeiro 2005 14:38, wrote: > Note that DAO is a very old library, and nowadays ADO would probably be > the preferred method in the Windows environment (can DAO even *use* > oledb providers?). ADO libraries are available - see > > http://www.markcarter.me.uk/computing/python/ado.html > > for example, or Google for "python ado". Bottom line, there are many > ways to skin this particular cat. Hmmm... I see. I'm trying to avoid having to install external modules at my client's server. Should I use, given that both DAO and ODBC are available with the win32all extensions, DAO or ODBC? Or would ADO give me so much more performance that I should really use it? -- Godoy. From mauriceling at acm.org Sun Jan 2 16:34:58 2005 From: mauriceling at acm.org (Maurice LING) Date: Sun, 02 Jan 2005 21:34:58 GMT Subject: How to make executable file ? In-Reply-To: <33r5gcF449bt0U1@individual.net> References: <33r5gcF449bt0U1@individual.net> Message-ID: <41d868ff@news.unimelb.edu.au> Hi all, This may be OT but is there a way to do the same for *nix type of system? Like cast a python interpreter with scripts together? I'm running Mac OSX here. The only remote idea I have is to use jythonc to convert everything into .class files and package that as a .jar file but I can't do that with C bindings. Any suggestions? Thanks, Maurice From xah at xahlee.org Sat Jan 15 21:31:18 2005 From: xah at xahlee.org (Xah Lee) Date: 15 Jan 2005 18:31:18 -0800 Subject: python mode indentation problem In-Reply-To: <1105802644.939051.229990@f14g2000cwb.googlegroups.com> References: <1105802644.939051.229990@f14g2000cwb.googlegroups.com> Message-ID: <1105842678.044409.270450@z14g2000cwz.googlegroups.com> ? ok, here's the ordeal. ? ? for i in range(5): ? print i ? for i in range(2): ? print i, 'tt' ? for i in [3]: ? print i ? for i in [32]: ? print i ? ? # 1 level, 4 space ? # 2 level, 1 tab ? # 3 level, 1 tab, 4 spaces ? # 4 level, 2 tabs. ? ? who the fuck coded the python mode in emacs? fuckhead please peruse: ? http://xahlee.org/UnixResource_dir/writ/responsible_license.html ? ? PS Thanks for the tip on (setq-default indent-tabs-mode nil). ? ? Xah ? xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html From fredrik at pythonware.com Sat Jan 22 19:21:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 01:21:59 +0100 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com><41EE24F7.7030303@jessikat.fsnet.co.uk><7x1xchlpqv.fsf@ruckus.brouhaha.com><41efeb82$0$27807$9b622d9e@news.freenet.de><41f1a70b$0$25959$9b622d9e@news.freenet.de><7xbrbiqdhk.fsf@ruckus.brouhaha.com><7xllalljah.fsf@ruckus.brouhaha.com><7xekgdmpll.fsf@ruckus.brouhaha.com><7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> you really don't have a fucking clue about anything, do you? > > You're not making any bloody sense. oh, I make perfect sense, and I think most people here understand why I found your little "lecture" so funny. if you still don't get it, maybe some- one can explain it to you. From orwin42 at mail.be Sun Jan 9 08:54:23 2005 From: orwin42 at mail.be (Nyx42) Date: Sun, 09 Jan 2005 08:54:23 -0500 Subject: Pygame and pyopengl with py2exe ? Message-ID: Hi, I have 2 programs which run without problems, but after building them with py2exe, they don't work (program opens the window and closed it immediately) First program (uses only pygame): screen = pygame.display.set_mode((W_WIDTH_F, W_HEIGHT)) This line refuses to be compiled correctly. Why ? Second program (pygame + pyopenGL): Py2exe can't import OpenGL.GL and OpenGL.GLU :( From apardon at forel.vub.ac.be Mon Jan 17 10:20:01 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2005 15:20:01 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-17, John Lenton schreef : > > > --vni90+aGYgRvsTuO > Content-Type: text/plain; charset=us-ascii > Content-Disposition: inline > Content-Transfer-Encoding: quoted-printable > > On Mon, Jan 17, 2005 at 11:41:20AM +0000, Antoon Pardon wrote: >> Op 2005-01-17, Steve Holden schreef : >> > Antoon Pardon wrote: >> > [...] >> >>>"A foolish consistency is the hobgoblin of little minds". Rules are ma= > de=20 >> >>>to be broken. >> >>=20 >> >>=20 >> >> Like only use immutables as dictionary keys. >> >>=20 >> > Fair enough, but don;t go advising newbies to do this. >>=20 >> How about something like this. >>=20 >> Because of the extra precautions one has to take when >> using mutables as hash keys, we advise newbies >> to stick with immutable keys until they have gathered >> enough knowledge and experience to adequatly weight >> the pro and cons of a mutable key solution against >> an immutable key solution. > > knowledgeable and experienced users know when to ignore the rules. Then why seems there to be so few acknowledgement that these rules may indeed be broken by users. My experience is that anyone who suggests so runs the risk of being branded a (python) heretic. -- Antoon Pardon From hans at zephyrfalcon.org Fri Jan 28 11:09:16 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 28 Jan 2005 11:09:16 -0500 Subject: Dynamic class methods misunderstanding In-Reply-To: References: Message-ID: Bill Mill wrote: > Hello all, > > I have a misunderstanding about dynamic class methods. I don't expect > this behavior: > > In [2]: class test: > ...: def __init__(self, method): > ...: self.method = method > ...: self.method() > ...: > > In [3]: def m(self): print self > ...: [...] > > TypeError: m() takes exactly 1 argument (0 given) > ----------------------------------------------------------------------------- > > Why doesn't m get the implicit self parameter in the self.method() > call? How would I make it a proper member of the class, so that a > self.method() call would work with the above "m" function? m is a function. When you assign it to self.method, it's still a function. You don't create a new method that way; all you have is a new attribute called 'method' containing the function. To add m as a new method to the *class*, do this: >>> class test: ... def __init__(self, method): ... self.__class__.method = method ... self.method() ... >>> def m(self): print self ... >>> test(m) <__main__.test instance at 0x0192ED78> <__main__.test instance at 0x0192ED78> >>> To add m as a new method to the *instance*, use new.instancemethod, as Diez B. Roggisch already pointed out. HTH, -- Hans Nowak http://zephyrfalcon.org/ From theller at python.net Tue Jan 4 13:57:11 2005 From: theller at python.net (Thomas Heller) Date: Tue, 04 Jan 2005 19:57:11 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> <41dae3c3$0$228$edfadb0f@dread12.news.tele.dk> Message-ID: Max M writes: > Thomas Heller wrote: > >> It seems also the error messages aren't too helpful: >> >>>>>"?".encode("latin-1") >> Traceback (most recent call last): >> File "", line 1, in ? >> UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position 0: ordinal not in range(128) >> Hm, why does the 'encode' call complain about decoding? > > Because it tries to print it out to your console and fail. While > writing to the console it tries to convert to ascii. Wrong, same error without trying to print something: >>> x = "?".encode("latin-1") Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position 0: ordinal not in range(128) >>> > > Beside, you should write: > > u"?".encode("latin-1") to get a latin-1 encoded string. I know, but the question was: why does a unicode string has a encode method, and why does it complain about decoding (which has already been answered in the meantime). Thomas From jerf at jerf.org Tue Jan 4 21:12:40 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 04 Jan 2005 21:12:40 -0500 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> Message-ID: On Tue, 04 Jan 2005 17:12:04 -0800, Paul Rubin wrote: > Irrelevant, the issue isn't what docs can be written if someone wants to > do it, it's what docs are actually already there.... > I just see various other free software projects as > trying to live up to higher standards and I think Python should aspire to > the same thing. So, nobody should have to write the docs because they should already be there, but "somebody" should have to write the docs? You need to think more clearly about the pronouns you are slinging around. Who is this "they" that should write the docs? (Yes, I know you didn't use that exact word but the concept is clearly there.) And what right do you have to demand this action from "they"? Are you willing to pay me to do it? From jurgenex at hotmail.com Sun Jan 30 03:09:54 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sun, 30 Jan 2005 08:09:54 GMT Subject: [perl-python] sending email References: <1107041765.890014.112530@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: [...] > Here's how the situation stands as of 2001 March: ^^^^^^^^^^ Well, at least now we know why Mr. Lee is a little bit behind .... jue From oglycans at yahoo.com Thu Jan 13 17:49:41 2005 From: oglycans at yahoo.com (oglycans at yahoo.com) Date: 13 Jan 2005 14:49:41 -0800 Subject: how to control the mouse pointer with python? References: <1105650438.311153.167410@f14g2000cwb.googlegroups.com> <34o9npF4et4hiU1@individual.net> <1105654593.637145.321290@z14g2000cwz.googlegroups.com> <41e6f6db$0$5416$a1866201@visi.com> Message-ID: <1105656581.837894.142790@z14g2000cwz.googlegroups.com> >What environment? It's X. From jtr at ofb.net Sun Jan 2 22:38:04 2005 From: jtr at ofb.net (John Reese) Date: Mon, 3 Jan 2005 03:38:04 +0000 (UTC) Subject: using HTTP Digest auth with arbitrary HTTP methods? References: Message-ID: In comp.lang.python, [I] wrote: > Hello there. I've run into some missing functionality with HTTP Digest > authentication in the 2.3 library and I was wondering if I'm just > missing something. > > Missing functionality the first: urllib2 > > 1a. You can add "handlers" to your opener indicating that you want to > use HTTP Digest auth. This is nice way to handle it, but I don't > see any way to use a custom verb in your URLOpener -- it always > uses either GET or POST depending on whether you provided data. > Is there any way to specify an arbitrary method? This would allow > urllib2 to be used to write WebDAV clients. > > 1b. HTTPDigestAuthHandler is initialized with an HTTPPasswordMgr > object, which unfortunately deals in cleartext passwords. Digest > authentication can be computed using only a hash of username, > password, and realm; it would be nice if there was an alternate > version of HTTPPasswordMgr that let you deal in hashes instead of > or in addition to plaintext passwords. Well, I figured out a workaround, but it requires changing urllib2.py since the bugs are in base classes. I instead copied it (to urllib3.py) and made the following changes: a. in AbstractDigestAuthHandler.get_authorization, call req.get_method() instead of req.has_data() and 'POST' or 'GET' (python has a ternary operator, who knew) b. in AbstractHTTPHandler.do_open, call req.get_method instead of the hard-coded if-logic which is the same as that in req.get_method Both of these seem like bugs in urllib2. Then I overrode urllib2.Request and made it possibly to set the method, and then passed an instance of my custom Request class (the one that shouldn't have to exist, since Request should allow method to be set explicitly) to OpenerDirector.open(). I'd like to see these changes make it into the standard library -- after being vetted by whoever's in charge of urllib2. Anybody know who I should talk to? From gsakkis at rutgers.edu Tue Jan 25 19:25:55 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Tue, 25 Jan 2005 19:25:55 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> <10vdj4s9ib19fe3@corp.supernews.com> Message-ID: <35o6cdF4qe45fU1@individual.net> "Jeff Shannon" wrote in message news:10vdj4s9ib19fe3 at corp.supernews.com... > George Sakkis wrote: > > > An iterator is perfectly ok if all you want is to iterate over the > > elements of a view, but as you noted, iterators are less flexible than > > the underlying sequence. The view should be (or at least appear) > > identical in functionality (i.e. public methods) with its underlying > > sequence. > > So, what problem is it, exactly, that you think you'd solve by making > tuple slices a view rather than a copy? > > As I see it, you get the *possibility* of saving a few bytes (which It all comes down on what you mean by "a few bytes". Since many (most?) slices are linear wrt to the original sequence's length, it is not hard to think of algorithms that involve the creation of *many* slices (e.g. most recursive divide-and-conquer algorithms). Implementing these using slices simply does not scale as the input sequence gets larger. Of course, you can always use the standard C/C++ approach and pass the original sequence along with the (start,stop,step) indices of the slice, as Terry Reedy mentioned, but then you lose in expressiveness. > may go in the other direction) at a cost of complexity and speed. You > have greater dependence of internal objects on each other, you can't > get rid of the original tuple while any slice views of it exist, you > gain nothing in the way of syntax/usage simplicity... so what's the > point? > > To my mind, one of the best things about Python is that (for the most > part) I don't have to worry about actual memory layout of objects. I > don't *care* how tuples are implemented, they just work. It seems to > me that you're saying that they work perfectly fine as-is, but that > you have a problem with the implementation that the language tries its > best to let you not care about. Is this purely abstract philosophy? No, it's called "scalability", and it's not purely abstract philosophy AFAIK. I fully agree that for the most part you don't have to care about it, and I'm grateful that python does all its magic trasparently. However if you do care about it, and at the same time you are unwilling to sacrifice the elegance of slices, the current implementation is not ideal. > Jeff Shannon > Technician/Programmer > Credit International George From ncoghlan at iinet.net.au Sun Jan 2 02:22:14 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 02 Jan 2005 17:22:14 +1000 Subject: PEP 288 ponderings In-Reply-To: <41D794BA.8090408@colorstudy.com> References: <41D794BA.8090408@colorstudy.com> Message-ID: <41D7A126.4060808@iinet.net.au> Ian Bicking wrote: > Using a one-element list is kind of annoying, because it isn't clear out > of context that it's just a way of creating shared state. But it's > okay, work right now, and provides the exact same functionality. Uh, isn't shared state what classes were invented for? Py> class mygen(object): ... def __init__(self, data): ... self.data = data ... def __iter__(self): ... while 1: ... print self.data ... yield None ... Py> g = mygen(0) Py> giter = iter(g) Py> giter.next() 0 Py> g.data = 1 Py> giter.next() 1 Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From peter at engcorp.com Sun Jan 9 09:50:51 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 09:50:51 -0500 Subject: time module precision In-Reply-To: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> References: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> Message-ID: janeaustine50 at hotmail.com wrote: > So the problem (waiting tens to hundreds of us without busy looping) > still remains... That's actually not a "problem", it's your solution to a problem. Can you describe the _real_ problem, what you are trying to do? _Why_ do you want to wait such brief amounts of time? I ask as someone with fairly extensive background in realtime software (which is basically what it sounds like you are trying to write here), and I suspect that you are either trying to achieve something that's not really possible on Windows XP, or that you are simply doing something that is entirely unnecessary, probably for good reasons but with too little experience of the issues involved. Can you expand on your situation? -Peter From jelle.feringa at ezct.net Tue Jan 11 11:31:07 2005 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Tue, 11 Jan 2005 17:31:07 +0100 Subject: os.spawnv & stdin trouble Message-ID: <20050111163036.808E91C00CE9@mwinf0108.wanadoo.fr> ##I know I should be using 2.4 and os.Popen, I know, I know. ##However, since most modules I need, I'm using 2.3 for this script I'm having troubles executing a shell script. The thing is that I'm produing material and geometry files that need to be compiled to a binary description (for those familiar to Radiance, oconv) The trouble I'm having is that when python goes through my loop, files are overwritten before os.system was able to process these! (who ways complaining python is slow, well I'm not!! ;-) So the obvious thing to do is to swap os.system for os.spawnv. Here's where I run into trouble. In my os.system version, I'm perfectly able to pipe into another file, since the process has no real connection to python whatsoever. Would someone be able to explain me how to do this, all the tools I'm using for this script are unix-like tools and heavily rely on piping. program = 'xform.exe' path = 'c:\Radiance\bin\' args = ['-t 0 8 0', 'wall0.rad', '>', 'wall0.TRANS.rad'] os.spawnv(os.P_WAIT, path, ('xform', args)) here's the cmd error message: xform: cannot find file ">" ##for your info I'm on win/xp, python 2.3.4 Cheers, Jelle. -------------- next part -------------- An HTML attachment was scrubbed... URL: From foo at bar.com Sun Jan 23 22:48:27 2005 From: foo at bar.com (Steve Menard) Date: Sun, 23 Jan 2005 22:48:27 -0500 Subject: JPype and classpath (Was Re: embedding jython in CPython... ) In-Reply-To: <1106517122.552509.318400@f14g2000cwb.googlegroups.com> References: <1106446384.384110.25150@z14g2000cwz.googlegroups.com> <1106517122.552509.318400@f14g2000cwb.googlegroups.com> Message-ID: johng2001 at rediffmail.com wrote: > Thanks for the response. However, I continue to have problems. Allow me > to give some more detail. > > For simplicity of testing, I hard coded the classpath and JVM path > (BTW getDefaultJVMPath() returns None on my system) > > import os, os.path > from jpype import * > > startJVM("C:/jdk1.5.0/jre/bin/client/jvm.dll", > "-Djava.class.path=D:/Temp/classes") > ... > shutdownJVM() > > > I have setup a classes folder in the script folder (D:/Temp) and have > placed test.class in it. > I run the script from the script folder (working directory is the same > as script's root path in this case) > > Now how do I load the class test? I am afraid I cannot make that out > from the docs. > > The simple test class is > public class test > { > public int i = 100; > } > > > What do I have to do before I can write > test().i > ? > > Thank you for your time. > About the getDefaultJVMPath(), could you send me your system information? On windows, JPype uses the contents of the registry to find the JVM. Of course, the usefulness of this mechanism is limited byt he sample of configurations i can test (I have only one machine). So any info you can provide me on yours can only help. About the classpath. JPype 0.4 currently cannot import classes that are in the "default" package. The fix is easy, simply put your "test" class in a package. For exmaple, if you put the class in the package "test", the code to load it would be : test = jpype.JPackage("test").test -- Steve Menard -------------------- Maintainer of http://jpype.sourceforge.net From robin at SPAMREMOVEjessikat.fsnet.co.uk Wed Jan 19 19:12:44 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Thu, 20 Jan 2005 00:12:44 +0000 Subject: rotor replacement In-Reply-To: <41EEF691.20706@jessikat.fsnet.co.uk> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> Message-ID: <41EEF77C.6030400@jessikat.fsnet.co.uk> Robin Becker wrote: >> Presumably he is talking about crypo-export rules. In the past strong >> cryptography has been treated as munitions, and as such exporting it >> (especially from the USA) could have got you into very serious >> trouble. > So Python is an American Language and must obey American Law. Luckily I seem to have escaped that fate. -- Robin Becker From steven.bethard at gmail.com Mon Jan 24 13:00:48 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Jan 2005 11:00:48 -0700 Subject: Tuple slices In-Reply-To: References: <35kn4mF4o44ufU1@individual.net> Message-ID: Fredrik Lundh wrote: > George Sakkis wrote: > >>Why does slicing a tuple returns a new tuple instead of a view of the existing one, given that >>tuples are immutable ? > > really? > > >>>>a = 1, 2, 3 >>>>b = a[:] >>>>a is b > True My impression was that full tuple copies didn't actually copy, but that slicing a subset of a tuple might. Not exactly sure how to test this, but: py> a = 1, 2, 3 py> a[:2] is a[:2] False So _something_ at least is different between the two slices... Steve From pedro.werneck at terra.com.br Mon Jan 24 13:21:41 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Mon, 24 Jan 2005 16:21:41 -0200 Subject: Tuple slices In-Reply-To: References: <35kn4mF4o44ufU1@individual.net> Message-ID: <20050124162141.0903e6c6.pedro.werneck@terra.com.br> On Mon, 24 Jan 2005 18:45:46 +0100 "Fredrik Lundh" wrote: > George Sakkis wrote: > > > Why does slicing a tuple returns a new tuple instead of a view of > > the existing one, given that tuples are immutable ? > > really? Well... seems like this case (slicing the whole tuple) is optimized to return the original tuple just incrementing its reference count and returning tupleobject.c, 330-335 if (ilow == 0 && ihigh == a->ob_size && PyTuple_CheckExact(a)) { Py_INCREF(a); return (PyObject *)a; } > > >>> a = 1, 2, 3 > >>> b = a[:] > >>> a is b > True > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Wed Jan 5 15:05:27 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 Jan 2005 15:05:27 -0500 Subject: Python 2.4 on Windows XP In-Reply-To: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> References: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> Message-ID: DavidHolt wrote: > I have a problem that I see on two different machines, one running XP > SP1 and one XP SP 2. Works fine here. (First time I've run it though... don't use it.) > On both I installed Python 2.4. > > I can't seem to start IDLE. When I try to start it, I get an hourglass > cursor for a short time then nothing more happens. This happens whether > I click the IDLE shortcut or click the pythonw.exe directly, or attempt > to launch pythonw from a command line. Try python.exe instead of pythonw.exe, also from the command line. That should give you *some* kind of additional detail. > I don't have any trouble running the python command line version. Do you mean "python.exe" here? Are you saying that you can run IDLE using python.exe, but not using pythonw.exe? Or something else? It's not clear. -Peter From FBatista at uniFON.com.ar Wed Jan 5 13:12:43 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 5 Jan 2005 15:12:43 -0300 Subject: Python 2.4 on Windows XP Message-ID: [DavidHolt] #- I have a problem that I see on two different machines, one running XP #- SP1 and one XP SP 2. #- #- On both I installed Python 2.4. #- #- I can't seem to start IDLE. When I try to start it, I get an IDLE uses sockets to communicate its windows. Check if the integrated firewall in WinXP is not blocking you.... . 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 ncoghlan at iinet.net.au Sat Jan 8 00:13:10 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 15:13:10 +1000 Subject: Getting rid of "self." In-Reply-To: References: Message-ID: <41DF6BE6.1080807@iinet.net.au> Roy Smith wrote: > It's actually kind of neat, but boy does it play headgames with me when > I switch back and forth between that and Python. Switching back and forth betwen C++ and Python plays headgames *anyway* }:> Cheers, Nick. Hardware control with Python is nice. . . -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From kendall at monkeyfist.com Mon Jan 3 07:52:52 2005 From: kendall at monkeyfist.com (Kendall Clark) Date: Mon, 3 Jan 2005 07:52:52 -0500 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <41D8F86E.6030300@colorstudy.com> References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> <20050102183402.GC8357@monkeyfist.com> <41D8F86E.6030300@colorstudy.com> Message-ID: <20050103125251.GA12713@monkeyfist.com> On Mon, Jan 03, 2005 at 01:46:54AM -0600, Ian Bicking wrote: > Kendall Clark wrote: > >Between this pressure (which isn't new, since as Steve points out, I > >was talking about this in Python community last year, and I wasn't > >nearly the first) and the growing popularity of Ruby on Rails, there's > >some small hint that Ruby is gaining on Python re: non-Java web app > >mind share. I think that's a v. important niche for Python and would > >like to see us remain strong there (though I've not *done* much about > >this, alas). > > I think that's probably true -- at least in terms of mindshare, even > though that might not reflect on actual work done. But, Rails is really > not a very experimental framework, and the existance of > continuation-based frameworks for Ruby is an aside. If such frameworks > happen at all for Python, I think they will be an aside as well. There's no sense whatever in which Rails is "experimental" -- who suggested such a thing? No, Rails hits a sweet spot, for a class (I suspect) of simple to mediumly-complex web app. Which is what most web apps *are*, after all. I don't begrudge Rails any popularity, I just want us to defend our turf. Sometimes that means ignoring what the other guy does, but sometimes it means aping him. I suspect in this case some aping would be a good thing. As for continuation-based frameworks, as you point out to Steve, that's largely an implementation technique and similar results may be achieved with other techniques (though I, unlike you, did *not* favor Steve's technique, as I recall). Continuations are certainly not experimental, nor are continuation-based modal web frameworks. The latter are *en vogue* and being seen to be *en vogue* is often an important technological virtue, especially for a perceived market niche leader. Kendall Clark -- Sometimes it's appropriate, even patriotic, to be ashamed of your country. -- James Howard Kunstler From janeaustine50 at hotmail.com Mon Jan 10 03:02:50 2005 From: janeaustine50 at hotmail.com (janeaustine50 at hotmail.com) Date: 10 Jan 2005 00:02:50 -0800 Subject: time module precision In-Reply-To: References: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> Message-ID: <1105344170.575115.230820@c13g2000cwb.googlegroups.com> Peter Hansen wrote: > janeaustine50 at hotmail.com wrote: > > So the problem (waiting tens to hundreds of us without busy looping) > > still remains... > > That's actually not a "problem", it's your solution > to a problem. Can you describe the _real_ problem, what > you are trying to do? _Why_ do you want to wait such > brief amounts of time? > > I ask as someone with fairly extensive background in > realtime software (which is basically what it sounds like > you are trying to write here), and I suspect that you are > either trying to achieve something that's not really possible > on Windows XP, or that you are simply doing something that > is entirely unnecessary, probably for good reasons but > with too little experience of the issues involved. Can > you expand on your situation? > > -Peter What I am trying to do is sending binary data to a serial port. Since the device attached to the port cannot handle a continous in-flow of data, I need to make an artificial tiny delay in-between data chunks(a few hundreds of KBs). The delay might be a few tens to hundreds of us. I'd like to make the transmission as fast as possible, uh.. well.. reasonably fast. [I sort of posted this already but hasn't got it through so am reposting it now] Thanks From jello at comics.com Wed Jan 12 10:48:58 2005 From: jello at comics.com (rzed) Date: Wed, 12 Jan 2005 15:48:58 GMT Subject: ConfigParser - add a stop sentinel? Message-ID: I am working with PythonCard in one of my apps. For its purposes, it uses an .ini file that is passed to ConfigParser. For my app, I also need configuration information, but for various reasons, I'd rather use a syntax that ConfigParser can't handle. I know I can maintain two separate configuration files, and if I have to I will, but I'd rather avoid that, if possible, and a solution that suits my purposes is quite straightforward. I insert a sentinel in the ini file and modify my local ConfigParser's _read method to stop accepting input when it encounters that value. I handle my app's portion of the configuration myself. This all works fine, but I was wondering whether it might be worthwhile to add a standard stop flag in ConfigParser itself. Am I the only one with this sort of use case? If there were a standard way of doing this, I'd much rather use that, particularly if I ever have reason to distribute the app elsewhere. -- rzed From richardjones at optushome.com.au Fri Jan 28 19:34:30 2005 From: richardjones at optushome.com.au (richard) Date: Sat, 29 Jan 2005 11:34:30 +1100 Subject: move bugs from Zope BITS into Bugzilla? References: <1106956988.391329.320610@z14g2000cwz.googlegroups.com> Message-ID: <41fada16$0$25421$afc38c87@news.optusnet.com.au> lmhaskins at yahoo.com wrote: > I inherited a bug reporting system at work, and it's currently in Zope > BITS (Bug Information Tracking System). This version of BITS uses ZODB > -- not the RDBMS version. I would like to export all the incident > reports from BITS to later import into Bugzilla, but as of yet I > haven't quite figured it out. As soon as I'm done with this, that's it > for BITS and Zope, so I'd like to avoid writing a Zope app just for > this. > > Anyone solved this problem, or at least the part about exporting from > BITS? I'd hand-enter the open issues, but they also want the closed > ones for tracking & posterity. I'm not helping you with your problem, just plugging my own tracker ;) Use Roundup! It's Pure Python :) http://roundup.sf.net/ Richard From invalidemail at aerojockey.com Sun Jan 9 20:13:10 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 9 Jan 2005 17:13:10 -0800 Subject: python3: 'where' keyword In-Reply-To: <7xr7ku26zs.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> Message-ID: <1105319590.641211.191630@c13g2000cwb.googlegroups.com> Paul Rubin wrote: > Nick Coghlan writes: > > Trying to push it a level further (down to expressions) would, IMO, be > > a lot of effort for something which would hurt readability a lot. > > I think we should just try to do things in a simple and general way > and not try to enforce readability. For example, the > slightly-overcomplex code that I proposed might have been generated by > a macro, or even by a compiler from some other language. No human > would ever have to look at it, so it doesn't matter whether it's > easily readable. There's no reason to add needless constraints on the > language just to make writing ugly code difficult. The main goal > should be to make writing clear code easy, not to worry about whether > someone might also write ugly code. I couldn't disagree more. I belive in the Zen of Python. I believe the Zen of Python is the major factor responsible for Python's success. I believe that moving away from the Zen of Python will only diminish the language. And I think allowing a where statement inside in expression goes against the Zen in so many ways it isn't even funny. Beautiful is better than ugly. Simple is better than complex. (Note that simple means different things to different people: for me, and I believe, for the Zen of Python, it means simple for a human to understand.) Flat is better than nested. (Seems to be the official Zen if effect here.) Readability counts. (Yes, if something's unreadable enough, I hope it's not in the language, not merely that no one uses it.) Special cases aren't special enough to break the rules. (Heretofore, Python has never had a nested block inside an expression; doing that would make it a special case.) I don't want Python to be LISP. I don't think it's an admirable goal for Python to strive to be like LISP for the sake of being like LISP, or for the sake of being general or pure. If Python borrows something from LISP, it should be because that aspect of LISP supports the Zen of Python. If I wanted to use LISP, I'd be using LISP. But I like my statements and expressions distinct. I like things that belong in statements to stay in statements, and things that belong in expressions to stay in expressions. And a suite, be it a def statement, a where block, or whatever, belongs in a statement, not an expression. -- CARL BANKS From scott at hcsprogramming.com Mon Jan 17 10:56:51 2005 From: scott at hcsprogramming.com (Scott) Date: 17 Jan 2005 07:56:51 -0800 Subject: help with wxSlider & wxPython Message-ID: <1105977411.527188.198370@f14g2000cwb.googlegroups.com> I have the code below. I have changed the background of the frame to white, but I cannot get the wxSlider to not be the ugly gray color. Can someone tell me how to change it to a transparent background (I tried wxTRANSPARENT_WINDOW without success)? import os from wxPython.wx import * ID_ABOUT=101 ID_EXIT=110 class MainWindow(wxFrame): def __init__(self,parent,id,title): wxFrame.__init__(self,parent,wxID_ANY, title, size = ( 800,600),style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) #self.control = wxTextCtrl(self, 1, style=wxTE_MULTILINE) wxStaticText(self, -1, "Distance to Move", (30, 40)) slider = wxSlider(self, 100, 25, 0, 3600, (30, 60), (400, -1),wxSL_HORIZONTAL | wxSL_TOP | wxSL_AUTOTICKS | wxSL_LABELS | wxTRANSPARENT_WINDOW) slider.SetTickFreq(1, 1) slider.SetValue(1800) self.CreateStatusBar() # A StatusBar in the bottom of the window # Setting up the menu. filemenu= wxMenu() filemenu.Append(ID_ABOUT, "&About"," Version 001") filemenu.AppendSeparator() filemenu.Append(ID_EXIT,"E&xit"," Terminate the program") # Creating the menubar. menuBar = wxMenuBar() menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content. EVT_MENU(self, ID_ABOUT, self.OnAbout) # attach the menu-event ID_ABOUT to the EVT_MENU(self, ID_EXIT, self.OnExit) # attach the menu-event ID_EXIT to the self.SetBackgroundColour(wxWHITE) self.Show(true) self.Center(wxBOTH) def OnAbout(self,e): d= wxMessageDialog( self, "test","About test", wxOK) d.ShowModal() # Shows it d.Destroy() # finally destroy it when finished. def OnExit(self,e): self.Close(true) # Close the frame. app = wxPySimpleApp() frame = MainWindow(None, -1, "test") app.MainLoop() TIA, Scott From tchur at optushome.com.au Sat Jan 15 17:36:28 2005 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 16 Jan 2005 09:36:28 +1100 Subject: hash patent by AltNet; Python is prior art? In-Reply-To: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> References: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> Message-ID: <41E99AEC.1020008@optushome.com.au> GerritM wrote: > ZDnet features an article about the had patent at AltNet > http://news.zdnet.com/2100-9588_22-5534087.html . Apparantly this issue > plays already for some time, now the p2p companies are threatened, becuase > they use hashing to recognize files. I find it incredibly annoying when journalists reporting on patent issues don't bother to quote the patent numbers (or patent application numbers) concerned (failure to do so probably means they haven't bothered to examine the patent or patent application themselves). In this case, a search is made doubly difficult because the patent was purchased from someone else, so a name serach can't be done. A quick keyworfd search on the USPTO web site revealed some related patents issued to Apple and Sony, but hard to identify this particular patent. > As far as I know hasing is a very old technique used to quickly look up > information. The use of hashing always requires an idnetity check, because > the lookup is not unique (mapping a very big amount of possibilities on a > limited amount of entries). This is a fast and robust way of finding > information, if the right hashing function is used. > > How can this type of fundamental knowledge be patented? I am afraid this is > again an example of a total failure of the current patent system. > Unfortunately these ridiculous examples endanger smaller companies, open > software activities amd innovation in general. What you have to remember is that the US (and some countries which have been stupid enough to follow its lead, like Japan, Australia and now it seems India) permits patents not just on software algorithms and techniques, but also on business methods. Thus the "novel" application of a well-known and widely-used technique such as hashing to a particular field of endeavour (like file sharing on the Internet) can be patented (in the US). To be novel, there must be no published prior art - but the prior art needs to be specific to the claims of the patent. So if the patent says "use of hashing to uniquely identify files in a peer-to-peer network via IP over the Internet", then the prior art needs to describe exactly that. The Australian government recently passed legislation which tightened this test of novelty (thank goodness) by allowing separate bits of prior art which describe aspects of a patent claim to be combined to some degree when opposing a patent - but the test for novelty remains remarkably lax in the US, I beleive. And I agree 100% with Alex Martelli - Europe and other countries must reject software, algorithmic and business method patents and thus create a powerhouse of innovation. let the US and fellow-travellers stew in their own juice - they will become powerhouses of litigation instead. Provided other countries don't recognise software and business method patents, the litigation will be confined within US borders, where resources can be productivelt spent making television dramas about attractive young patent attorneys and plodding, tram-riding patent clerks who are really brilliant physicists if only someone would recognise their potential. So yes, please write to your MP and MEP and protest against the prospect of software and business method patents in Europe. Hopefully one day within my lifetime we'll have a governemt here in Australia which will roll back the damage done to our patent system by trying to make just like the US system, just so we can conclude an unbelieveably inequitable free trade agreement with the US. But that's our problem. Tim C From mensanator at aol.com Mon Jan 10 12:52:03 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 10 Jan 2005 09:52:03 -0800 Subject: Old Paranoia Game in Python In-Reply-To: References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> <1105318366.966577.107460@c13g2000cwb.googlegroups.com> Message-ID: <1105379523.253933.278550@f14g2000cwb.googlegroups.com> Lucas Raab wrote: > mensanator at aol.com wrote: > > Aahz wrote: > > > >>Trust the computer, the computer is your friend. > > > > > > However, the computer isn't a fuckin' mind reader. > > > > If you're going to post source code on the usenet, don't > > have lines longer than 72 characters. Otherwise you'll > > find your code has wrapped lines. This not only causes > > syntax errors in your choose and print statements but > > also fucks up the formatting of of printed paragraphs. > > > > Stupid human. > > > > Temper, temper... But if I hadn't thrown a temper tantrum, I never would have learned about pyparsing (which I downloaded and installed). From chrisdewinN0SPAM at yahoo.com.au Tue Jan 18 17:42:44 2005 From: chrisdewinN0SPAM at yahoo.com.au (Dfenestr8) Date: Wed, 19 Jan 2005 08:42:44 +1000 Subject: python/cgi/html bug Message-ID: Hi. I've written a cgi messageboard script in python, for an irc chan I happen to frequent. Bear with me, it's hard for me to describe what the bug is. So I've divided this post into two sections: HOW MY SCRIPTS WORKS, and WHAT THE BUG IS. HOW MY SCRIPT WORKS Basically, it's divided into two executable scripts...... One is the thread viewer, ppthread.py, which views threads. When someone posts a new topic, for instance called "Generic new topic", it creates a file called "Generic new topic.thread". It stores the post, and any subsequent posts under in the thread in that file. Nice and simple I figured. The other executable script is the topic viewer, pptopic.py. All that does is display the topics, by doing a "tops = os.popen('ls -c *.thread')" The "ls -c" part reads the threads in the order in which they've been modified, so the first item in the list is always the thread most recently posted in. It then creates an html link to each of the threads ... on the page the html looks like.... foo
WHAT THE BUG IS .... The problem is when someone posts a new topic, and that topic happens to have "" double quotes, or any other strange character, some strange glitches occur. Best way to describe is to demonstrate it is go to the forum and try it yourself. Try entering a topic with straight, ordindary characters, not that you can re enter the thread any time you want and make new posts under it. Then try entering a thread with new or whacky characters and see how far you get. http://funkmunch.net/~pirch/cgi-bin/alphaforum/pptopic.py BTW, if you want to download the script, here it is in gzipped form http://funkmunch.net/~pirch/pepperpot.tgz From klachemin at comcast.net Fri Jan 28 11:08:12 2005 From: klachemin at comcast.net (Kamilche) Date: 28 Jan 2005 08:08:12 -0800 Subject: Dynamic class methods misunderstanding References: Message-ID: <1106928492.114459.191320@c13g2000cwb.googlegroups.com> I see what you're attempting to do. However, your code, if it DID run, would result in a method being added to the object, not the object's class! Modify the class itself, not the object, as follows: |class Test: | def __init__(self): | self.method() | |def m(self): | print self | |setattr(Test, 'method', m) |Test() From deetsNOSPAM at web.de Tue Jan 18 09:29:06 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 18 Jan 2005 15:29:06 +0100 Subject: generator expressions: performance anomaly? References: <354esdF4fouh0U1@individual.net> Message-ID: <354kntF4g4crnU1@individual.net> > I don't see how generating byte code for a = 9; when seeing the > expression a = 3 + 6, would be a problem for non-functional > languages. Most probably. But I don't see much code of that type that it would be worth optimizing for, either. The cost for re-evaluation such an expression doesn't really account for any performance problems you hit - in python, of course. See this: deets at kumquat:/usr/lib/python2.3$ python timeit.py -c "[4*5 for i in xrange(10000)]" 100 loops, best of 3: 5.5e+03 usec per loop deets at kumquat:/usr/lib/python2.3$ python timeit.py -c "[20 for i in xrange(10000)]" 100 loops, best of 3: 4.3e+03 usec per loop Now of course the longer the expressions get, the more time it costs - but how many long arithmetical expression of constant evaluation value do you have? > > I agree that things like [time.time() for i in xrange(10)] shouldn't > be pregenerated and that the problem is more complicated as I thought. > > But during compilation the compilor could do an anlysis of the code > do determine whether there are side effects or not. If the compilor > then would store a code in the byte code for functions that are > guaranteed side-effect free and only pregenerated objects generated > by expressions with no side-effect, some common subexpression > elimination could be done even in a non-functional language. This analysis would only be possible for the most primitive of examples, the reason beeing that due to the dynamic features syntactically equivalent expressions can have totally different semantics. So its not really worth the effort. -- Regards, Diez B. Roggisch From jbperez808 at wahoo.com Wed Jan 12 20:26:29 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Thu, 13 Jan 2005 09:26:29 +0800 Subject: Another look at language comparisons In-Reply-To: References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> <34llf5F4apou6U2@individual.net> Message-ID: <34m12rF4cppjeU1@individual.net> Terry Reedy wrote: > It would hardly make more sense with the photos. The photos would be graphic evidence and would make it more entertaining to read through. > "Not the law is clear? There is a beard - there is a success. > There is no beard - you are guilty. " > > Terry J. Reedy And what about the moustache issue and Grace Hopper (COBOL is/was a very popular language but very much maligned and criticized like Perl and BASIC whose creators had moustaches instead of beards) ? Also, what about C#? AFAIK, Heljsberg has neither beard nor moustache, or is he sprouting one now (no pic to confirm...)? From eppstein at ics.uci.edu Wed Jan 19 13:19:55 2005 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 19 Jan 2005 10:19:55 -0800 Subject: Dictionary keys (again) (was Re: lambda) References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: In article , Nick Coghlan wrote: > For a 'mutable key' to make sense, the following: > > lst = [] > dct = {l: "Hi!"} > print dct[[]] > print dct[lst] > lst.append(1) > print dct[[1]] > print dct[lst] > > Should print: > Hi > Hi > Hi > Hi Yes, and what should the following do? lst1 = [1] lst2 = [2] dct = {lst1: "1", lst2: "2"} lst2[0]=1 lst1[0]=2 print dct[[1]] print dct[[2]] -- David Eppstein Computer Science Dept., Univ. of California, Irvine http://www.ics.uci.edu/~eppstein/ From steve at holdenweb.com Mon Jan 31 13:03:54 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 13:03:54 -0500 Subject: variable declaration In-Reply-To: <1gr9lyc.1rrm543162uefN%aleaxit@yahoo.com> References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1107188359.375703.110590@f14g2000cwb.googlegroups.com> <1gr9lyc.1rrm543162uefN%aleaxit@yahoo.com> Message-ID: <41FE730A.4030201@holdenweb.com> Alex Martelli wrote: > Michael Tobis wrote: > [...] >>Let me add that I remain unconvinced that a language cannot combine the >>best features of Python with very high performance, which is ultimately > > > I'm also unconvinced. Fortunately, so is the EU, so they have approved > very substantial financing for the pypy project, which aims in good part > exactly at probing this issue. If any single individual can be called > the ideator of pypy, I think it's Armin Rigo, well-known for his > excellent psyco specializing-compiler for Python: the key research > thesis behind both projects is that a higher-level, dynamic language > need not have performance inferior to a lower-level one and indeed may > well beat it. > I should be failing in my duty as Chairman if I didn't remind readers at this point that they can hear Armin Rigo's talk "PyPy and Type Inference" at PyCon at 5:30 on Wednesday March 23. http://www.python.org/pycon/dc2005/register.html While Alex is not necessarily too modest to mention it he might forget that he is also giving three talks to PyCon. I believe this is the first year he has been able to attend PyCon, so delegates are definitely in for a treat this year. 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 ncoghlan at iinet.net.au Fri Jan 28 20:33:37 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 29 Jan 2005 11:33:37 +1000 Subject: Who should security issues be reported to? In-Reply-To: References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> <41FA22DA.2090402@iinet.net.au> Message-ID: <41FAE7F1.8060008@iinet.net.au> Fredrik Lundh wrote: > Nick Coghlan wrote: > > >>>I'm sorry, but this isn't really good enough. If Open Source wants to >>>say that they are better than these proprietary companies, they need >>>to deal with these sorts of things more professionally and establish >>>decent channels of communications for dealing with it. >> >>Is that the sound of a volunteer I hear? >> >>All you have to do is put your hand up, and the problem will be solved. If not you, who? > > > oh, please. this is a security issue. it needs a little more coordination > than an ordinary bug report. > > Well, a less facetious answer to the OP's question would be Anthony Baxter. As the current release manager, he's the best contact point I can think of. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From bokr at oz.net Sat Jan 22 23:28:27 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 23 Jan 2005 04:28:27 GMT Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) References: Message-ID: <41f325b5.1576259210@news.oz.net> On Sat, 22 Jan 2005 16:22:33 +1000, Nick Coghlan wrote: >Steven Bethard wrote: >> I wrote: >> > If you really want locals that don't contribute to arguments, I'd be >> > much happier with something like a decorator, e.g.[1]: >> > >> > @with_consts(i=1, deftime=time.ctime()) >> > def foo(x, y=123, *args, **kw): >> > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime >> > >> > Then you don't have to mix parameter declarations with locals >> > definitions. >> > >> > Steve >> > >> > [1] I have no idea how implementable such a decorator would be. I'd >> > just like to see function constants declared separate from arguments >> > since they mean such different things. >> >> I played around with this, and I think it's basically implementable: > >Raymond's constant binding decorator is probably a good model for how to do it: >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 > I thought so too. I modified it to accept **presets as a keyword argument and generate constants and assignments from its values matching assignment names when the rhs was __frompresets__, e.g., >>> from makeconstpre import make_constants as pre >>> import time >>> @pre(verbose=True, deftime=time.ctime(), a=1, b=2, c=3, pi=__import__('math').pi) ... def foo(): ... deftime = __frompresets__ ... b, a = __frompresets__ ... c = __frompresets__ ... pi = __frompresets__ ... return locals() ... __frompresets__ : deftime --> Sat Jan 22 20:18:09 2005 __frompresets__ : ('b', 'a') --> (2, 1) __frompresets__ : c --> 3 __frompresets__ : pi --> 3.14159265359 locals --> >>> import dis >>> dis.dis(foo) 3 0 LOAD_CONST 1 ('Sat Jan 22 20:18:09 2005') 3 STORE_FAST 3 (deftime) 4 6 LOAD_CONST 2 ((2, 1)) 9 UNPACK_SEQUENCE 2 12 STORE_FAST 2 (b) 15 STORE_FAST 0 (a) 5 18 LOAD_CONST 3 (3) 21 STORE_FAST 1 (c) 6 24 LOAD_CONST 4 (3.1415926535897931) 27 STORE_FAST 4 (pi) 7 30 LOAD_CONST 5 () 33 CALL_FUNCTION 0 36 RETURN_VALUE >>> foo() {'a': 1, 'c': 3, 'pi': 3.1415926535897931, 'b': 2, 'deftime': 'Sat Jan 22 20:18:09 2005'} Not vary tested as yet, but seems to work. I want to eliminate redundant constants if the same name is assigned = __frompresets__ more than once. Right now I brute force generate another constant. Regards, Bengt Richter From rupole at hotmail.com Fri Jan 28 02:04:57 2005 From: rupole at hotmail.com (Roger Upole) Date: Fri, 28 Jan 2005 02:04:57 -0500 Subject: PythonWin (build 203) for Python 2.3 causes Windows 2000 to grind to a halt? References: <3f233389.0501271147.43572416@posting.google.com> Message-ID: <41f9e4a9$1_1@127.0.0.1> These look like symptoms of sf bug #1017504 http://sourceforge.net/tracker/index.php?func=detail&aid=1017504&group_id=78018&atid=551954 What version of Pywin32 are you running ? There's a (semi) fix for this in the latest build. hth Roger "Chris P." wrote in message news:3f233389.0501271147.43572416 at posting.google.com... > I've been having a problem with PythonWin that seemed to start > completely spontaneously and I don't even know where to START to find > the answer. The only thing I can think of that marks the point > between "PythonWin works fine" and "PythonWin hardly every works fine" > was that I changed the size of my Virtual Paging file, noticing that > it was too small (I currently have a P4 with 1G of RAM). I tried > returning it to its original (smaller) size, but it didn't fix the > problems. > > The first time I noticed it, I was using PythonWin and then > right-clicked on My Computer to use "Explore". Instead of the usual > full listing (approx 10 items), I got a mini-listing of 4 items. > Then, after clicking "Explore", I either don't get a new window at all > OR I get a strange file explorer that won't let me look at files, > won't let me copy files, etc. The "mini-lising" thing also happens if > I click the "Start" button while PythonWin is open. > > Another problem is trying to open another program while PythonWin is > running - generally, the program will not start, but I also don't get > any kind of error popping up on the screen. My request is just > ignored (although I sometimes get a "system beep".) If I already have > other programs open and then open PythonWin, my menu bar might refuse > to function. Is it significant that, when the menu bar IS working, > the drop-down menu fades in quite slowly, instead of popping up > immediately? > > At the end of this message, I've pasted a screen dump of a message I > get when I try to open a file and I've got other apps open (note that > I can have very few, non-memory intensive apps open and I still get > it). > > Thanks for any help you can give, > > - Chris > > [SCREEN DUMP AFTER I TRY TO OPEN A .PY FILE] > File "C:\Python23\Lib\site-packages\pythonwin\pywin\mfc\docview.py", > line 91, in CreateNewFrame > wnd.LoadFrame(self.GetResourceID(), -1, None, context) # triggers > OnCreateClient... > win32ui: LoadFrame failed > > win32ui: CreateNewFrame() virtual handler ( SyntEditTemplate.CreateNewFrame of > 0x01193F30>>) raised an exception > TypeError: PyCTemplate::CreateNewFrame must return a PyCFrameWnd > object. ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From mfranklin1 at gatwick.westerngeco.slb.com Tue Jan 25 08:44:32 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 25 Jan 2005 13:44:32 +0000 Subject: tkinter socket client ? In-Reply-To: <1106659122.977876.234250@z14g2000cwz.googlegroups.com> References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> <1106318469.311179.126140@c13g2000cwb.googlegroups.com> <1106319270.932204.180590@c13g2000cwb.googlegroups.com> <1106659122.977876.234250@z14g2000cwz.googlegroups.com> Message-ID: Tonino wrote: > Hi, > > thanks for this info - I had to abandon the createfilehandler() method > as it is not supported in windows and the GUI "might" be used there at > some time ... > > So - I went the threading route - works well - for now - so I will > stick to it ... > > BUT - the next question: > In the Text() widget - why - when the text scrolls off the screen - > does the window not follow it ? > > I have added a scrollbar to it : > > self.center_frame = Frame(self.top_frame, background="tan", > relief=RIDGE) > > self.text=Text(self.center_frame,background='white') > scroll=Scrollbar(self.center_frame) > self.text.configure(yscrollcommand=scroll.set) > > self.text.pack(side=LEFT, fill=BOTH, expand=YES) > scroll.pack(side=RIGHT,fill=Y) > self.center_frame.pack(side=RIGHT, expand=YES, fill=BOTH) > > > but the window does not scroll to follow the text ? > Any ideas ? > This is the default behavior of the Text widget. You have two options (as I see it) one, put the new text at the top of the Text widget textwidget.insert(0, "your new text") or two, use the yview_pickplace method to move the view down every time you insert text textwidget.yview_pickplace('end') I wrote a sub-class of the ScrolledText widget to do just this I gave it a write method - so I could re-direct stdout to it - and also called yview_pickplace in that method. HTH Martin. From fccoelho at gmail.com Tue Jan 11 06:32:01 2005 From: fccoelho at gmail.com (Flavio codeco coelho) Date: 11 Jan 2005 03:32:01 -0800 Subject: Checking for X availability Message-ID: I have a program that uses pythondialog for its UI. Pythondialog is a wrapper of the shell dialog and xdialog libs. But I would like for it to switch between using Dialog ( when X is not available ) and xdialog (when X is available) So my question is: how can I check for the availability of X? i.e., How will my program know if its running in a text only console or in console window over X? thanks, Fl?vio From rkern at ucsd.edu Mon Jan 31 00:29:51 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 30 Jan 2005 21:29:51 -0800 Subject: PyGame not working(?) In-Reply-To: <20050130152208505-0800@news.claremont.edu> References: <20050129232540162-0800@news.claremont.edu> <20050130152208505-0800@news.claremont.edu> Message-ID: Chris Weisiger wrote: > Thanks; I've now successfully installed Numeric, as well as all of the > other dependencies listed for PyGame. However, PyGame appears to still > not be working. When I try to run the program at the top of this page: > http://www.pygame.org/docs/tut/tom/games2.html > I get the following error: > > % python main.py > Fatal Python error: Interpreter not initialized (version mismatch?) > Abort A couple things: * Are you sure you are using the same python executable that you compiled the extension modules against? * If you aren't using the X11 versions of SDL et al., then you need to run your scripts with pythonw, which will run the framework's interpreter in such a way that it can communicate with the native window server. This shouldn't give you the error above, though. -- 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 andre.roberge at gmail.com Fri Jan 21 20:57:48 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 21 Jan 2005 17:57:48 -0800 Subject: finding name of instances created References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> Message-ID: <1106359068.802501.35190@z14g2000cwz.googlegroups.com> Using the method suggested by Steven Bethard, I *almost* got it working the way I would like. Here's my program: === .class PrivateClass(object): . dict = {} . def not_so_simple_method(self): . for name in PrivateClass.dict.keys(): . if PrivateClass.dict[name] == self: . print "instance " + name + " called not so simple" . apparently_simple_method = not_so_simple_method . def __init__(self): . print "instance created" . for name, value in globals().iteritems(): . if isinstance(value, PrivateClass): . PrivateClass.dict[name] = value .def public_class(): . return PrivateClass() .print "=== start===" .alpha = public_class() .print "created alpha" .print PrivateClass.dict .print "### alpha is not there\n" .beta = public_class() .print "created beta" .print PrivateClass.dict .print "### we are always one behind in the dict content\n" .alpha.apparently_simple_method() .beta.apparently_simple_method() ================================= The output follows: === start=== instance created created alpha {} ### alpha is not there instance created created beta {'alpha': <__main__.PrivateClass object at 0x0117CDD0>} ### we are always one behind in the dict content instance alpha called not so simple ======= Note that instance beta was never recognized when it called "apparently simple method". I'm sure there must be a way to do this.... Andr? From jack at performancedrivers.com Wed Jan 26 12:03:01 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 26 Jan 2005 12:03:01 -0500 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: <1a72l6umj80r6.dlg@usenet.alexanderweb.de> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> Message-ID: <20050126170301.GJ1607@performancedrivers.com> On Wed, Jan 26, 2005 at 05:18:59PM +0100, Alexander Schremmer wrote: > On Tue, 25 Jan 2005 22:08:01 +0100, I wrote: > > >>>> sys.safecall(func, maxcycles=1000) > > could enter the safe mode and call the func. > > This might be even enhanced like this: > > >>> import sys > >>> sys.safecall(func, maxcycles=1000, > allowed_domains=['file-IO', 'net-IO', 'devices', 'gui'], > allowed_modules=['_sre']) > > Any comments about this from someone who already hacked CPython? Yes, this comes up every couple months and there is only one answer: This is the job of the OS. Java largely succeeds at doing sandboxy things because it was written that way from the ground up (to behave both like a program interpreter and an OS). Python the language was not, and the CPython interpreter definitely was not. Search groups.google.com for previous discussions of this on c.l.py -Jack From ialbert at mailblocks.com Wed Jan 12 09:16:08 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 12 Jan 2005 09:16:08 -0500 Subject: shutil.move has a mind of its own In-Reply-To: References: Message-ID: Daniel Bickett wrote: > In my script, rather than a file being moved to the desired location, > it is, rather, moved to the current working directory (in this case, > my desktop -- without any exceptions, mind you). As it happens, the what is the output generated by the lines: fdir, fname = randFileInfo.new() debugMess( "Generated file information: %s, %s" % ( fdir, fname ) ) Istvan. From bob.ducharme at gmail.com Fri Jan 21 13:37:18 2005 From: bob.ducharme at gmail.com (bobdc) Date: 21 Jan 2005 10:37:18 -0800 Subject: short programming projects for kids Message-ID: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> I will be teaching an "Introduction to Programming" class to some middle school aged children and will be using Python, obviously. Does anyone have suggestions for simple little programs to create and analyze with them after I get past turtle graphics? Turtle graphics will be plenty for the first session, and I will leave time to ask them what they'd like to do in later sessions, but I was curious if anyone on the list has experience picking pedagogical programming examples appropriate for twelve-year-olds' attention spans. thanks, Bob From tjreedy at udel.edu Sun Jan 30 03:37:08 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Jan 2005 03:37:08 -0500 Subject: Test of comp.lang.python to python-list to gmane pathway. References: <1107040729.535936.42230@c13g2000cwb.googlegroups.com> Message-ID: Feel free to ignore this. Some system falsely labeled this post (sent via gmane) as possible spam. I am sending it back in the opposite direction to see what transpires that way. Sorry for the disturbance. tjr "Terry Reedy" wrote in message news:cthdth$fp0$1 at sea.gmane.org... > > "Michael Tobis" wrote in message > news:1107040729.535936.42230 at c13g2000cwb.googlegroups.com... > >> I'd like to dynamically add a method to an instance at >> instantiation time. > > No can do. A method is function that is an attribute of a class, even if > accessed via an instance. A function added to an instance as an > attribute of the instance remains a function. It is instance-specific > data that methods and other code can use, just like other instance data, > for instance-specific effects. Two common examples: > > class composer: > # skip obvious init > def __call__(self, x): return self.outer(self.inner(x)) > > sincos = composer(math.sin, math.cos) > # yes, this can also be done with composer function with nested scope > > class memoizer: # posted several times > # skip init again > def __call__(self,x): > # return previously computed self.memodict[x] if it exists > # or calculate, store, and return self.func(x) > > \> PS - any idea how to get past google's stupid formatting these days? I >> thought they were supposed to like python, but they just ignore leading >> blanks. > > Don't use google to post on clp. Go to news.gmane.org instead. > > Terry J. Reedy > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From g.horvath at mx.at Tue Jan 4 14:40:25 2005 From: g.horvath at mx.at (Gregor Horvath) Date: Tue, 04 Jan 2005 19:40:25 GMT Subject: HTML table input data grid Message-ID: Hi, I googled for a possibilty to create a html table where the user can input data. I just found this site: http://www.codeproject.com/aspnet/I3HTree2.asp That is what I am looking for. Is there an existing solution for python? -- Greg From steve at holdenweb.com Mon Jan 17 07:21:16 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 07:21:16 -0500 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Antoon Pardon wrote: > Op 2005-01-17, Steve Holden schreef : > >>Antoon Pardon wrote: >>[...] >> >>>>"A foolish consistency is the hobgoblin of little minds". Rules are made >>>>to be broken. >>> >>> >>>Like only use immutables as dictionary keys. >>> >> >>Fair enough, but don;t go advising newbies to do this. > > > How about something like this. > > Because of the extra precautions one has to take when > using mutables as hash keys, we advise newbies > to stick with immutable keys until they have gathered > enough knowledge and experience to adequatly weight > the pro and cons of a mutable key solution against > an immutable key solution. > There you go with the minutiae again. How about: "Don't use mutables as hash keys"? 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 jcribbs at twmi.rr.com Sun Jan 30 18:06:49 2005 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Sun, 30 Jan 2005 23:06:49 GMT Subject: ANNOUNCE: KirbyBase 1.7 In-Reply-To: <7xy8ea1qgt.fsf@ruckus.brouhaha.com> References: <7xy8ea1qgt.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > That's cute, especially the part about using Python expressions > instead of SQL to express queries. I don't see anything in the info > page about what happens when you have multiple clients updating the db > concurrently. Do you make any attempt to handle that? Yep. There are two server scripts included with the distribution. One (kbsimpleserver.py) does serial, blocking requests, so there are no concurrent-access issues. The second server script (kbthreadedserver.py) is threaded and non-blocking. I have code in the script that manages read and write locks for each table. I'm no rocket scientist, but I have been using kbthreadedserver.py at work for several months with no issues so far, so I am beginning to trust the code. :) Jamey From fredrik at pythonware.com Fri Jan 28 08:29:34 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 28 Jan 2005 14:29:34 +0100 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com><1106911061.429966.303510@f14g2000cwb.googlegroups.com><7x3bwlsqnj.fsf@ruckus.brouhaha.com> Message-ID: Duncan Booth wrote: > I think its a bit borderline whether this really was a security bug in > Python rather than just a problem with the way some people used Python. It > was a standard library which if used in the wrong way opens a security hole > on your machine for SmartCookie, that should be "if used, opens a security hole" From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 14:32:59 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Mon, 10 Jan 2005 20:32:59 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <1f7befae050110111239496b07@mail.gmail.com> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> Message-ID: <41E2D86B.5080909@ribosome.natur.cuni.cz> Tim Peters wrote: > [Martin MOKREJ?] > >> just imagine, you want to compare how many words are in English, German, >>Czech, Polish disctionary. You collect words from every language and record >>them in dict or Set, as you wish. > > > Call the set of all English words E; G, C, and P similarly. > > >> Once you have those Set's or dict's for those 4 languages, you ask >>for common words > > > This Python expression then gives the set of words common to all 4: > > E & G & C & P > > >>and for those unique to Polish. > > > P - E - G - C > > is a reasonably efficient way to compute that. Nice, is it equivalent to common / unique methods of Sets? > > >>I have no estimates >>of real-world numbers, but we might be in range of 1E6 or 1E8? >>I believe in any case, huge. > > > No matter how large, it's utterly tiny compared to the number of > character strings that *aren't* words in any of these languages. > English has a lot of words, but nobody estimates it at over 2 million > (including scientific jargon, like names for chemical compounds): > > http://www.worldwidewords.org/articles/howmany.htm As I've said, I analyze in real something else then languages. However, it can be described with the example of words in different languages. But nevertheless, imagine 1E6 words of size 15. That's maybe 1.5GB of raw data. Will sets be appropriate you think? >>My concern is actually purely scientific, not really related to analysis >>of these 4 languages, but I believe it describes my intent quite well. >> >> I wanted to be able to get a list of words NOT found in say Polish, >>and therefore wanted to have a list of all, theoretically existing words. >>In principle, I can drop this idea of having ideal, theoretical lexicon. >>But have to store those real-world dictionaries anyway to hard drive. > > > Real-word dictionaries shouldn't be a problem. I recommend you store > each as a plain text file, one word per line. Then, e.g., to convert > that into a set of words, do > > f = open('EnglishWords.txt') > set_of_English_words = set(f) I'm aware I can't keep set_of_English_words in memory. > f.close() M. From jeff at ccvcorp.com Mon Jan 17 19:50:21 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 17 Jan 2005 16:50:21 -0800 Subject: Fuzzy matching of postal addresses In-Reply-To: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <10uon0ir3n6b7ac@corp.supernews.com> Andrew McLean wrote: > The problem is looking for good matches. I currently normalise the > addresses to ignore some irrelevant issues like case and punctuation, > but there are other issues. I'd do a bit more extensive normalization. First, strip off the city through postal code (e.g. 'Beaminster, Dorset, DT8 3SS' in your examples). In the remaining string, remove any punctuation and words like "the", "flat", etc. > Here are just some examples where the software didn't declare a match: And how they'd look after the transformation I suggest above: > 1 Brantwood, BEAMINSTER, DORSET, DT8 3SS > THE BEECHES 1, BRANTWOOD, BEAMINSTER, DORSET DT8 3SS 1 Brantwood BEECHES 1 BRANTWOOD > Flat 2, Bethany House, Broadwindsor Road, BEAMINSTER, DORSET, DT8 3PP > 2, BETHANY HOUSE, BEAMINSTER, DORSET DT8 3PP 2 Bethany House Broadwindsor Road 2 BETHANY HOUSE > Penthouse,Old Vicarage, 1 Clay Lane, BEAMINSTER, DORSET, DT8 3BU > PENTHOUSE FLAT THE OLD VICARAGE 1, CLAY LANE, BEAMINSTER, DORSET DT8 3BU Penthouse Old Vicarage 1 Clay Lane PENTHOUSE OLD VICARAGE 1 CLAY LANE > St John's Presbytery, Shortmoor, BEAMINSTER, DORSET, DT8 3EL > THE PRESBYTERY, SHORTMOOR, BEAMINSTER, DORSET DT8 3EL St Johns Presbytery Shortmoor PRESBYTERY SHORTMOOR > The Pinnacles, White Sheet Hill, BEAMINSTER, DORSET, DT8 3SF > PINNACLES, WHITESHEET HILL, BEAMINSTER, DORSET DT8 3SF Pinnacles White Sheet Hill PINNACLES WHITESHEET HILL Obviously, this is not perfect, but it's closer. At this point, you could perhaps say that if either string is a substring of the other, you have a match. That should work with all of these examples except the last one. You could either do this munging for all address lookups, or you could do it only for those that don't find a match in the simplistic way. Either way, you can store the Database B's pre-munged address so that you don't need to constantly recompute those. I can't say for certain how this will perform in the false positives department, but I'd expect that it wouldn't be too bad. For a more-detailed matching, you might look into finding an algorithm to determine the "distance" between two strings and using that to score possible matches. Jeff Shannon Technician/Programmer Credit International From claird at lairds.us Thu Jan 6 18:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 06 Jan 2005 23:08:03 GMT Subject: Excluded and other middles in licensing (was: The Industry choice) References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> Message-ID: <75r0b2-ohg.ln1@lairds.us> In article <1gpz9qx.vmv8hav17z8qN%aleaxit at yahoo.com>, Alex Martelli wrote: . . . >One last reflection -- I believe there are or used to be some programs >written by people no doubt of very good will, distributed with all >sources and often with no profit motive at all, which are NOT open >source because they include in the license some restrictive clause, such >as "no military use", "no use by organizations which perform testing of >cosmetics on animals", or something of that kind. These would be >examples of closed-source software which DO allow ALMOST any kind of use >-- any EXCEPT the specific one the authors dislike so intensely. > >While most people may not think of such programs as "closed source", >they most definitely ARE: the definition of open source is very strict >about this aspect. > > >Alex With my mathematical background, I'm consistent about calling these "non-open" rather than "closed". I don't insist others adopt my nomenclature ... From ncoghlan at iinet.net.au Thu Jan 27 05:31:20 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 27 Jan 2005 20:31:20 +1000 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <41F8C2F8.8060203@iinet.net.au> Davor wrote: > data structures > and > functions that operate on these data structures Eh? What do you think a class is? Py> data = range(10) Py> list.extend(data, range(5)) Py> list.sort(data) Py> print data [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9] The fact that data.extend(range(5)) and data.sort() are alternative spellings for the second and third lines doesn't change the fact that a class is just a data structure grouped with a bunch of functions that operate on that data structure. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From grante at visi.com Mon Jan 17 14:50:13 2005 From: grante at visi.com (Grant Edwards) Date: 17 Jan 2005 19:50:13 GMT Subject: List problems in C code ported to Python References: <41ebed38$0$87063$a1866201@visi.com> <1105981814.317402.192940@f14g2000cwb.googlegroups.com> Message-ID: <41ec16f5$0$87076$a1866201@visi.com> On 2005-01-17, wittempj at hotmail.com wrote: >>>> l = [] >>>> for i in range(2): > for j in range(2): > l[i][j] = 'x' > > > > Traceback (most recent call last): > File "", line 3, in -toplevel- > l[i][j] = 'x' > IndexError: list index out of range > > So you still have to dimension the list before you can use it , eg like >>l = [] >>for i in range(2): >> l.append([]) >> for j in range(2): >> l[i].append(j) > > then you do not get the indexerror, but I feel a class is what you need > here to make life easier and the program more readable I'd probably numeric python (which I beleive is depricated, but it's what I have installed) or numarray. I think either would make it a lot easier. Using lists of lists when what you want is a matrix can be made to work, but there are a lot of non-obvious traps to fall into. -- Grant Edwards grante Yow! I always wanted a at NOSE JOB!! visi.com From aleaxit at yahoo.com Thu Jan 6 13:55:10 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 6 Jan 2005 19:55:10 +0100 Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> Message-ID: <1gpzgcv.1a4vagsqm9b69N%aleaxit@yahoo.com> Peter Hansen wrote: > Jacek Generowicz wrote: > > Peter Hansen writes: > >>Why the heck would I ever have to do "rectangle operations" on a > >>regular basis? ;-) > > > > Well, given that all editors are cat equivalent[*], you don't _have_ > > to use any of their features :-) > > This "cat equivalent" thing is a red-herring. I can rarely type more I tried offering a red herring to my cat to check this out, and, sure enough, she indignantly refused it and miaowed loudly for less smelly food. So, you may have a point here. Alex From mwm at mired.org Mon Jan 3 17:38:42 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 03 Jan 2005 16:38:42 -0600 Subject: Continuations Based Web Framework - Seaside. References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> Message-ID: <861xd2qgst.fsf@guru.mired.org> Steve Holden writes: > It's the *ideas* that are important, though, rather than the > implementation, and my initial hope was to publicise the weakness of > statelessness on the web as applications become more complex. This needed publicity? Isn't it obvious to anyone who has ever written a non-trival web application? Enough so that people started referring to non-web applications as "stately" rather than "stateful". http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From martyn_quick at yahoo.co.uk Fri Jan 21 10:39:12 2005 From: martyn_quick at yahoo.co.uk (Martyn Quick) Date: 21 Jan 2005 07:39:12 -0800 Subject: Configuring Python for Tk on Mac Message-ID: On my desk here at work I have a Mac G4 running Mac OS X v10.2.8. When I go into a terminal and type "python" up comes a nice python interface and all seems great. However when I type "import Tkinter" I'm greeted by the following error. >>> import Tkinter Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 35, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter So I guess something about this implementation is not appropriately configured. I'm guessing this is the default behaviour since I don't think anyone did anything special about python when they set up my machine. What do I do to set it up so I can use Tkinter? Thanks... and sorry if this is an FAQ... but I couldn't find the info easily. Yours, Martyn From http Fri Jan 7 16:48:41 2005 From: http (Paul Rubin) Date: 07 Jan 2005 13:48:41 -0800 Subject: "A Fundamental Turn Toward Concurrency in Software" References: Message-ID: <7x4qhs52rq.fsf@ruckus.brouhaha.com> aurora writes: > Just gone though an article via Slashdot titled "The Free Lunch Is > Over: A Fundamental Turn Toward Concurrency in Software" > [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that > the continous CPU performance gain we've seen is finally over. And > that future gain would primary be in the area of software concurrency > taking advantage hyperthreading and multicore architectures. Well, another gain could be had in making the software less wasteful of cpu cycles. I'm a pretty experienced programmer by most people's standards but I see a lot of systems where I can't for the life of me figure out how they manage to be so slow. It might be caused by environmental pollutants emanating from Redmond. From jtr at ofb.net Fri Jan 21 16:52:59 2005 From: jtr at ofb.net (John Reese) Date: Fri, 21 Jan 2005 21:52:59 +0000 (UTC) Subject: Is there a library to parse Mozilla "mork" documents? References: <1rb1v0566bmkesg9mclsk28idkjopgofuc@4ax.com> Message-ID: On Thu, 20 Jan 2005 23:48:34 -0800, Tim Roberts wrote: > John Reese wrote: >> >>Mozilla, Firefox, Thunderbird, and so forth use this awful format >>called MORK to store all kinds of things: which messages you've read >>in a newsgroup, headers and indexes into the mbox file of messages in >>a mail folder, and address books. > > Yes. What a crock that is. The MORK format is a great way to compress > tabular information, IF the information consists of the same pieces of data > over and over. E-mail boxes do not fit into that class, so I have no doubt > that the typical Thunderbird MORK file is singificantly LARGER than the > same file would be in, say, INI format. > > I wrote a Python script to parse it, but it isn't terribly robust. I was > able to produce a dictionary, but I didn't do anything with the results. > You're welcome to take a look: > http://www.probo.com/timr/parsemsf.py Thanks, I'll work with this. I have to say that this has all been worth it just to read about Jamie Zawinski railing against this file format. I think your comment at the top sums it up well: # Why am I doing this? From tjreedy at udel.edu Thu Jan 13 15:08:16 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Jan 2005 15:08:16 -0500 Subject: lambda References: Message-ID: "Egor Bolonev" wrote in message news:opskje6vb7xejsk1 at theurs.octopusnet.lan... > why functions created with lambda forms cannot contain statements? Because lambda was only ever intended to be an inline abbreviation of simple one-use functions whose body consists of 'return '. It is clear to me that the word 'lambda' was a mistake since it engenders expectations of more than that from too many people, such as you. Terry J. Reedy From akineko at pacbell.net Fri Jan 14 01:00:10 2005 From: akineko at pacbell.net (Aki Niimura) Date: 13 Jan 2005 22:00:10 -0800 Subject: Pickled text file causing ValueError (dos/unix issue) Message-ID: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> Hello everyone, I started to use pickle to store the latest user settings for the tool I wrote. It writes out a pickled text file when it terminates and it restores the settings when it starts. It worked very nicely. However, I got a ValueError when I started the tool from Unix when I previously used the tool from Windows. File "/usr/local/lib/python2.3/pickle.py", line 980, in load_string raise ValueError, "insecure string pickle" ValueError: insecure string pickle If I do 'dos2unix ' to convert the file, then everything becomes fine. I found in the Python release note saying ... "pickle: Now raises ValueError when an invalid pickle that contains a non-string repr where a string repr was expected. This behavior matches cPickle." I guess DOS text format is creating this problem. My question is "Is there any elegant way to deal with this?". I certainly can catch ValueError and run 'dos2unix' explicitly. But I don't like such crude solution. Any suggestions would be highly appreciated. Best regards, Aki Niimura From duncan.booth at invalid.invalid Thu Jan 6 11:30:20 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Jan 2005 16:30:20 GMT Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> <87pt0iegga.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Nick Vargish wrote: > eeykay at gmail.com writes: > >> Can somebody there to point me any good commercial applications >> developed using python ? > > Python is used in several games, including Temple of Elemental Evil > and the forthcoming Civilization 4. Humungous Games, which makes > software for children, is also using Python. Sorry if games would give > your boss the wrong impression... Also "Startrek Bridge Commander", and "Uru: Ages beyond Myst". From amk at amk.ca Fri Jan 21 14:20:03 2005 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 21 Jan 2005 13:20:03 -0600 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> Message-ID: On Fri, 21 Jan 2005 18:54:50 +0100, Fredrik Lundh wrote: > judging from http://yaml.org/spec/current.html (750k), the YAML designers are > clearly insane. that's the most absurd software specification I've ever seen. they > need help, not users. IMHO that's a bit extreme. Specifications are written to be detailed, so consequently they're torture to read. Seen the ReStructured Text spec lately? The basic idea -- a data dumping format that's human-readable -- isn't a bad one. OTOH, I can't recall wanting such a thing -- when I want readable output I'm happy using unreadable pickle files, unpickling the object and calling a .dump() or .as_text() method.) But YAML seems to have started out with the goal of being human-writable, something you would write in Emacs, and that seems to have gotten lost; the format is now just as complicated as Restructured Text, but more cryptic (the URI namespacing for tags, for example), not really simpler than XML and in some ways weaker (e.g. only two encodings supported, more complicated escaping rules). For a pure Python application, I can't see a need for YAML; use pickle/cPickle instead, because they're already there. Exchanging serialized objects between Python/Perl/Ruby scripts might be a good use case for YAML, but XML has wider software support and S-expressions are simpler, so my inclination would be to use them instead of YAML. --amk From elephantum at dezcom.mephi.ru Sat Jan 8 06:43:36 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sat, 08 Jan 2005 14:43:36 +0300 Subject: python3: 'where' keyword In-Reply-To: <41dfc018.305122743@news.oz.net> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> Message-ID: <349vb9F45c9crU1@individual.net> Bengt Richter wrote: >>>It also allows the necessary but uninteresting setup for an expression >>>to be moved "out of the way", bringing the expression that does the real >>>work to prominence. >>Killer app for this keyword: >> >>class C(object): >> >> x = property(get, set) where: >> def get(self): >> return "Silly property" >> def set(self, val): >> self.x = "Told you it was silly" > Yes, that is cool and it _is_ an interesting idea. Are suites nestable? E.g., is this legal? ... > And, is the whole thing after the '=' an expression? E.g., > > x = ( foo(x) where: > x = math.pi/4.0 > ) where: > def foo(x): print 'just for illustration', x > > or is this legal? > > for y in ([foo(x) for x in bar] where: > bar = xrange(5) > ): baz(y) where: > def baz(arg): return arg*2 > > Not trying to sabotage the idea, really, just looking for clarification ;-) yes, all your examples are correct. And that's the way I'd like to use this feature. From lard at tardis.ed.ac.molar.uk Wed Jan 26 10:35:59 2005 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Wed, 26 Jan 2005 15:35:59 GMT Subject: cookielib and urllib2: thread-safe? Message-ID: I'm writing a test script in python for pulling web pages from a web server using urllib2 and cookielib. Since the main thing I am testing is what happens when concurrent requests are made to the web server, I need to make several requests concurrently, which I'll do from different threads in my python script. So the important question is: are cookielib and urllib2 thread safe? Are there any precautions that apply to using these libs in a multi-threaded context? thanks! alex From lkirsh at cs.ubc.ca Thu Jan 20 04:28:34 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Thu, 20 Jan 2005 01:28:34 -0800 Subject: why are these not the same? Message-ID: On a webpage (see link below) I read that the following 2 forms are not the same and that the second should be avoided. They look the same to me. What's the difference? Lowell ---- def functionF(argString="abc", argList = None): if argList is None: argList = [] ... def functionF(argString="abc", argList=None): argList = argList or [] ... http://www.ferg.org/projects/python_gotchas.html (number 5) From fperez.net at gmail.com Mon Jan 31 02:22:19 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Mon, 31 Jan 2005 00:22:19 -0700 Subject: Image stats - going from Matlab to Python References: <1107153660.431217.145160@f14g2000cwb.googlegroups.com> Message-ID: tjv at hotmail.com wrote: > Hi all, > I am working with images in python using PIL. I come from a MATLAB > background so I am finding it to be sometimes frustrating to do things > correctly and quickly. All I need to do is load an image and store a > list of pixel coordinates at which the alpha channel is set to 1. > In Matlab this would be easy...Lets say we have a 2x2x4 array that > represents the image. I would just type something like: > > indices = find(im(:,:,3)==1); > > then work with indices to get xy coords. Is there a similar way to > accomplish the same thing in python and PIL without having a nested for > loop and checking every pixel? > I would appreciate advice. Thanks very much for your attention! The kind of array functionality which you have in mind is implemented in python by the Numeric/Numarray libraries. You can (and should) use the PIL for the more image-specific tasks, but basic array things are done via those others. You may also want to look at matplotlib, for a high level, matlab-compatible plotting library. Regards, f From http Tue Jan 11 13:49:43 2005 From: http (Paul Rubin) Date: 11 Jan 2005 10:49:43 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <34h7m9F43vomsU1@individual.net> <7xsm58lcms.fsf@ruckus.brouhaha.com> Message-ID: <7xu0pn4x88.fsf@ruckus.brouhaha.com> Robin Becker writes: > A few months ago I tried and failed to get squirrelmail/php to run > with Apache2 and freeBSD 4.9. It seems that php prefers the old style > apache 1.3 work flow. I got some help from the php guys, but not > enough. I suppose I could have run a separate apache13 server, but > that seems like a cop out to me. We don't want to maintain an extra > set of configs etc etc. I think mod_php doesn't play nice with apache2 but am not aware of any cgi interoperability problems. I ran squirrelmail/php as an apache 1.3 cgi a while back (low enough traffic to not get killed by cgi overhead), if that helps. Note that squirrelmail itself has a bunch of security bugs that the maintainers refuse to acknowledge as bugs. Anyway, I'm still using apache 1.3 (haven't had a reason to modernize) so I can run mod_php if I need to. > Mailman, moinmoin and others work fine with apache2 maybe because they > use a cgi style interface. I would stick with a pythonic solution > unless there's a good reason not too. Yes, I certainly prefer Python to PHP. From jerf at jerf.org Fri Jan 21 18:07:24 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 21 Jan 2005 18:07:24 -0500 Subject: finding name of instances created References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> Message-ID: On Fri, 21 Jan 2005 21:01:00 -0400, Andr? Roberge wrote: > etc. Since I want the user to learn Python's syntax, I don't want to > require him/her to write > alex = CreateRobot(name = 'alex') > to then be able to do > alex.move() This is just my opinion, but I've been involved with teaching new programmers before so I think it is an informed one. I don't think you teach a language by hiding how the language works, no matter what the intentions. You should be *minimizing* the magic. You're going to train your students that Python objects have names (they don't) and that's going to mess them up later. Actually, it's going to mess them up almost right away, because how can they have a list of robots like this: for robot in robots: robot.turn_left() That can't work, right, the command inside the loop can only affect the robot named "robot", right? You can't teach Python if what you're actually teaching them is a variant that you have created that is used nowhere else on Earth, and is internally inconsistent to boot (see loop above, the *real* Python variable semantics conflict with the semantics you are teaching). Considering that not a month goes by where someone doesn't post a question related to this, and it has been a FAQ entry for as long as I've used Python, I think you are doing a major disservice to your "users" by training them that objects magically gets the name when assigned. I strongly urge you to do absolutely no pre-processing of any kind to the programs they generate. (By which I mean changes to the code; running pychecker on it would be OK; and I'd urge you to resist the temptation to process its output, either. Provide a "translation table" if you need to, but they need to learn to read the real output, too.) Programming is hard enough with burdening people with "pleasant falsehoods". Trust your students to handle the truth (and of course rationally minimize the truth they have to handle, and by using Python you're off to a great start there). If they can't handle the truth, with time, effort, and support, they *sure* as hell can't handle lies! From roy at panix.com Fri Jan 7 23:59:07 2005 From: roy at panix.com (Roy Smith) Date: Fri, 07 Jan 2005 23:59:07 -0500 Subject: Getting rid of "self." References: Message-ID: Jeremy Bowers wrote: > were I programming in C++ routinely now I'd prefix "this" and > dispense with that ugly "m_" garbage. (One of the things I ***hate*** > about C++ culture is its acceptance of hideously ugly variable names, > but now I'm two parentheticals deep so I probably ought to stop.)) I'm currently working in a C++ system where they have a wrapper class that provides some transaction locking functionality for member access. The colloquial name for the wrapped "this" pointer is self, i.e. they do "self = wrapper (this)" at the beginning of functions that need it. You can then do "member" to get the bare access or "self.member" to get the locking functionality. It's actually kind of neat, but boy does it play headgames with me when I switch back and forth between that and Python. From jeff at ccvcorp.com Mon Jan 10 12:53:13 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 10 Jan 2005 09:53:13 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> Message-ID: <10u5fu3o7v4h9e3@corp.supernews.com> Jacek Generowicz wrote: > "Anna" writes: > >>But first, wouldn't something like: >> >>[x+1 for x in seq] >> >>be even clearer? > > I'm glad you mentioned that. [...] > > As to whether it is clearer. That depends. I would venture to suggest > that, given a pool of laboratory rats with no previous exposure to > Python, more of them would understand the map-lambda than the list > comprehension. I would venture to suggest the exact opposite, that the syntax of a list comprehension is in itself suggestive of its meaning, while 'map' and 'lambda' are opaque until you've researched them. The verb 'to map', in this mathematical sense, is not part of standard usage among anyone that *I* know. Instead, they'd speak of doing something for (or to) each item in a group -- exactly what list comps express. Speaking for *this* laboratory rat, at least, map/lambda was always a nasty puzzle for me and difficult to sort out. But when list comps were introduced, after reading just a sentence or two on how they worked, they were completely clear and understandable -- much more so than map/lambda after many months of exposure. Jeff Shannon Technician/Programmer Credit International From vincent at visualtrans.de Tue Jan 25 14:32:11 2005 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 25 Jan 2005 20:32:11 +0100 Subject: module for 'po' files In-Reply-To: References: Message-ID: Sara Fwd wrote: > Hi all > Is there a module for processing & handling '.po' > files in python? Don't know exactly what you mean by "processing & handling". What do you want to do? -- Vincent Wehren > > > > __________________________________ > Do you Yahoo!? > Read only the mail you want - Yahoo! Mail SpamGuard. > http://promotions.yahoo.com/new_mail From http Tue Jan 4 20:12:04 2005 From: http (Paul Rubin) Date: 04 Jan 2005 17:12:04 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> Message-ID: <7x652che6z.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > Start writing (or reorganizing). Folks, this is open source. I'm > sure by the traffic on the list most people here know how to write. Irrelevant, the issue isn't what docs can be written if someone wants to do it, it's what docs are actually already there. I mean every shortcoming anyone could raise about Python or anything else could have the same answer, "it's open source, go fix it". The question is what does the existing stuff do. > In the case of Tkinter, you should probably get the okay of the > authors of various external docs before incorporating them into the > Python docs, If such permission is available then the external docs should just be dropped into the distro. > but note that several Tkinter-related documents are referenced > directly from the Tkinter module docs: Irrelevant, the Python docs mean the ones that are included, not the ones that are merely referenced. > This being the Internet and all, it's not clear that referencing external > documentation is somehow worse than incorporating it directly into the > distribution. The same thing could be said for software. So why not eliminate the Python library and let everyone download each module separately? Because it's bogus is why. It really does matter whether something is included or just referenced. That's what "batteries included" is supposed to be about--you get ONE package and it's supposed to have everything you need without having to go forage for additional components. It matters because most users shouldn't need to care about the Python distro at all, since they got Python through its inclusion in some bigger distro. E.g., I'm now running the Python that was included in Fedora Core 3 GNU/Linux, a complete OS distro on a DVD-ROM, containing about 3 gigabytes not including sources. And when a user installs 3 gigabytes of software from a DVD, they can reasonably expect that they've installed a complete system and shouldn't need to download anything additional to use all the features of the programs on the DVD. Now the Fedora maintainers aren't Python gurus--people ask for Python so they did the obvious thing: downloaded it, ran its installer, put the output into their distro, and said "ok, Fedora has Python". That's all they should need to do to incorporate Python into Fedora. So it's up to the Python maintainers, not the Fedora maintainers or the user, to make sure that the Python distro has everything that users need, without further downloading. And that was just about Tkinter, for which good docs exist but just don't happen to be in the distro. How about something like SocketServer, for which no reasonable docs exist at all? There's no way to figure out how to use it without reading the source. Or the socket library, whose docs say to go buy a book by W. Richard Stevens. The book is very good, but having to go buy a proprietary book is the opposite of what self-contained free software documentation is supposed to mean. I'm not trying to bash Python, which is excellent in many ways, or I wouldn't be using it. I just see various other free software projects as trying to live up to higher standards and I think Python should aspire to the same thing. > As for stuff that exists in PEPs and release notes, they should > already all have the necessary copyright (either they were placed in > the public domain or they are already part of the Python > distribution) to allow you do just check out a CVS tree, make the > necessary edits and either check the files back in or submit a patch > to SourceForge. And about that full featured Python web browser and native-code Python compiler, all you have to do is go write it. Come on. Having to piece together info from a dozen obscure and inconsistent PEP's and stuff in the CVS tree and source comments is not what most people think of as "documentation". Documentation means I can look in the manual and the info is right there, properly referenced in the table of contents and in the proper section for that type of language feature, unified with the rest of the docs. > In the documentation arena, I think more thought should probably be > given to producing online docs that can be directly annotated, thus > further reducing the barrier to more complete documentation (and > more updates). Take a look at latex2html, propose or implement > changes, or just rewrite the damn thing in Python. I think > latex2html is probably a recurring nightmare for Fred Drake. I've personally been happy with Texinfo for other kinds of docs and would consider it easier to deal with than latex2html. It might even be feasible to edit it in a wiki, so anyone could improve it easily. Another idea is web-based doc comments like PHP and MySQL have, so the doc editors can incorporate the info from the comments in subsequent doc releases. From deetsNOSPAM at web.de Mon Jan 3 08:10:15 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 03 Jan 2005 14:10:15 +0100 Subject: Async-signal safe functions in signal handlers (unix) References: <6942fc70.0501030347.29253110@posting.google.com> Message-ID: > So, is there a) any mechanism inside Python that can detect if the > current code is executed in a signal handler, or b) a list of > statements that must not be used in a Python signal handler in order > to avoid glibc function calls that are not async-signal safe? The execution of signal handlers in python is not done really asynchronous - instead, an incoming signal is noticed and flagged to the interpreters byte code loop - so the signal gets dealed with when the current bytecode instruction is termintated. Read section 7.1 in the docs about the signal module. In other words: Don't worry, be happy. -- Regards, Diez B. Roggisch From luismgz at gmail.com Mon Jan 10 10:49:53 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 10 Jan 2005 07:49:53 -0800 Subject: else condition in list comprehension In-Reply-To: References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> <1105305000.052714.188980@c13g2000cwb.googlegroups.com> Message-ID: <1105372193.185270.279290@c13g2000cwb.googlegroups.com> It's me wrote: > > z = [i + (2, -2)[i % 2] for i in range(10)] > > But then why would you want to use such feature? Wouldn't that make the > code much harder to understand then simply: > > z=[] > for i in range(10): > if i%2: > z.append(i-2) > else: > z.append(i+2) > > Or are we trying to write a book on "Puzzles in Python"? Once you get used to list comprehensions (and it doesn't take long), they are a more concise and compact way to express these operations. I think that writing 6 lines instead of 1 could be more readable of you are a beginner, but after playing a little bit with listcomps for the first time, you'll see they are very practical yet readable. From news at NOwillmcguganSPAM.com Wed Jan 26 11:25:43 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Wed, 26 Jan 2005 16:25:43 +0000 Subject: Help With Python In-Reply-To: <41f7c3a7$0$7777$db0fefd9@news.zen.co.uk> References: <41f7c3a7$0$7777$db0fefd9@news.zen.co.uk> Message-ID: <41f7c487$0$7777$db0fefd9@news.zen.co.uk> > > >>> print "Spam, " * 510 + "Spam" Or if you have 2.4.. >>> print ", ".join( "Spam" for _ in xrange( 511 ) ) Although, the replys with links will ultimately be more helpful! Will McGugan From deetsNOSPAM at web.de Mon Jan 24 16:33:27 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 24 Jan 2005 22:33:27 +0100 Subject: add indexes on the fly to lists References: Message-ID: The data structure you want to use is a dictionary - known as hashmap or hash or map in other languages. Lets say you have a few objects of type town that you want to access using their zip, then things could look like this: ------------ class Town(object): def __init__(self, zip, cool_clubs): self.zip = zip self.colo_clubs = cool_clubs towns = [Berlin(10439, ["Marietta", "ICON", "Bastart"]), Cologne(50000, ["Subway", "Stadtgarten", "Geb?ude 9"])] index = {} for town in towns: index[town.zip] = town ---------------- Hope that makes it clear to you - look into the tutorial for a chapter about python data structures. -- Regards, Diez B. Roggisch From ncoghlan at iinet.net.au Sat Jan 8 00:10:06 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 15:10:06 +1000 Subject: sorting on keys in a list of dicts In-Reply-To: <10ttukogfl43p62@corp.supernews.com> References: <10tr9ejf05pv660@corp.supernews.com> <10ttukogfl43p62@corp.supernews.com> Message-ID: <41DF6B2E.3030700@iinet.net.au> Jeff Shannon wrote: > Agreed. I'd started typing before I realized that it'd provide a stable > sort, which pretty much answered my own question, but decided to send it > anyhow in case I'd missed anything else... :) And it turns out we both missed the fact that it avoids comparing the dictionaries which could save a *lot* of number crunching (as well as making otherwise unsortable lists sortable). So it's a good thing you did decide to send it :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From fuzzyman at gmail.com Tue Jan 25 11:02:47 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2005 08:02:47 -0800 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: <1106643765.733317.27440@f14g2000cwb.googlegroups.com> Message-ID: <1106668967.677864.36690@f14g2000cwb.googlegroups.com> Nick Coghlan wrote: > Fuzzyman wrote: > > An implementation of the core language semantics - without any modules > > or file operations would be dead useful. > > > > It could replace some of the function of the long dead rexec modules as > > well as support projects like this. > > Securing a custom build of the CPython interpreter would probably be > significantly easier than designing a 'secure mode' that ran on top of the > standard version. The former might even be a stepping stone towards the latter. > > Still not easy though (the main task would be to prevent Python code from > accessing the OS, while still allowing module imports to work). Pure python imports only... no C extensions. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > > Cheers, > Nick. > > -- > Nick Coghlan | ncoghlan at email.com | Brisbane, Australia > --------------------------------------------------------------- > http://boredomandlaziness.skystorm.net From sjmachin at lexicon.net Tue Jan 11 15:26:48 2005 From: sjmachin at lexicon.net (John Machin) Date: 11 Jan 2005 12:26:48 -0800 Subject: unicode mystery In-Reply-To: References: Message-ID: <1105475208.187957.282650@c13g2000cwb.googlegroups.com> Sean McIlroy wrote: > I recently found out that unicode("\347", "iso-8859-1") is the > lowercase c-with-cedilla, so I set out to round up the unicode numbers > of the extra characters you need for French, and I found them all just > fine EXCEPT for the o-e ligature (oeuvre, etc). I examined the unicode > characters from 0 to 900 without finding it; then I looked at > www.unicode.org but the numbers I got there (0152 and 0153) didn't > work. Can anybody put a help on me wrt this? (Do I need to give a > different value for the second parameter, maybe?) Characters that are in iso-8859-1 are mapped directly into Unicode. That is, the first 256 characters of Unicode are identical to iso-8859-1. Consider this: >>> c_cedilla = unicode("\347", "iso-8859-1") >>> c_cedilla u'\xe7' >>> ord(c_cedilla) 231 >>> ord("\347") 231 What you did with c_cedilla "worked" because it was effectively doing nothing. However if you do unicode(char, encoding) where char is not in encoding, it won't "work". As John Lenton has pointed out, if you find a character in the Unicode tables, you can just use it directly. There is no need in this circumstance to use unicode(). HTH, John From john at grulic.org.ar Sat Jan 15 00:11:58 2005 From: john at grulic.org.ar (John Lenton) Date: Sat, 15 Jan 2005 02:11:58 -0300 Subject: finding/replacing a long binary pattern in a .bin file In-Reply-To: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> Message-ID: <20050115051158.GA12018@grulic.org.ar> On Wed, Jan 12, 2005 at 10:36:54PM -0800, yaipa wrote: > What would be the common sense way of finding a binary pattern in a > .bin file, say some 200 bytes, and replacing it with an updated pattern > of the same length at the same offset? > > Also, the pattern can occur on any byte boundary in the file, so > chunking through the code at 16 bytes a frame maybe a problem. The > file itself isn't so large, maybe 32 kbytes is all and the need for > speed is not so great, but the need for accuracy in the > search/replacement is very important. ok, after having read the answers, I feel I must, once again, bring mmap into the discussion. It's not that I'm any kind of mmap expert, that I twirl mmaps for a living; in fact I barely have cause to use it in my work, but give me a break! this is the kind of thing mmap *shines* at! Let's say m is your mmap handle, a is the pattern you want to find, b is the pattern you want to replace, and n is the size of both a and b. You do this: p = m.find(a) m[p:p+n] = b and that is *it*. Ok, so getting m to be a mmap handle takes more work than open() (*) A *lot* more work, in fact, so maybe you're justified in not using it; some people can't afford the extra s = os.stat(fn).st_size m = mmap.mmap(f.fileno(), s) and now I'm all out of single-letter variables. *) why isn't mmap easier to use? I've never used it with something other than the file size as its second argument, and with its access argument in sync with open()'s second arg. -- John Lenton (john at grulic.org.ar) -- Random fortune: If the aborigine drafted an IQ test, all of Western civilization would presumably flunk it. -- Stanley Garn -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From peter at engcorp.com Sat Jan 29 23:12:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 Jan 2005 23:12:05 -0500 Subject: cx_freeze error In-Reply-To: <1107057808.297752.168780@z14g2000cwz.googlegroups.com> References: <1107048210.548048.152870@z14g2000cwz.googlegroups.com> <1107054796.999110.18380@c13g2000cwb.googlegroups.com> <1107057808.297752.168780@z14g2000cwz.googlegroups.com> Message-ID: <1Lqdnd44o_AOw2HcRVn-og@powergate.ca> zyqnews at 163.net wrote: > Thanks for your answer. > I tried it and the result is: > [cxfreeze]$ python > Python 2.2.3 (#1, Oct 15 2003, 23:33:35) > [GCC 3.3.1 20030930 (Red Hat Linux 3.3.1-6)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import re >>>>re.compile > > > >>>>re.__file__ > > '/usr/lib/python2.2/re.pyc' > > Is there any hint? "Hint", maybe. Clear answer, not for me. What it means is that your re module definitely has a "compile" function, as it is supposed to. What that suggests is that when the textwrap.py module is being imported by cx_freeze, it is not finding the correct "re" module when it imports it. I don't know anything about cx_freeze, and I don't have an appropriately configured Linux box to help troubleshoot, so I can't help further, but maybe somebody else could try compiling a simple "hello.py" like you did and offer some suggestions. -Peter From steven.bethard at gmail.com Fri Jan 21 19:30:08 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 17:30:08 -0700 Subject: default value in a list In-Reply-To: References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: Paul McGuire wrote: > expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen] Or if you're afraid of lambda like me: def expand(lst,default,minlen):return (lst + [default]*minlen)[0:minlen] or perhaps more readably: def expand(lst, default, minlen): return (lst + [default]*minlen)[0:minlen] No need for an anonymous function when you're naming it. ;) Steve From rschroev_nospam_ml at fastmail.fm Fri Jan 14 11:27:44 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 14 Jan 2005 16:27:44 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: <4qSFd.30758$Qv5.2842746@phobos.telenet-ops.be> Skip Montanaro wrote: > Fredrik> no, expressions CAN BE USED as statements. that doesn't mean > Fredrik> that they ARE statements, unless you're applying belgian logic. > > Hmmm... I'd never heard the term "belgian logic" before. Googling provided > a few uses, but no formal definition (maybe it's a European phrase so > searching for it in English is futile). I'm from Belgium, and I've never heard it before either. Probably a public secret, very carefully being kept hidden from us Belgians ;) -- "Codito ergo sum" Roel Schroeven From adonisv at DELETETHISTEXTearthlink.net Tue Jan 11 19:57:41 2005 From: adonisv at DELETETHISTEXTearthlink.net (Adonis) Date: Wed, 12 Jan 2005 00:57:41 GMT Subject: Newbie: Pythonwin In-Reply-To: References: Message-ID: <9C_Ed.4799$C52.960@newsread2.news.atl.earthlink.net> Brent W. Hughes wrote: > 1) I'm running a program within Pythonwin. It's taking too long and I want > to stop/kill it. What do I do (other than ctrl-alt-del)? > > 2) I'm running a long program and I want to minimize it to let it continue > to run in the background while I do something else in the foreground. I try > clicking on Pythonwin's minimize box but it doesn't respond until the Python > program finally quits Then it minimizes! Any way I can do what I want > here? > > Brent > > Try running your script using (from command prompt): \path\python.exe \path\script.py Alternatively go to its folder in explorer and double click it to run. pythonwin is just a developing enviroment, and the execution of scripts within it is just for debugging use. Hope this helps. Adonis From __peter__ at web.de Thu Jan 13 07:42:42 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Jan 2005 13:42:42 +0100 Subject: from __future__ import decorators References: Message-ID: Jacek Generowicz wrote: > I have some code, which makes copious use of the @decorator syntax > which was introduced in Python2.4. Now I find myself in a situation > where I have to run the code under Python 2.3. However, I would like > to keep developing the code with the new syntax. > > How could I best automate the process of making the syntax digestible > by Python2.3 ? Have a look at Bill Mill's redecorate utility: http://llimllib.f2o.org/files/redecorate.py Peter From itsme at yahoo.com Fri Jan 7 11:26:55 2005 From: itsme at yahoo.com (It's me) Date: Fri, 07 Jan 2005 16:26:55 GMT Subject: sorting on keys in a list of dicts References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: What does it mean by "stability in sorting"? Can somebody please give a sample for using the code posted? I am a little lost here and I like to know more about the use of keys.... Thanks, "Nick Coghlan" wrote in message news:mailman.298.1105112062.22381.python-list at python.org... > Jeff Shannon wrote: > > I suppose that your version has the virtue that, if the sortkey value is > > equal, items retain the order that they were in the original list, > > whereas my version will sort them into an essentially arbitrary order. > > Is there anything else that I'm missing here? > > Stability in sorting is a property not to be sneezed at - it means switching to > sorting by a second key gives the effect of "sort by key 1, then by key 2", > whereas that doesn't hold with an unstable sort algorithm. If you've ever used > an application with an unstable sorting process and that only allows sorting a > table on one column at a time, you'll appreciate the frustration that can cause :) > > Also, it's required to match the behaviour of the Python 2.4 version (which gets > to take advantage of the stability of the builtin sort). > > Cheers, > Nick. > > -- > Nick Coghlan | ncoghlan at email.com | Brisbane, Australia > --------------------------------------------------------------- > http://boredomandlaziness.skystorm.net From steven.bethard at gmail.com Mon Jan 24 02:31:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Jan 2005 00:31:17 -0700 Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) In-Reply-To: <41f490e8.1669238027@news.oz.net> References: <41f325b5.1576259210@news.oz.net> <6I2dnYLoXdcTmGncRVn-vw@comcast.com> <41f490e8.1669238027@news.oz.net> Message-ID: Bengt Richter wrote: > So, e.g., for > > >>> presets = dict(a=1, b=2, deftime=__import__('time').ctime()) > > in the decorator args, the next version will act as if the decorated > function had the source code > > >>> print '%s = __frompresets__' % ', '.join(sorted(presets)) > a, b, deftime = __frompresets__ > > for the current version, except that it will be hidden. Cool! Keep us posted. I assume you'll put this into the Cookbook? Steve From uche at ogbuji.net Thu Jan 27 22:40:43 2005 From: uche at ogbuji.net (Uche Ogbuji) Date: 27 Jan 2005 19:40:43 -0800 Subject: 4suite XSLT thread safe ? In-Reply-To: <35praqF4p8vohU2@individual.net> References: <6lkkc2-fbd.ln1@pluto.i.infosense.no> <35pntaF4os76kU1@individual.net> <35ppqeF4nu516U1@individual.net> <35praqF4p8vohU2@individual.net> Message-ID: <1106883643.169034.74750@c13g2000cwb.googlegroups.com> Sorry I'm late to the whole thread. Diez B. Roggisch is pretty much right on the money in all his comments. 4XSLT *is* thread safe, but each individual processor instance is not thread safe. Yes, this is typical OO style: you encapsulate state in an instance so that as long as each thread has its own instance, there are no state clashes. Therefore, you should be creating at least one processor object per thread. Note: the 4Suite server is a multi-threaded architecture that uses 4XSLT heavily using processor-per-thread. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://4Suite.org http://fourthought.com Use CSS to display XML - http://www.ibm.com/developerworks/edu/x-dw-x-xmlcss-i.html Introducing the Amara XML Toolkit - http://www.xml.com/pub/a/2005/01/19/amara.html Be humble, not imperial (in design) - http://www.adtmag.com/article.asp?id=10286UBL 1.0 - http://www-106.ibm.com/developerworks/xml/library/x-think28.html Manage XML collections with XAPI - http://www-106.ibm.com/developerworks/xml/library/x-xapi.html Default and error handling in XSLT lookup tables - http://www.ibm.com/developerworks/xml/library/x-tiplook.html Packaging XSLT lookup tables as EXSLT functions - http://www.ibm.com/developerworks/xml/library/x-tiplook2.html From harold.fellermann at upf.edu Thu Jan 13 11:26:11 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 13 Jan 2005 17:26:11 +0100 Subject: Using Tix and Tkinter In-Reply-To: References: Message-ID: On 31.12.2004, at 16:50, Harlin Seritt wrote: > import Tix > from Tkconstants import * > from Tkinter import * > > root = Tix.Tk() > > Label(root, text="Hello!").pack() > Tix.tixControl().pack() > > root.mainloop() > When I run this, I get the following error: > > Traceback (most recent call last): > File "TixTest.py", line 8, in ? > Tix.tixControl().pack() > AttributeError: 'module' object has no attribute 'tixControl' in the Tix module this widget is called Control. writing Tix.Control().pack() should work. - harold - -- Man will occasionally stumble over the truth, but most of the time he will pick himself up and continue on. -- Winston Churchill From steven.bethard at gmail.com Tue Jan 4 04:45:49 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 04 Jan 2005 09:45:49 GMT Subject: Hlelp clean up clumpsy code In-Reply-To: References: Message-ID: <7BtCd.276928$5K2.111655@attbi_s03> It's me wrote: > Another newbie question. > > There must be a cleaner way to do this in Python: > > #### section of C looking Python code #### > a = [[1,5,2], 8, 4] > a_list = {} > i = 0 > for x in a: > if isinstance(x, (int, long)): > x = [x,] > for w in [y for y in x]: > i = i + 1 > a_list[w] = i > print a_list > ##### > > The code prints what I want but it looks so "C-like". How can I make it > more Python like? Don't know what version of Python you're using, but if you're using 2.4 (or with a few slight modifications, with 2.3), you can write: py> dict((item, i+1) ... for i, item in enumerate( ... a_sub_item ... for a_item in a ... for a_sub_item ... in isinstance(a_item, (int, long)) and [a_item] or a_item)) {8: 4, 1: 1, 2: 3, 4: 5, 5: 2} Basically, I use a generator expression to flatten your list, and then use enumerate to count the indices instead of keeping the i variable. Steve From jan.dries at dcube-resource.be Sat Jan 1 01:46:12 2005 From: jan.dries at dcube-resource.be (Jan Dries) Date: Sat, 01 Jan 2005 07:46:12 +0100 Subject: Any Python XML Data Binding Utilities Avaiable? In-Reply-To: <41D61BB9.5030701@263.net> References: <41D61BB9.5030701@263.net> Message-ID: <41D64734.6090709@dcube-resource.be> SeSe wrote: > Hi, every one, happy new year! > > I am working on XML with Python. I wonder if there is any XML Schema<-> > Python Object mapping tools so that we can convert one to another. > Thanks. You may want to look at generateDS. It can generate Python data structures from an XML Schema document. It supports only a subset of the schema spec, but is nonetheless quite useful. See http://www.rexx.com/~dkuhlman/generateDS.html There's also minixsv, which does something similar. I've never used it myself though. See http://www.leuthe.homepage.t-online.de/minixsv/minixsv_overview.html The most complete Schema validator in Python is probably XSV. It doesn't have the ability to generate Python object mappings though. See http://www.ltg.ed.ac.uk/~ht/xsv-status.html Another extensive schema parser is part of (and well hidden in) the wsdl toolset from the pywebsvcs project. It does support Python object mapping generation, but the usefulness of the result is limited outside the context of web services. See http://pywebsvcs.sourceforge.net/ Regards, Jan From peter at engcorp.com Sat Jan 8 13:14:17 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 13:14:17 -0500 Subject: Recent infoworld column In-Reply-To: <41DEEF0F.5000300@nospamyahoo.com> References: <41DEEF0F.5000300@nospamyahoo.com> Message-ID: Dwarf Electrician wrote: > from a long time listener... > > http://www.infoworld.com/article/04/12/30/01OPstrategic_1.html Kudos for Roger Binns! From aleaxit at yahoo.com Mon Jan 31 08:16:39 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 31 Jan 2005 14:16:39 +0100 Subject: implicit conversion References: Message-ID: <1gr9bia.1nrrc8q1ny2zngN%aleaxit@yahoo.com> Benjamin Schmeling wrote: ... > I don't know how to achieve implicit conversion at this point, turning an > long automatically into an bigint. The other way round, turning an bigint > into long can be realized by defining __long__. Perhaps adding to your bigint class a constructor (not declared as ``explicit'', if you're coding C++) which accepts as its argument a python long might help...? Alex From G.Franzkowiak at web.de Sat Jan 15 12:22:16 2005 From: G.Franzkowiak at web.de (franzkowiak) Date: Sat, 15 Jan 2005 18:22:16 +0100 Subject: interpret 4 byte as 32-bit float (IEEE-754) Message-ID: <34t1p2F4foiplU1@individual.net> Hello, I've read some bytes from a file and just now I can't interpret 4 bytes in this dates like a real value. An extract from my program def l32(c): return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) + (ord(c[3])<<24) ... value = l32(f.read(4)) <--- 3F 8C CC CD should be 1.11 Anybody an answer ? regards gf From aleaxit at yahoo.com Tue Jan 4 04:10:00 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 4 Jan 2005 10:10:00 +0100 Subject: Frameworks for "Non-Content Oriented Web Apps" References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> <1104672631.884144.294730@c13g2000cwb.googlegroups.com> <1104771690.845547.264630@z14g2000cwz.googlegroups.com> Message-ID: <1gpv02y.1bwcbv218q4i02N%aleaxit@yahoo.com> wrote: > Moreover, I recently saw Dabo(http://www.dabodev.com/about), a > framework for developing 3 tier apps with Python and wxPython(and other > supported GUI toolkits). I have not tried it but I think something > similar, but for web-apps, is a close definition of "A Framework for > Non-Content Oriented Web Apps". Once you're on a multilayer track, whether the presentation is on the web or on some other UI should just be an issue for the very last layer (closest to the user). That's definitely how we did things at AB Strakt (www.strakt.com). Of course, the web-based presentation layer will be generally simpler/poorer than ones based on richer GUI toolkits -- as a compensation, it may more easily be "skinnable" by using CSS and the like, and it's way more easily _testable_ thanks to many good packages for webpage-generators testing. Alex From jeffrey at cunningham.net Fri Jan 21 21:30:22 2005 From: jeffrey at cunningham.net (Jeffrey Cunningham) Date: Fri, 21 Jan 2005 18:30:22 -0800 Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: On Fri, 21 Jan 2005 03:08:50 -0800, Xah Lee wrote: > i've started to read python tutorial recently. > http://python.org/doc/2.3.4/tut/tut.html > (snip rest of misleading filler) > > http://xahlee.org/PageTwo_dir/more.html The first line is solipsistic (..like..'so what?'). But I think its all misleading. The real purpose of his cross-post is to get people to visit his website, ooh-and-ahh at his unique and daring Bush-bashing at the top, and finally admire (along with Xah himself) the pictures he takes of himself. Vanity, vanity, all is vanity... The only remaining question is 'why does he restrict his cross-posting to this particular collection of groups?' I don't have an answer to that one. [incidentally, I'm still cracking up over k.t. and the soldier...] --Jeff From tonino.greco at gmail.com Thu Jan 27 03:16:21 2005 From: tonino.greco at gmail.com (Tonino) Date: 27 Jan 2005 00:16:21 -0800 Subject: tkinter socket client ? In-Reply-To: References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> <1106318469.311179.126140@c13g2000cwb.googlegroups.com> <1106319270.932204.180590@c13g2000cwb.googlegroups.com> <1106659122.977876.234250@z14g2000cwz.googlegroups.com> Message-ID: <1106813781.056257.245180@f14g2000cwb.googlegroups.com> great - thanks ;) Tonino From lbates at syscononline.com Wed Jan 12 12:39:31 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 12 Jan 2005 11:39:31 -0600 Subject: ConfigParser - add a stop sentinel? In-Reply-To: References: Message-ID: You should probably consider NOT doing what you suggest. You would need to do some rather extensive work so you can support the .write method of ConfigParser. With a little ingenuity I've been able to user ConfigParser to support some very different and complex syntaxes on different projects. If this won't work, just have two different (separate) files. If you are dead set on combining these two, put your foreign syntax lines into the file as comments. ConfigParser will not process them, and you can have some other class extract only the comments and parse them independently. Regards, Larry Bates rzed wrote: > I am working with PythonCard in one of my apps. For its purposes, it > uses an .ini file that is passed to ConfigParser. For my app, I also > need configuration information, but for various reasons, I'd rather > use a syntax that ConfigParser can't handle. > > I know I can maintain two separate configuration files, and if I have > to I will, but I'd rather avoid that, if possible, and a solution > that suits my purposes is quite straightforward. I insert a sentinel > in the ini file and modify my local ConfigParser's _read method to > stop accepting input when it encounters that value. I handle my app's > portion of the configuration myself. > > This all works fine, but I was wondering whether it might be > worthwhile to add a standard stop flag in ConfigParser itself. Am I > the only one with this sort of use case? If there were a standard way > of doing this, I'd much rather use that, particularly if I ever have > reason to distribute the app elsewhere. From craig at postnewspapers.com.au Mon Jan 3 15:45:36 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Tue, 04 Jan 2005 04:45:36 +0800 Subject: Bad Interpreter In-Reply-To: <1104783849.754892.47560@c13g2000cwb.googlegroups.com> References: <1104783849.754892.47560@c13g2000cwb.googlegroups.com> Message-ID: <1104785136.4535.12.camel@albert.localnet> On Mon, 2005-01-03 at 12:24 -0800, RajaSrinivasan at hotmail.com wrote: > I have seen some previous messages about such a problem. I have this > problem but it is not clear what the solution really was. > > I am running FC2, python 2.3.3 > > the script i have sock.py runs if i say something like : > > python sock.py > > but ./sock.py results in a :bad interpreter error > how do i troubleshoot something like this? You probably have Windows-style line endings in the file. The kernel sees the ^M at the end of the line and gets all confused. -- Craig Ringer From google_groups_001 at yahoo.com Tue Jan 25 10:03:33 2005 From: google_groups_001 at yahoo.com (google_groups_001 at yahoo.com) Date: 25 Jan 2005 07:03:33 -0800 Subject: *IMPORTANT* Message for Google Group users! Message-ID: <1106665413.546265.22710@z14g2000cwz.googlegroups.com> Good News! Do you know how simple it is to go to Heaven after this life has ended? Some people believe that belonging to a local church, temple, mosque or synagogue will get them to Heaven. Others believe that water baptism, obeying the ten commandments or just being a good person will get them to Heaven. There are many other beliefs as well, but the good news about God's way to Heaven is found in the Holy Bible. The good news is that God came from Heaven to earth in the person of Jesus Christ over 2000 years ago and died for our sins(misdeeds). He was born in the land of Israel supernaturally to a virgin Jewish woman named Mary. He lived a sinless life for thirty-three years and then sacrificed His sinless blood and died on a cross to pay the death penalty for our sins. After Jesus was placed in a tomb He rose from the dead three days later as He said He would. The Holy Bible also tells us that Jesus Christ ascended into Heaven and that all who accept Him as their Lord and Saviour will live forever with Him in Heaven where there is no more death, sorrow, sickness and pain. The Bible says, "For the wages of sin is death, but the gift of God is eternal life through Christ Jesus our Lord." (Romans 6:23) This verse in the Bible says, "For ALL HAVE SINNED, and come short of the glory of God." (Romans 3:23) This verse says, "But God demonstrates his own love for us in this: While we were still sinners, Christ died for us." (Romans 5:8) In this passage the Bible clearly explains how simple it is to be saved and on your way to Heaven, "For if you confess with your mouth, "Jesus is Lord," and believe in your heart that God raised him from the dead, you WILL BE SAVED." (Romans 10:9) You can be saved right now and on your way to Heaven if you will open your heart to Jesus and pray the following prayer out loud: Dear Jesus Christ, I want to be saved so that I can have a home in Heaven when this life is over. I agree with You that I am a sinner. I believe You love me and want to save me. I believe that You bled and died on the cross to pay the penalty for my sins. I believe that You rose from the dead. Please forgive my sins and come into my heart and be my Lord and Saviour. Thank You Lord Jesus Christ for forgiving me and saving me through Your merciful grace. Amen. You are now a Christian if you said the prayer and allowed God to save you. Welcome to the family of God. Salvation is not a reward but a gift. The Bible says it this way, "For it is by GRACE you have been SAVED, through FAITH and this not from yourselves, it is the GIFT of God." (Ephesians 2:8) Nothing in the world is more important than your eternal destiny. The Bible says, "In Him(Jesus) we have redemption through His blood, the forgiveness of sins..." (Ephesians 1:7) If you have not yet made a decision to be saved, please do so now before it is too late. The reason why it is so important to be saved now is because you do not know exactly when you will die. You may die prematurely in a traffic accident, terrorist attack or some other way before you get another chance to be saved. The Bible tells us that we will spend eternity in Heaven or a place of eternal torment called Hell. It would be terrible to die and go to Hell when all you have to do is accept Jesus Christ as your personal Lord and Saviour. Some people that have already made Jesus Christ their Lord and Saviour worry about losing their salvation. The Bible teaches Christians that we can never lose our salvation no matter what happens. The Bible says it this way, "My dear children, I write this to you so that you will not sin. But if anybody does sin, we have one who speaks to the Father in our defense Jesus Christ, the Righteous One." Yes my friend, Jesus Christ is able to save you and keep you saved. Please tell your family and friends, thanks! Have a great day! Internet Evangelist R.L. Grossi 1. http://www.biblegateway.com << Free Online Bible 2. http://www.free-hoster.com/goodnews << Passion of the Christ 3. http://www.carm.org/cults/cultlist.htm << Beware Of Cults 4. http://www.equip.org/free/DH198.htm << About Hell 5. http://www.powertochange.com/questions/qna2.html << Is Jesus God? From __peter__ at web.de Wed Jan 26 04:06:50 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Jan 2005 10:06:50 +0100 Subject: need help on generator... (re) References: <63b5e209.0501241406.4fb5980b@posting.google.com> Message-ID: Joh wrote: >> def gen(iterable, start, end): >>it?=?iter(iterable) >>while?True: >>it,?a?=?tee(it) >>a?=?tuple(islice(a,?end-1)) >>for?sz?in?xrange(start,?len(a)+1): >>yield?a[:sz] >>it.next() >> >> if __name__ == "__main__": >>print?list(gen(range(1,?5),?2,?4)) > > please, this one looks interesting, could you explain a bit how it > works and why it "remain memory-efficient" ? If you have a generator of the form def gen1(iterable): for i in iterable: yield f(i) for i in iterable: yield g(i) and then use it for item in gen1(range(huge_number)): do_something_useful_with(item) it will only work when you feed it with something you can iterate over multiple times, e. g. a list, not a generator that reads data on every call of the next() method. That means you must store the data for (to keep it simple) the lifetime of gen1(). If you can modify the generator to def gen2(iterable): for i in iterable: yield f(i) yield g(i) for item in gen2(xrange(huge_number)): # switched from range() to xrange() do_something_useful_with(item) there is no such restriction to the iterable. All data can be read, processed and garbage-collected immediately. The gen() generator is a bit more complex in that it has to store a few adjacent items instead of only one and allows for an arbitrary number of functions (inlined as yield of an n-tuple) instead of always two functions, but the idea is the same. Peter From lbolognini at gmail.com Thu Jan 6 06:27:56 2005 From: lbolognini at gmail.com (lbolognini at gmail.com) Date: 6 Jan 2005 03:27:56 -0800 Subject: wxPython clipboard Message-ID: <1105010876.075011.261070@z14g2000cwz.googlegroups.com> Hi all, I'm thinking about coding a free version of this software: http://www.pitrinec.com/pkindex.htm I would use wxPython and wx.Clipboard class (hoping to be able to make it cross-platform) The software above detects macros you code in any Windows active window and replaces them with a text: something like you write "/ff" and he pastes "Feel free to call us back for whatever questions you might have". This kind of softwares are very usefull in a call-centre environment (where I'm currently working). The thing is I'm thinking about the best approach (in terms of CPU resources) to detect the macro. Not sure how keyloggers work but I suspect I could run a service that compares everything beign written in the active window with the macros I saved in the software configuration. Could you please give me some advice on the best approach to solve this problem? Thanks a lot, Lorenzo -- http://www.bolognini.net From usenet_spam at janc.invalid Fri Jan 7 19:26:33 2005 From: usenet_spam at janc.invalid (JanC) Date: Sat, 08 Jan 2005 00:26:33 GMT Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> <41DD5C6B.2070708@holdenweb.com> Message-ID: Peter Hansen schreef: > Steve Holden wrote: > >> Or even used cut(1) from the command line. > > Or myybe not :-) > > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > c:\>cut > 'cut' is not recognized as an internal or external command, > operable program or batch file. Microsoft Windows 2000 [versie 5.00.2195] (C) Copyright 1985-2000 Microsoft Corp. C:\>cut cut: u moet een lijst van bytes, tekens, of velden geven Probeer `cut --help' voor meer informatie. Seems to work just fine... :-P Have a look at: They have native win32 builds of many of the GNU commandline utilities... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From bo at systemhouse.dk Tue Jan 25 22:01:27 2005 From: bo at systemhouse.dk (Bo Jacobsen) Date: Wed, 26 Jan 2005 04:01:27 +0100 Subject: Can't load bytecode with execfile ? Message-ID: I have a number of files compiled to bytecode using py_compile.compile(). The .pyc files can be invoked by python directly ($python file.pyc), but "loading" them by execfile just throws an exception ? Any suggestions Bo. From aut_gbarros at uolinc.com Wed Jan 5 11:37:36 2005 From: aut_gbarros at uolinc.com (Gabriel Cosentino de Barros) Date: Wed, 5 Jan 2005 14:37:36 -0200 Subject: How to make executable file ? Message-ID: <2814F26DA6908F41927A81C410C4991A02079C33@siamun.server.bl.corp.intranet> > Also, you can try with py2exe. It's very easy. > Catalin. > > You may want to try cx_freeze. I brief experience with both. may be helpful 1. I did a little program on python/TK. Some 100 lines or less 2. executed cx_freeze 3. executed py2exe In the end, i had a dir with the name of the script: 03/12/04 18:08 . 03/12/04 18:08 .. 03/12/04 18:07 28.672 bugger.12.exe 25/05/04 21:19 45.117 datetime.pyd 03/12/04 18:07 563.528 library.zip 09/11/04 15:41 964 palavras.txt (this is data, i put here) 25/05/04 21:17 974.909 python23.dll 03/12/04 18:07 tcl 31/03/04 21:34 569.344 tcl84.dll 31/03/04 21:41 1.011.200 tk84.dll 25/05/04 21:18 16.384 w9xpopen.exe 25/05/04 21:18 57.401 _sre.pyd 25/05/04 21:19 36.925 _tkinter.pyd 10 File(s) 3.304.444 bytes 3 Dir(s) 2.143.559.680 bytes free Despite the fact that it got extremely big (but i wasn't expecting less when i started) it got pretty clumsy for what i had in mind. I was hoping for something like a 10Mb-single-exe-file kinda of result :) I belive cx_freeze didn't did much because i had no small includes. just the huge ones like Tk. Gabriel -------------- next part -------------- An HTML attachment was scrubbed... URL: From cabrera at wrc.xerox.com Mon Jan 31 20:47:41 2005 From: cabrera at wrc.xerox.com (jose isaias cabrera) Date: Mon, 31 Jan 2005 20:47:41 -0500 Subject: Java Integer.ParseInt translation to python References: <008d01c507f4$451d9b30$2820790d@stso.xcdg.xerox.com> <797fe3d405013116284ecfab68@mail.gmail.com> Message-ID: <003801c50800$04dea710$d6b8850d@jicman> Yes, that's my problem. I don't want to go through the java stuff. :-) Thanks. ----- Original Message ----- From: "Bill Mill" To: "jose isaias cabrera" Cc: Sent: Monday, January 31, 2005 7:28 PM Subject: Re: Java Integer.ParseInt translation to python > Jose, > > On Mon, 31 Jan 2005 19:23:35 -0500, jose isaias cabrera > wrote: >> >> Greetings! >> >> I've looked through the internet (not long, though) but I have not been >> able >> to find a python translation to >> >> buffer[0] = (byte)Integer.parseInt(string,16); > > Tell me what this does, give me an example or two, and I'll translate > it for you. I don't feel like going to read the java docs to figure it > out. > > You probably want to look at the built-in int() function though. Type > help(int) at the python prompt. > > Peace > Bill Mill > bill.mill at gmail.com > -- > http://mail.python.org/mailman/listinfo/python-list > From stephen.thorne at gmail.com Wed Jan 5 18:52:15 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 6 Jan 2005 09:52:15 +1000 Subject: Decorators and static typing. In-Reply-To: <41DC7893.2090707@oz.net> References: <41DC7893.2090707@oz.net> Message-ID: <3e8ca5c805010515525cddb69e@mail.gmail.com> On Wed, 05 Jan 2005 15:30:27 -0800, whisper at oz.net wrote: > Well, the decorator war is over (Python lost IMO!) and now we've got the > static typing war to fight! > > Both of these seem like syntax sugar to avoid writing good code! One has > already introduced ugly coding and the 2nd is likely to do the same! IMHO, the syntax is irrelevent. The goal of making it a core language feature is to remove the necessity of people writing their own type checkers and interface implementations. Essentially at the moment we have a situation with zope.interfaces that is causing many python projects that are completely unrelated to Zope (for instance, twisted) to depend on zope.interfaces, because its the most standard way of doing interfaces in Python. No one is going to like the syntax, and if anyone actually does, they're not going to speak up. Guido knows this. Thats why he's the BDFL, he can just dictate what the syntax SHALL be, and avoid 150 post threads over if '@' is better than 'dec' for decorators. Sure, we can implement type checking without language changes, but in doing so, we kill the entire point. Something standard is desired. Why don't we make it a language feature so that we don't have to waste even more lines of code and brain-cycles with obscure things like: def f(n): assert type(n) in (int, float) or subscribesToDuckType("number") using handwritten APIs that differ between every project. Regards Stephen Thorne From ariza at flexatone.com Thu Jan 13 04:43:19 2005 From: ariza at flexatone.com (ariza) Date: 13 Jan 2005 01:43:19 -0800 Subject: site.here on python 2.4 Message-ID: <1105609399.915874.71150@z14g2000cwz.googlegroups.com> greetings. it seems that the attribute site.here, of the site module, has vanished in python 2.4. up until python 2.3, site.here seemed (to me at least) a convenient way to get the complete path to the python library on any platform: >>> import site >>> site.here '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3' i do not see any information about this change save that in the new documentation it says: """ This module is automatically imported during initialization. The automatic import can be suppressed using the interpreter's -S option. Importing this module will append site-specific paths to the module search path. """ can anyone propose a similarly effective and cross-platform solution for easily discovering the the library path on any python installation? From bjourne at gmail.com Fri Jan 7 20:23:32 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 8 Jan 2005 02:23:32 +0100 Subject: Securing a future for anonymous functions in Python In-Reply-To: <10tu91mhv8mn89d@corp.supernews.com> References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <7xis6930ah.fsf@ruckus.brouhaha.com> <7xvfa90w6g.fsf@ruckus.brouhaha.com> <10tu91mhv8mn89d@corp.supernews.com> Message-ID: <740c3aec05010717232a784961@mail.gmail.com> The more features a language has, the harder it becomes to learn. An example of that is C++ which has almost everything. Classes, structs, templates, strange keywords that noone uses like auto, inline const, passing by reference/value, enum, union, lots of macros, multiple inheritance, namespaces etc. I'll bet that you could shave off 50% of C++'s features and it would still be 95% as usable[*]. Judging by the number of PEP proposals and syntax additions that appear on the mailing list every day Python could some day become as bloated. We don't want that, do we? So how do we avoid feature bloat?: 1. We stop adding features, either now or at some point in the future. 2. We remove some features. Either way we have to put a limit on the number of features we want Python to have. Let's call that number X where X is a number much smaller than infinity. With a set limit, the discussion becomes "which features should be selected for use in Python?" instead of "should this feature be added/removed?" Personally, I don't care either way if lambda is removed or retained, but I would much rather have the "with" keyword someone proposed, do-while loops or whatever. I think there are way too many good features out there just waiting to take lambdas place. * - Please don't ask me to make that bet. -- mvh Bj?rn From moma at example.net Fri Jan 28 15:41:05 2005 From: moma at example.net (moma) Date: Fri, 28 Jan 2005 21:41:05 +0100 Subject: Where can I find sample "beginner" programs to study? In-Reply-To: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> References: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> Message-ID: Todd_Calhoun wrote: > I'm trying to learn Python (and programming), and I'm wondering if there are > any places where I can find small, simple programs to study. > > Thanks. > Hello, http://www.python.org (docs -> tutorial) http://www.python.org/doc/ ! http://www.diveintopython.org http://www.byteofpython.info Eggs are here. Bring some bacon. http://www.python-eggs.org/links.html -------- Cross platform GUI-programs: http://www.wxPython.org Widgets documentation: http://www.wxPython.org -------- IDEs (programmers Python editors, if you want one): Eric http://www.die-offenbachs.de/detlev/eric3.html Dr.Python http://drpython.sourceforge.net/ ? // moma http://www.futuredesktop.org/OpenOffice.html http://www.futuredesktop.org/hpc_linux.html From pierre.barbier at cirad.fr Tue Jan 18 02:30:33 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Tue, 18 Jan 2005 08:30:33 +0100 Subject: extension module, thread safety? In-Reply-To: References: Message-ID: <41ecbaae$0$1046$626a14ce@news.free.fr> David Bolen a ?crit : > > If the threads under discussion are all Python threads, then by > default yes, the extension module C functions will appear to be atomic > from the perspective of the Python code. When the Python code calls > into the extension module, the GIL (global interpreter lock) is still > being held. Unless the extension module code explicitly releases the > GIL, no other Python threads can execute (even though those threads > are in fact implemented as native platform threads). Indeed, there is this (so annoying) GIL ... is there any project about extracting the (few ?) critical points of the python interpreter to put locks around them instead of choosing the opposite strategy (ie. locking anythime but when we know the section is not critical) ? Because it would made embedding a python interpreter in another language much more easy ! With the current CPython, it's very hard to mix Python and C in a multithreading application (with C-threads, not Python-threads). In fact I never really succeeded in that task because of that GIL ! I have a multi-thread application but every bit of Python code must be run into a Python thread. To be more precise, I wanted to be able to call Python code in response to some GUI events, and I didn't want to instanciate a new interpreter for I wanted to be able to access the environment of my main Python interpreter. By the way, if someone succeeded in a similar task, I'll be happy to hear about it :) Pierre PS: if the main code is in C (in fact C++ ...) and not Python it's for historical reasons of course ;) From peter at engcorp.com Thu Jan 6 10:59:07 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jan 2005 10:59:07 -0500 Subject: OT: spacing of code in Google Groups In-Reply-To: <41DD5C6B.2070708@holdenweb.com> References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> <41DD5C6B.2070708@holdenweb.com> Message-ID: Steve Holden wrote: > Peter Hansen wrote: >> But the whole argument is fairly moot... I've needed a rectangle >> operation only once in the last ten years, and if I hadn't known at >> the time that my editor could do it (and spent about half an hour >> figuring out how it worked), I could have written a utility to >> do the job faster if I'd been using Python at the time... > > Or even used cut(1) from the command line. Or myybe not :-) Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. c:\>cut 'cut' is not recognized as an internal or external command, operable program or batch file. -Peter From hcslmf at texlife.com Mon Jan 10 14:56:44 2005 From: hcslmf at texlife.com (brolewis) Date: 10 Jan 2005 11:56:44 -0800 Subject: Importing Problem on Windows In-Reply-To: <1105382542.552797.125200@c13g2000cwb.googlegroups.com> References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> <1105382542.552797.125200@c13g2000cwb.googlegroups.com> Message-ID: <1105387004.434581.194560@c13g2000cwb.googlegroups.com> Sorry. 2.4 in both locations From steve at holdenweb.com Fri Jan 14 16:51:44 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 16:51:44 -0500 Subject: why are people still using classic classes? In-Reply-To: References: <7x6522gegg.fsf@ruckus.brouhaha.com> Message-ID: <41E83EF0.2020402@holdenweb.com> Peter Hansen wrote: > Paul Rubin wrote: > >> Simon Wittber writes: >> >>>> Is there a reason NOT to use them? If a classic class works fine, what >>>> incentive is there to switch to new style classes? >>> >>> >>> Perhaps classic classes will eventually disappear? >> >> >> It just means that the formerly "classic" syntax will define a >> new-style class. Try to write code that works either way. > > > Unfortunately, if we should follow the recent advice about > always using "super()" in the __init__ method, it's hard > to do what you suggest (though it sounds like good advice) > without resorting to extreme ugliness: > > >>> class Classic: > .... def __init__(self): > .... super(Classic, self).__init__() > .... > >>> c = Classic() > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in __init__ > TypeError: super() argument 1 must be type, not classobj > > Could classic classes ever be removed without us having manually > to fix all __init__ calls to the superclass? > That's not really an issue unless there's a diamond-shaped inheritance graph and linearisation of the the super classes is required to ensure that things stay sane. Remembering that the MO for classic classes and types are rather different, how many cases do you think it will matter? 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 peter at engcorp.com Thu Jan 13 13:30:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 13:30:00 -0500 Subject: [perl-python] 20050112 while statement In-Reply-To: References: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> Message-ID: <-oSdnYnagrc_I3vcRVn-3Q@powergate.ca> Steven Bethard wrote: > Xah Lee wrote: [some Python code] > Because you're posting this to newsgroups, it would be advisable to use > only spaces for indentation -- tabs are removed by a lot of newsreaders, > which means your Python readers are going to complain about > IndentationErrors. Unfortunately, there are now two ways to post screwed up Python code, and using tabs is only one of them. The other is to post from Google Groups, and that's what Xah Lee is doing. (The rest of your advice, about going away, is pretty good though. ;-) -Peter From fredrik at pythonware.com Fri Jan 28 04:32:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 28 Jan 2005 10:32:57 +0100 Subject: unicode and data strings References: <41FA03C1.50404@geochemsource.com> Message-ID: Laszlo Zsolt Nagy wrote: > Now I installed Python 2.3.4 and wxPython 2.5.3 (with unicode support). I'm getting this > exception: > > exceptions.UnicodeDecodeError:'ascii' codec can't decode byte 0x91 in position 0: ordinal not in > range(128) >From where? Can you include a "print repr()" of the string you're trying to convert, and enough code from your script to be able to reproduce the problem? > The I tried this: > > >>>'\x91'.decode('utf8') > UnicodeDecodeError: 'utf8' codec can't decode byte 0x91 in position 0: unexpected code byte > >>>'\x91'.encode('utf8') > > Here is the question: I would like to use simple binary data strings (like an array of bytes). > I do not care about encodings. How do I do that? Unicode errors only appear if you're converting between "raw 8-bit data" and Unicode strings (which contain Unicode characters, not bytes or integers). You cannot do that without caring about encodings... From paolo_veronelli at yahoo.it Tue Jan 4 04:07:32 2005 From: paolo_veronelli at yahoo.it (paolo_veronelli) Date: Tue, 04 Jan 2005 09:07:32 +0000 Subject: Frameworks for "Non-Content Oriented Web Apps" In-Reply-To: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <41DA5CD4.8060900@yahoo.it> mirnazim at gmail.com wrote: >Hi, > >There are great Python Web Application Framework. But most of them are >meant for content oriented web apps. > >Is there something that can ease the development of application that >are not content oriented(I call them "NON CONTENT-ORIENTED WEB >APPLICATIONS" because I don't know what else to call them). I mean the >applications like, accounting, high volume data entry apps, where >normally GUI clients have ruled. I know very high quality ERP and >similar packages have been implemented in a web based environment. But >problem is that they have been developed with the tools that were >actually meant for content oriented apps like Zope, PHP, etc. > >But is there some sort of framework or something that is actually meant >for such web apps,application that make heavy use of forms, have very >high amount of user interaction etc. > >What I am asking here may sound off beat, but I think, in todays world >where web based solutions offers such a flexibility, we really need it. > >I also know that I am to ambiguous, but as is the characteristic of >this wonderful community, talks that start as most abigous, transform >in crystal clear. > >PS: I am a web developer, using PHP for living. I have been playing >with python for a while. I found python is really a cool language(do I >need to say that ;-)) with a really, really impressive collection of >modules and frameworks. While developing a school information system, I >felt the need of such a framework that makes developing of "Non-Content >Oriented Web-Apps" easy. > >I know I posted a similar message earlier, but this time I a bit more >general. > > > In pytypus everything is not content is metadata( a part from some of the code ,which part is useful for accessing informations) ,so my definition will simply be metadata oriented. From snail at objmedia.demon.co.uk Tue Jan 25 10:46:30 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Tue, 25 Jan 2005 15:46:30 +0000 Subject: is there better 32 clock() timing? References: <41f61372.1768192005@news.oz.net> <41f63d79.1778950866@news.oz.net> Message-ID: In message <41f63d79.1778950866 at news.oz.net>, Bengt Richter writes >I believe that is quite wrong as a general statement. Actually my initial statement should have been written "accessing a resource, the accuracy of which is no better than 10ms.". I was thinking of the 1ms multimedia timer but wrote about clock() instead. 10ms, coincidentally is the approx minimum scheduling granularity for threads unless you are in a multimedia thread (or real time thread - not sure about real time threads in NT). >If the "resource" only had ~1ms granularity, >the minimum would be zero, as it is if you call time.time() in a tight loop, Correct. Write your app in C and call clock(). Thats what you get. You can call clock 20000 times and still get a delta of zero. The next delta (on my system) is 10ms at about 22000 calls. >>There are various timers available, documented and undocumented, all of >>which end up at 1ms or 1.1ms, give or take. For anything shorter you Whoops here we go, same typo - should have been 10ms or 11ms. There is a 1ms timer in the multimedia timing group. >>need QueryPerformanceCounter() (but that *is* a slow call), or use the >Have you timed it, to make that claim? Yes. >What do you mean by "slow"? Slower than any other Win32, CRT or Undocumented NT function you can use to get timer information. Yes, I have timed them all, a few years ago. QueryPerformanceCounter is 47 times slower to call than clock() on my 1Ghz Athlon. QueryPerformanceCounter may have finer granularity, but called in a tight loop it'll crush your program. >>RDTSC instruction which is fast but gives a count of instruction cycles >>executed and is thus not totally accurate (multiple execution pipelines, >>plus multithreading considerations). >Accurate for what. See below - you haven't taken things into account, despite my comment in brackets above which gives a big hint. >A single clock AFAIK drives RDTSC Correct. >The main problem with a CPU clock based reading is that it's very stable unless >there's variable clock rate due to power management. Try running multiple apps at the same time you are doing your measurement, each of which has a variable loading. Each of these apps is contributing to the count returned by RDTSC. That is what I was referring to. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From http Fri Jan 7 16:49:44 2005 From: http (Paul Rubin) Date: 07 Jan 2005 13:49:44 -0800 Subject: how to extract columns like awk $1 $5 References: Message-ID: <7xzmzk3o5j.fsf@ruckus.brouhaha.com> roy at panix.com (Roy Smith) writes: > Something along the lines of: > > words = input.split() > print words[4], words[5] That throws an exception if there are fewer than 6 fields, which might or might not be what you want. From rschroev_nospam_ml at fastmail.fm Fri Jan 14 11:40:29 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 14 Jan 2005 16:40:29 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: <1CSFd.30772$Qv5.2842746@phobos.telenet-ops.be> Antoon Pardon wrote: > IMO we have a: dogs are mamals kind of relationship in Python. I see what you mean, but I don't think it's true. > Every expression can be used where a statement is expected. > (And this can be worded as: every expression is a statement.) Not really. An expression statement is a statement that looks like an expression, but actually it's more than that: not only does it calculate the value of the expression, it also prints the value. Note that it would be perfectly possible to modify the syntax into expression_stmt ::= "exprstmt" expression_list so that you would have to write exprstmt 6*9 instead of just 6*9 That makes it clearer to see the distinction: 6*9 is an expression, exprstmt 6*9 is a statement. An expression statement, more precisely. > Not every statement can be used where an expression is expected. AFAIK *no* statement can be used where an expression is expected. -- "Codito ergo sum" Roel Schroeven From air_jlin at yahoo.com Thu Jan 20 22:24:43 2005 From: air_jlin at yahoo.com (Johnny Lin) Date: 20 Jan 2005 19:24:43 -0800 Subject: Unbinding multiple variables Message-ID: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> Hi! Is there a way to automate the unbinding of multiple variables? Say I have a list of the names of all variables in the current scope via dir(). Is there a command using del or something like that that will iterate the list and unbind each of the variables? Thanks much! (If anyone posts an answer, if you could also cc your reply to my email air_jlin at yahoo.com, would be much obliged. Thanks again!) Best, -Johnny www.johnny-lin.com From grante at visi.com Mon Jan 31 23:29:13 2005 From: grante at visi.com (Grant Edwards) Date: 01 Feb 2005 04:29:13 GMT Subject: need for binary floats (except performance)? References: <81300027.0501312006.72454fd6@posting.google.com> Message-ID: <41ff0599$0$10746$a1866201@visi.com> On 2005-02-01, kartik wrote: > Since the Decimal type can represent any given fractional number > exactly, including all IEEE binary floating-point numbers, wouldn't it > be advisable to use Decimals for all floating point numbers (except > possibly for performance)? That's a pretty huge "except" for some applications. -- Grant Edwards grante Yow! HUGH BEAUMONT died at in 1982!! visi.com From rnd at onego.ru Wed Jan 19 15:45:15 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 19 Jan 2005 23:45:15 +0300 (MSK) Subject: RuntimeError: dictionary changed size during iteration Message-ID: I think, the behaviour below is misfeature: >>> [e for e in vars()] Traceback (most recent call last): File "", line 1, in ? RuntimeError: dictionary changed size during iteration >>> e = None >>> [e for e in vars()] ['e', '__builtins__', 'rlcompleter', '__file__', '_[1]', 'atexit', '__name__', 'readline', '__doc__'] Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From peter at engcorp.com Thu Jan 13 10:28:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 10:28:05 -0500 Subject: How to install pyparallel In-Reply-To: <41e689fc$0$15700$626a14ce@news.free.fr> References: <41e689fc$0$15700$626a14ce@news.free.fr> Message-ID: Michel LE VAN KIEM wrote: > > I'm trying to install the pyparallel module for my Python 2.3.4 (runs on > a FC3) but I do have some troubles. > > >>> p=parallel.Parallel() > ppdev0: failed to register device ! > ... > IOError: [No such device or address] > > Some help would be appreciated. Did you read the notes in the parallelppydev.py file's Parallel class? I suspect they may be of some help... (I don't see any other significant documentation of pyParallel, so I'm not sure where else one would look for assistance.) Also, perhaps one of these threads would be of help: http://groups.google.ca/groups?q=parallel+ppdev0+failed+to+register+device -Peter From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sun Jan 16 13:19:39 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Do Re Mi chel La Si Do) Date: Sun, 16 Jan 2005 19:19:39 +0100 Subject: Scriptomatic 2.0 Message-ID: <41eab05f$0$25799$8fcfb975@news.wanadoo.fr> Hi ! Scriptomatic 2.0 can, now, to generate scripts in Python. Download : http://www.microsoft.com/downloads/thankyou.aspx?FamilyID=09dfc342-648b-4119-b7eb-783b0f7d1178&displaylang=en Note : scriptomatic is a generator of WMI's scripts, for Windows, (and compatibles WBEM). Good night -- Michel Claveau From craig at postnewspapers.com.au Sat Jan 15 18:51:02 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sun, 16 Jan 2005 07:51:02 +0800 Subject: [Fwd: Re: Embedding Multiplr Python interpreter in C++] In-Reply-To: <41E7DA3B.9000005@holdenweb.com> References: <41E7DA3B.9000005@holdenweb.com> Message-ID: <1105833061.2858.1.camel@rasputin.localnet> On Fri, 2005-01-14 at 22:42, Steve Holden wrote: > Take a look at mod_python's code: that allows several independent > interpreters in the same Apache process using Py_NewInterpreter() I've never been entirely clear on whether mod_python does its magic by relying on having one thread per sub-interpreter, or if it can support multiple sub interpreters in a single thread. Any ideas? I'm pretty sure it's the former, but it'd be nice to be sure. -- Craig Ringer From robin at SPAMREMOVEjessikat.fsnet.co.uk Thu Jan 20 03:59:10 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Thu, 20 Jan 2005 08:59:10 +0000 Subject: rotor replacement In-Reply-To: References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> <7xacr4ewjk.fsf@ruckus.brouhaha.com> <41ef4a7a.1323588509@news.oz.net> <7xwtu8vb17.fsf@ruckus.brouhaha.com> Message-ID: <41EF72DE.5030305@jessikat.fsnet.co.uk> Peter Maas wrote: > Paul Rubin schrieb: > >>> Wasn't there a default 40-bit version that was ok (weak), but you had >>> to declare yourself US resident to download 128-bit support? >> >> >> >> That was years ago. The regulations changed since then, so they all >> have 128 bits now. > > > Perhaps the NSA has found a way to handle 128bit in the meantime. > But this is unlikely because there is no export regulation to ban > 512bit as far as I know :) > Apparently factorization based crypto is on the way out anyhow (as an article in Scientific American is reported to claim). http://www.sciam.com/article.cfm?chanID=sa006&articleID=000479CD-F58C-11BE-AD0683414B7F0000&ref=rdf -can't wait to get my quantum computer-ly yrs- Robin Becker From macrocosm at fastmail.fm Wed Jan 5 08:54:23 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Wed, 05 Jan 2005 08:54:23 -0500 Subject: project In-Reply-To: <20050104201100.73284.qmail@web80902.mail.scd.yahoo.com> References: <20050104201100.73284.qmail@web80902.mail.scd.yahoo.com> Message-ID: <41DBF18F.6040703@fastmail.fm> jerry wise wrote: >Please help me out! Your solution seems doable pretty easily, but I have very little experience in this so I need some help. At the very least respond, because I'm getting kind of desperate. Thank you so much. > > > "I'm getting kind of desperate", no kidding. Firstly, did you ask Jeff to help you understand the algorithm? Secondly, did you read up on the PyMedia docs? Thirdly, what do you have very little experience in exactly and why are you so desperate? Is this some sort of school project? You need to be able to answer yes to the first two questions if you want my and/or likely anyone else's help. I am very busy, but if you take the necessary preliminary steps, and do the work, there are many /very/ friendly and knowledgeable people here who would likely be willing to help you, given that you are willing to do some work/research yourself and ask good questions. Best regards, Arich From Rolf.Wester at t-online.de Sun Jan 2 11:52:52 2005 From: Rolf.Wester at t-online.de (Rolf Wester) Date: Sun, 02 Jan 2005 17:52:52 +0100 Subject: run region in IDLE Message-ID: <41D826E4.3020500@t-online.de> Hi, I would like to send a marked region of an IDLE editing window to the IDLE shell for evaluating, so that I can develop software incrementally. I know that I could type directly into the shell window (or copy and paste between an editing window and the shellwindow) but I'm looking for a way of doing it like it's possible with Emacs and Python. Is there any way of doing this? Regards Rolf Wester From tim at zeos.net Mon Jan 17 03:21:23 2005 From: tim at zeos.net (Timothy Babytch) Date: Mon, 17 Jan 2005 10:21:23 +0200 Subject: how to print unicode structures? Message-ID: Imagine you have some list that looks like ('unicode', 'not-acii', 'russian') and contains characters not from acsii. or list of dicts, or dict of dicts. how can I print it? not on by one, with "for" - but with just a simple print? My debugging would be MUCH simpler. Now when I try print or pprint that variable I get a page full of '\xe4\xeb\xa2\xa0\xe6\xe3\xaa\xe6\xe3\xaa' and so on. I use Python 2.4, Fedora Linux, UTF-8 locale From jgrahn-nntq at algonet.se Wed Jan 12 16:41:07 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 12 Jan 2005 21:41:07 GMT Subject: pulling info from website References: <41e2a556$0$14576$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: On 10 Jan 2005 16:06:33 GMT, Duncan Booth wrote: > bob wrote: > >> i am trying to write a script for Xbox media center that will pull >> information from the bbc news website and display the headlines , how >> do i pull this info into a list??? > > Google for "Python RSS reader" and read some of the results. And for the general (and fundamentally broken) approach, google for "web scraping". /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From sjmachin at lexicon.net Fri Jan 21 15:40:47 2005 From: sjmachin at lexicon.net (John Machin) Date: 21 Jan 2005 12:40:47 -0800 Subject: Simple (newbie) regular expression question References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> Message-ID: <1106340047.788392.74130@f14g2000cwb.googlegroups.com> Andr? Roberge wrote: > Sorry for the simple question, but I find regular > expressions rather intimidating. And I've never > needed them before ... > > How would I go about to 'define' a regular expression that > would identify strings like > __alphanumerical__ as in __init__ > (Just to spell things out, as I have seen underscores disappear > from messages before, that's 2 underscores immediately > followed by an alphanumerical string immediately followed > by 2 underscore; in other words, a python 'private' method). > > Simple one-liner would be good. > One-liner with explanation would be better. > > One-liner with explanation, and pointer to 'great tutorial' > (for future reference) would probably be ideal. > (I know, google is my friend for that last part. :-) > > Andre Firstly, some corrections: (1) google is your friend for _all_ parts of your question (2) Python has an initial P and doesn't have private methods. Read this: >>> pat1 = r'__[A-Za-z0-9_]*__' >>> pat2 = r'__\w*__' >>> import re >>> tests = ['x', '__', '____', '_____', '__!__', '__a__', '__Z__', '__8__', '__xyzzy__', '__plugh'] >>> [x for x in tests if re.search(pat1, x)] ['____', '_____', '__a__', '__Z__', '__8__', '__xyzzy__'] >>> [x for x in tests if re.search(pat2, x)] ['____', '_____', '__a__', '__Z__', '__8__', '__xyzzy__'] >>> I've interpreted your question as meaning "valid Python identifier that starts and ends with two [implicitly, or more] underscores". In the two alternative patterns, the part in the middle says "zero or more instances of a character that can appear in the middle of a Python identifier". The first pattern spells this out as "capital letters, small letters, digits, and underscore". The second pattern uses the \w shorthand to give the same effect. You should be able to follow that from the Python documentation. Now, read this: http://www.amk.ca/python/howto/regex/ HTH, John From invalidemail at aerojockey.com Wed Jan 12 13:53:29 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 12 Jan 2005 10:53:29 -0800 Subject: complex numbers In-Reply-To: References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: <1105556009.063965.145210@z14g2000cwz.googlegroups.com> It's me wrote: > The world would come to a halt if all of a sudden nobody understands complex > numbers anymore. :-) Actually, it would oscillate out of control. -- CARL BANKS From hans at zephyrfalcon.org Fri Jan 21 14:21:20 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 21 Jan 2005 14:21:20 -0500 Subject: Funny Python error messages In-Reply-To: <1106315907.551660.276380@c13g2000cwb.googlegroups.com> References: <1106315907.551660.276380@c13g2000cwb.googlegroups.com> Message-ID: Will Stuyvesant wrote: > Add your funny or surprising Python error messages to this > thread. A requirement is that you should also show > (minimal) code that produces the message. Put the code > below, so people can think about how to generate the message > first, a little puzzle if you like. > > Perhaps this will even be a useful thread, to brighten the > life of the brave people doing the hard work of providing us > with error messages. I always liked: ValueError: insecure string pickle This error message is not strange if you think of "insecure", "string" and "pickle" as programming terms, but it's hugely mystifying to someone who isn't a programmer, since all of these words have different meanings in real life. Some code to produce it: >>> import cPickle >>> x = cPickle.dumps([1,2,3,"ratsj"]) >>> y = x[:18] + "?" + x[18:] >>> cPickle.loads(y) Traceback (most recent call last): File "", line 1, in ? ValueError: insecure string pickle -- Hans Nowak http://zephyrfalcon.org/ From steve at holdenweb.com Fri Jan 21 01:43:13 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Jan 2005 01:43:13 -0500 Subject: Does anyone want one? In-Reply-To: <20050120232749.14147.00000205@mb-m10.aol.com> References: <20050120232749.14147.00000205@mb-m10.aol.com> Message-ID: Drummmachine wrote: > http://www.freeiPods.com/?r=14249501 > > just go here to get started. It's very easy and very real. This is no scam. > Complete an offer, get 5 others to do the same and you'll receive a free Ipod > of your choice. > thanks for your time. Free ipods are real. > > As are pyramid scams. -- 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 maxm at mxm.dk Tue Jan 4 13:43:53 2005 From: maxm at mxm.dk (Max M) Date: Tue, 04 Jan 2005 19:43:53 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> Message-ID: <41dae3c3$0$228$edfadb0f@dread12.news.tele.dk> Thomas Heller wrote: > It seems also the error messages aren't too helpful: > >>>>"?".encode("latin-1") > > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position 0: ordinal not in range(128) > > Hm, why does the 'encode' call complain about decoding? Because it tries to print it out to your console and fail. While writing to the console it tries to convert to ascii. Beside, you should write: u"?".encode("latin-1") to get a latin-1 encoded string. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From usenet at horvath.com Tue Jan 4 01:42:46 2005 From: usenet at horvath.com (Bob Horvath) Date: Tue, 04 Jan 2005 00:42:46 -0600 Subject: Zope newsgroups? Need help with POSKeyError In-Reply-To: References: <41d5e51d$0$4095$afc38c87@news.optusnet.com.au> Message-ID: Dan Stromberg wrote: > On Sat, 01 Jan 2005 10:47:41 +1100, richard wrote: > > >>Bob Horvath wrote: >> >>>I have a Zope/Plone combination that I have been having POSKeyErrors >>>with for a while now. Are there any newsgroups that deal with Zope? >> >>No, but there is a mailing list - see zope.org >> >>Also, try google searching for POSKeyError. >> >> >> Richard > > > You could also see if the zeop mailing list is gatewayed to nntp on gmane. > They have a huge number of FLOSS development mailing lists on that nntp > server. Google should be able to find it easily. Hey thanks. That gmane tip will come in handy for many things! From anand at esi-india.com Thu Jan 6 05:34:16 2005 From: anand at esi-india.com (Anand K Rayudu) Date: Thu, 06 Jan 2005 16:04:16 +0530 Subject: Python C Object Comparison Message-ID: <41DD1428.1030503@esi-india.com> Dear All, I have some question regarding embedding and exposing of C pointers. We have embedded python and extended to expose our APIs and c objects to python. Every thing is working fine as far as customizing our application through python. How ever i am expecting following behavior but it failed. Can some oe suggest a work around!! Here is my python code import myModule a=myModule.myAPI1("1") b=myModule.myAPI2("name") # basically both above functions return same C pointer. # so i want to compare if(a==b): print "They are same" else : print "They are different" python always prints they are different, I guess this is because in python layer we create PythonCObject for every C pointer, and that is how it is exposed to python. Though both the APIs are returning the same C pointer, they are different instances of PythonCObject. So i guess that is the reason comparison is failing. How ever is it possible to make python to compare actual C pointer, rather than the PythonCObject Pointer. Can some one please suggest Regards, Anand From skip at pobox.com Mon Jan 17 12:10:35 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 17 Jan 2005 11:10:35 -0600 Subject: strange note in fcntl docs In-Reply-To: <16875.54085.712019.524951@montanaro.dyndns.org> References: <20050117053949.GA28456@grulic.org.ar> <16875.54085.712019.524951@montanaro.dyndns.org> Message-ID: <16875.61835.168746.328412@montanaro.dyndns.org> Skip> I could have sworn that os.open supported the O_SHLOCK and Skip> O_EXLOCK flags. I submitted a patch to posixmodule.c for these: http://python.org/sf/1103951 Skip From peter at somewhere.com Thu Jan 27 04:16:43 2005 From: peter at somewhere.com (Peter Maas) Date: Thu, 27 Jan 2005 10:16:43 +0100 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: Terry Reedy schrieb: > But if the class method syntax were > manditory, there would be class and/or class hierarchy bloat due to the > unlimited number of possible functions-of-a-float and large number of > actual such functions that have been written. You are right. I'm not an OO purist, I just wanted to convince Davor, that anti-OO purism can be harmful too. It's good for programmers to have a choice. > Your Four Steps to Python Object Oriented Programming - vars, lists, dicts, > and finally classes is great. I'm glad you like it :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From http Wed Jan 12 23:06:39 2005 From: http (Paul Rubin) Date: 12 Jan 2005 20:06:39 -0800 Subject: why are people still using classic classes? References: Message-ID: <7x6522gegg.fsf@ruckus.brouhaha.com> Simon Wittber writes: > > Is there a reason NOT to use them? If a classic class works fine, what > > incentive is there to switch to new style classes? > > Perhaps classic classes will eventually disappear? It just means that the formerly "classic" syntax will define a new-style class. Try to write code that works either way. It would be nice if a __future__ directive were added right now (if it's not there already) that processes all class definitions as new-style. Otherwise there's no easy way to test for compatibility. From wittempj at hotmail.com Tue Jan 25 15:51:38 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 25 Jan 2005 12:51:38 -0800 Subject: __deepcopy__ without recursive copies? In-Reply-To: <1106677008.086803.76270@c13g2000cwb.googlegroups.com> References: <1106677008.086803.76270@c13g2000cwb.googlegroups.com> Message-ID: <1106686298.584607.116100@c13g2000cwb.googlegroups.com> In this thread a solution is given on how to work with __deepcopy__: http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/c34431c5fd3c223b/427866340239edd7?q=__deepcopy__+example&_done=%2Fgroups%3Fq%3D__deepcopy__+example+%26hl%3Den%26lr%3D%26safe%3Doff%26sa%3DN%26tab%3Dwg%26&_doneTitle=Back+to+Search&&d#427866340239edd7 For you this would give something like: -import copy -class DeviceManager(object): - def __init__(self,devFile): - DevFile = open(devFile) - devList = [Device(line) for line in DevFile] - #etc, etc... - - def __deepcopy__(self, memo): - x = DeviceManager.__new__(DeviceManager) - memo[id(self)] = x - for n, v in self.__dict__.iteritems(): - setattr(x, n, copy.deepcopy(v, memo)) - return x - -class Device(object): - def __init__(self,line): - self.copies = [] - #do something with line here - - def __deepcopy__(self, memo): - x = Device.__new__(Device) - memo[id(self)] = x - for n, v in self.__dict__.iteritems(): - setattr(x, n, copy.deepcopy(v, memo)) - return x - -DevMan1 = DeviceManager(r'c:\autoexec.bat') -DevMan2 = copy.deepcopy(DevMan1) - -print DevMan1 is DevMan2 From phr at localhost.localdomain Tue Jan 25 17:56:47 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Tue, 25 Jan 2005 22:56:47 GMT Subject: What's so funny? WAS Re: rotor replacement References: <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" writes: > There isn't. The interface might be beautifully designed, and you might > claim it is, and I would *still* require that the module gets field > testing before being incorporated into Python. Yes, of course, that's completely reasonable. > If other people start attesting that the module is beatifully > designed, and should be included in the Python core - *then* it is > worth looking into inclusion. You said something more than that. You said it's not worth even thinking about inclusion until the finished module is actually in distribution outside the core. That it's not appropriate for the distro maintainers to look at the spec and the reference (pure Python) implementatation and say "yes, we want this, go write the C version and we'll include it after it's had some testing". I think that's silly. (Anyway I don't think "beautifully designed" needs to be a requirement, and I don't claim to have done a beautiful design. "Gets the job done straightforwardly" is all that's needed and is all that I've aimed for). When the inestimable Alexbot went to O'Reilly to pitch "Python in a Nutshell", I'm sure they didn't tell him "go write the whole book from cover to cover, circulate it for at least a year and get it thoroughly reviewed, and if enough people recommend it, then and only then will we begin to think about distributing it ourselves". More normally, he'd have given them a proposal with an outline and maybe a sample chapter and they used that to decide to give him a go-ahead. Usually at that point, they'd even also pay him some money in advance to do the rest of the work with, and promise to pay him a cancellation fee if they changed their mind about the book. I certainly never asked for anything like that from the Python guys about the crypto module. I did ask for, and receive, a "this looks good, we want it". I later heard that they backed off because of legal concerns, so I put the task aside. Similarly, look at how the whole PEP process works. There are lots of times when a PEP has been accepted before any working code is distributed. To take your view to an extreme, no project should even have a task list of desired features that people are invited to implement. There's been numerous times when I've written something for the GNU project because it's been on a list like that, and it's been accepted after checking that it does what it's supposed to. > > I'm happy to have that kind of testing (and I requested it), given > > that the goal is inclusion in the core, and the core developers have > > told me (as they did) that the proposal looks good and they'd like to > > have the module, so I can reasonably expect it to go into the core if > > it meets its technical expectations. > > Not if I have a say in it. *Any* new module should see out-of-the-core > distribution first (unless there is BDFL pronouncement to include it, > of course). > > This really is a matter of development process, not of technical > quality. That's bizarre and abnormal as a development process. What kind of development process in industry doesn't decide whether to include a feature, until after the feature is completely implemented at a production scale? They figure out what the features should be, and write them into a specification. The specification defines what features will be included. Then they implement the features. (I'm talking specificially about straightforward, well-defined features, not blue-sky or experimental concepts). You see, they decide in advance what features they're going to include, because development consumes resources and they don't want to burn resources to develop something unless they're pretty sure they're going to use the result once it's done. (Of course it doesn't always work out that way. Everyone has worked on projects that have gotten cancelled before delivery. However that by definition means that something has gone wrong. No engineer likes it when that happens.) You seem to have the attitude that since volunteer development effort doesn't consume actual PSF funds, the volunteer effort is worth nothing and can be expended arbitrarily. The volunteers may not feel that way. > > If the developers instead say (as they seemed to somewhat later) that > > because of legal/political concerns, there's no way the module can > > possibly go into the core no matter how good it is technically, then > > my motivation for writing the module dries up quite a bit. > > I personally would not say that, although I can imagine that some people > do say that, and I would also defend an inclusion, and push compliance > the BXA requirements so we can legally export Python out of the U.S.A. The BXA notification on the US side is pretty easy to handle, as you know. If you look at those Python-dev messages, the concern was about importing Python-with-crypto into countries like Holland, not about exporting it from the USA. Those concerns are not necessarily something to sneeze at. Salman Rushdie had to go into hiding for years, after publishing a book in England whose contents were illegal in Iran. So, I can't get too upset with the Python maintainers for deciding to stay away from such political messes, even though I don't feel such strong concern myself. > In either case, the user would best use the pre-compiled binary that > somebody else provided for the platform. Who's the "somebody else"? The module author might also not have had a compiler for that platform. Are you suggesting that he maintain his own distribution of multiple binaries, duplicating the machinery of the Python distro for managing multi-platform builds? Do you do that with your own modules, and still say that it's easy? If you don't, then how does the end user know where to get the module for his platform? > No, I'm merely repeating myself, and rephrasing each time. > I have to, because apparently you don't see what my requirement is. Unless your requirement is different than what you say it is, I do see what it is, and I'm saying it's better to do what normal projects do and what Python has done in the past. That is, it's perfectly ok to decide to do something and then do it, rather than insisting, bizarrely, that it always be the other way around. > The original source code of the SHA-1 implementation is the NIST code > (Gutmann, then Hollerbach), so I guess that had hundreds of users before > the module was contributed to Python. Not terribly relevant, the NIST code was not a Python module. > The module itself (including the API) was written by Greg Stein and > Andrew Kuchling. I believe (without being able to verify) that they > distributed this module for quite some time, before contributing it > to Python. We would have to ask them how many users they had until > they felt confident to contribute the code. I think that question isn't the right one. We need to ask how many users the sha module was required to have, before Greg and Andrew could have reasonable confidence that the sha module would go into the core once it was tested enough and shown to be reliable. I suspect they were able to have that confidence long before testing was complete, and maybe before implementation even started. That is, they were likely able to decide that the core obviously needed a sha module, before setting off to write and test one for that purpose. If Andrew is reading this, maybe he can comment. From craig at postnewspapers.com.au Tue Jan 11 06:10:34 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Tue, 11 Jan 2005 19:10:34 +0800 Subject: here document In-Reply-To: <1166F26E-63BE-11D9-B3E0-003065FB7B26@upf.edu> References: <1166F26E-63BE-11D9-B3E0-003065FB7B26@upf.edu> Message-ID: <1105441834.3448.2.camel@rasputin.localnet> On Tue, 2005-01-11 at 18:46, harold fellermann wrote: > On 11.01.2005, at 11:34, Nader Emami wrote: > > Would somebody help me how i can write the 'here document' in > > Python script please? I have a csh script in which a program > > is invoked with some argument in the form of here document: > > > > /bin/exe.x << End_Here > > CategorY = GRIB > > etc. > > End_Here > > > > I translate this script to Python and i don't know how can I > > do this! > > f = open("/bin/exe.x","w") > print >>f , """CategoryY = GRIB > etc. > """ You mean "os.popen" not "open" I assume? The former opens a pipe to a command, the latter overwrites the file. I'd use: os.popen("/bin/exe.x", "w").write("""\ CategorY = GRIB etc. """) myself, but that's just taste (well, and performance I suspect). -- Craig Ringer From michele.simionato at gmail.com Tue Jan 4 03:26:54 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 4 Jan 2005 00:26:54 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" In-Reply-To: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <1104827214.733305.273410@z14g2000cwz.googlegroups.com> Well, with your first post you managed to get a very unclear picture of what you mean by "non-content oriented Web Application" ;-) Judging from your following posts, you want an easy way to construct Web interfaces, i.e. forms. This can be done with any Web framework, but a typical Web framework provides a lots of content-related functionality you don't want. For instance you could use Plone for your task, but you would waste 99% of its functionality and it would be absolutely overkill. If I had to write a Web application such as Webmin, for instance, i.e. one that use a Web interface to manage other applications, I would use Quixote as my Web framework of choice. Its key points are simplicity and the fact that it provides *very little*. Just the form library would be enough for you. Since the different part of Quixote are well separated, the learning curve is really really small. It also takes a little time to evaluate it. I suggest you to give a look at it. Michele Simionato From sean at buildingonline.com Wed Jan 19 22:38:22 2005 From: sean at buildingonline.com (Sean) Date: Wed, 19 Jan 2005 19:38:22 -0800 Subject: list item's position References: Message-ID: Not sure if this is what you are looking for but... >>> li = ['this','is','a','list','of','strings'] >>> li = [l for l in li if li.index(l) >= li.index('a')] >>> li ['a', 'list', 'of', 'strings'] >>> -- Sean Berry ~ Internet Systems Programmer BuildingOnline Inc. The Building Industry's Web Design and Marketing Agency Celebrating our 9th year in business, founded Aug. 1995 Ph: 888-496-6648 ~ Fax: 949-496-0036 --> Web Design Agency site: http://www.BuildingOnline.net --> Building Industry Portal: http://www.BuildingOnline.com --> Building Industry News: http://www.BuildingOnline.com/news/ --> Home Plans: http://www.eHomePlans.com "Bob Smith" wrote in message news:csn747$3fq$1 at solaris.cc.vt.edu... > Hi, > > I have a Python list. I can't figure out how to find an element's numeric > value (0,1,2,3...) in the list. Here's an example of what I'm doing: > > for bar in bars: > if 'str_1' in bar and 'str_2' in bar: > print bar > > This finds the right bar, but not its list position. The reason I need to > find its value is so I can remove every element in the list before it so > that the bar I found somewhere in the list becomes element 0... does that > make sense? > > Thanks, > > Bob From steven.bethard at gmail.com Thu Jan 27 16:07:40 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 14:07:40 -0700 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: Francis Girard wrote: > Le jeudi 27 Janvier 2005 21:29, Steven Bethard a ?crit : >> >>So None being smaller than anything (except itself) is hard-coded into >>Python's compare routine. My suspicion is that even if/when objects of >>different types are no longer comparable by default (as has been >>suggested for Python 3.0), None will still compare as smaller than >>anything... > > Well, here's python doesn't seem to confirm what you're saying : > > >>>>a = "10" >>>>b = 10 >>>>a > b > > True > >>>>b > a > > False > >>>>id(a) > > 1077467584 > >>>>id(b) > > 134536516 Actually, this code doesn't contradict what I said at all. I said that None (and only None) was special-cased. > It really looks like the addresses are compared when objects are of different > types if there is no __cmp__ or __lt__ user made specification to compare > objects of different types. Use the source Luke! ;) Download it from CVS and take a look. The end of default_3way_compare: static int default_3way_compare(PyObject *v, PyObject *w) { ... /* None is smaller than anything */ if (v == Py_None) return -1; if (w == Py_None) return 1; /* different type: compare type names; numbers are smaller */ if (PyNumber_Check(v)) vname = ""; else vname = v->ob_type->tp_name; if (PyNumber_Check(w)) wname = ""; else wname = w->ob_type->tp_name; c = strcmp(vname, wname); if (c < 0) return -1; if (c > 0) return 1; /* Same type name, or (more likely) incomparable numeric types */ return ((Py_uintptr_t)(v->ob_type) < ( Py_uintptr_t)(w->ob_type)) ? -1 : 1; } So it looks like Python uses the type name. Testing this: py> A = type('A', (object,), {}) py> Z = type('Z', (object,), {}) py> lst = [str('a'), dict(b=2), tuple(), Z(), A()] py> [type(o).__name__ for o in lst] ['str', 'dict', 'tuple', 'Z', 'A'] py> sorted(type(o).__name__ for o in lst) ['A', 'Z', 'dict', 'str', 'tuple'] py> sorted(lst) [<__main__.A object at 0x011E29D0>, <__main__.Z object at 0x011E29F0>, {'b': 2}, 'a', ()] Yup. Looks about right. (Note that the source code also special-cases numbers...) So, the order is consistent, but arbitrary, just as Fredrik Lundh pointed out in the documentation. Steve From francis.girard at free.fr Thu Jan 27 16:30:57 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 27 Jan 2005 22:30:57 +0100 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <200501272230.57840.francis.girard@free.fr> Very complete explanation. Thank you Francis Girard Le jeudi 27 Janvier 2005 22:15, Steven Bethard a ?crit?: > Francis Girard wrote: > > I see. There is some rule stating that all the strings are greater than > > ints and smaller than lists, etc. > > 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 From steve at holdenweb.com Fri Jan 21 12:13:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Jan 2005 12:13:40 -0500 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> Message-ID: Skip Montanaro wrote: > Steve> The fact that a bright bunch like the Python developers didn't > Steve> realize that it would be sensible to have a local scope for the > Steve> list comprehension variable is a perfect demonstration of that > Steve> point. > > Actually, I seem to recall that the topic came up, but at the time the goal > was that list comprehensions be semantically the same as for loops, so the > fact that the loop variable survived to pollute the namespace was deemed > okay. > > Skip > Thanks, Skip. I remember the discussions on python-dev, but I don't think that invalidates my point. I wasn't suggesting nobody realized there would be name-droppings, simply that nobody realized that a later goal of namespace purity would take priority over the initial one of for-loop compatibility. Similar issues surrounded nested scopes, if I remember, and even there the jury's still out. Which is why I "accused" Paul Rubin of requiring psychic powers from language developers when he said "So once we can see where it's going, why not proceed to the finish line immediately instead of bothering with the intermediate steps?" we-can't-always-see-where-we're-going-ly y'rs - 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 mcfletch at rogers.com Fri Jan 21 20:23:58 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 21 Jan 2005 20:23:58 -0500 Subject: Class introspection and dynamically determining function arguments In-Reply-To: <41f18d10.1471646806@news.oz.net> References: <41f18d10.1471646806@news.oz.net> Message-ID: <41F1AB2E.7080902@rogers.com> >On Thu, 20 Jan 2005 11:24:12 -0000, "Mark English" wrote: > > > >>I'd like to write a Tkinter app which, given a class, pops up a >>window(s) with fields for each "attribute" of that class. The user could >>enter values for the attributes and on closing the window would be >>returned an instance of the class. The actual application I'm interested >>in writing would either have simple type attributes (int, string, etc.), >>or attributes using types already defined in a c-extension, although I'd >>prefer not to restrict the functionality to these requirements. >> >> Hmm, I missed the original post, but I'll jump in anyway: This sounds a heck of a lot like a property-editing system. When creating a property-modeled system, the best approach is normally to use something that actually models the properties, rather than trying to guess at the metadata involved by poking around in an arbitrarily structured object. My BasicProperty system allows for this kind of interaction (property-sheets) using wxPython (rather than Tkinter) when using wxoo. You declare classes as having a set of data-properties (which can have defaults or not, constraints or not, restricted data-types or not, friendly names or not, documentation or not). Normally you create these classes as subclasses of a class that knows how to automatically assign __init__ parameters to properties, and knows how to tell (e.g.) wxoo about the properties of the class. Those same property classes also allow for editing properties of database rows in PyTable, but that isn't likely relevant to your case. We've also used them internally to create a rather large web-based property-editing mechanism (applied to such databases), but again, not really relevant to the case at hand. Anyway, if you aren't interested in BasicProperty for this task; another project on which I work, PyDispatcher provides fairly robust mechanism (called robustApply) for providing a set of possible arguments and using inspect to pick out which names match the parameters for a function in order to pass them in to the function/method/callable object. That said, doing this for __init__'s with attribute values from an object's dictionary doesn't really seem like the proper way to approach the problem. Good luck, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From macrocosm at fastmail.fm Sun Jan 9 23:13:04 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Sun, 09 Jan 2005 23:13:04 -0500 Subject: Python Operating System??? In-Reply-To: <7x6526otw3.fsf@ruckus.brouhaha.com> References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> Message-ID: <41E200D0.6010402@fastmail.fm> Paul Rubin wrote: >"Roose" writes: > > > ... > >>Upon reading back in the thread I see that you mean compiled Lisp, >>no? I was thinking that there would be a Lisp interpreter in a >>kernel, which afaik doesn't exist. >> >> > >Yes, compiled Lisp. There are Python compilers too.\ > > ??? You mean like Pyrex or some such? I wouldn't exactly call these "Python" compilers, as that kind of obscures some underlying (critical) facts. >>In any case, as I said before I don't think it is impossible, just a >>poor engineering decision and I don't see the rationale behind it. >> >> > >I don't see a convincing case against writing an OS even in >interpreted Python, though of course I'd want it to be compiled if >possible. > >What do you think OS's do, that Python wouldn't be suitable for? Your >examples of task switching and virtual memory are unconvincing. Those >just require setting up some suitable tables and then calling a >low-level routine to poke some CPU registers. File systems can be >more performance intensive, but again, in those, much of the cpu drain >can be relegated to low-level routines and the complexity can be >handled in Python. > > Correct. From rmemmons at member.fsf.org Sat Jan 8 11:31:05 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Sat, 08 Jan 2005 10:31:05 -0600 Subject: The best way to do web apps with Python? References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: > > > > > > > >
What is Just FYI -- the post you posted was in HTML -- you might want to avoid this in the future. 99% of all posts to news groups are in text, not html. Html is hard for everyone to read with normal news readers and not usually of any extra value. It's also more of a security risk to read it -- because there is more potential for exploitation. Anyway, just thought I'd mention it if you didn't know. Take care, Rob From aorfanakos at gmail.com Sun Jan 30 21:58:10 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 30 Jan 2005 18:58:10 -0800 Subject: Regarding exception handling In-Reply-To: References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> Message-ID: <1107140290.363099.273690@c13g2000cwb.googlegroups.com> Good point, but with your way, if "s = ... # socket opens" fails, then nothing will catch it. What I usually do is what I wrote above (place it below the 2nd try), and when attempting to close it, first use an if like: "if locals().has_key('s'):". From kartic.krishnamurthy at gmail.com Tue Jan 25 15:05:54 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 25 Jan 2005 12:05:54 -0800 Subject: Import from database In-Reply-To: References: <1106587145.067483.14710@z14g2000cwz.googlegroups.com> Message-ID: <1106681053.863328.261670@f14g2000cwb.googlegroups.com> Steve, Hmmm... Yes, I see what you are saying. Could you post your create table statement so that I can create a db and play around with dbimport? Thanks, --Kartic From foo at bar.com Sun Jan 23 20:29:23 2005 From: foo at bar.com (Steve Menard) Date: Sun, 23 Jan 2005 20:29:23 -0500 Subject: Help on project, anyone? In-Reply-To: <35ienhF4lu88lU1@individual.net> References: <35ienhF4lu88lU1@individual.net> Message-ID: <5cYId.2514$zV3.523375@wagner.videotron.net> Georg Brandl wrote: > Hello, > > to train my Python skills I am looking for some project I can contribute > to. I learned Python about one year ago, and had already some > programming background behind (I contributed to SharpDevelop for > instance), so I'm not the complete newbie. > > About myself: I'm a 20 year old German with strong interests in > programming and, of course, especially in Python (I love it...). > > Does anyone run, or participate in, a project looking for fellow > programmers? I don't have a special area of interest, well, perhaps web > programming... > > Thanks, > Georg You know what I would do? I would go on Sourceforge. Try to find a project that seems interestingto you. and then contact the Maintainer see if you can help. Many project also advertise the kind of help they need. -- Steve Menard -------------------- Maintainer of http://jpype.sourceforge.net From bokr at oz.net Sat Jan 8 06:31:08 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 08 Jan 2005 11:31:08 GMT Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> Message-ID: <41dfc018.305122743@news.oz.net> On Sat, 08 Jan 2005 16:42:16 +1000, Nick Coghlan wrote: >Nick Coghlan wrote: >> It also allows the necessary but uninteresting setup for an expression >> to be moved "out of the way", bringing the expression that does the real >> work to prominence. > >Killer app for this keyword: > >class C(object): > > x = property(get, set) where: > def get(self): > return "Silly property" > def set(self, val): > self.x = "Told you it was silly" > Yes, that is cool and it _is_ an interesting idea. Are suites nestable? E.g., is this legal? x = term1 + term2 where: term1 = a*b where: a = 123 b = 456 term2 = math.pi Reminds me of some kind of weird let ;-) And, is the whole thing after the '=' an expression? E.g., x = ( foo(x) where: x = math.pi/4.0 ) where: def foo(x): print 'just for illustration', x or is this legal? for y in ([foo(x) for x in bar] where: bar = xrange(5) ): baz(y) where: def baz(arg): return arg*2 Not trying to sabotage the idea, really, just looking for clarification ;-) Regards, Bengt Richter From http Sun Jan 9 01:48:27 2005 From: http (Paul Rubin) Date: 08 Jan 2005 22:48:27 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> Message-ID: <7xr7kvm72c.fsf@ruckus.brouhaha.com> "Roose" writes: > But are you really going to write a virtual memory system in Python? Are > you going to write a file system, and a task scheduler in Python? Are you > going to have people write device drivers in Python? Do you know how virtual memory systems, file systems, task schedulers, and device drivers actually work? Have you ever written any of them? What exactly do you think the obstacles are to writing them in Python? I've written file systems in Python, and task schedulers in Javascript, and they were fine for their purposes. Virtual memory and device drivers are just more of the same. > > It doesn't prove anything of the sort. The Lisp hardware was needed > > for performance reasons, back in the day. > > OK, then give me an example of Lisp OS that runs on a PC. I would like to > install it on my PC tomorrow. Or maybe my Mac. That was your whole point, > originally, that since it could be done in Lisp, why not Python? Huh? That's a non-sequitur, nothing prevents you from running Lisp on your PC or Mac. The same issues issues that apply to OS code, also apply to user code. The Lisp machine hardware wasn't needed only to make the OS run fast. The Lisp machine was developed so that people could deploy large user-level applications written in Lisp, and the hardware was there to support those applications. And given such a good Lisp environment, there was no reason to think of writing the OS in anything other than Lisp. In fact, the reason the Lisp machine died off was because general purpose workstation hardware (and later, PC-class hardware) became fast enough to run Lisp applications without needing special purpose CPU's. That same PC hardware speed is what makes it possible to run user applications in Python. From cam.ac.uk at mh391.invalid Sun Jan 23 09:57:42 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 23 Jan 2005 14:57:42 +0000 Subject: is there better 32 clock() timing? In-Reply-To: References: Message-ID: Ray Schumacher wrote: > I have a need for a time.clock() with >0.000016 second (16us) accuracy. > The sleep() (on Python 2.3, Win32, at least) has a .001s limit. > > Are they lower/better on other's platforms? The meaning of time.clock() is entirely different on other platforms. See the documentation. You could probably get a slight speedup by using "from time import clock" and then just clock(). -- Michael Hoffman From http Mon Jan 10 20:13:17 2005 From: http (Paul Rubin) Date: 10 Jan 2005 17:13:17 -0800 Subject: Writing huge Sets() to disk References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <7xmzvgren6.fsf@ruckus.brouhaha.com> <7xis64ree5.fsf@ruckus.brouhaha.com> Message-ID: <7xr7ks3h02.fsf@ruckus.brouhaha.com> =?windows-1252?Q?Martin_MOKREJ=8A?= writes: > Yes, I'm. I still don't get what that acronym CLRS stands for ... :( CLRS = the names of the authors, Cormen, Leiserson, Rivest, and Stein, if I spelled those correctly. :) From golux at comcast.net Sat Jan 22 16:40:16 2005 From: golux at comcast.net (Stephen Waterbury) Date: Sat, 22 Jan 2005 16:40:16 -0500 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> Message-ID: <41F2C840.2050304@comcast.net> Steve Holden wrote: > It seems to me the misunderstanding here is that XML was ever intended > to be generated directly by typing in a text editor. It was rather > intended (unless I'm mistaken) as a process-to-process data interchange > metalanguage that would be *human_readable*. The premise that XML had a coherent design intent stetches my credulity beyond its elastic limit. From aaronwmail-usenet at yahoo.com Sat Jan 8 06:53:26 2005 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 8 Jan 2005 03:53:26 -0800 Subject: OT: google groups bug, or worse? In-Reply-To: <41df13b7.260993058@news.oz.net> References: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> <41df13b7.260993058@news.oz.net> Message-ID: <1105185206.674806.155330@c13g2000cwb.googlegroups.com> Bengt Richter wrote: > What did you google with? Is this it? > http://groups-beta.google.com/groups?hl=en&ie=UTF-8&q=%22The+xsdbXML+framework+provides+a+flexible+and+well+defined+infrastructure%22&qt_s=Search+Groups That was my *reply* to one of the original posts using Google, which I faked up when I couldn't find it (posted using google). The two originals aren't there. hmmm. -- Aaron Watters === You'd be paranoid too, if everyone was out to get you! From steve at holdenweb.com Mon Jan 31 17:49:53 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 17:49:53 -0500 Subject: Want to meet any of these people? They are registered for PyCon In-Reply-To: References: Message-ID: Aahz wrote: > In article , > Steve Holden wrote: > >>Note that the sort order isn't perfect - I just sorted on the second >>"word" in each name. PyCon is a *great* place to meet people and discuss >>ideas. Hope to see you there. > > > Good thing I'm not coming this year, eh? ;-) If you mean specifically for sorting purposes, it would have put the null second name at the beginning just like you'd expect. 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 bearophileHUGS at lycos.com Wed Jan 5 19:40:47 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 5 Jan 2005 16:40:47 -0800 Subject: Other notes References: <86r7l7sczp.fsf@guru.mired.org> Message-ID: <1104972047.050366.211670@f14g2000cwb.googlegroups.com> Thank you to all the gentle people that has given me some comments, and sorry for bothering you... Doug Holton: >This will also likely never appear in Python. I know, that's why I've defined it "wild". >Also, you might request the NetLogo and StarLogo developers to support Jython (in addition to Logo) scripting in their next version< I was suggesting the idea of adding the complex data structures of NetLogo (patches, etc) to the normal Python. ------------- Andrew Dalke: >(BTW, it needs to be 1 .. 12 not 1..12 because 1. will be interpreted as the floating point value "1.0".)< Uhm, I have to fix my ignorance about parsers. Cannot a second "." after the first tell that the first "." isn't in the middle of a floating point number? >In Pascal it works because you also specify the type and Pascal has an incr while Python doesn't.< The Pascal succ function (that works on chars and all integer types) is often useful (it's easy to define it in Python too). >>This may allow: assert 5 interval 9 == interval(5,9) >Maybe you could give an example of when you need this in real life?< Every time you have a function with 2 parameters, you can choose to use it infix. >Does this only work for binary or is there a way to allow unary or other n-ary (including 0-ary?) functions?< It's for binary functions only. For unary the normal fun(x) syntax is good enough, and for n-ary the sintax becomes unnecessary complex, and you can use the normal function syntax again. >But to someone with C experience or any language which derives its formatting string from C, Python's is easier to understand than your Pascal one.< You can be right, but "understanding" and "being already used to something" are still two different things :-) >A Python view is that there should be only one obvious way to do a task. Supporting both C and Pascal style format strings breaks that.< Okay. >I don't think Pascal is IEEE enough.< Well, if you assign that FP number inside the program (and not as a constant) Delphi 4 too gives a more "correct" answer ^_^ (I don't know/remember why there are such differences inside Delphi between constants and variables). >note also that the Pascal-style formatting strings are less capable than Python's,< I know... >though few people use features like< Right. >A real-life example would also be helpful here.< (I was parsing trees for Genetic Programming). People here can probably suggest me 10 alternative ways to do what I was trying to do :-) As list comprehensions, that suggestion of mine cannot solve new kinds of problems, it's just another way of doing things. >What does map(len, "Blah", level = 200) return?< Well: "c" == "c"[0][0][0][0][0][0] map(len, "blah") == [1, 1, 1, 1] So I think that answer is still [1, 1, 1, 1]. >You need to learn more about the Pythonic way of thinking of things. The usual solution for this is to have "level = None".< To Steven Bethard I've suggested an alternative syntax (using a level-ed flatten with a standard map command). >There's also tmPython.< Thank you, the screenshoots are quite nice :-) http://dkbza.org/11.0.html -------------- Steven Bethard: >Since I can't figure it out intuitively (even with examples), I don't think this syntax is any less inscrutable than '%.f'.< Well, I haven't given a textual explanation, but just few examples. >My suspicion is that you're just biased by your previous use of Pascal.< This is possible. >This packs two things into map -- the true mapping behaviour (applying a function to a list) and the flattening of a list.< Okay, then this is my suggestion for the syntax of an iterable xflatten: xflatten(sequence, level=-1, monadtuple=False, monadstr=True, safe=False]) - level allows to specify the mapping level: level=0 no flattening. level=1 the flattening is applied to the first and second level. Etc. And like in the indexing of lists: level=-1 (default) means the flattening is applied up to the leaves. level=-2 flattens up to pre-leaves. Etc. - monadtuple (default False) if True tuples are monads. - monadstr (default True) if False then strings with len>1 are sequences too. - safe (default False) if True it cheeks (with something like an iterative isrecursive) for recursive references inside the sequence. >(Also, Google for flatten in the python-list -- you should find a recent thread about it.)< I've discussed it too in the past :-) http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d0ba195d98f35f66/ >and that your second example gains nothing over< Right, but maybe with that you can unify the def and lambda into just one thing ^_^ >def foo(x): > globals()['y'] = globals()['y'] + 2 >Not exactly the same syntax, but pretty close. Thank you for this idea. >I'll second that. Please, "Bearophile", do us the courtesy of checking [...] before posting another such set of questions. While most of the people on this list are nice enough to answer your questions anyway, the answers are already out there for at least half of your questions, if you would do us the courtesy of checking first.< I've read many documents, articles and PEPs and, but I'm still new, so I've missed many things. I'm sorry... I'm doing my best. ----------- Terry J. Reedy >I also suggest perusing the archived PyDev (Python Development mailing list) summaries for the last couple of years (see python.org). Every two weeks, Brett Cannon has condensed everything down to a few pages.< Okay, thank you. Bear hugs, Bearophile From steve at holdenweb.com Sat Jan 22 10:34:08 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 22 Jan 2005 10:34:08 -0500 Subject: What YAML engine do you use? In-Reply-To: <41f1a3e6.1477492061@news.oz.net> References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> Message-ID: Bengt Richter wrote: > On Fri, 21 Jan 2005 12:04:10 -0600, "A.M. Kuchling" wrote: > > >>On Fri, 21 Jan 2005 18:30:47 +0100, >> rm wrote: >> >>>Nowadays, people are trying to create binary XML, XML databases, >>>graphics in XML (btw, I'm quite impressed by SVG), you have XSLT, you >>>have XSL-FO, ... . >> >>Which is an argument in favor of XML -- it's where the activity is, so it's >>quite likely you'll encounter the need to know XML. Few projects use YAML, >>so the chance of having to know its syntactic details is small. >> > > > I thought XML was a good idea, but IMO requiring quotes around > even integer attribute values was an unfortunate decision. I don't buy > their rationale of keeping parsing simple -- as if extracting a string > with no embedded space from between an equal sign and terminating white > space were that much harder than extracting the same delimited by double quotes. It isn't that much harder, but if there are two ways to do the same thing then effectively one of them has to become a special case, thereby complicating the code that has to handle it (in this case the parser). "There should be one (and preferably only one) ..." should be a familiar mantra around here :-) > The result is cluttering SVG with needless cruft around numerical graphics parameters. > > It seems to me the misunderstanding here is that XML was ever intended to be generated directly by typing in a text editor. It was rather intended (unless I'm mistaken) as a process-to-process data interchange metalanguage that would be *human_readable*. Tools that *create* XML are perfectly at liberty not to require quotes around integer values. > OTOH, I think the HTML XML spec is very readable, and nicely designed. > At least the version 1.0 spec I snagged from W3C a long time ago. > .... I see the third edition at http://www.w3.org/TR/REC-xml/ is differently styled, > (I guess new style sheets) but still pretty readable (glancing at it now). > > Regards, > Bengt Richter 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 max at alcyone.com Fri Jan 7 16:43:14 2005 From: max at alcyone.com (Erik Max Francis) Date: Fri, 07 Jan 2005 13:43:14 -0800 Subject: Notification of PEP Updates In-Reply-To: References: Message-ID: Nick Coghlan wrote: > I can't recall which thread this came up in, so I'm starting a new one. . . > > Barry Warsaw has kindly added a "peps" topic to the python-checkins mailing > list. If you want to be notified only when PEP's get updated, then subscribe to > python-checkins and edit your settings to select just the 'peps' topic. Maybe someone could roll this into an RSS feed? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis There's a reason why we / Keep chasing morning -- Sandra St. Victor From jepler at unpythonic.net Thu Jan 27 22:29:59 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 27 Jan 2005 21:29:59 -0600 Subject: tkinter: Can You Underline More Than 1 Char In A Menu Title In-Reply-To: References: Message-ID: <20050128032958.GA17445@unpythonic.net> On Thu, Jan 27, 2005 at 06:38:22AM -0500, Tim Daneliuk wrote: > Is it possible to underline more than a single character as I am doing > with the 'underline=0' above. I tried 'underline=(0,2)' but that didn't > work. No. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From gandalf at geochemsource.com Mon Jan 24 07:45:15 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Mon, 24 Jan 2005 13:45:15 +0100 Subject: wx.BoxSizer problem In-Reply-To: <48F31575-6BD2-11D9-9482-003065B11E84@leafe.com> References: <41F11AC1.6040108@geochemsource.com> <48F31575-6BD2-11D9-9482-003065B11E84@leafe.com> Message-ID: <41F4EDDB.3080807@geochemsource.com> >> My problem is that only one of the buttons is visible and that one is >> not expanded. (System: Windows, Python 2.3.4, wxPython 2.5.3) > > > Works as expected on Mac OS X 10.3.7, python 2.3.4, wxPython 2.5.2.8. Thanks. Probably the problem is with my bitmap (I used a bitmap instead of a button). Please do not spend more time on it - I'll handle. Best, Laci 2.0 From claird at lairds.us Mon Jan 17 15:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Mon, 17 Jan 2005 20:08:04 GMT Subject: PyChecker messages References: <1105983271.574296.37740@c13g2000cwb.googlegroups.com> Message-ID: In article <1105983271.574296.37740 at c13g2000cwb.googlegroups.com>, Ben Sizer wrote: >But you could use a dict of return values, or even just assigning a >different return value in each if clause. The end result is that you >have a single well-defined exit point from the function, which is >generally considered to be preferable. > Well, no; I'm trying to say exactly that there are times when "a dict of return values" only adds complexity. Or perhaps I'm missing a bet- way to code: def condition_label(): if x13.fluid_level() > lower_threshhold: return "OK" if user in restricted_list: return "Ask for help" if not current_time.in_range(beginning, end): return "Uncorrectable exception reported" ... When conditions live in a space with higher dimensionality than any handy immutable range, no dict-ification is a benefit. From mcfletch at rogers.com Mon Jan 24 10:35:58 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 24 Jan 2005 10:35:58 -0500 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <1f7befae0501231720428ca3c@mail.gmail.com> References: <41F427EB.3000200@rogers.com> <1f7befae0501231720428ca3c@mail.gmail.com> Message-ID: <41F515DE.8000600@rogers.com> Tim Peters wrote: >[Mike C. Fletcher] > > >>I'm looking at rewriting parts of Twisted and TwistedSNMP to eliminate >>__del__ methods (and the memory leaks they create). >> >> >A worthy goal! > > Well, as of now it seems to have eliminated the last leaks in TwistedSNMP, and that's likely going to eliminate the last of our leaks in our products, so yes, I suppose it was :) . >A callback is strongly referenced from the weakref(s) containing it. > > Thanks. >It would really help to give a minimal example of self-contained >executable code. I'm not sure how you're using this code, and >guessing takes too long. > > Sorry about that. I was expecting a theoretical problem, not a practical one, so didn't think to provide a practical example. >The "2" there is important, just because this is an interactive >session. The point of it was to stop `_` from holding a reference to >the created weakref. In your code > > weakref.ref( self, self.close ) > >the weakref itself becomes trash immediately after it's created, so >the weakref is thrown away entirely (including its strong reference to >self.close, and its weak reference to self) right after that line >ends. Of course callbacks aren't *supposed* to be called when the >weakref itself goes away, they're supposed to be called when the thing >being weakly referenced goes away. So this all looks vanilla and >inevitable to me -- the callback is never invoked because the weakref >itself goes away long before self goes away. > > Alex already scooped you on this "smack yourself on the head, Mikey". I was assuming the weakref object was a proxy for a reference in an internal structure; I was expecting a list of weak references that was nothing but a series of functions to call after finalising the object. My bad. >I'm pretty sure it's just because there's nothing here to keep the >weakref itself alive after it's created. You could try, e.g., > > self.wr = weakref.ref( self, self.close ) > >to keep it alive, but things get fuzzy then if self becomes part of >cyclic trash. > > Yes, so it requires an external storage mechanism and code to clean that up... ick. __del__ looks cleaner and cleaner by comparison. You'd think I would have noticed the huge tables of weakref objects in PyDispatcher as I was working in there... >>I can work around it in this particular case by defining a __del__ on >>the Closer, but that just fixes this particular instance (and leaves >>just as many __del__'s hanging around). I'm wondering if there's a >>ready recipe that can *always* replace a __del__'s operation? >> >> > >In the presence of cycles it gets tricky; there's a lot of >more-or-less recent words (less than a year old ) about that on >python-dev. It gets complicated quickly, and it seems nobody can make >more time to think about it. > > Sigh, guess I should stop listening to rumours just because they are saying something about that for which I yearn. >>I know I heard a rumour somewhere about Uncle Timmy wanting to eliminate >>__del__ in 2.5 or thereabouts, >> >> > >Python 3 at the earliest. That's the earliest everything nobody can >make time for lands <0.5 wink>. > > Well, we darn well better solve it by then! Don't want memory leaks when we're hard-wired into someone's brain. >There are unresolved issues about how to get all this stuff to work >sanely. The driving principle behind cyclic-trash weakref endcases >right now is "do anything defensible that won't segfault". > >I'll note that one fairly obvious pattern works very well for weakrefs >and __del__ methods (mutatis mutandis): don't put the __del__ method >in self, put it in a dead-simple object hanging *off* of self. Like >the simple: > >class BTreeCloser: > def __init__(self, btree): > self.btree = btree > > def __del__(self): > if self.btree: > self.btree.close() > self.btree = None > > Yes, this was the "work around" I'd implemented (well, with __call__ instead and del just calling it). Of course, that didn't actually eliminate any __del__ methods, but oh well, if we're not losing those until 3.x it doesn't really matter :) . The fix for the Deferred in Twisted got a little hideous (there the __del__ is poking around into lots of different attributes of the Deferred. To hack that I created a descriptor class that forwards a variable to the held object and wrapped each of the needed variables in one of those... I'm going to have to find something a little less baroque if I'm going to get it into Twisted... really, it doesn't look like any of it's necessary, it's just logging an error if the Deferred ended on a Failure. Something should be done though, leaking memory from a core object in the framework is just a PITA. >When a weakref and its weak referent are both in cyclic trash, Python >currently says "the order in which they die is undefined, so we'll >pretend the weakref dies first", and then, as at the start of this >msg, the callback is never invoked. > So external storage of a weakref is basically a requirement to make it useful. Hmm. >The problem this avoids is that >the callback may itself be part of cyclic trash too, in which case >it's possible for the callback to resurrect anything else in cyclic >trash, including the weakly-referenced object associated with the >callback. But by hypothesis in this case, that object is also in >cyclic trash, and horrible things can happen if a partially destructed >object gets resurrected. > > Reasonable I suppose. >So the real rule right now is that, if you want a guarantee that a >callback on a weakly referenced object gets invoked, you have to write >your code to guarantee that the referent becomes trash before its >weakref becomes trash. (And note that if you do, the callback >necessarily will be alive too, because a weakref does in fact hold a >strong reference to its callback.) > > Guess I'll go back to the sub-object approach for all things and merely dream of a far off weakref utopia free of all __del__ methods. Thanks, Tim, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From fredrik at pythonware.com Sat Jan 22 05:25:08 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 11:25:08 +0100 Subject: list unpack trick? References: <1gqsalx.4ip95k18168r0N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: >> or (readable): >> >> if len(list) < n: >> list.extend((n - len(list)) * [item]) > > I find it just as readable without the redundant if guard -- just: > > alist.extend((n - len(alist)) * [item]) the guard makes it obvious what's going on, also for a reader that doesn't know exactly how "*" behaves for negative counts. once you've seen the "compare length to limit" and "extend", you don't have to parse the rest of the statement. From a at b.c Tue Jan 4 15:19:44 2005 From: a at b.c (Doug Holton) Date: Tue, 04 Jan 2005 14:19:44 -0600 Subject: Python evolution: Unease In-Reply-To: <98WdnVGqi-yaUkfcRVn-tw@giganews.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> Message-ID: Istvan Albert wrote: > Doug Holton wrote: > >> application is so important that I expect Python 3000 will have >> optional type declarations integrated into the argument list." > > > I think that *optional* part of the "optional type declaration" > is a myth. > > It may be optional in the sense that the language will > accept missing declarations but as soon as the feature > is available it will become "mandatory" to use it > (peer pressure, workplace practices). I didn't write that, Guido did. I agree with you, and others who have made the same point you made. I would have to think Guido is already aware of this issue (keep python simple). I'm not sure what his motivations are for wanting to add static typing to python, not that I'm against it. It doesn't matter a whole lot either way since Python 3000 is still years away and you can already do static typing now with Pyrex or boo, as well as many other things that people have requested for python from little things like ++i to bigger features like multi-line anonymous methods/closures. From roy at panix.com Sat Jan 1 09:27:30 2005 From: roy at panix.com (Roy Smith) Date: Sat, 01 Jan 2005 09:27:30 -0500 Subject: what is lambda used for in real code? References: Message-ID: In article , Adam DePrince wrote: > We can operate on every other class without having to involve the > namespace, why should functions be any different? def is a weird beast. It does more than just bind a lambda to a name, it also alters the function so it knows its own name. For example, the following: -------------- def foo (): print "I am foo" bar = foo def foo (): print "I am foo's evil twin" foo() print foo bar() print bar baz = lambda : "I am lambda" print baz print baz() -------------- will print: I am foo's evil twin I am foo at 0x363770> I am lambda From Jared.Cohen at noaa.gov Wed Jan 5 17:22:21 2005 From: Jared.Cohen at noaa.gov (Jared Cohen) Date: Wed, 05 Jan 2005 17:22:21 -0500 Subject: Please help -- Pmw PanedWidget inside ScrolledFrame Message-ID: <41DC689D.5010305@noaa.gov> I'm trying to use a Pmw.ScrolledFrame which contains a PanedWidget. But I can't get the PanedWidget to expand to fill the interior frame. It expands fine if I just grid it into the toplevel window; and when I tried gridding DIFFERENT widgets into the ScrolledFrame, they expanded just fine. So both the ScrolledFrame and PanedWidget seem to work OK on their own, but when I try to put one inside the other, something goes haywire. Can anyone help please? -------------- next part -------------- An HTML attachment was scrubbed... URL: From daranrife at yahoo.com Fri Jan 28 19:13:18 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 16:13:18 -0800 Subject: LinearAlgebra incredibly slow for eigenvalue problems In-Reply-To: References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> <1106952951.834888.65430@f14g2000cwb.googlegroups.com> Message-ID: <1106957598.136667.45430@z14g2000cwz.googlegroups.com> Hi David, Yes, when Numeric compiles it does look like the linking is being done properly. I captured the build to a file and see a few lines similar to: gcc -pthread -shared build/temp.linux-i686-2.4/Src/lapack_litemodule.o -L/d2/lib/atlas -llapack -lptcblas -lptf77blas -latlas -lg2c -o build/lib.linux-i686-2.4/lapack_lite.so I checked the files in build/lib.linux-i686-2.4 and none have dependencies on ATLAS. When I run Python interpreter with: >>> import Numeric >>> Numeric.__file__ I get the answer I expect. I am totall baffled. Any other ideas? Thanks for your help, Daran From peter at engcorp.com Sun Jan 23 19:00:18 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jan 2005 19:00:18 -0500 Subject: OT: problems mirroring python-list to c.l.py? In-Reply-To: References: <1d6cdae305012310535980e82d@mail.gmail.com> <20050123190637.GA4820@grulic.org.ar> Message-ID: Daniel Bickett wrote: > John Lenton wrote: >>>On Sun, Jan 23, 2005 at 01:53:52PM -0500, Daniel Bickett wrote: >>>>Is there a reason that Google Groups isn't mirroring python-list >>>>exactly like it used to, or is it simply a conspiracy I'm not in on? >>> >>>You should not ask this kind of question in a public forum, >> >>and *you* should know better than to go around flapping your mouth >>like that. > > Now I'm further confused, because I don't know what you quoted, but it > isn't on the mailing list and it isn't on c.l.py :) Maybe I should > give up trying to figure these things out. For what it's worth, I'm seeing the same behaviour as what you (Daniel) are seeing, and I read the group through comp.lang.python via NTTP, not via the mail-based python-list or Google Groups. > You didn't include a name at the beginning of your citation... Who had > the audacity to take my joke seriously? ;-) Apparently somebody who doesn't understand that unlike most other public fora, comp.lang.python is "special" in that it is mirrored to and from the mailing list, and that there is no other more appropriate place to ask such a question (at least until it's apparent that it is a problem with a specific part of this system, rather than being entirely unclear just _what_ the problem is). -Peter From iddwb at moroni.pp.asu.edu Thu Jan 13 20:26:09 2005 From: iddwb at moroni.pp.asu.edu (David Bear) Date: Fri, 14 Jan 2005 01:26:09 +0000 (UTC) Subject: query python env Message-ID: How does one query the python environment, ie pythonhome, pythonpath, etc. also, are there any HOWTO's on keeping multiple versions of python happy? From jdhunter at ace.bsd.uchicago.edu Mon Jan 31 11:01:15 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 31 Jan 2005 10:01:15 -0600 Subject: barchart for webpage needed In-Reply-To: (dimitri pater's message of "Mon, 31 Jan 2005 16:54:52 +0100") References: Message-ID: >>>>> "dimitri" == dimitri pater writes: dimitri> Hello, I am looking for a Python tool to create graphs dimitri> and charts on a webpage. Chartdirector is too expensive dimitri> for me. A simple script for creating a barchart should be dimitri> sufficient as a starting point. matplotlib does barcharts, errorbars, stacked bars, and more (and its free). See the following links # matplotlib with web app servers: http://matplotlib.sourceforge.net/faq.html#APPSERVER # a barchart screenshot with example code http://matplotlib.sourceforge.net/screenshots.html#barchart_demo # the bar command for making bar charts http://matplotlib.sourceforge.net/matplotlib.pylab.html#-bar JDH From jzgoda at gazeta.usun.pl Tue Jan 25 16:06:21 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Tue, 25 Jan 2005 22:06:21 +0100 Subject: snakespell and myspell In-Reply-To: <1106657932.301181.150050@z14g2000cwz.googlegroups.com> References: <1106657932.301181.150050@z14g2000cwz.googlegroups.com> Message-ID: Fuzzyman wrote: > I'm looking to implement a plugin spell checker. > > I'm probably going to go with PyEnchant, as it looks to be the most > promising currently maintained spell checker. > > I just wondered if anyone knew what happened to snakespell and myspell. > Both seem to have dissapeared from the net. People have reported good > results from both - and it seems a shame to lose them. Well, myspell-python is no longer maintained, original author resigned some time ago and I didn't found anybody who would like to take responsibility on this package. I provide myspell-1.0 download from my project page at BerliOS (http://developer.berlios.de/projects/jpa/), but I do not maintain this package. If you look for spell-checking library, I'd consider using python binding for aspell, available at http://www.republika.pl/wmula/proj/aspell-python/ (currently I'm rewriting my program to use python-aspell). This library is actively maintained and Wojtek Mula is active member of Polish Python community. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From aut_gbarros at uolinc.com Thu Jan 27 09:04:41 2005 From: aut_gbarros at uolinc.com (Gabriel Cosentino de Barros) Date: Thu, 27 Jan 2005 12:04:41 -0200 Subject: Point of Sale Message-ID: <2814F26DA6908F41927A81C410C4991A02079C72@siamun.server.bl.corp.intranet> Hi, i'm curently doing a POS. But mine is a small scale and stand alone. Are you planing on developing in house and then opening? develop at open or simple use open source tools and keep it closed? I'm going to post my progress at source forge next week when i finish proof reading the design docs. i'm curently focused in the HCI layer (primarily using only plain tk) and haven't gave much tought to the 'external' stuff, like integrating wire money cards and such Gabriel -----Original Message----- From: Andreas Pauley [mailto:andreasp at qbcon.com] Sent: quinta-feira, 27 de janeiro de 2005 11:08 To: python-list at python.org Subject: Point of Sale Hi, My company has given me a rather cool project: I have to provide them with an open-source python-based point-of-sale / cash register system that can integrate with their existing ERP backend. The project will include development to ensure that the features they require are included in the open-source POS system. Can you recommend anything that I can use? Regards, Andreas -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From ola.natvig at infosense.no Wed Jan 26 11:06:27 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Wed, 26 Jan 2005 17:06:27 +0100 Subject: access private field in python 2.4 In-Reply-To: <1106754371.637295.82160@z14g2000cwz.googlegroups.com> References: <1106754371.637295.82160@z14g2000cwz.googlegroups.com> Message-ID: <4prkc2-ini.ln1@pluto.i.infosense.no> ajikoe at gmail.com wrote: > Hello, > I'm new to python, > How can I access private field in python. > > thanks > In python there realy are not private fields. There are those fields that you start with a double underline (__) theese are translated to ___ Withouth the < and > markers, but there are not good practice to access theese through that name. -- -------------------------------------- Ola Natvig infoSense AS / development From aurora00 at gmail.com Sat Jan 22 13:03:27 2005 From: aurora00 at gmail.com (aurora) Date: Sat, 22 Jan 2005 10:03:27 -0800 Subject: list unpack trick? References: Message-ID: Thanks. I'm just trying to see if there is some concise syntax available without getting into obscurity. As for my purpose Siegmund's suggestion works quite well. The few forms you have suggested works. But as they refer to list multiple times, it need a separate assignment statement like list = s.split('=',1) I am think more in the line of string.ljust(). So if we have a list.ljust(length, filler), we can do something like name, value = s.split('=',1).ljust(2,'') I can always break it down into multiple lines. The good thing about list unpacking is its a really compact and obvious syntax. On Sat, 22 Jan 2005 08:34:27 +0100, Fredrik Lundh wrote: ... >> So more generally, is there an easy way to pad a list into length of n >> with filler items appended >> at the end? > > some variants (with varying semantics): > > list = (list + n*[item])[:n] > > or > > list += (n - len(list)) * [item] > > or (readable): > > if len(list) < n: > list.extend((n - len(list)) * [item]) > > etc. > > From benn at cenix-bioscience.com Wed Jan 12 04:48:58 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Wed, 12 Jan 2005 10:48:58 +0100 Subject: Game programming in Python In-Reply-To: References: Message-ID: <41E4F28A.3000806@cenix-bioscience.com> Baza wrote: >I'm looking for any books or on-line resources on game programming using >Python. Does anyone have any advice? >-- >Computer says, 'no' > > > > Like the end quote : eh, eh, eeehhhhhh!! -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 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 steven.bethard at gmail.com Wed Jan 26 18:02:47 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 16:02:47 -0700 Subject: inherit without calling parent class constructor? In-Reply-To: References: Message-ID: Christian Dieterich wrote: > On D? C?adaoin, Ean 26, 2005, at 13:45 America/Chicago, Steven Bethard > wrote: > >> Note that: >> @deco >> def func(...): >> ... >> is basically just syntactic sugar for: >> def func(...): >> ... >> func = deco(func) > > > Oh, I learned something new today :-) Nice thing to know, these > descriptors. Just a note of clarification: The @deco syntax is called *decorator* syntax. Classes with a __get__ method are called *descriptors*. But yes, they're both nice things to know. ;) Steve From mb at muenster.de Thu Jan 13 16:35:51 2005 From: mb at muenster.de (Martin Bless) Date: Thu, 13 Jan 2005 21:35:51 GMT Subject: Pyrex-0.9.3: definition mismatch with distutils of Python24 Message-ID: <41e6e1c5.8718906@news.muenster.de> Now that I've got my extension building machine using the VC++ Toolkit 2003 up and running I'm keen on using Pyrex (Pyrex-0.9.3, Python-2.4.0). But the definition of the swig_sources() method seems to have changed. When I try to build the examples from Pyrex I get a TypeError: c:\Pyrex-0.9.3\Demos> python Setup.py build_ext --inplace running build_ext building 'primes' extension [...] File "C:\Python24\lib\distutils\command\build_ext.py", line 442, in build_extension sources = self.swig_sources(sources, ext) TypeError: swig_sources() takes exactly 2 arguments (3 given) I can see that Pyrex.Distutils.build_ext.py subclasses distutils.command.build_ext.build_ext, and the number of arguments of the swig_sources method seems to have changed. Pyrex uses: def swig_sources (self, sources): whereas the distutils use: def swig_sources (self, sources, extension): If I just add the "extension" arg to the Pyrex definitions everything seems to work. But I have to admit that I don't really know what I'm doing here and I feel sorry I can't contribute more than just reporting the error. mb - Martin Bless From aleaxit at yahoo.com Sat Jan 22 08:10:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 14:10:36 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <7xu0p9lk4h.fsf@ruckus.brouhaha.com> Message-ID: <1gqsn7o.qyazai1nh7smmN%aleaxit@yahoo.com> Paul Rubin wrote: > Dave Benjamin writes: > > Can we get a show of hands for all of those who have written or are > > currently maintaining code that uses the leaky listcomp "feature"? > > It's really irrelevant whether anyone is using a feature or not. If > the feature is documented as being available, it means that removing > it is an incompatible change that can break existing code which > currently conforms to the spec. If the "feature" is described as the > bug that it is, anything that relies on it is nonconformant. > > I do remember seeing some cute tricks (i.e. capable of becoming > idioms) that depend on the leakage. Sure, ``if [mo for mo in [myre.search(line)] if mo]: use(mo)`` and the like, used to simulate assign-and-test. No doubt maintaining backwards compat with this kind of horrors means listcomps need to keep leaking until Python 3.0, alas. But hopefully no farther... Alex From daranrife at yahoo.com Fri Jan 28 14:31:44 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 11:31:44 -0800 Subject: Installing Numeric with ATLAS and LAPACK In-Reply-To: References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> Message-ID: <1106940704.164253.134630@c13g2000cwb.googlegroups.com> Thanks John. Those are the steps I followed, and to no avail. Interestingly, I downloaded and installed SciPy, and ran the same eigenvector problem. SciPy greatly speeds up the calculation...was 1.5 hours using Numeric, now only 15 min with SciPy. Unfortunately, SciPy only solves ordinary and generalized eigenvalue problems of a square matrix. They do not test to see if the matrix is symmetric, then call the appropriate routine from LAPACK. Daran From littlejohn.75NOSPAM at news.free.fr.invalid Mon Jan 31 11:41:44 2005 From: littlejohn.75NOSPAM at news.free.fr.invalid (F. Petitjean) Date: 31 Jan 2005 16:41:44 GMT Subject: Crude statistics on the standard library Message-ID: <41fe5fc7$0$29873$636a15ce@news.free.fr> I have written a script to find the modules which export the largest number of names. The gc.getreferrers(*objs) function gives also an idea of the dependencies between the modules. The code (statsmod.py) : #!/usr/bin/env python # -*- coding: latin-1 -*- """ statsmod.py module rudimentaire de statistiques des noms export?s par les modules de la biblioth?que standard """ import sys import gc from glob import glob import os, os.path from os.path import basename def browse_stdlib(): """browse the standard library returns list of names of modules """ pyver = 'python%s' % (sys.version[:3],) pyglob = os.path.join(sys.prefix, 'lib', pyver, '*.py') # lpys = glob(pyglob) if os.path.exists(os.path.join(sys.prefix, 'Lib', 'os.pyc')): pyglob = os.path.join(sys.prefix, 'Lib', '*.py') lpys = map(basename, glob(pyglob)) names = [ name[:-3] for name in lpys ] # remove some obsolete modules ('this' + DeprecationWarning) for dontparse in ("this", "tzparse", 'FCNTL', 'posixfile', 'pre', 'regsub', 'statcache', 'TERMIOS', 'xmllib'): try: names.remove(dontparse) except ValueError: continue return names def exports(names, with_modules=False): """imports all the modules in names returns a 2-tuple : - list of tuples : NumberOfExternalNames len(dir(module)) nodname - list of modules (if with_modules is true) """ res = [] add = res.append _all = [] modules = [] # this simple minded method (__import__) doesn't include sys ? for name in names: print name, " ", try: module = __import__(name, globals(), locals(), _all) ldir = len(dir(module)) if hasattr(module, '__all__'): nexports = len(module.__all__) else: nexports = ldir add((nexports, ldir, name)) if with_modules: modules.append(module) # del sys.modules[name] except ImportError, msg: print "cannot import module", name, msg return res, modules def pm_histo(values, nbins=20): """a poor man histogram Return a list of nbins tuples (left, right) such that the union of the consecutive ranges(left, right) is range(len(values)+1) values[k] """ vlo, vhi = values[0], values[-1]+1 nbins = min(nbins, vhi-vlo) deltax = int((vhi - vlo)/nbins) assert deltax > 0 ranges = [] add = ranges.append left = 0 # left index first bin val = vlo + deltax while val < vhi: for right in range(left, len(values)): if values[right] > val: break add((left, right)) left = right val = val + deltax return ranges def basic_stat(seq): """basic statistics on the values in seq Returns NumberOfItems, MeanValue, StandardDeviation, variance """ s0, s1, s2 = 0, 0, 0 for indx, item in enumerate(seq): s0 = s0 + 1 # seq may be an iterable without len Xi = float(item) if not indx: Xmin = Xi s1 = s1 + Xi s2 = s2 + Xi*Xi # s0 = len(seq) # sum of 0 order Xm = s1/s0 # mean value Xmax = Xi median = (Xmin + Xmax)*0.5 variance = (s2 - s0*Xm*Xm)/s0 # ecart-type ** 2 import math stddev = math.sqrt(variance) # ecart-type return s0, Xmin, Xmax, median, Xm, stddev # , variance if __name__ == '__main__': names = ['cStringIO', 'sys', 'gc' ] names.extend(browse_stdlib()) freqs, modules = exports(names, True) print # exports() prints without new line print "%d imported modules and %d in sys.modules" % ( len(freqs), len(sys.modules)) print "number of unreachable objects", gc.collect() simples = [] while modules: module = modules.pop() # print module.__name__, sys.getrefcount(module) items = gc.get_referrers(module) litems = len(items) if litems <= 2: simples.append(module.__name__) del sys.modules[module.__name__], module, items else: print "referrers of %s" % (module.__name__,) for item in items[2:]: name = item.get('__file__', 'unknown') if name.endswith('__init__.pyc'): pslash = name.rfind(os.sep) pslash = name[:pslash].rfind(os.sep) name = name[pslash+1:][:-4] # strip .pyc elif name.endswith('__init__.py'): pslash = name.rfind(os.sep) pslash = name[:pslash].rfind(os.sep) name = name[pslash+1:][:-3] # strip .py elif name.endswith('.pyc'): pslash = name.rfind(os.sep) name = name[pslash+1:][:-4] # strip .pyc elif name.endswith('.py'): pslash = name.rfind(os.sep) name = name[pslash+1:][:-3] # strip .py print name, del module, items print print "number of unreachable objects", gc.collect() print "new length of sys.modules %d" % (len(sys.modules),) print "%d simple modules" % (len(simples),) freqs.sort() values = [item[0] for item in freqs ] # print freqs[-2:] # supprim?s # del values[-2:] ranges = pm_histo(values) ranges2 = [ item for item in ranges if item[1] > item[0]] limite = ranges[0][1] + 1 # first bin rangesbas = pm_histo(values[:95], 6) print rangesbas lbin = 11 start = 0 print "St Nb. min max median average stddev" fmt = "%3d%3d%6.1f%6.1f%8.3f%8.3f%8.3f" while start < len(values): res = (start,) + basic_stat(values[start:start+lbin]) print fmt % res start = start + lbin print "modules with a lot of external names :" for item in freqs[140:]: print item Parts of output of python -i statsmod.py (python2.4 windows) repr rexec rfc822 rlcompleter cannot import module rlcompleter No module named readline robotparser sched ... etc ... whrandom C:\Python24\lib\whrandom.py:38: DeprecationWarning: the whrandom module is deprecated; please use the random module DeprecationWarning) xdrlib xmlrpclib zipfile ... etc ... _threading_local __future__ __phello__.foo Hello world... cannot import module __phello__.foo No module named foo cannot import module __phello__.foo No module named foo number of unreachable objects 0 referrers of __future__ referrers of __future__ ... etc ... referrers of socket asynchat asyncore BaseHTTPServer SocketServer urllib httplib ftplib imaplib nntplib poplib smtpd smtplib Utils ... etc ... referrers of cStringIO logging\__init__ xmlrpclib number of unreachable objects 564 new length of sys.modules 154 121 simple modules [(0, 39), (39, 58), (58, 74), (74, 79), (79, 91), (91, 94)] St Nb. min max median average stddev 0 11 1.0 1.0 1.000 1.000 0.000 11 11 1.0 2.0 1.500 1.545 0.498 22 11 2.0 2.0 2.000 2.000 0.000 33 11 2.0 3.0 2.500 2.455 0.498 44 11 3.0 3.0 3.000 3.000 0.000 55 11 3.0 4.0 3.500 3.727 0.445 66 11 4.0 5.0 4.500 4.273 0.445 77 11 5.0 6.0 5.500 5.818 0.386 88 11 6.0 8.0 7.000 6.909 0.668 99 11 9.0 10.0 9.500 9.545 0.498 110 11 10.0 12.0 11.000 11.182 0.716 121 11 12.0 16.0 14.000 13.818 1.113 132 11 16.0 21.0 18.500 17.636 1.367 143 11 21.0 29.0 25.000 24.818 2.367 154 11 31.0 51.0 41.000 38.364 7.413 165 11 55.0 92.0 73.500 70.636 10.764 176 5 97.0 136.0 116.500 111.400 13.865 modules with a lot of external names : (18, 40, 'cgi') (19, 19, 'cgitb') ... etc ... (72, 72, 'pydoc') (74, 74, 'cookielib') (78, 78, 'urllib2') (86, 86, 'symbol') (92, 92, 'sre_constants') (97, 97, 'xmlrpclib') (101, 118, 'os') (107, 107, 'sre_compile') (116, 116, 'sre_parse') (136, 151, 'socket') Output with python 2.3.3 Linux gives a greater number for socket as the OpenSSL library is wrapped. gc.collect() at the interactive prompt gives 0. (good) Conclusion : sre_compile and sre_parse should be coded with a __all__ attribute The standard library contains a module 'tzparse' which cannot be imported ! Most library modules do not begin with #!/usr/bin/env python and a coding cookie. Regards From just.starting at gmail.com Tue Jan 25 03:38:05 2005 From: just.starting at gmail.com (just starting) Date: Tue, 25 Jan 2005 14:08:05 +0530 Subject: how to call python code from C# In-Reply-To: <41F54FF6.30209@pythonapocrypha.com> References: <8LGdneLOysys1WjcRVn-1Q@powergate.ca> <41F54FF6.30209@pythonapocrypha.com> Message-ID: <3898fa73050125003838dc376c@mail.gmail.com> Thanks for all your kind information. I haven't used COM objects so far.I think now I have to learn it.Anyway thanks a lot again. paritosh. On Mon, 24 Jan 2005 12:43:50 -0700, Dave Brueck wrote: > Peter Hansen wrote: > > paritosh mahana wrote: > > > >> How can I call python code from my C# code. > [snip] > > You could use ctypes or the pywin32 package to provide your > > Python code with an ActiveX interface. Then you could just > > use it via COM, like any other COM object. Lots of references > > available via Google if you want to learn more about this > > approach... > > Lemme add my two cents and say that this approach works well. > > We have a component that uses ctypes and runs as a COM local server (its own > .exe) and we currently use it both from Internet Explorer and from a C# > application. COM can be hairy initially, but if you have any experience with COM > then this approach is pretty straightforward. > > -Dave > -- > http://mail.python.org/mailman/listinfo/python-list > From aleaxit at yahoo.com Sat Jan 22 06:30:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 12:30:36 +0100 Subject: Class introspection and dynamically determining function arguments References: <359lfnF4hd6e3U1@individual.net> <359nmoF4koiepU1@individual.net> Message-ID: <1gqsidn.1n13vyo85fvd7N%aleaxit@yahoo.com> Diez B. Roggisch wrote: > Nick Coghlan wrote: > > > > If this only has to work for classes created for the purpose (rather than > > for an arbitrary class): > > Certainly a step into the direction I meant - but still missing type > declarations. And that's what at least I'd like to see - as otherwise you > don't know what kind of editing widget to use for a property. Though it may be overkill for your needs, you'll be interested in Enthought's "Traits", I think; see, for example, . Facilitating such presentation tasks (no doubt including editing) appears to be a major driving force for Traits. Alex From detlev at die-offenbachs.de Sat Jan 29 12:12:41 2005 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 29 Jan 2005 18:12:41 +0100 Subject: ANN: eric3 3.6.1 released Message-ID: Hi, this is to let all of you know, that eric3 3.6.1 has just been released. It fixes a few nasty bugs, which were reported since the last release. It is available via http://www.die-offenbachs.de/detlev/eric3.html Eric3 is an Integrated Development Environment for Python. For details please see the above mentioned URL. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From oceanwavecn at gmail.com Sun Jan 2 10:03:41 2005 From: oceanwavecn at gmail.com (oceanwave) Date: 2 Jan 2005 07:03:41 -0800 Subject: Gate Oxide thickness of CMOS In-Reply-To: <69fbfcd3.0108291911.76f12106@posting.google.com> References: <69fbfcd3.0108291911.76f12106@posting.google.com> Message-ID: <1104678221.272720.73830@c13g2000cwb.googlegroups.com> it's depend on the various product, 200 Angstrom or 30 Angstrom is possible. the number of mask:15 or 30 ^^^^^^ From jeff at ccvcorp.com Thu Jan 27 20:38:49 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 27 Jan 2005 17:38:49 -0800 Subject: Question about 'None' In-Reply-To: <1106873904.761513.153710@z14g2000cwz.googlegroups.com> References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> <2fCdnYr1l-CZwmTcRVn-ig@comcast.com> <1106873904.761513.153710@z14g2000cwz.googlegroups.com> Message-ID: <10vj5hv8hcn3k9f@corp.supernews.com> flamesrock wrote: > I should also mention that I'm using > version 2.0.1 (schools retro solaris machines :( ) > At home (version 2.3.4) it prints out 'True' for the above code block. That would explain it -- as /F mentioned previously, the special case for None was added in 2.1. Jeff Shannon Technician/Programmer Credit International From spam at nospam.org Thu Jan 27 17:59:45 2005 From: spam at nospam.org (Erik Johnson) Date: Thu, 27 Jan 2005 15:59:45 -0700 Subject: building Python: up arrow broken on SuSE Linux 8.2 References: <41f6c3f7$1@nntp.zianet.com> <41f85dd8@nntp.zianet.com> Message-ID: <41f97058$1@nntp.zianet.com> "Peter Otten" <__peter__ at web.de> wrote... > Have you ensured (with yast) that readline-devel is actually installed? I had not previously, but (not surprisingly) version 4.3 is installed. :) Good idea - I thought maybe I would be able to do an online update (YOU) to it, but it is taking forever to get a patch list. I don't understand it, we have a pretty decent internet connection (DSL). I now have the readline version 5.0 library built locally. Can someone give me some clues about how to get it statically linked? Thanks, -ej From john at grulic.org.ar Tue Jan 18 18:28:14 2005 From: john at grulic.org.ar (John Lenton) Date: Tue, 18 Jan 2005 20:28:14 -0300 Subject: simultaneous multiple requests to very simple database In-Reply-To: References: Message-ID: <20050118232814.GA15780@grulic.org.ar> On Tue, Jan 18, 2005 at 11:26:46AM -0500, Eric S. Johansson wrote: > I have an application where I need a very simple database, effectively a > very large dictionary. The very large dictionary must be accessed from > multiple processes simultaneously. I need to be able to lock records > within the very large dictionary when records are written to. Estimated > number of records will be in the ballpark of 50,000 to 100,000 in his > early phase and 10 times that in the future. Each record will run about > 100 to 150 bytes. > > speed is not a huge concern although I must complete processing in less > than 90 seconds. The longer the delay however the greater number of > processes must be running parallel in order to keep the throughput up. > It's the usual trade-off we have all come to know and love. > > it is not necessary for the dictionary to persist beyond the life of the > parent process although I have another project coming up in which this > would be a good idea. > > at this point, I know they will be some kind souls suggesting various > SQL solutions. While I appreciate the idea, unfortunately I do not have > time to puzzle out yet another component. Someday I will figure it out > because I really liked what I see with SQL lite but unfortunately, today > is not that day (unless they will give me their work, home and cell > phone numbers so I can call when I am stuck. ;-) I'm sure we could agree on a fee for me to do so :) > So the solutions that come to mind are some form of dictionary in shared > memory with locking semaphore scoreboard or a multithreaded process > containing a single database (Python native dictionary, metakit, gdbm??) > and have all of my processes speak to it using xmlrpc which leaves me > with the question of how to make a multithreaded server using stock xmlrpc. berkley db (at least version 3, http://pybsddb.sourceforge.net/) supports multiple readers and writers, with fine-grained locking, it looks like a dictionary, and it isn't sql. The use you have in mind is a bit more complicated than the simple create-me-a-dictionary-in-a-file, but is pretty straightforward. The documentation mostly refers you to the C API, but fortunately it (the C API) is clear and well written. HTH -- John Lenton (john at grulic.org.ar) -- Random fortune: Today is National Existential Ennui Awareness Day. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From irmen at -nospam-remove-this-xs4all.nl Sun Jan 30 09:57:50 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 30 Jan 2005 15:57:50 +0100 Subject: ANN: Frog 1.3 released (python 'blog' application) Message-ID: <41fcf53b$0$28986$e4fe514c@news.xs4all.nl> I've just uploaded the Frog 1.3 release. Frog is a blog (web log) system written in 100% Python. It is a web application written for Snakelets. It outputs XHTML, is fully unicode compatible, small, and doesn't require a database. You can read about it and download it here: http://snakelets.sourceforge.net/frog/ It's 60Kb if you already have Snakelets, otherwise 122Kb. Frog 1.3 uses the same storage format as 1.2 so no conversion is required. If you encounter bugs or problems, or want to give some feedback, please let me know. Enjoy, --Irmen de Jong. PS I'm running Frog for my personal blog, so if you want to see it in action, please visit: http://www.razorvine.net/snake/frog/user/irmen/ (still somewhat experimental and most is in Dutch) From http Wed Jan 12 09:16:48 2005 From: http (Paul Rubin) Date: 12 Jan 2005 06:16:48 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <1105509379.301556.178130@z14g2000cwz.googlegroups.com> Message-ID: <7xoefuenqn.fsf@ruckus.brouhaha.com> michele.simionato at gmail.com writes: > > I can't imagine how it could be worse than the learning curve of > > __metaclass__, which we already have. > > To me, learning macros *and their subtilities* was much more difficult > than learning metaclasses. I guess I've only used Lisp macros in pretty straightforward ways, that weren't hard to understand. That's enough for anything I've needed. But we don't hear much about __metaclass__ because almost nobody understands it. > Go to comp.lang.scheme and google for "macros and module system"; > you will get everything you want to know and much more! OK, I might do this. > Well, I see this as a positive fact. If a syntax is contrived (such > as a ternary operator, for instance) it is better *not* to have it > than to have one hundred custom made syntaxes. At the end, we are > just talking about syntax sugar here, not about lack of > functionality. I think the idea is there would be some experimentation and then one of the versions would make it into the standard library. > > [compiling Lisp to Python bytecode] > This is a bizarre idea if you want to make Python run faster. It is > not so bizarre if what you want is to have access to Python from > Lisp/Scheme in the same sense Jython has access to Java. Why not just use a foreign function interface? From tim.golden at viacom-outdoor.co.uk Thu Jan 20 13:58:25 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 20 Jan 2005 18:58:25 -0000 Subject: Print to Windows default Printer Message-ID: <9A28C052FF32734DACB0A288A35339910359D9@vogbs009.gb.vo.local> [Samantha] | The printer is on LPT1, but I sure can't get the temp file to | print for some | reason. | I am using Windows XP SP2. | S i'm afraid I have to step out here (metaphorically speaking): I'm using Win2K and have no access to XP boxes. The technique works fine here; it may be that either they've removed the functionality under XP, or that there's some security context which is preventing you from accessing the port. Can anyone else try a "PRINT blah" or a "COPY blah LPT1:" on XP SP2? 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 steven.bethard at gmail.com Sun Jan 2 04:22:59 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 02 Jan 2005 09:22:59 GMT Subject: PEP 288 ponderings In-Reply-To: References: Message-ID: Raymond Hettinger wrote: > [Steven Bethard] >>(2) Since in all the examples there's a one-to-one correlation between >>setting a generator attribute and calling the generator's next function, >>aren't these generator attribute assignments basically just trying to >>define the 'next' parameter list? > > They are not the same. The generator needs some way to receive the values. The > function arguments cannot be used because they are needed to create the > generator-iterator. The yield statements likewise won't work because the first > yield is not encountered until well after the first next() call. Yeah, I wasn't trying to claim that passing the arguments to .next() is equivalent to generator attributes, only that the point at which new values for the generator state variables are provided correspond with calls to .next(). So if there was a means within a generator of getting access to the arguments passed to .next(), generator attributes would be unnecessary for the examples provided. > The given examples are minimal and are intended only to demonstrate the idea. Do you have an example where the generator state isn't updated in lock-step with .next() calls? I'd be interested to look at an example of this... >>I definitely don't like the >>idea of a magical __self__ variable that isn't declared anywhere. > > It is no more magical than f.__name__ or f.__doc__ for functions. I'm not sure this is quite a fair parallel. The difference here is that f.__name__ and f.__doc__ are accessed as attributes of the f object, and the __name__ and __doc__ attributes are created as a result of function creation. The proposed __self__ is (1) not an attribute that becomes available, rather, a new binding local to the function, and (2) not created as a result of generator object creation but created as a result of calling .next() on the generator object. > Also, the __self__ argument is a non-issue because there are other alternate > approaches such as providing a function that retrieves the currently > running generator. Is there a discussion of some of these alternate suggested approaches somewhere you could point me to? > The more important part of the PEP is the idea for generator exceptions. The > need arises in the context of flushing/closing resources upon generator > termination. I wonder if maybe it would be worth moving this part to a separate PEP. It seems like it could probably stand on its own merit, and having it in with the generator attributes PEP means it isn't likely to be accepted separately. Of course, I would probably declare a class and provide a .close() method. =) Steve From tim.peters at gmail.com Wed Jan 19 23:54:58 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 19 Jan 2005 23:54:58 -0500 Subject: Zen of Python In-Reply-To: <7xis5szpdj.fsf@ruckus.brouhaha.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> Message-ID: <1f7befae05011920543bb58720@mail.gmail.com> [Paul Rubin] > Huh? [1,2,[3,4,5],[6,[[[[7]],8]]]] is a perfectly valid Python list. You're claiming not to know any relevant difference between Python lists and Lisp lists? Heh. > And you can break out of a containing loop from a nested loop > with try/raise. Heh heh. Yes, you can. I've never seen a real Python program that did, but there's nothing to stop you. What did you think the "direct" in "direct way" might have been intended to mean? > More troublesome is not being able to see a variable in a > containing scope from a nested scope, unless the containing > scope is the global one. Why bother debating lexical scope for > years before deciding to add it, only to stop halfway? I'd call it 80% of the way, but suit yourself. The debates are all easily found, if you really want to know. From devries at idolstarastronomer.com Sun Jan 23 14:43:06 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: Sun, 23 Jan 2005 14:43:06 -0500 Subject: make install with python In-Reply-To: References: <35d4i9F4makucU1@individual.net> Message-ID: <20050123194306.GA1296@miyu.cjas.org> On Sat, Jan 22, 2005 at 01:54:17AM +0100, Uwe Mayer wrote: > Any suggestions how I handle uninstallation? This was provided by automake > rather mechanically. I didn't find a section on that in the distutils > documentation... :( I've been using distutils for a couple of projects I've written for work. Overall I love it as I rarely have to consult documentation (I always need to look at documentation to use autoconf, though I must admit I have only used autoconf/automake on two projects). On the distutils2.0 Wiki page (http://www.python.org/moin/DistUtils20) I found the quote: "Uninstallation is solved as soon as we have an installation database, which is part of what we're trying to do here." -- BobIppolito So it looks like they are working on it. Chris From removethis.kartic.krishnamurthy at gmail.com Thu Jan 20 20:34:17 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Fri, 21 Jan 2005 01:34:17 GMT Subject: Print a string in binary format In-Reply-To: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> Message-ID: neutrino said the following on 1/20/2005 7:53 PM: > Greetings to the Python gurus, > > I have a binary file and wish to see the "raw" content of it. So I open > it in binary mode, and read one byte at a time to a variable, which > will be of the string type. Now the problem is how to print the binary > format of that charater to the standard output. It seems a common task > but I just cannot find the appropriate method from the documentation. > Thanks a lot. Not a guru, but I will try to help out :-) how about this: >>> import binhex >>> binhex.binhex('C:/windows/system32/telnet.exe', 'C:/TEMP/telnet.hex') >>> Now this is what telnet.hex looks like: (This file must be converted with BinHex 4.0) :#R4PE'jPG#jPH'8!2j!)!!!!!4B!N!@9[deDN!!!!`!!!!3!!!$rr`!!Z!#3"d! !N#2J!!!!$Kqk$J#d#FdKZ!&-c5&8D'Pc)("bEfGbB at dJBf&ZEQpd)'*P)(*eEL" TEL"%6e-JE at pNC5i0$3SN!*!(Q$X`mpaDAU$F at PkJh&THS#Cj(U$G at PkJh&TIS'P DAU!QH8HJceTHS%Yj'k$G at PkJ"RP#S-TDAU!'H81Jh9THS#CjBk$G at PkJ8QPMD0a DAU!!N""343!!6!%$!&VGE6d!N!MJ!!m"#`%(!!$!!!!!"J)!N!AQ[3!!!"!!!!$ 3!*!&!3!3!!!!!J!!"3!"!!8!!3!%!*!)i!)!!!3!!&Hl!3!$!!#!!!!%!!!3!*! %%!!!%!#3"K!!N!Z3!-%!!-J!N!5J!J"B1!#3'[!5!!!F!*!M8!)!!-`!N!33!!$ F!J#3'LjdCAKd!!!!rVm!!!!3!!!!`!!!!!3!N!iJ!!"J,Q4KG'%!!!"mb`%!!0! (... Big Snip ...) Or how about this? >>> f = open('C:/windows/system32/telnet.exe', 'rb') >>> fcontents = f.read() >>> import binhex >>> print binhex.binascii.hexlify(fcontents[0:10]) '4d5a9000030000000400' >>> Is this what you want??? Thanks, --Kartic From tzot at sil-tec.gr Mon Jan 3 14:11:10 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 03 Jan 2005 21:11:10 +0200 Subject: BASIC vs Python References: <1103327631.570908.321770@c13g2000cwb.googlegroups.com> Message-ID: <9q5jt09llq0ak9h587d2ctvq29r2ag85t9@4ax.com> On 17 Dec 2004 15:53:51 -0800, rumours say that "ladasky at my-deja.com" might have written: >> The BASICs of my youth also supported graphics and sounds. >> >> PLAY "CGFED>CC >Now wait a minute, shouldn't that be... > >PLAY "CGFED>CC': 2.0} # octave modifier def play(sequence): """Play a sequence of notes.""" octave=1.0 for note in sequence: try: # to play a note winsound.Beep(int(round(notes[note]*octave)), 200) except KeyError: # well, it wasn't octave *= modifiers[note] if __name__ == "__main__": play("CGFED>CC" and "<" for example if I got them correctly). [1] and then I "inherited" a Stride with an 68010 from a student friend who finished studies and got drafted, who himself had it borrowed from the company of a friend of his so that he would develop code that could be used by the company, and in general all my troubles seem to come from exposure to Unix in my puberty, but that's another story :) -- 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 rkern at ucsd.edu Fri Jan 28 20:29:22 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 28 Jan 2005 17:29:22 -0800 Subject: LinearAlgebra incredibly slow for eigenvalue problems In-Reply-To: <1106960619.700424.278180@z14g2000cwz.googlegroups.com> References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> <1106952951.834888.65430@f14g2000cwb.googlegroups.com> <1106957598.136667.45430@z14g2000cwz.googlegroups.com> <1106957760.485860.104760@f14g2000cwb.googlegroups.com> <1106960619.700424.278180@z14g2000cwz.googlegroups.com> Message-ID: drife wrote: > David, > > I noticed that the libraries that ATLAS builds are not shared > objects (e.g., liblapack.a). Should these be shared objects? > I see nothing in the ATLAS documentation about building > things as shared objects. > Wondering if this is why the Numeric install is failing. No, they should work just fine as static libraries. -- 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 peter at engcorp.com Wed Jan 26 10:33:08 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 Jan 2005 10:33:08 -0500 Subject: is there better 32 clock() timing? In-Reply-To: References: <41f61372.1768192005@news.oz.net> Message-ID: Stephen Kellett wrote: >>> that time.clock() is inaccurate. The problem is that the "time.clock()" >>> statement takes several hundred microseconds to execute. > > The statement is incorrect. clock() itself isn't slow, but it is > accessing a resource, the accuracy of which is no better than 1ms. > > There are various timers available, documented and undocumented, all of > which end up at 1ms or 1.1ms, give or take. For anything shorter you > need QueryPerformanceCounter() (but that *is* a slow call), or use the > RDTSC instruction which is fast but gives a count of instruction cycles > executed and is thus not totally accurate (multiple execution pipelines, > plus multithreading considerations). (I've read the five or so following messages you and Bengt have posted, but not in detail so I'm not sure where you're going with all this, but... ) According to the docs for time.clock(), "On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond." Depending on whether you really meant "accuracy" above, and on other things, this is either irrelevant, or contradicts your first statement... -Peter From ncoghlan at iinet.net.au Thu Jan 6 06:58:46 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 06 Jan 2005 21:58:46 +1000 Subject: Deferred expressions (was Re: Lambda as declarative idiom) In-Reply-To: <41dc4099.75876003@news.oz.net> References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> <41dc4099.75876003@news.oz.net> Message-ID: <41DD27F6.6040700@iinet.net.au> Bengt Richter wrote: > I like the fact that 'def' can serve as a mnemonic for 'defer' or 'deferred' ;-) Yeah, me too. I didn't actually notice that until after I'd thought of the phrase. > OTOH, I like concise notation for expressions, and the def and from aren't > really necessary if you can tag the first expression with some syntax marker. > I suggested (: rather than (def since (: is illegal now and won't break anything. True, but I've always liked Python's preference for keywords over punctuation. And 'def' is only 2 characters longer than ':', too. > That is an advantage of having it inside the outer parens, which my (:expr)(params) > couldn't benefit from -- unless I just take your format and substitute ':' for > both def and from: But where does that leave "Python is executable pseudocode"? Compare: (lambda (a, b, c) : f(a) + o(b) - o(c)) (: f(a) + o(b) - o(c) : (a, b, c)) (def f(a) + o(b) - o(c) from (a, b, c)) Which of the above most clearly expresses "defer a functional expression taking arguments a, b, and c"? For comparison, named syntax requires 3 lines, since Guido also wants to remove suite one-liners in Py3k: def f1(a, b, c): return f(a) + o(b) - o(c) f1 Not so bad for a single deferred expression (particularly a not-completely-trivial one like this), but fares significantly worse for simple zero-argument functions, or if you are just setting up a couple of deferred expressions in a function call. There's no more virtue in completely squandering vertical screen real estate than there is in being overly conservative with it. > What was the point of all this again? Pretending lambda goes away without really killing it? ;-) Actually, it was started by the "please don't take our lamdbas!" comments regarding Python 3k. I suggested that one of the problems with lambda is that it is an expression but looks like a one-liner statement ("it's ugly as sin" may have been closer to my actual phrasing), that the syntax would be deservedly rejected if proposed as a new addition to the language, and a more productive response might be to consider nicer alternative syntax that Guido would consider retaining in Python 3k (since it would make sense to try out such a syntax in the Python 2.x series before committing to it for 3.0). Of course, after making that suggestion, my brain decided to start working on its *own* ideas for a more Pythonic syntax (trying to learn from generator expressions), which seemed to set off a few other people :) The name 'deferred expression' is intended to emphasise what I see as the most appropriate application for anonymous functions - using an entire named function statement to defer a simple expression is serious overkill. Recognising this use case was what switched me from "I won't miss lambdas" to "You know, I'd really regret it if they disappeared completely". Basically, I think lambda has a PR problem - its usefulness as a way to defer expression evaluation is obscured by its ugly syntax and its current explanation as "a neutered form of function definition, but at least you can use it in an expression". On backticks, they have a major problem in that many fonts make ` and ' virtually indistinguishable. A secondary problem is that printed text often renders an opening single quote like a backtick. Guido has already mentioned this in one of Python Regrets talks (in the context of the backtick repr syntax). So I don't expect any syntax involving backticks to even be looked at by the BDFL. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From gstoyanoff at gmail.com Thu Jan 27 19:39:01 2005 From: gstoyanoff at gmail.com (g_xo) Date: Thu, 27 Jan 2005 19:39:01 -0500 Subject: Hello Message-ID: Hello everyone, I am a python beginner and look forward to learning the language and working on some interesting projects using it. I was wondering if anybody may help me get access to the news group comp.lang.python I am trying to access it using KNode but I get an "unable to resolve host name" error. Thank you. George +------------------------------------------------+ Linux - the future is free +------------------------------------------------+ From bulba at bulba.com Tue Jan 4 13:13:52 2005 From: bulba at bulba.com (Bulba!) Date: Tue, 04 Jan 2005 19:13:52 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Message-ID: On Sun, 2 Jan 2005 23:59:53 -0800, "Eric Pederson" wrote: >I'm decades behind on economics research, but I remember >modeling clustering based on mass and distance (the gravity model). >On a decision making basis there seems to be an aspect of it that is >binary: (0) either give in to gravity and gain shared advantage as >part of a massive object, or (1) choose an alternate "location" far >enough away not to be much affected by the force of the massive >objects, and try to build "mass" there. I suspect Python is a (1) in >that regard, but I may be wrong. Frankly, I find such models to be built on over-stretched analogies to physics - how _exactly_ is gravity supposed to be an analogy equivalent to economic "forces"? Sure such model can be built - but is it adequate in explaining real-world phenomenons? Analogy tends to be the weakest form of reasoning. I'd be wary of making such analogies. Models like this probably tend to be built by French engineers from this joke: The American and French engineers work together on some product (that would look strange nowadays but it's not impossible in principle). The Americans show the French engineers a working prototype. The French engineers scratch their heads and ask warily: "OK, it works in practice; but will it work in theory?" -- Real world is perfectly indifferent to lies that are the foundation of leftist "thinking". From tjreedy at udel.edu Sat Jan 22 18:36:12 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 Jan 2005 18:36:12 -0500 Subject: need help on need help on generator... References: <63b5e209.0501210558.686f5c10@posting.google.com><1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> <200501221106.49241.francis.girard@free.fr> Message-ID: "Francis Girard" wrote in message news:200501221106.49241.francis.girard at free.fr... >If I understand correctly, Almost... > a "generator" produce something over which you can > iterate with the help of an "iterator". To be exact, the producer is a generator function, a function whose body contains 'yield'. In CPython, the difference after executing the def is that a generator function has a particular flag set. People sometimes shorten 'generator function' to 'generator' as you did, but calling both a factory and its products by the same name is confusing. (For instance, try calling an automobile factory an automobile). >>> def genf(): yield 1 ... >>> genf The result of calling a generator function is a generator, which is one but only one type of iterator. >>> gen = genf() >>> gen >>> dir(gen) [, '__iter__', ' gi_frame', 'gi_running', 'next'] The .__iter__ and .next methods make this an iterator. The two data attributes are for internal use. > Can you iterate (in the strict sense >of an "iterator") over something not generated by a "generator" ? Of course. Again, a generator is one specific type of iterator, where an iterator is anything with the appropriate .__iter__ and .next methods. Terry J. Reedy From jean.rossier at epfl.ch Wed Jan 19 04:40:55 2005 From: jean.rossier at epfl.ch (jean.rossier at epfl.ch) Date: Wed, 19 Jan 2005 10:40:55 +0100 Subject: problem with import pylab from a website Message-ID: <1106127655.41ee2b2758a9a@imapwww.epfl.ch> Hello All, I am facing a problem while importing pylab library(in a .py program file) via web browser however the same program works when I execute it from the command prompt. my configuration : Fedora Core 3 Apache 2.0 python 2.3.4 postgresql 7.3.4 mod_python-3.1.3-5 Error message we get: [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] Traceback (most recent call last):, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/var/www/html/sensor_data/get_graph.py", line 15, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] import pylab, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/pylab.py", line 1, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] from matplotlib.pylab import *, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/matplotlib/pylab.py", line 184, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] from axes import Axes, PolarAxes, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/matplotlib/axes.py", line 14, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] from axis import XAxis, YAxis, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/matplotlib/axis.py", line 20, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] from font_manager import FontProperties, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/matplotlib/font_manager.py", line 942, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] fontManager = FontManager(), referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/matplotlib/font_manager.py", line 786, in __init__, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] rebuild(), referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/matplotlib/font_manager.py", line 780, in rebuild, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] pickle.dump(self.ttfdict, file(ttfcache, 'w')), referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] IOError, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] : , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] [Errno 13] Permission denied: '/usr/share/matplotlib/.ttffont.cache', referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] Premature end of script headers: get_graph.py, referer: http://128.178.156.101/sensor_data/readings.php Thanks in advance. Regards, jean From kartic.krishnamurthy at gmail.com Thu Jan 6 07:10:45 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 6 Jan 2005 04:10:45 -0800 Subject: navigating/changing directories In-Reply-To: References: Message-ID: <1105013445.219752.99060@z14g2000cwz.googlegroups.com> > /this/directory when I exit the script. Is it possible to have a script > that can drop me off into a different directory than where I initiated it > from? Use os.chdir(newpath) So, you can code os.chdir(r'/a/totally/different/directory') and find yourself in /a/totally/different/directory after the script completes. Thanks, --Kartic From steven.bethard at gmail.com Wed Jan 26 15:41:20 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 13:41:20 -0700 Subject: can not use __methods__ In-Reply-To: <1106769790.604491.290680@c13g2000cwb.googlegroups.com> References: <1106769790.604491.290680@c13g2000cwb.googlegroups.com> Message-ID: ajikoe at gmail.com wrote: > I try to use __methods__ in python 2.4 and 2.2 it always fail. > Can some one tell me if I want to itterate the methods in a class and > print it in a string format ( it is possible using __methods__ ). > Is there any replacement? py> class C(object): ... a = 1 ... b = 2 ... def f(self): ... pass ... def g(self): ... pass ... py> import inspect py> for attr, value in C.__dict__.iteritems(): ... if inspect.isroutine(value): ... print attr, value ... g f or: py> for attr, value in vars(C).iteritems(): ... if inspect.isroutine(value): ... print attr, value ... g f or if you want to include special methods: py> for attr in dir(C): ... value = getattr(C, attr) ... if inspect.isroutine(value): ... print attr, value ... __delattr__ __getattribute__ __hash__ __init__ __new__ __reduce__ __reduce_ex__ __repr__ __setattr__ __str__ f g This is probably useful for introspection at the Python prompt, but if you're planning on doing this in your code somewhere, you might present the problem you're trying to solve to the list, because this is likely not the best way to approach it... Steve From john.thingstad at chello.no Fri Jan 14 06:03:15 2005 From: john.thingstad at chello.no (John Thingstad) Date: Fri, 14 Jan 2005 12:03:15 +0100 Subject: huygens lands on titan Message-ID: -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From lee at example.com Wed Jan 5 17:41:15 2005 From: lee at example.com (Lee Harr) Date: Wed, 05 Jan 2005 22:41:15 GMT Subject: get the IP address of a host References: Message-ID: On 2005-01-05, none <""> wrote: > I want to determine the outside (non local, a.k.a. 127.0.0.x) ip > addresses of my host. It seems that the socket module provides me with > some nifty tools for that but I cannot get it to work correctly it seems. > > Can someone enlightened show a light on this: > > import socket > def getipaddr(hostname='default'): > """Given a hostname, perform a standard (forward) lookup and return > a list of IP addresses for that host.""" > if hostname == 'default': > hostname = socket.gethostname() > ips = socket.gethostbyname_ex(hostname)[2] > return [i for i in ips if i.split('.')[0] != '127'][0] > > It does not seem to work on all hosts. Sometimes socket.gethostbyname_ex > only retrieves the 127.0.0.x ip adresses of the local loopback. Does > someone has a more robust solution? > > Targetted OS'es are Windows AND linux/unix. I found that the socket solutions only work if your DNS entries are correct ... which in my case was not true. So I came up with this: import commands ifconfig = '/sbin/ifconfig' # name of ethernet interface iface = 'eth0' # text just before inet address in ifconfig output telltale = 'inet addr:' def my_addr(): cmd = '%s %s' % (ifconfig, iface) output = commands.getoutput(cmd) inet = output.find(telltale) if inet >= 0: start = inet + len(telltale) end = output.find(' ', start) addr = output[start:end] else: addr = '' return addr Basically, it scrapes the output from ifconfig for the actual address assigned to the interface. Works perfectly on FreeBSD and Linux (given the correct configuration). From jjl at pobox.com Sun Jan 30 17:19:23 2005 From: jjl at pobox.com (John J Lee) Date: Sun, 30 Jan 2005 22:19:23 +0000 (GMT) Subject: RFC 2965 cookies, cookielib, and mailman. Message-ID: Just noticed your c.l.py post quoted below. Nobody but me knows or cares about this obscure stuff ;-) so I'm not surprised you got no answer... C. Titus Brown Dec 27 2004, 12:41 pm wrote: [...] > The issue turned out to be that mailman sends out RFC 2965 [1] cookies, > which are by default rejected by cookielib. I don't remotely pretend to > understand the issues involved; hence my post ;). > > A few questions for those more clued in than me: > > * what is the difference between RFC 2965 cookies and others? See "Where can I find out more about the HTTP cookie protocol?" here: http://wwwsearch.sourceforge.net/ClientCookie/ For both very short, slightly longer (first link in that section, to a section of the ClientCookie docs on the cookie standards), and insanely detailed (Kristol's paper) explanations. > * why would mailman implement RFC 2965 cookies over the old format? > (I'm guessing simply because it's the latest/best/format?) Because Barry didn't realise that almost no browsers implement it (and never will), I guess. > * why would cookielib NOT accept RFC 2965 cookies by default? See above: browsers don't implement it. It's essentially dead as an internet standard. The only real standard is "what IE and Mozilla do", plus some wisdom from RFCs 2109, 2965 and (more readably!) 2964. [...] > In any case, the way to make the cookielib example work for mailman is > like so: > > policy = cookielib.DefaultCookiePolicy(rfc2965=True) > cj = cookielib.LWPCookieJar('cookies.lwp', policy=policy) Hmm, cookielib should work if IE and Mozilla do, so that's a bug :( You shouldn't need to turn on 2965 handling. Do you have a script that demonstrates the problem, so I can fix it? Thanks John From mambuhl at earthlink.net Fri Jan 28 19:02:07 2005 From: mambuhl at earthlink.net (Martin Ambuhl) Date: Fri, 28 Jan 2005 19:02:07 -0500 Subject: what's OOP's jargons and complexities? In-Reply-To: References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: <360244F4lolueU1@individual.net> Dan Perl wrote: > Actually, it can be as simple as: > public class test { There is no "public" or "class" in C. Please don't post such trash to comp.lang.c. In fact, C++ is not topical in any of the five newsgroups you posted to. I don't know where you're posting from, so I apologize to the perl, python, lisp, scheme, and C people who see this in their newsgroups. Followup-To set to comp.lang.c++ where you can play with your bloated language all you wish. From jeff at ccvcorp.com Fri Jan 7 14:33:42 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 07 Jan 2005 11:33:42 -0800 Subject: The Industry choice In-Reply-To: <7xhdluuq3k.fsf@ruckus.brouhaha.com> References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <10trej2fl8dip65@corp.supernews.com> <7xhdluuq3k.fsf@ruckus.brouhaha.com> Message-ID: <10ttomdd6mp7711@corp.supernews.com> Paul Rubin wrote: > Jeff Shannon writes: > >>Note that the so-called 'viral' nature of GPL code only applies to >>*modifications you make* to the GPL software. > > > Well, only under an unusually broad notion of "modification". True enough. It can be difficult, in software development, to define a distiction between a situation where two software products are distinct but cooperative, and a situation where one software product is derivative of another. Stallman has chosen a particular definition for use in the GPL; one may debate the value of using this definition over any other possible definition, but the line had to be drawn *somewhere*. (And given Stallman's philosophies, it shouldn't be too surprising that he's drawn it about as broadly as he reasonably could.) >>(Problems may come if someone licenses a library under the GPL; that's >>what the LGPL was invented for. But the issue here is not that the >>GPL is bad, it's that the author used the wrong form of it.) > > > The "problem" is not a problem except that in the case of some > libraries, simply being able to use a library module is often not > enough incentive to GPL a large application if the library module's > functionality is available some other way (including by > reimplemntation). If the library does something really unique and > difficult, there's more reason to GPL it instead of LGPL'ing it. To my mind, the intent of the GPL is "use it, but if you change it or make a derivative, share the changes". With libraries, though, you *can't* use it without hitting the FSF-specified definition of a derivative. The LGPL exists to make it clear that, for libraries, the common meaning of "using" and "changing" are different than they are for applications. Of course, there's nothing that stops people from insisting that, if you *use* their libraries, anything you use them for must be free-as-in-speech (which is the effect of using the GPL instead of the LGPL); it's the author's choice what restrictions should be put on the software. But the usage-restrictions on a library under GPL are more severe than they are on an application under GPL. The unfortunate thing, in my opinion, is that a fair number of library authors don't think about that when they GPL their code. Jeff Shannon Technician/Programmer Credit International From cartermark46 at ukmail.com Mon Jan 10 06:22:57 2005 From: cartermark46 at ukmail.com (Mark Carter) Date: Mon, 10 Jan 2005 11:22:57 +0000 Subject: Port blocking Message-ID: <34f6sgF4asjm7U1@individual.net> Supposing I decide to write a server-side application using something like corba or pyro. What's the chance that in big corporations, the client's ports (in both senses of the word: fee-paying, and application) will be blocked, thereby immediately scuppering whatever I have written? Has this problem ever arisen for anyone? Also, is there a good tool for writing database UIs? From dhwild at argonet.co.uk Fri Jan 28 15:41:36 2005 From: dhwild at argonet.co.uk (David H Wild) Date: Fri, 28 Jan 2005 20:41:36 +0000 (GMT) Subject: Talking to the wind References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> <1106875259.426213.252030@z14g2000cwz.googlegroups.com> Message-ID: <4d3481485adhwild@argonet.co.uk> In article , Terry Reedy wrote: > > Xah Lee, > > > > Do you want to be taken seriously? > > First, stop posting. > > Second, learn perl. > > Third, learn python. > Hey all, I have seen no evidence that XL even reads the responses that > have been directed thereto. The above is like > /dev/null, > Why don't you ever answer the messages I keep sending to you? He's been in my killfile for quite some time. If **everyone** ignored him, this newsgroup would be a better place. :-)) -- __ __ __ __ __ ___ _____________________________________________ |__||__)/ __/ \|\ ||_ | / Acorn StrongArm Risc_PC | || \\__/\__/| \||__ | /...Internet access for all Acorn RISC machines ___________________________/ dhwild at argonet.co.uk From apardon at forel.vub.ac.be Fri Jan 14 03:24:17 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Jan 2005 08:24:17 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-01-13, Terry Reedy schreef : > > "Antoon Pardon" wrote in message > news:slrncucmeo.5qu.apardon at rcpc42.vub.ac.be... >> Op 2005-01-13, Fredrik Lundh schreef : >>> Antoon Pardon wrote: >>> >>>> Well, it seems that Guido is wrong then. The documentation clearly >>>> states that an expression is a statement. >>> >>> no, it says that an expression statement is a statement. if you don't >>> understand the difference, please *plonk* yourself. >> >> And what else is an expression statement but an expression (list) used >> as a statement. > > Whereas an expression used within a statement is not a statement, and that > is the difference. > > And of course, statements, in general, are not expressions and are not used > within statements (except within compound statements). Here you are stating the opposite of what Guido is supposed to have said. IMO we have a: dogs are mamals kind of relationship in Python. Every expression can be used where a statement is expected. (And this can be worded as: every expression is a statement.) Not every statement can be used where an expression is expected. -- Antoon Pardon From max at alcyone.com Mon Jan 24 17:01:39 2005 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Jan 2005 14:01:39 -0800 Subject: Looking for Form Feeds In-Reply-To: References: Message-ID: Greg Lindstrom wrote: > I have a file generated by an HP-9000 running Unix containing form feeds > signified by ^M^L. I am trying to scan for the linefeed to signal > certain processing to be performed but can not get the regex to "see" > it. Suppose I read my input line into a variable named "input" > > The following does not seem to work... > input = input_file.readline() > if re.match('\f', input): print 'Found a formfeed!' > else: print 'No linefeed!' > > I also tried to create a ^M^L (typed in as Q M L) but that > gives me a syntax error when I try to run the program (re does not like > the control characters, I guess). Is it possible for me to pull out the > formfeeds in a straightforward manner? What's happening is that you're using .match, so you're only checking for matches at the _start_ of the string, not anywhere within it. It's easier than you think actually; you're just looking for substrings, so searching with .find on strings is probably sufficient: if line.find('\f') >= 0: ... If you want to look for ^M^L, that'd be '\r\f': if line.find('\r\f') >= 0: ... If you want to keep a running count, you can use .count, which will count the number of substrings in the line. -- 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 would have liked to have seen Montana. -- Capt. Vasily Borodin From http Mon Jan 10 00:29:26 2005 From: http (Paul Rubin) Date: 09 Jan 2005 21:29:26 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> <7xvfa53obd.fsf@ruckus.brouhaha.com> Message-ID: <7x3bx9c0nd.fsf@ruckus.brouhaha.com> Arich Chanachai writes: > > And I think Pypy is currently set up to compile Python > >into Pyrex and then run the Pyrex results through GCC. > > > But of course, who's going to argue that Pyrex produces "compiled > Python"? Pyrex produces compiled Python in the same sense that asm produces "compiled C". PyPy contains a Python compiler which reads Python source and produces Pyrex output. The Pyrex output then gets compiled by the Pyrex compiler and then the C compiler before ending up with machine code. There is nothing terribly bizarre about this kind of compiler. For example, Gnu Common Lisp compiles Lisp code into C, then runs the C code through gcc. For that matter, the Yacc/Bison parser generators do something similiar. From timr at probo.com Sun Jan 9 03:05:51 2005 From: timr at probo.com (Tim Roberts) Date: Sun, 09 Jan 2005 00:05:51 -0800 Subject: Getting rid of "self." References: Message-ID: BJ?rn Lindqvist wrote: >I think it would be cool if you could refer to instance variables >without prefixing with "self." I know noone else thinks like me so >Python will never be changed, but maybe you can already do it with >Python today? > >.import sys >. >.def magic(): >. s = "" >. for var in sys._getframe(1).f_locals["self"].__dict__: >. s += var + " = self." + var + "\n" >. return s >. >.class A: >. def __init__(self): >. self.hi = "yo" >. >. def meth(self): >. exec(magic()) >. print hi >. >.a = A() >.a.meth() > >It works! exec(magic()) does the needed hi = self.hi. Does it? class A: def __init__(self): self.hi = "yo" def meth(self): exec(magic()) print hi hi = "baby" print hi def other(self): exec(magic()) print hi a = A() a.meth() a.other() That's way too fragile to be useful. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dan.gass at gmail.com Sun Jan 30 21:04:58 2005 From: dan.gass at gmail.com (Dan Gass) Date: Sun, 30 Jan 2005 20:04:58 -0600 Subject: [Python-Announce] cfgparse v01_00 released Message-ID: I'm pleased to announce the initial release of cfgparse (V01_00) Background ------------------------------------------------------------- cfgparse is a more convenient, flexible, and powerful module for parsing configuration files than the standard library ConfigParser module. cfgparse uses a more declarative style modelled after the popular optparse standard library module. cfgparse can optionally cooperate with the optparse module to provide coordination between command line and configuration file options. In addition, the cooperation can be used to allow the user to control features of the parser from the command line. URLs ------------------------------------------------------------- Docs/home page: http://cfgparse.sourceforge.net/ Download: http://sourceforge.net/projects/cfgparse/ Feature Summary ------------------------------------------------------------- + Simple ini style configuration syntax + Type checking with error handling and help messages + Help summary modelled after that in optparse + Round trip - read, modify, write configuration files with comment retention + Cooperates with optparse for configuration file options that should be overridden by command line options + Supports heirarchically organized option settings * User may store multiple option settings in a arbitrarily deep keyed dictionary. * Application uses a key list to walk into the dictionary to obtain a setting. * User controls key list with setting in configuration file. * Supports adding keys to the list through a command line option or from environment variables. + Supports allowing user control of configuration files used. * Environment variables may be used to allow user to specify a default configuration file. * Command line options to specify configuration file supported. * Configuration files may include other configuration files where where sections are read in parallel. * Configuration files may be nested heirarchically by including configuration files from within a section or subsection. + Configuration files may alternatively be written in Python. * full power and flexibility of Python available for creation of option settings * allows options settings to be real Python objects * this feature is NOT enabled by default + May be extended to support syntax such as XML. Enjoy, Dan Gass From fredrik at pythonware.com Mon Jan 24 02:22:53 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 08:22:53 +0100 Subject: Asynchronous event handling...? References: Message-ID: Chris Line wrote: > When the 'stop' button is selected after 'count', it does > not execute until the count command finishes at 500. > Instead, it is desired to stop counting immediately and > execute the 'stop' method. > > Is there a simple way to handle this situation? calling self.update() at regular intervals inside the loop (at least a couple of times per second, if you can arrange that) will give Tkinter a chance to process incoming events. another possibility is to use a thread to do the processing, but that involves other tricky issues (especially if you want to update the UI from the thread). From fredrik at pythonware.com Wed Jan 12 18:19:49 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Jan 2005 00:19:49 +0100 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: Chris Lasher wrote: > Since the file I'm working with contains tens of thousands of these > records, I believe I need to find a way to hash this file such that I > can retrieve the respective sequence more quickly than I could by > parsing through the file request-by-request. However, I'm very new to > Python and am still very low on the learning curve for programming and > algorithms in general; while I'm certain there are ubiquitous > algorithms for this type of problem, I don't know what they are or > where to look for them. So I turn to the gurus and accost you for help > once again. :-) If you could help me figure out how to code a solution > that won't be a resource whore, I'd be _very_ grateful. (I'd prefer to > keep it in Python only, even though I know interaction with a > relational database would provide the fastest method--the group I'm > trying to write this for does not have access to a RDBMS.) keeping an index in memory might be reasonable. the following class creates an index file by scanning the FASTA file, and uses the "marshal" module to save it to disk. if the index file already exists, it's used as is. to regenerate the index, just remove the index file, and run the program again. import os, marshal class FASTA: def __init__(self, file): self.file = open(file) self.checkindex() def __getitem__(self, key): try: pos = self.index[key] except KeyError: raise IndexError("no such item") else: f = self.file f.seek(pos) header = f.readline() assert ">" + header + "\n" data = [] while 1: line = f.readline() if not line or line[0] == ">": break data.append(line) return data def checkindex(self): indexfile = self.file.name + ".index" try: self.index = marshal.load(open(indexfile, "rb")) except IOError: print "building index..." index = {} # scan the file f = self.file f.seek(0) while 1: pos = f.tell() line = f.readline() if not line: break if line[0] == ">": # save offset to header line header = line[1:].strip() index[header] = pos # save index to disk f = open(indexfile, "wb") marshal.dump(index, f) f.close() self.index = index db = FASTA("myfastafile.dat") print db["CW127_A02"] ['TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAG... tweak as necessary. From vincent at visualtrans.de Mon Jan 3 15:10:43 2005 From: vincent at visualtrans.de (vincent wehren) Date: Mon, 03 Jan 2005 21:10:43 +0100 Subject: Developing Commercial Applications in Python In-Reply-To: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: eeykay at gmail.com wrote: > Hello All, > I am trying to convince my client to use Python in his new product. He > is worried about the license issues. Can somebody there to point me any > good commercial applications developed using python ?. The licence > clearly says Python can be used for commercial applications. Is there > any other implications like that of GPL to make the source open ? > Thanks for any help. > eeykay At CSB-System AG, we use Python extensively as embedded scripting language throughout the ERP system we develop (fields of application: system automation, GUI scripting, programmable user exits, reporting, data access/replication, autotests, and apart from that, everywhere we need something done fast ;-). I'm sure that its liberal license was among the main drivers to use it in the first place! -- Vincent Wehren From simon.alexandre at cetic.be Tue Jan 11 08:17:42 2005 From: simon.alexandre at cetic.be (simon.alexandre) Date: Tue, 11 Jan 2005 14:17:42 +0100 Subject: [csv module] duplication of end of line character in output file generated References: <41e3ceb6$1_3@newspeer2.tds.net> Message-ID: ok thanks it works S. "Kent Johnson" a ?crit dans le message de news:41e3ceb6$1_3 at newspeer2.tds.net... > simon.alexandre wrote: > > Hi all, > > > > I use csv module included in python 2.3. I use the writer and encouter the > > following problem: in my output file (.csv) there is a duplication of the > > end of line character, so when I open the csv file in Ms-Excel a blank line > > is inserted between each data line. > > From the docs for csv.writer(): > writer( csvfile[, dialect='excel'[, fmtparam]]) > ...If csvfile is a file object, it must be opened with the 'b' flag on platforms where that > makes a difference. > > Windows is a "platform where that makes a difference." So try > self.writer = csv.writer(file("Test.csv", "wb")) > > Kent > > > > > OS: W2k > > > > Someone has an idea ? > > > > thanks in advance > > > > the source code is the following: > > > > --------------------------------------------------> > > import csv > > > > class CsvDumper: > > > > def __init__(self): > > self.object = > > [['la','mb','mc','md'],['ma','mb','mc','md'],['ma','mb','mc','md']] > > self.writer = csv.writer(file("Test.csv", "w")) > > > > def DumpCsvFile(self): > > for row in self.object: > > self.writer.writerow(row) > > > > c = CsvDumper() > > c.DumpCsvFile() > > > > From daranrife at yahoo.com Fri Jan 28 17:55:51 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 14:55:51 -0800 Subject: LinearAlgebra incredibly slow for eigenvalue problems In-Reply-To: References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> Message-ID: <1106952951.834888.65430@f14g2000cwb.googlegroups.com> Hi David, I performed the above check, and sure enough, Numeric is --not-- linked to the ATLAS libraries. I followed each of your steps outlined above, and Numeric still is not linking to the ATLAS libraries. My setup.py file is attached below. Thanks , Daran --#!/usr/bin/env python # To use: # python setup.py install # or: # python setup.py bdist_rpm (you'll end up with RPMs in dist) # import os, sys, string, re from glob import glob if not hasattr(sys, 'version_info') or sys.version_info < (2,0,0,'alpha',0): raise SystemExit, "Python 2.0 or later required to build Numeric." import distutils from distutils.core import setup, Extension # Get all version numbers execfile(os.path.join('Lib','numeric_version.py')) numeric_version = version execfile(os.path.join('Packages', 'MA', 'Lib', 'MA_version.py')) MA_version = version headers = glob (os.path.join ("Include","Numeric","*.h")) extra_compile_args = [] # You could put "-O4" etc. here. mathlibs = ['m'] define_macros = [('HAVE_INVERSE_HYPERBOLIC',None)] undef_macros = [] # You might need to add a case here for your system if sys.platform in ['win32']: mathlibs = [] define_macros = [] undef_macros = ['HAVE_INVERSE_HYPERBOLIC'] elif sys.platform in ['mac', 'beos5']: mathlibs = [] # delete all but the first one in this list if using your own LAPACK/BLAS sourcelist = [os.path.join('Src', 'lapack_litemodule.c')] # set these to use your own BLAS; library_dirs_list = ['/d2/lib/atlas'] libraries_list = ['lapack', 'ptcblas', 'ptf77blas', 'atlas', 'g2c'] # set to true (1), if you also want BLAS optimized matrixmultiply/dot/innerproduct use_dotblas = 1 include_dirs = ['/d2/include'] # You may need to set this to find cblas.h # e.g. on UNIX using ATLAS this should be ['/usr/include/atlas'] extra_link_args = [] # for MacOS X to link against vecLib if present VECLIB_PATH = '/System/Library/Frameworks/vecLib.framework' if os.path.exists(VECLIB_PATH): extra_link_args = ['-framework', 'vecLib'] include_dirs = [os.path.join(VECLIB_PATH, 'Headers')] # The packages are split in this way to allow future optional inclusion # Numeric package packages = [''] package_dir = {'': 'Lib'} include_dirs.append('Include') ext_modules = [ Extension('_numpy', [os.path.join('Src', '_numpymodule.c'), os.path.join('Src', 'arrayobject.c'), os.path.join('Src', 'ufuncobject.c')], extra_compile_args = extra_compile_args), Extension('multiarray', [os.path.join('Src', 'multiarraymodule.c')], extra_compile_args = extra_compile_args), Extension('umath', [os.path.join('Src', 'umathmodule.c')], libraries = mathlibs, define_macros = define_macros, undef_macros = undef_macros, extra_compile_args = extra_compile_args), Extension('arrayfns', [os.path.join('Src', 'arrayfnsmodule.c')], extra_compile_args = extra_compile_args), Extension('ranlib', [os.path.join('Src', 'ranlibmodule.c'), os.path.join('Src', 'ranlib.c'), os.path.join('Src', 'com.c'), os.path.join('Src', 'linpack.c')], extra_compile_args = extra_compile_args), Extension('lapack_lite', sourcelist, library_dirs = library_dirs_list, libraries = libraries_list, extra_link_args = extra_link_args, extra_compile_args = extra_compile_args) ] # add FFT package (optional) packages.append('FFT') package_dir['FFT'] = os.path.join('Packages','FFT','Lib') include_dirs.append(os.path.join('Packages','FFT','Include')) ext_modules.append(Extension('FFT.fftpack', [os.path.join('Packages','FFT','Src', 'fftpackmodule.c'), os.path.join('Packages', 'FFT', 'Src', 'fftpack.c')], extra_compile_args = extra_compile_args)) # add MA package (optional) packages.append('MA') package_dir['MA'] = os.path.join('Packages', 'MA', 'Lib') # add RNG package (optional) packages.append('RNG') packages.append('RNG') package_dir['RNG'] = os.path.join('Packages', 'RNG', 'Lib') include_dirs.append(os.path.join('Packages', 'RNG', 'Include')) ext_modules.append(Extension('RNG.RNG', [os.path.join('Packages', 'RNG', 'Src', 'RNGmodule.c'), os.path.join('Packages', 'RNG', 'Src', 'ranf.c'), os.path.join('Packages', 'RNG', 'Src', 'pmath_rng.c')], extra_compile_args = extra_compile_args)) # add dotblas package (optional) if use_dotblas: packages.append('dotblas') package_dir['dotblas'] = os.path.join('Packages', 'dotblas', 'dotblas') ext_modules.append(Extension('_dotblas', [os.path.join('Packages', 'dotblas', 'dotblas', '_dotblas.c')], library_dirs = library_dirs_list, libraries = libraries_list, extra_compile_args=extra_compile_args)) long_description = """ Numerical Extension to Python with subpackages. The authors and maintainers of the subpackages are: FFTPACK-3.1 maintainer = "Numerical Python Developers" maintainer_email = "numpy-discussion at lists.sourceforge.net" description = "Fast Fourier Transforms" url = "http://numpy.sourceforge.net" MA-%s author = "Paul F. Dubois" description = "Masked Array facility" maintainer = "Paul F. Dubois" maintainer_email = "dubois at users.sf.net" url = "http://sourceforge.net/projects/numpy" RNG-3.1 author = "Lee Busby, Paul F. Dubois, Fred Fritsch" maintainer = "Paul F. Dubois" maintainer_email = "dubois at users.sf.net" description = "Cray-like Random number package." """ % (MA_version, ) # Oops, another bug in Distutils!? # Write rpm_build.sh pointing to this python rpm_build_text="""env CFLAGS="$RPM_OPT_FLAGS" %setup.py build\n""" % sys.executable rpm_script = open("rpm_build.sh", "w") rpm_script.write(rpm_build_text) rpm_script.close() # Write rpm_install.sh pointing to this python rpm_install_text=sys.executable +""" setup.py install --root=$RPM_BUILD_ROOT cat >INSTALLED_FILES <>INSTALLED_FILES """ rpm_script = open("rpm_install.sh", "w") rpm_script.write(rpm_install_text) rpm_script.close() setup (name = "Numeric", version = numeric_version, maintainer = "Numerical Python Developers", maintainer_email = "numpy-developers at lists.sourceforge.net", description = "Numerical Extension to Python", long_description = long_description, url = "http://numpy.sourceforge.net", # distutils allows you to fix or fudge anything :-) extra_path = 'Numeric', packages = packages, package_dir = package_dir, headers = headers, include_dirs = include_dirs, ext_modules = ext_modules ) print 'MA Version', MA_version print 'Numeric Version', numeric_version From peter at engcorp.com Tue Jan 18 01:00:18 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Jan 2005 01:00:18 -0500 Subject: python execution path In-Reply-To: <1106027652.064860.12650@z14g2000cwz.googlegroups.com> References: <1106027652.064860.12650@z14g2000cwz.googlegroups.com> Message-ID: qhfgva at gmail.com wrote: > Peter Hansen wrote: >>The best approach, if it's really intended to be a debugging >>aid, might be to learn about "pdb" .... > > This is more of a what if-ish question I guess. I use pdb fairly > regularly, I'm just looking to extend my debugging toolkit. I saw an > article recently about how perl has the sh -x type functionality and I > was curious if anything like that was possible in python. Not entirely > sure how it would make my life better, but it seems intriguing. Ah. In that case, investigate sys.settrace(). There are doubtless a variety of recipes and snippets available in either the Cookbook or in the mailing list archives, after you do the basic reading in http://www.python.org/doc/2.4/lib/module-sys.html . -Peter From skip at pobox.com Thu Jan 6 21:02:44 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 6 Jan 2005 20:02:44 -0600 Subject: Please Contribute Python Documentation! In-Reply-To: <10to8qulnc3vke1@news.supernews.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> Message-ID: <16861.60868.409947.889215@montanaro.dyndns.org> I'm changing the subject so that hopefully people who have long ago tuned out the "Python evolution: Unease" subject will read this note. John> I would like to contribute some documentation to Python. I've got John> the time, I write quite a bit, etc. I've got fairly strong John> opinions about some things that need to be documented, (such as John> all the new style class descriptor stuff from 2.2) and I have John> relatively little difficulty matching the existing style. John> However, I don't know TEX, Latex, CVS or Sourceforge. (The latter John> two are on my "learn sometime soon so I can put PyFIT where it John> belongs" list.) John> I have no desire to install Perl to run the documentation John> toolchain. I also have no particular desire to write up a bunch John> of final format stuff and drop it on someone else to put into the John> latex format so it can be included. I'm really not picking on John. I just happen to be replying to his message. Others have echoed sentiments similar to his. Let me emphasize this. You do not (repeat, *do not*) need to install any tools to contribute content to the documentation. Just whip out your favorite text editor and type plain old text. There are plenty of us around who know enough LaTeX to markup anything you contribute. Don't let lack of a specific set of tools be a barrier to contribution! The preferred way to submit documentation changes is by submitting a patch to the Python project on SourceForge: http://sourceforge.net/projects/python If you discover an error that requires little more than calling attention to the problem (or if you don't know how to fix it), just submit a bug report instead of a patch. In either case, select "Documentation" as the category. There is no need to assign it to anyone. It will get seen shortly. The correctness of a documentation fix is generally easier to verify than that for a code fix, so they tend to get applied pretty quickly. The only (small) barrier to submitting bug reports and patches via SourceForge is that you must register first. We used to allow anonymous reports but found that too often they were incomplete and required further input. With no way to contact the submitter of an anonymous report we had no choice but to hope they returned to check for progress. That only happened rarely, so the usual resolution was simply to delete the report. Fred Drake releases new development versions of the docs frequently (typically once every month or two). I normally use the development docs instead of the regular ones for my day-to-day work. They are available here: http://www.python.org/dev/doc/devel/ It's useful to check to see the most current status of the docs. The only thing more current is the source in CVS. Skip From rparnes at megalink.net Sat Jan 29 07:58:57 2005 From: rparnes at megalink.net (Bob Parnes) Date: Sat, 29 Jan 2005 12:58:57 -0000 Subject: Maximum Number of Class Attributes References: Message-ID: On Wed, 26 Jan 2005 10:03:47 +0100, Sylvain Thenault wrote: > On Wed, 26 Jan 2005 02:03:12 +0000, Bob Parnes wrote: > >> In its default configuration, my version of pylint (0.5.0) sets the >> maximum number of class attributes at 7. This seems low to me, but I can >> see how an excessive number might make maintenance more difficult. Is this >> indeed the best value for a maximum under ordinary conditions? If not, can >> anyone suggest a more reasonable value? > > well, this value is very subjective, and may change from one context to > another... For instance at some point I hope that pylint will detect "GUI" > classes and allow more attributes (and methods?) to those. > Anyway that's just an indicator, not a rule of thumb (and pylint itself > has some class with more than 7 attributes...). > > And FYI, this value has been taken from a post to the > testdrivendevelopment at yahoogroups (as most others default values in the > "design analysis" checker). Hum, well... After checking it seems that the > post said 20 attributes. I don't remember why did i get this number down > to 7. If this discussion leads to an agreement for a better number, I > can change the default value. > > -- > Sylvain Th?nault LOGILAB, Paris (France). > > http://www.logilab.com http://www.logilab.fr http://www.logilab.org > > Thanks for the information. I *am* using gui classes. -- Bob Parnes rparnes at megalink.net From martin at v.loewis.de Tue Jan 4 03:44:49 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 04 Jan 2005 09:44:49 +0100 Subject: Using ICL to compile C extensions In-Reply-To: <1104815892.984903.182190@f14g2000cwb.googlegroups.com> References: <1104815892.984903.182190@f14g2000cwb.googlegroups.com> Message-ID: <41da5779$0$1652$9b622d9e@news.freenet.de> dayzman at hotmail.com wrote: > Does anyone know how I can use "icl" (Intel C++) to compile C > extensions? I'm on Windows, and my Python is compiled using VS7.1 > (binary distribution). Right now, when I run setup.py install, it uses > cl.exe (MSVC++ Toolkit 2003), and I would like to use icl because > MSVC++ 2003 does not support C99. It should be possible to use this compiler, as long as you can link to msvcr71.dll (i.e. as long as you have header files of the MS C library, and an import library that links to msvcr71). Whether you can use distutils to run the build process is a different issue - you might need to extend distutils. Regards, Martin From aahz at pythoncraft.com Tue Jan 4 10:12:05 2005 From: aahz at pythoncraft.com (Aahz) Date: 4 Jan 2005 10:12:05 -0500 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1104830276.579755.133870@f14g2000cwb.googlegroups.com> <7x652dk0gh.fsf@ruckus.brouhaha.com> <1104831798.408560.228940@c13g2000cwb.googlegroups.com> Message-ID: In article <1104831798.408560.228940 at c13g2000cwb.googlegroups.com>, wrote: > >Maybe a PSF grant would help? I guess this has been considered ... The first three PSF grants were all in some way not directly related to changing the core language. One was for a library, one for improving Jython, and one for improving docs. Giving the PSF more money increases the chances for additional work. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From steve at holdenweb.com Mon Jan 31 09:37:04 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 09:37:04 -0500 Subject: Want to meet any of these people? They are registered for PyCon Message-ID: In accordance with PyCon's privacy policy, there are currently 29 PyCon registrants who have asked that their names not be published. The remainder, however, are listed here just in case you've ever wanted to meet any of them, and could do so by registering for PyCon at http://www.python.org/pycon/2005/register.html Note that the sort order isn't perfect - I just sorted on the second "word" in each name. PyCon is a *great* place to meet people and discuss ideas. Hope to see you there. regards Steve Chris Akre Brad Allen Kevin Altis Ummesalma Amil Stephen Apiki Dan Arico Larry Austin Suresh Babu Eddala Jim Baker Amir Bakhtiar Greg Barr Facundo Batista Anton Benard Thomas Bennett Bill Bergmann Ian Bicking Brian Bilbrey David Binger Zachery Bir Matthew Blecker Chris Blunck Ben Bodner Jonah Bossewitch Ivo Busko Theodore C. Pollari Matthew Cahn JP Calderone Brett Cannon Katie Capps Parlante Vern Ceder Michael Chermside Martin Chilvers Anders Chrigstrom Daniel Chudnov Tom Cocagne Eric Coffman Kevin Cole Tim Couper Matt Croydon Kevin Cully Andrew Dalke R. David Murray Zoltan Deak Stephan Deibel Catherine Devlin Cory Dodt Bruce Donald Campbell Brian Dorsey Scott Downie Fred Drake Matt Drew Michael Droettboom Reggie Dugard Donovan Eastman Bruce Eckel John Ehresman Alan Elkner Jeffrey Elkner Richard Emslie Mathieu Fenniak Robert Ferguson Abe Fettig Russell Finn Timothy Fitz Mike Fletcher Alec Flett Paul Flint Mitchell Foral Doug Fort Robin Friedrich Phil Frost Jim Fulton Patrick Garrett Philip Gaudette David Geller Grig Gheorghiu Christopher Gillett John Goebel Matthew Good David Goodger Nat Goodspeed Perry Greenfield Joe Grossberg David Grumm Walter H. Rauser Warren Hack Walker Hale IV Jacob Hallen David Hancock Andrew Harrington Travis Hartwell Randy Heiland Mark Hertel Raymond Hettinger Rob Hill Tom Hoffman Steve Holden Jim Hugunin John Hunter Jeremy Hylton Bob Ippolito Joseph J. Pamer Kevin Jacobs Vineet Jain Michael Johnson Eric Jones Evan Jones Ian Jones Richard Jones Francisco Juarez Patrick K. O'Brien Jacob Kaplan-Moss Don Kauffman David Keeney Peter Kessler Shahthureen Khan Brian Kirsch Sally Kleinfeldt Josheph Kocherhans Jeff Kowalczyk Daniel Krech Kartic Krishnamurthy Peter Kropf Andrew Kuchling Bob Kuehne Jeff Kunce Lloyd Kvam Jason L Asbahr MAN-YONG LEE Cameron Laird LD Landis Jukka Laurila Aaron Lav Phil Lawrence Edward Leafe Charles Leake Glyph Lefkowitz Ted Leung Michelle Levesque Bailing Li Greg Lindstrom Yihsiang Liow Peter Lyons John M. Camara Matthew MacInnes Andrew MacKeith Bryan MacRae Brian Mahoney Alex Martelli Andrej Masiar Peter Masiar Roger Masse Mark McClain Alan McIntyre Michael McLay Paul McNett Simon Michael Charles Moad Andrew Moore David Morrill David Muffley Edward Muller Robin Munn Eric Newton Edward Ng Rob Nichols Nestor Nissen Greg Noble Neal Norwitz Peter Olsen Mike Orr Brad Palmquist Guy Pardoe Bob Parks Thomas Parsli Anders Pearson Joel Pearson Samuele Pedroni Dave Perkins Tim Peters Carl Phillips Charles Phillips John Pinner Mike Pirnat Patrick Power Mark Pratt Kashif Qureshi James R Hall-Morrison Michael R. Bernstein Douglas R. Caldwell Andrew R. Gross Robert R. Knight Christian R. Simms Anna Ravenscroft Jimmy Retzlaff John Rhodes Anthony Rhudd Armin Rigo Nicholas Riley Arnaldo Riquelme Tracy Ruggles Jeff Rush Ollie Rutherfurd Dr. S. Candelaria de Ram Mike Salib Prasan Samtani Michel Sanner Phil Schumm Bill Sconce Chris Shenton Allen Short Jim Sizelove Brian Skahan Erik Smartt Garrett Smith Jason Smith Jacob Smullyan Jeff Sprandel David Stanek William Stein Yusei TAHARA Geoff Talvola Lee Taylor Mike Taylor Christian Theune Rick Thomas Andy Trice George Trojan Jamie Turner Karl Ulbrich Kirby Urner Eric V. Smith Andi Vajda Hernando Vera Thomas Verghese Martin Walsh Barry Warsaw Steve Waterbury Michael Weigend Chad Whitacre Kendall Whitesell Frank Wilder Derek Willis Simon Willison Mark Wittner Russ Woodman Andy Wright Linden Wright Peter Wu Yahong Wu James Y Knight Ka-Ping Yee Nathan Yergler Wai Yip Tung Rici Yu Peter Zhang Brian Zimmer matthew daiprai holger krekel clint malone Martin v. Loewis Guido van Rossum Tom von Schwerdtner -- 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 ebbaalm at uiuc.edu Fri Jan 7 16:00:54 2005 From: ebbaalm at uiuc.edu (Ebba Cecilia Ovesdotter Alm) Date: Fri, 7 Jan 2005 15:00:54 -0600 Subject: Tkinter: using a Listbox Message-ID: <6fb0c302.bb18916d.865c900@expms2.cites.uiuc.edu> Hello, I'm learning how to use the Tkinter module. I would like to use an element similar to a drop-down form, where the user can select one option out of many. I thought that a Listbox item could do just this. The following extract from my code (with the listbox part basically mirroring http://effbot.org/books/tkinterbook/listbox.htm), does, however, not create a visable Listbox. Am I interpreting the Listbox incorrectly? Ideas or suggestions are appreciated. #Frame & label for the listbox self.selectFrame = Frame(self.root) self.selectFrame.pack(side=TOP, fill=X, padx=10) Label(self.selectFrame, text='Primary choice').pack(side=LEFT) #Listbox self.listbox = Listbox(self.selectFrame) self.listbox.insert(END, "a list entry") for item in ["A","B","C"]: self.listbox.insert(END, item) Thanks, Cecilia From tim.golden at viacom-outdoor.co.uk Thu Jan 20 04:03:17 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 20 Jan 2005 09:03:17 -0000 Subject: Print to Windows default Printer Message-ID: <9A28C052FF32734DACB0A288A35339910359D1@vogbs009.gb.vo.local> [Samantha] | Thanks Tim. I didn't realize it would be so difficult. | S Strictly, if all you want to do is print text and you have mapped LPTx: to some printer (local or network) then the venerable "PRINT " or "COPY LPTx:" may well be what you want. You can issue these via an os.system call from within Python, and if that serves the purpose, well... import os f = open ("temp.txt", "w") f.write ("""I must go down to the sea again, To the lonely sea and the sky. And all I ask is a tall ship And a star to steer her by. """) f.close () os.system ("print temp.txt") TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From http Fri Jan 7 21:54:26 2005 From: http (Paul Rubin) Date: 07 Jan 2005 18:54:26 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> Message-ID: <7xk6qoeil9.fsf@ruckus.brouhaha.com> Arich Chanachai writes: > >But I thought Python was an all-purpose language. After all, OS's > >have been written in Lisp before too. > > > Pure Lisp? Or a Lisp/C/Asm combo? Lisp has a compiled flavor by the way. Compiled flavor? Lisp has been compiled since the 1950's. No, there was no C code on Lisp machines. There was some low-level code at the bottom whose capabilities were such that you could accurately call it asm, but it was Lisp too, just a very restricted form. From peter at engcorp.com Tue Jan 18 14:53:10 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Jan 2005 14:53:10 -0500 Subject: hex notation funtion In-Reply-To: <41ed66d5$0$92053$a1866201@visi.com> References: <41ed60f9$0$29427$a1866201@visi.com> <41ed66d5$0$92053$a1866201@visi.com> Message-ID: Grant Edwards wrote: > On 2005-01-18, Grant Edwards wrote: > >>On 2005-01-18, tertius wrote: >> >> >>>Is there a builtin function that will enable me to display the hex >>>notation of a given binary string? (example below) >> >>' '.join('%02x' % ord(b) for b in s) > > > Oops. Should be: > > ' '.join(['%02x' % ord(b) for b in s]) The first works fine under Python 2.4, actually... you need the list comprehension only on previous versions. -Peter From aahz at pythoncraft.com Thu Jan 6 19:01:46 2005 From: aahz at pythoncraft.com (Aahz) Date: 6 Jan 2005 19:01:46 -0500 Subject: The Industry choice References: <10trej2fl8dip65@corp.supernews.com> Message-ID: In article <10trej2fl8dip65 at corp.supernews.com>, Jeff Shannon wrote: > >Note that the so-called 'viral' nature of GPL code only applies to >*modifications you make* to the GPL software. The *only* way in which >your code can be 'infected' by the GPL is if you copy GPL source. That's not true -- consider linking to a GPL library. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From steven.bethard at gmail.com Sun Jan 23 15:08:11 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 23 Jan 2005 13:08:11 -0700 Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) In-Reply-To: References: Message-ID: Nick Coghlan wrote: > Steven Bethard wrote: > >> I wrote: >> > If you really want locals that don't contribute to arguments, I'd be >> > much happier with something like a decorator, e.g.[1]: >> > >> > @with_consts(i=1, deftime=time.ctime()) >> > def foo(x, y=123, *args, **kw): >> > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime >> > >> > Then you don't have to mix parameter declarations with locals >> > definitions. >> > >> > Steve >> > >> > [1] I have no idea how implementable such a decorator would be. I'd >> > just like to see function constants declared separate from arguments >> > since they mean such different things. >> >> I played around with this, and I think it's basically implementable: > > > Raymond's constant binding decorator is probably a good model for how to > do it: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 Yeah, I thought about this recipe, but opcodes always scare me too much. ;) Steve From jeff at ccvcorp.com Thu Jan 6 16:00:18 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jan 2005 13:00:18 -0800 Subject: sorting on keys in a list of dicts In-Reply-To: References: Message-ID: <10tr9ejf05pv660@corp.supernews.com> Jp Calderone wrote: > L2 = [(d[key], i, d) for (i, d) in enumerate(L)] > L2.sort() > L = [d for (v, i, d) in L2] Out of curiosity, any reason that you're including the index? I'd have expected to just do L2 = [(d[key], d) for d in L] L2.sort() L = [d for (v, d) in L2] I suppose that your version has the virtue that, if the sortkey value is equal, items retain the order that they were in the original list, whereas my version will sort them into an essentially arbitrary order. Is there anything else that I'm missing here? Jeff Shannon Technician/Programmer Credit International From holbertr at dma.org Wed Jan 5 10:37:53 2005 From: holbertr at dma.org (Rick Holbert) Date: Wed, 05 Jan 2005 10:37:53 -0500 Subject: % operation References: Message-ID: It also looks like you are using an old version of Python running on an old version of Linux. Time to upgrade? Christopher Koppler wrote: > On Wed, 05 Jan 2005 15:36:30 +0900, Daewon YOON wrote: > >> ==== >> Python 1.5.2 (#1, Jul 5 2001, 03:02:19) [GCC 2.96 20000731 (Red Hat >> Linux 7.1 2 on linux-i386 >> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >> >>> x=9 >> >>> y=4 >> >>> x%y >> 1 >> >>> for z in range(44): >> ... z%9 >> File "", line 2 >> z%9 >> ^ >> SyntaxError: invalid syntax >> >> ==== >> What's wrong with the above operation and how can I get the correct >> modulo result with Python? > > There's nothing wrong with the operation, but it looks like you forgot to > indent your loop body (which the interactive shell doesn't automagically > do for you): > >>>> for z in range(44): > ... z%9 > ... > > [result snipped] > From case.nelson at gmail.com Wed Jan 12 21:47:50 2005 From: case.nelson at gmail.com (snoe) Date: 12 Jan 2005 18:47:50 -0800 Subject: Help Optimizing Word Search In-Reply-To: References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: <1105584470.524744.324640@z14g2000cwz.googlegroups.com> With a list of letters: 'ABAE?S?' your implementation ran 3.5 times faster than the one from http://blog.vrplumber.com/427 (in 0.437 seconds vs 1.515) Without wildcards yours runs slightly quicker as well. I guess with the wildcards, using an re as a quick filter against each word, versus the translate method is much faster. From macrocosm at fastmail.fm Sun Jan 9 10:01:08 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Sun, 09 Jan 2005 10:01:08 -0500 Subject: Python Operating System??? In-Reply-To: <7xr7kvm72c.fsf@ruckus.brouhaha.com> References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> Message-ID: <41E14734.5050908@fastmail.fm> Paul Rubin wrote: > ... > >>OK, then give me an example of Lisp OS that runs on a PC. I would like to >>install it on my PC tomorrow. Or maybe my Mac. That was your whole point, >>originally, that since it could be done in Lisp, why not Python? >> >> > >Huh? That's a non-sequitur, nothing prevents you from running Lisp on >your PC or Mac. The same issues issues that apply to OS code, also >apply to user code. The Lisp machine hardware wasn't needed only to >make the OS run fast. The Lisp machine was developed so that people >could deploy large user-level applications written in Lisp, and the >hardware was there to support those applications. And given such a >good Lisp environment, there was no reason to think of writing the OS >in anything other than Lisp. > >In fact, the reason the Lisp machine died off was because general >purpose workstation hardware (and later, PC-class hardware) became >fast enough to run Lisp applications without needing special purpose >CPU's. That same PC hardware speed is what makes it possible to run >user applications in Python. > > So true, there was indeed a contextual reason for special hardware, and the context has since changed (dramatically). From uche at ogbuji.net Sat Jan 15 01:07:06 2005 From: uche at ogbuji.net (Uche Ogbuji) Date: 14 Jan 2005 22:07:06 -0800 Subject: XPath and XQuery in Python? In-Reply-To: References: Message-ID: <1105769226.435105.19310@c13g2000cwb.googlegroups.com> Interesting discussion. My own thoughts: http://www.oreillynet.com/pub/wlg/6224 http://www.oreillynet.com/pub/wlg/6225 Meanwhile, please don't make the mistake of bothering with XQuery. It's despicable crap. And a huge impedance mismatch with Python. --Uche From hpk at trillke.net Fri Jan 7 19:14:11 2005 From: hpk at trillke.net (holger krekel) Date: Sat, 8 Jan 2005 01:14:11 +0100 Subject: AttributeError of a module instance In-Reply-To: <43B02B32.6010805@yahoo.it> References: <43B02B32.6010805@yahoo.it> Message-ID: <20050108001411.GC7646@solar.trillke.net> On Mon, Dec 26, 2005 at 17:41 +0000, Paolino wrote: > I'd like to catch AttributeError on the module level,so that I can > declare default bindings for useds defore definition.How is this to be > done?Thanks for help. It cannot be done directly but with a small hack. This is the idea: import sys class A: def __getattr__(self,name): if name[:1] != '_': return name raise AttributeError(name) sys.modules['a'] = A() import a print a.helloworld # will print "helloworld" Note, that subsequently you can "import a" also from other modules because the import statement consults sys.modules. This is all a bit bothersome and thus it's often easier to just do "from somemod import a" directly and forget about the above magic. cheers, holger From tmohr at s.netic.de Wed Jan 26 00:44:51 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Wed, 26 Jan 2005 06:44:51 +0100 Subject: import hook, overwrite import? Message-ID: Hi, is there some description available to overwrite the import hook? By googling i found out so far that i need to overwrite __builtins__.__import__ with something else. Can i also do this with a C function that is provided when using an embedded python interpreter? So my own C program provides this and when linking with python.lib the function is overwritten? Or is there some extension hook? Does this also handle "from module import *" not only the normal "import module"? Thanks for any hints, Torsten. From nick at craig-wood.com Sat Jan 22 05:30:22 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 22 Jan 2005 10:30:22 GMT Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: TB wrote: > Is there an elegant way to assign to a list from a list of unknown > size? For example, how could you do something like: > > >>> a, b, c = (line.split(':')) > if line could have less than three fields? You could use this old trick... a, b, c = (line+"::").split(':')[:3] Or this version if you want something other than "" as the default a, b, b = (line.split(':') + 3*[None])[:3] BTW This is a feature I miss from perl... -- Nick Craig-Wood -- http://www.craig-wood.com/nick From list.adam at twardoch.com Sat Jan 29 23:15:34 2005 From: list.adam at twardoch.com (Adam Twardoch) Date: Sun, 30 Jan 2005 05:15:34 +0100 Subject: [Plone] Detailed poll results? Message-ID: Hello, Is there a method, or an alternative module that could be used, to have "polls" in Plone that display detailed results of the poll, i.e. all users and the votes they have given? Adam From jdhunter at ace.bsd.uchicago.edu Thu Jan 20 15:27:56 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 20 Jan 2005 14:27:56 -0600 Subject: problem with import pylab from a website In-Reply-To: <1106127655.41ee2b2758a9a@imapwww.epfl.ch> (jean.rossier@epfl.ch's message of "Wed, 19 Jan 2005 10:40:55 +0100") References: <1106127655.41ee2b2758a9a@imapwww.epfl.ch> Message-ID: >>>>> "jean" == jean rossier writes: jean> Hello All, I am facing a problem while importing pylab jean> library(in a .py program file) via web browser however the jean> same program works when I execute it from the command jean> prompt. jean> Error message we get: Permission denied: '/usr/share/matplotlib/.ttffont.cache', referer: One solution is to give yourself write permission to /usr/share/matplotlib. If this is not possible or in unpalatable for sysadmin reasons, you have a couple of options. matplotlib creates a font cache .ttffont.cache of the ttf files it finds on your system. If the HOME environment variable is set, it places the cache file in the HOME dir. So if setting HOME is a viable option for you, simply set this to a writable directory on your system and you are good to go. This is the approach I recommend. If HOME does not exist, matplotlib falls back on its data path: this is where fonts, icons and other goodies live. You can also customize this directory by setting the MATPLOTLIBDATA environment variable. If you go this route, more all the files currently in /usr/share/matplotlib to some other directory, say /my/dir, and make sure it is writable, and then set MATPLOTLIBDATA to point to it. Note matplotlib has a configuration file that controls all of the default settings for the plot. If you want to edit these, the edited file can also be placed in the HOME directory. See http://matplotlib.sf.net/.matplotlibrc . Hope this helps, JDH From a at b.c Sat Jan 15 10:55:41 2005 From: a at b.c (Doug Holton) Date: Sat, 15 Jan 2005 09:55:41 -0600 Subject: java 5 could like python? In-Reply-To: References: Message-ID: vegetax wrote: > In the other hand, with the recent changes in java 5 i can pythonize > java, Have you seen Jython? http://www.jython.org/ It may be the best option for you. It will run just as fast as a regular java program. Also there is groovy: http://groovy.codehaus.org/ From TheDolphin at ivonet.nl Wed Jan 26 16:56:12 2005 From: TheDolphin at ivonet.nl (Ivo Woltring) Date: Wed, 26 Jan 2005 22:56:12 +0100 Subject: subprocess.Popen() redirecting to TKinter or WXPython textwidget??? References: <41f80b1b$0$148$3a628fcd@reader1.nntp.hccnet.nl> <1106775371.049857.36360@z14g2000cwz.googlegroups.com> Message-ID: <41f811fe$0$148$3a628fcd@reader1.nntp.hccnet.nl> wrote in message news:1106775371.049857.36360 at z14g2000cwz.googlegroups.com... > Ivo, my initial thought would be, you need to know how much text you > will get back from popen. My Python reference has the following > example: > > import os > dir = os.popen('ls -al', 'r') > while (1): > line = dir.readline() > if line: > print line, > else: > break > > that example shows how to capture the process output in a file-type > object, then bring it into a string with readline(). > >[.... snip ....] > cheers > S > Thanx for trying Stewart, but that is not what I need The output of mencoder is not readable with readlines (i tried it) because after the initial informational lines You don't get lines anymore (you get a linefeed but no newline) The prints are all on the same line (like a status line) something like Pos: 3,1s 96f ( 0%) 42fps Trem: 0min 0mb A-V:0,038 [171:63] which is coninually updated while the process runs... > in your app, you could create a Tkinter stringVar, say myOutput, for > the process output. In your Tkinter widget, you could then set a > textvariable=myOutput. also use the wait_variable and watch options How does this work? wait?? anyone? > (hope I recall these correctly, don't have my Tkinter ref. at hand) to > detect when there's been a change to the contents of the StringVar and > update the contents of the label. > Hope this helps, if not, write back. I really like to know how I can catch the output of a subproces.Popen() command and redirect it to something else (like a textwidget ) and I really like to use the subprocess module (standard in v2.4) to get to know it. Another reason to use the subprocess module is I can stop the process because I know the handle of the thread. The subprocess module knows all this. cheerz, Ivo. From starbuck_ms at yahoo.com Fri Jan 21 17:56:31 2005 From: starbuck_ms at yahoo.com (PyStarbuck) Date: 21 Jan 2005 14:56:31 -0800 Subject: PyXML problem between python 2.3 and python 2.4 Message-ID: <1106348191.156451.282180@c13g2000cwb.googlegroups.com> Hi All, Has anybody had an issue with compatiblity between XML files between python 2.3 and python 2.4. I have PyXML 0.8.3 installed in ClearCase and it is shared between Solaris and Windows. Here is an example on my system: ActivePython 2.3.4 Build 233 (ActiveState Corp.) based on Python 2.3.4 (#53, Oct 18 2004, 20:35:07) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path.insert(0, r"C:\cc\sweeneym_atf\reuse_python") >>> import xml >>> xml.__file__ 'C:\\cc\\sweeneym_atf\\reuse_python\\xml\\__init__.py' >>> import xml.marshal.generic as m >>> f = open(r"C:\test.xml", "w+") >>> m.dump_format(sys.path, f) >>> f.close() ActivePython 2.4 Build 243 (ActiveState Corp.) based on Python 2.4 (#60, Nov 30 2004, 09:34:21) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path.insert(0, r"C:\cc\sweeneym_atf\reuse_python") >>> import xml >>> import xml.marshal.generic as m >>> fd = open(r"C:\test.xml", "r") >>> l = m.load(fd) Traceback (most recent call last): File "", line 1, in ? File "C:\cc\sweeneym_atf\reuse_python\xml\marshal\generic.py", line 377, in load return m._load(file) File "C:\cc\sweeneym_atf\reuse_python\xml\marshal\generic.py", line 396, in _load p.parseFile(file) File "C:\cc\sweeneym_atf\reuse_python\xml\sax\drivers\drv_pyexpat.py", line 74, in parseFile self.close() File "C:\cc\sweeneym_atf\reuse_python\xml\sax\drivers\drv_pyexpat.py", line 132, in close if self.parser.Parse("", 0) != 1: xml.parsers.expat.ExpatError: parsing finished: line 17, column 0 I then performed a test by doing the following: 1) From python 2.4, marshal sys.path into a test24.xml file. 2) From python 2.3 un-marshal the test24.xml file, it workes. 3) From python 2.3 re-marshal the just un-marshaled list into test23.xml 4) Back in python24, un-marshal test23.xml, it failed. 5) Perform a diff on the new files, identical. Any Ideas? From francis.girard at free.fr Wed Jan 26 16:18:30 2005 From: francis.girard at free.fr (Francis Girard) Date: Wed, 26 Jan 2005 22:18:30 +0100 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <200501262135.30872.francis.girard@free.fr> Message-ID: <200501262218.31133.francis.girard@free.fr> Le mercredi 26 Janvier 2005 21:44, PA a ?crit?: > On Jan 26, 2005, at 21:35, Francis Girard wrote: > >> Project fails for many reasons but seldomly because one language is > >> "better" or "worst" than another one. > > > > I think you're right. But you have to choose the right tools that fit > > your > > needs. But I think that's what you meant anyway. > > Yes. But even with the "best" tool and the "best" intents, projects > still fail. In fact, most IT projects are considered failures: > > http://www.economist.com/business/PrinterFriendly.cfm?Story_ID=3423238 Well, let's go back home for some gardening. My wife will be happy. > > Cheers > > -- > PA > http://alt.textdrive.com/ From genezhang at gmail.com Sun Jan 9 20:21:24 2005 From: genezhang at gmail.com (Gene) Date: 9 Jan 2005 17:21:24 -0800 Subject: path to python file given module In-Reply-To: <1105319404.902746.179690@c13g2000cwb.googlegroups.com> References: <1105315568.887724.260370@c13g2000cwb.googlegroups.com> <1105315923.520581.280580@c13g2000cwb.googlegroups.com> <1105317971.205487.82770@c13g2000cwb.googlegroups.com> <1105319404.902746.179690@c13g2000cwb.googlegroups.com> Message-ID: <1105320084.044360.221800@c13g2000cwb.googlegroups.com> It works now. Thanks. From steven.bethard at gmail.com Tue Jan 25 15:24:03 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 13:24:03 -0700 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: Message-ID: Michael Spencer wrote: > Safe eval recipe posted to cookbook: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 This recipe only evaluates constant expressions: "Description: Evaluate constant expressions, including list, dict and tuple using the abstract syntax tree created by compiler.parse" It means you can't eval arbitrary Python code -- it's basically just a data parser. Handy in some situations, but not the equivalent of a limited Python virtual machine. > Likewise, function calls are easily intercepted I'm not sure I follow this... How do you intend to intercept all function calls? > As you say, attribute access to core functions appears to present the > challenge. It is easy to intercept attribute access, harder to know > what's safe. If there were a known set of 'dangerous' objects e.g., > sys, file, os etc... then these could be checked by identity against any > attribute returned It sounds like you're suggesting overriding the global attribute access mechanism. Is that right? So that every time Python encountered an attribute access, you would verify that the attribute being accessed is not on the 'dangerous' list? I don't know how to do that without basically rewriting some of Python's C code, though certainly I'm no expert in the area... Also, I'm not sure identity is sufficient: py> import sys py> import new py> new.module('newsys') py> newsys = new.module('newsys') py> newsys.__dict__.update(sys.__dict__) py> newsys is sys False py> newsys == sys False Steve From PeterMayne at ap.spherion.com Mon Jan 3 22:25:02 2005 From: PeterMayne at ap.spherion.com (PJDM) Date: 3 Jan 2005 19:25:02 -0800 Subject: [Hack] Import binary extensions from zipfiles, windows only References: Message-ID: <1104809102.966779.18480@f14g2000cwb.googlegroups.com> I'm trying to make ZopeX3 start faster by zipping up the "zope" directory. (Because this will be stored on a CD, having less data to read will make it quicker to start.) The standard python zipimporter won't work with the ZopeX3 .pyd files, so zipextimporter came along at just the right time. However, it doesn't seem to work for me (Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32, Windows XP SP2). Sample script: ---- import zipextimporter zipextimporter.install() import sys print 'Hooks:\n', sys.path_hooks sys.path.append(r'C:\tmp\zope.zip') print 'Path:\n', sys.path # Try an innocuous import first to make sure we have the path correct. import zope.server print 'Server file:\n', zope.server.__file__ # Now try a .pyd import. import zope.thread._zope_thread print 'Thread file:\n', zope.thread._zope_thread.__file__ ---- Output: ---- Hooks: [, ] Path: ['C:\\tmp', 'C:\\WINDOWS\\system32\\python23.zip', 'C:\\tmp', 'C:\\opt\\Python23\\DLLs', 'C:\\opt\\Python23\\lib', 'C:\\opt\\Python23\\lib\\plat-win', 'C:\\opt\\Python23\\lib\\lib-tk', 'C:\\opt\\Python23', 'C:\\opt\\Python23\\lib\\site-packages', 'C:\\tmp\\zope.zip'] Server file: C:\tmp\zope.zip\zope\server\__init__.py Traceback (most recent call last): File "zei.py", line 15, in ? import zope.thread._zope_thread ImportError: No module named _zope_thread ---- The zope.zip file contains zope.thread: ---- $ unzip -l zope.zip |grep zope/thread 0 11-08-04 11:00 zope/thread/ 0 07-03-04 04:34 zope/thread/DEPENDENCIES.cfg 65 07-28-04 22:52 zope/thread/SETUP.cfg 994 07-03-04 04:34 zope/thread/tests.py 748 11-08-04 11:00 zope/thread/tests.pyc 748 11-08-04 11:00 zope/thread/tests.pyo 20480 11-07-04 00:54 zope/thread/_zope_thread.pyd 7838 08-17-04 17:20 zope/thread/__init__.py 7808 11-08-04 11:00 zope/thread/__init__.pyc 7808 11-08-04 11:00 zope/thread/__init__.pyo ---- What am I missing? Thanks. PJDM From michele.simionato at gmail.com Wed Jan 26 08:27:48 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 26 Jan 2005 05:27:48 -0800 Subject: FTP Server In-Reply-To: References: <1106743852.600769.72820@c13g2000cwb.googlegroups.com> Message-ID: <1106746068.798541.219240@c13g2000cwb.googlegroups.com> > If you're after a simple FTP server, have a look at medusa. Uhm ... Medusa does not seem actively maintained nowadays. M.S. From as006d4848 at blueyonder.co.uk Fri Jan 28 23:41:57 2005 From: as006d4848 at blueyonder.co.uk (Philip Smith) Date: Sat, 29 Jan 2005 04:41:57 GMT Subject: Elliptic Code References: <7x3bwl9n40.fsf@ruckus.brouhaha.com> Message-ID: Quite so - but thanks for your help in any case "Paul Rubin" wrote in message news:7x3bwl9n40.fsf at ruckus.brouhaha.com... > Nick Craig-Wood writes: >> > I understand the algorithm quite well but how to code the >> > multiplication >> > stage most efficiently in python eludes me. >> >> You might want to look at >> >> http://gmpy.sourceforge.net/ >> >> It has very fast multiplication up to any size you like! > > I think he's talking about point multiplication on the elliptic curve > group, not integer multiplication. From reinhold-birkenfeld-nospam at wolke7.net Sat Jan 1 16:25:53 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 01 Jan 2005 22:25:53 +0100 Subject: What can I do with Python ?? In-Reply-To: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> Message-ID: <33oir1F40vpumU2@individual.net> BOOGIEMAN wrote: > Beginners question, but really what can you do with it ? > How hard is Python to learn compared with other languages > (let's say C#). Can you make fullscreen game with it (for example) ? > I've looked at http://www.python.org but nothing concrete there For fullscreen games, see PyGame (www.pygame.org). BTW, I don't know of a way to write fullscreen games in C#... Reinhold From itsme at yahoo.com Tue Jan 4 13:16:39 2005 From: itsme at yahoo.com (It's me) Date: Tue, 04 Jan 2005 18:16:39 GMT Subject: Hlelp clean up clumpsy code References: Message-ID: What's "LBYL"? Oh...Look-before-you-leap. OK. I think I understand what's going on now (I read up on generator and iterators and my head still hurts). I knew there must be a cleaner way of "walking" around in Python. I will experiment with generator more. Thanks everybody. "Jp Calderone" wrote in message news:mailman.140.1104857018.22381.python-list at python.org... > > > On Tue, 04 Jan 2005 08:18:58 -0800, Scott David Daniels wrote: > >Nick Coghlan wrote: > > > A custom generator will do nicely: > > > > > > Py> def flatten(seq): > > > ... for x in seq: > > > ... if hasattr(x, "__iter__"): > > > ... for y in flatten(x): > > > ... yield y > > > ... else: > > > ... yield x > > > > Avoiding LBYL gives you: > > def flatten(seq): > > for x in seq: > > try: > > for y in flatten(x): > > yield y > > except TypeError: > > yield x > > But totally messes up on error handling. Instead: > > def flatten(seq): > for x in seq: > try: > subseq = iter(x) > except TypeError: > yield x > else: > for subx in flatten(subseq): > yield subx > > to avoid catching TypeErrors from .next(). > > Jp From bokr at oz.net Thu Jan 13 18:04:21 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 23:04:21 GMT Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> <39ednWfqlrgB6HvcRVn-iA@powergate.ca> Message-ID: <41e6f606.777680996@news.oz.net> On Thu, 13 Jan 2005 08:18:25 -0500, Peter Hansen wrote: >and-google at doxdesk.com wrote: >> In Mythical Future Python I would like to be able to use any base in >> integer literals, which would be better. Example random syntax: >> >> flags= 2x00011010101001 >> umask= 8x664 >> answer= 10x42 >> addr= 16x0E800004 # 16x == 0x >> gunk= 36x8H6Z9A0X > >I think I kinda like this idea. Allowing arbitrary values, >however, would probably be pointless, as there are very >few bases in common enough use that a language should make >it easy to write literals in any of them. So I think "36x" >is silly, and would suggest limiting this to 2, 8, 10, and >16. At the very least, a range of 2-16 should be used. >(It would be cute but pointless to allow 1x000000000. :-) > My concern is negative numbers when you are interested in the bits of a typical twos-complement number. (BTW, please don't tell me that's platform-specific hardware oriented stuff: Two's complement is a fine abstraction for interpreting a bit vector, which is another fine abstraction ;-) One way to do it consistently is to have a sign digit as the first digit after the x, which is either 0 or base-1 -- e.g., +3 and -3 would be 2x011 2x101 8x03 8x75 16x03 16xfd 10x03 10x97 Then the "sign digit" can be extended indefinitely to the left without changing the value, noting that -3 == 97-100 == 997-1000) and similarly for other bases: -3 == binary 101-1000 == 111101-1000000 etc. IOW, you just subtract base** if the first digit is base-1, to get the negative value. This would let us have a %.b format to generate the digits part and would get around the ugly hack for writing hex literals of negative numbers. def __repr__(self): return '<%s object at %08.16b>' %(type(self).__name__, id(self)) and you could write based literals in the above formats with e.g., with '16x%.16b' % number or '2x%.2b' % number etc. Regards, Bengt Richter From mhartl at post.harvard.edu Thu Jan 6 15:40:49 2005 From: mhartl at post.harvard.edu (mhartl at post.harvard.edu) Date: 6 Jan 2005 12:40:49 -0800 Subject: File Handling Problems Python I/O References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> <1105034789.700445.291380@z14g2000cwz.googlegroups.com> <1105043692.497106.315270@z14g2000cwz.googlegroups.com> Message-ID: <1105044049.815913.17830@z14g2000cwz.googlegroups.com> Sorry, the BASE variable should be 'C:\\' on Windows: >>> BASE = 'C:\\' >>> import os >>> os.path.join(BASE, 'foo', 'bar', 'baz') 'C:\\foo\\bar\\baz' From vze4rx4y at verizon.net Sun Jan 16 07:18:23 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 16 Jan 2005 12:18:23 GMT Subject: generator expressions: performance anomaly? References: <1105854381.117059.59940@c13g2000cwb.googlegroups.com> Message-ID: "John Machin" wrote in message news:1105854381.117059.59940 at c13g2000cwb.googlegroups.com... > Please consider the timings below, where a generator expression starts > out slower than the equivalent list comprehension, and gets worse: > > >python -m timeit -s "orig=range(100000)" "lst=orig[:];lst[:]=(x for x > in orig)" . . . > >python -m timeit -s "orig=range(200000)" "lst=orig[:];lst[:]=(x for x > in orig)" This has nothing to do with genexps and everything to do with list slice assignment. List slice assignment is an example of a tool with a special case optimization for inputs that know their own length -- that enables the tool to pre-allocate its result rather than growing and resizing in spurts. Other such tools include tuple(), map() and zip(). The incredulous tone of the posting suggests a presumption that genexps always outperform list comps. That is not the case. Sometimes you want a list instead of a generator because you want more than just iteration; perhaps the consumer function may be able to take advantage of length reporting, indexing, slicing, re-iterability or other useful list behaviors. Also, the timing jig bites. Use xrange() instead of range(). Otherwise, there's an immediate forfeit of the memory savings normally being sought by the use of generators and iterators. > Background: There was/is a very recent thread about ways of removing > all instances of x from a list. /F proposed a list comprehension to > build the result list. FWIW, deques have a natural idiom for this kind of situation: for i in xrange(len(mydeque)): x = mydeque.popleft() if some_condition(x): mydeque.append(x) > Given a requirement to mutate the original list, > this necessitates the assignment to lst[:]. Sometimes people introduce arbitrary requirements and twist themselves in knots when real applications tend to allow a wider range of alternative solutions. There is a funky code smell emanating from any code resembling a[:]=some_iterator. It would make me examine how 'a' is being used and check whether the surrounding code can use the iterator or an new object. > Comments, clues, ... please. As a point of interest, note that Py2.4 improved some of its built-in iterators to report their length if requested. Now you now why. >>> d = dict(a=1, b=2, c=3, d=4) >>> len(d.iteritems()) 4 Raymond Hettinger From gene.tani at gmail.com Sun Jan 30 20:40:08 2005 From: gene.tani at gmail.com (gene.tani at gmail.com) Date: 30 Jan 2005 17:40:08 -0800 Subject: Help! Host is reluctant to install Python In-Reply-To: References: Message-ID: <1107135608.548166.243620@f14g2000cwb.googlegroups.com> Based on discusses with these guys, who know LAMP, python, ruby inside and out, and support it well: http://textdrive.com/ I'm guessing you'd have a hard time finding mod_python / apache hosting unless you get a dedicated server. It's pretty labor-intensive setup and admin-wise. linux shell / python / SSH shdn't be a big deal, tho. From tim.peters at gmail.com Wed Jan 26 22:51:02 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 26 Jan 2005 22:51:02 -0500 Subject: threading.py Condition wait overflow error In-Reply-To: <40E605146701DE428FAF21286A97D309174516@wphexa02.corp.lh.int> References: <40E605146701DE428FAF21286A97D309174516@wphexa02.corp.lh.int> Message-ID: <1f7befae050126195119b1ba9@mail.gmail.com> [Tim Peters] ... >> The most common cause for "impossible exceptions" > is flawed C code in an extension that fails to >> check a Python C API call for an error return. [Mark English] > Yes, I use a lot of C modules which I wrote. Then you know where to start looking . > It could certainly be one of them (although which one could be an > interesting challenge to find out). It may even have something to do > with moving to the VC7.1 compiler. Hard to say in advance. Since you have VC7.1, that opens a world of possiblities if you recompile Python. There are extra checks in ceval.c in a debug build, trying to catch "a call lied about whether it raised an exception" soon(er) after it happens. Rebuilding all your extensions in debug mode too could be a PITA, so you could get the same effect by #define'ing CHECKEXC in a release build. But a debug build has all sorts of extra checks that can help, and you could get into the debugger then and set a breakpoint on the unexpected OverflowError ... a quick check of the source shows that "long int too large to convert to int" is produced only by longobject.c's PyLong_AsLong() function. There's no way we _should_ be getting into that function by applying min() to floats, of course. > Thank you very much for your suggestion. Without it I would never have > thought to look at that code. Nobody ever does . From steve at holdenweb.com Fri Jan 14 16:55:56 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 16:55:56 -0500 Subject: Refactoring; arbitrary expression in lists In-Reply-To: References: Message-ID: <_hXFd.75450$Jk5.55685@lakeread01> Peter Maas wrote: > Steven Bethard schrieb: > >> BJ?rn Lindqvist wrote: > > [...] > >>> I believe this can be nicelier written as: >>> >>> if "Makefile" in basename: >>> >> >> +1 for "nicelier" as VOTW (Vocabulation of the week) =) > > > Me too, because nicelier is nicer than more nicely. :) > Is that really the niceliest way to express that thought? regards-li-er y'rs - 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 limodou at gmail.com Wed Jan 19 02:46:36 2005 From: limodou at gmail.com (limodou) Date: Wed, 19 Jan 2005 15:46:36 +0800 Subject: safest way to kill a thread In-Reply-To: <1106115159.200989.60870@c13g2000cwb.googlegroups.com> References: <1106106497.429643.307440@f14g2000cwb.googlegroups.com> <1106115159.200989.60870@c13g2000cwb.googlegroups.com> Message-ID: <41EE105C.6060407@gmail.com> I think only those threads which invoked with setDaemon() method will exit, and others will not, as the main program exit. martinnitram at excite.com wrote: > limodou wrote: > >>Using Thread's method setDaemon() before you call the start() method. >>Just like : >>t.setDaemon(True) >>t.start() > > thank for fast reply. > from python.org doc, said that setDaemon() function as > "The entire Python program exits when no active non-daemon threads > are left." > is it mean that when the main program exit (normally/abnormally), all > threads created will also exit? > Thank again. > -- I love python! My Blog: http://www.donews.net/limodou From gdr at integrable-solutions.net Sat Jan 29 00:57:11 2005 From: gdr at integrable-solutions.net (Gabriel Dos Reis) Date: 29 Jan 2005 06:57:11 +0100 Subject: what's OOP's jargons and complexities? References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> <360244F4lolueU1@individual.net> Message-ID: Martin Ambuhl writes: | Dan Perl wrote: | | > Actually, it can be as simple as: | > public class test { | | There is no "public" or "class" in C. Please don't post such trash to | comp.lang.c. In fact, C++ is not topical in any of the five But, it was anything but C++. Maybe Java. -- Gabriel Dos Reis gdr at integrable-solutions.net From richie at entrian.com Tue Jan 4 05:55:29 2005 From: richie at entrian.com (Richie Hindle) Date: Tue, 04 Jan 2005 10:55:29 +0000 Subject: Python! Is! Truly! Amazing! In-Reply-To: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: <2etkt0pstn12l5d4l2o28ivei9np7cl3a2@4ax.com> [Erik] > I am now a super gushing fan-boy. +1 Quote of the Week! -- Richie Hindle From bokr at oz.net Tue Jan 18 23:55:53 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 19 Jan 2005 04:55:53 GMT Subject: Has apparent 2.4b1 bug been fixed? flatten in Lib\compiler\ast.py overloads 'list' name Message-ID: <41ede67e.1232456679@news.oz.net> What am I missing? (this is from 2.4b1, so probably it has been fixed?) def flatten(list): l = [] for elt in list: ^^^^--must be expecting list instance or other sequence t = type(elt) if t is tuple or t is list: ^^^^--looks like it expects to refer to the type, not the arg for elt2 in flatten(elt): l.append(elt2) else: l.append(elt) return l Regards, Bengt Richter From fredrik at pythonware.com Thu Jan 27 15:44:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 27 Jan 2005 21:44:50 +0100 Subject: Question about 'None' References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: Steven Bethard wrote: > So None being smaller than anything (except itself) is hard-coded into Python's compare routine. > My suspicion is that even if/when objects of different types are no longer comparable by default > (as has been suggested for Python 3.0), None will still compare as smaller than anything... from the change log for Python 2.1: "An implementation detail changed in 2.1a1 such that None now compares less than any other object. Code relying on this new behavior (like code that relied on the previous behavior) does so at its own risk." the documentation (which I quoted earlier) still applies. From ncoghlan at iinet.net.au Fri Jan 14 02:15:02 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 14 Jan 2005 17:15:02 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: <41e6dc9b.771173178@news.oz.net> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> <41e6dc9b.771173178@news.oz.net> Message-ID: <41E77176.9070002@iinet.net.au> Bengt Richter wrote: > Problems? (Besides NIH, which I struggle with regularly, and had to overcome to accept Tim's > starting point in this ;-) The ideas regarding creating blocks whose name bindings affect a different scope are certainly interesting (and relevant to the 'using' out-of-order execution syntax as well). Out-of-order execution appeals to me, but the ability to flag 'hey, this is just setup for something I'm doing later' might be a reasonable alternative (particularly with the affected names highlighted on the first line). As Jeff pointed out, it would be significantly less surprising for those encountering the construct for the first time. Folding code editors would be able to keep the setup clause out of the way if you really wanted to hide it. On the other hand, it might be feasible to construct a virtually identical out-of-order two suite syntax, similar to the mathematical phrasing "let f = c/lambda where f is the frequency, c is the speed of light and lambda is the wavelength". Either way, you've convinced me that two suites (and a new compound statement), as well as specifying which names can be rebound in the containing scope, is a better way to go than trying to mess with the definition of Python statements. On keywords, while 'let' is nice for assignments, I find it just doesn't parse properly when I put function or class definitions in the clause. So, I'll swap it for 'use' in the examples below. The statement could then be read "use these outer bindable names, and this additional code, in this suite". YMMV, naturally. Let's consider some of the examples given for 'where' using an in-order let/in type syntax (the examples only bind one name at a time, but would allow multiple names): # Anonymous functions use res: def f(x): d = {} exec x in d return d in: res = [f(i) for i in executable] # Declaring properties class C(object): use x: def get(self): print "Demo default" def set(self, value): print "Demo default set" in: x = property(get, set) # Design by contract use foo: def pre(): pass def post(): pass in: @dbc(pre, post) def foo(): pass # Singleton classes use C: class _C: pass in: C = _C() # Complex default values use f: def default(): return "Demo default" in: def f(x=default()): pass They actually read better than I expected. Nicely, the semantics of this form of the syntax *can* be articulated cleanly with current Python: use : in: as equivalent to: def __use_stmt(): def _in_clause(): return return _in_clause() __use_stmt_args = {} = __use_stmt() del __use_stmt Those semantics don't allow your switch statement example, though, since it doesn't use any magic to write to the outer scope - it's just a normal return and assign. However, I don't think starting with these semantics would *preclude* adding the ability to name the second block at a later date, and make the name rebinding part of executing that block - the standard usage doesn't really care *how* the names in the outer scope get bound, just so long as they do. Whether I think that's a good idea or not is an entirely different question :) Another aspect to consider is whether augmented assignment operations in the inner-scopes should work normally - if so, it would be possible to alter the semantics to include passing the existing values as arguments to the inner scopes. Moving on to considering a two-suite out-of-order syntax, this would have identical semantics to the above, but a syntax that might look something like: as : using: # Anonymous functions as res: res = [f(i) for i in executable] using: def f(x): d = {} exec x in d return d # Declaring properties class C(object): as x: x = property(get, set) using: def get(self): print "Demo default" def set(self, value): print "Demo default set" # Design by contract as foo: @dbc(pre, post) def foo(): pass using: def pre(): pass def post(): pass # Singleton classes as C: C = _C() using: class _C: pass # Complex default values as f: def f(x=default()): pass using: def default(): return "Demo default" Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From http Fri Jan 7 02:20:40 2005 From: http (Paul Rubin) Date: 06 Jan 2005 23:20:40 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> Message-ID: <7xpt0h66yf.fsf@ruckus.brouhaha.com> Roman Suzi writes: > I do not like the idea of having stubs. Once I had an experience working with > CPAN (I tried to install SpamAssassin and it required some specific modules.) > "Magic" install shell, provided by Perl, upgraded half the Perl distro, > including newer version of Perl! > > So, I do like Python distutils better. it is not a major problem to > install something even if it required something else. Of course, > this depends on the package authors. But distutils don't help the problem that the module requires stuff that's missing. That's what happened with the thing I downloaded last week, that needed wxPython. I don't understand why the author felt he had to use wxPython instead of tkinter, since it wasn't a really fancy gui, but after already-described hassles trying to instead wxPython, I just used the application's command line interface instead, which worked fine. But if wxPython is so much better, maybe it's time for Python to include it. I want to start using Audacity pretty soon, which I think really does depend on wxPython, so I'm going to have to deal with this wxPython installation problem which is definitely not completely trivial. What a pain. > Yes, probably there could be a no-brainer script to run install > directly from zip and/or tar.gz/bz2 file, but I usually check > md5, pgp sigs and look inside anyway before running something. I thought distutils doesn't have any code-signing features. From kartic.krishnamurthy at gmail.com Thu Jan 13 11:01:52 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 13 Jan 2005 08:01:52 -0800 Subject: Free python server. In-Reply-To: <1105631360.938494.286750@c13g2000cwb.googlegroups.com> References: <1105631360.938494.286750@c13g2000cwb.googlegroups.com> Message-ID: <1105632112.104412.183870@f14g2000cwb.googlegroups.com> And yes, they have python installed... From richie at entrian.com Tue Jan 4 06:06:50 2005 From: richie at entrian.com (Richie Hindle) Date: Tue, 04 Jan 2005 11:06:50 +0000 Subject: hidding the "console" window + system global shortcut keys In-Reply-To: <2814F26DA6908F41927A81C410C4991A02079C19@siamun.server.bl.corp.intranet> References: <2814F26DA6908F41927A81C410C4991A02079C19@siamun.server.bl.corp.intranet> Message-ID: [Gabriel] > 2. Set global key biddings. You can do this using ctypes: http://groups.google.co.uk/groups?selm=mailman.929.1069345408.702.python-list%40python.org -- Richie Hindle richie at entrian.com From craig at postnewspapers.com.au Mon Jan 3 10:28:32 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Mon, 03 Jan 2005 23:28:32 +0800 Subject: removing comments form a file In-Reply-To: References: Message-ID: <1104766112.4535.5.camel@albert.localnet> On Mon, 2005-01-03 at 11:46 -0300, Batista, Facundo wrote: > - Used file instead of open, to don't read the whole file in memory. [craig at albert ~]$ python Python 2.3.4 (#1, Oct 26 2004, 16:42:40) .>>> file is open True .>>> print repr(file), repr(open) I'd be interested if you could clarify what you mean there. As far as I know, the whole file will only be read into memory if you use file.read () or file.readlines(). If you use an iterator it does internal readahead, but won't read the lot at once. If you use read() it reads only what you say. -- Craig Ringer From pedro.werneck at terra.com.br Mon Jan 24 10:04:11 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Mon, 24 Jan 2005 13:04:11 -0200 Subject: TCP server In-Reply-To: <1106576718.263709.280380@c13g2000cwb.googlegroups.com> References: <1106576718.263709.280380@c13g2000cwb.googlegroups.com> Message-ID: <20050124130411.1a91fa65.pedro.werneck@terra.com.br> A quick example for you: ### import SocketServer class EchoRequestHandler(SocketServer.BaseRequestHandler): def setup(self): print self.client_address, 'connected!' self.request.send('hi ' + str(self.client_address) + '\n') def handle(self): while 1: data = self.request.recv(1024) self.request.send(data) if data.strip() == 'bye': return def finish(self): print self.client_address, 'disconnected!' self.request.send('bye ' + str(self.client_address) + '\n') #server host is a tuple ('host', port) server = SocketServer.ThreadingTCPServer(('', 5000), EchoRequestHandler) server.serve_forever() ### Telnet to localhost 5000 and any data you sent will be echoed back to you... send 'bye' and the connection is closed On 24 Jan 2005 06:25:18 -0800 "assaf" wrote: > i am try to create a server > what am i suppose to send to SocketServer.TCPServer > what is the client_address ("127.0.0.1:80" ?) > and BaseRequestHandler = ? > > thanks > > -- > http://mail.python.org/mailman/listinfo/python-list From tjreedy at udel.edu Fri Jan 28 14:48:24 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Jan 2005 14:48:24 -0500 Subject: py.dll for version 2.2.1 (Windows) References: <1106937199.667357.42040@z14g2000cwz.googlegroups.com> Message-ID: "mike" wrote in message news:1106937199.667357.42040 at z14g2000cwz.googlegroups.com... > Just recently, my virus checker detected what it called a Trojan Horse > in the py.dll file in the python22 folder. Installation is version > 2.2.1 and I think that it came installed when I bought the PC in > October 2002. My HP came with 2.2 also, but nothing caught by McAfee > Does anyone know where I can get a copy of the py.dll file from version > 2.2.1 for Windows (XP) ? > > I looked at www.python.org and do not see a py.dll file in the > self-installation or .tgz versions of 2.2.1 that are posted. If the installer is not a selectively extractable archive, delete and reinstall fresh might be easiest. Terry J. Reedy From deetsNOSPAM at web.de Thu Jan 20 12:20:33 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 20 Jan 2005 18:20:33 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> Message-ID: <35a7grF4jjrcsU1@individual.net> > I know that there are different YAML engines for Python out there (Syck, > PyYaml, more?). > > Which one do you use, and why? I first used yaml, tried to migrate to syck. What I like about syck is that it is faster and doesn't try to create objects but only dicts - but it crashed if the number of yaml objects grew larger. So I still use yaml. > > For those of you who don't know what YAML is: visit http://yaml.org/! > You will be amazed, and never think of XML again. Well, almost. It is certainly nice. -- Regards, Diez B. Roggisch From fredrik at pythonware.com Mon Jan 24 17:19:06 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 23:19:06 +0100 Subject: What's so funny? WAS Re: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com><41EE24F7.7030303@jessikat.fsnet.co.uk><7x1xchlpqv.fsf@ruckus.brouhaha.com><41efeb82$0$27807$9b622d9e@news.freenet.de><41f1a70b$0$25959$9b622d9e@news.freenet.de><7xbrbiqdhk.fsf@ruckus.brouhaha.com><7xllalljah.fsf@ruckus.brouhaha.com><7xekgdmpll.fsf@ruckus.brouhaha.com><7xpszxcnfa.fsf@ruckus.brouhaha.com><7xllalcmqc.fsf@ruckus.brouhaha.com><7xbrbhosh7.fsf@ruckus.brouhaha.com><7xzmz0lw6h.fsf@ruckus.bro Message-ID: wrote > As an app writer I want to publish code that runs on multiple > platforms without needing special attention from the end user, and > preferably without needing special platform-specific attention from > me. please answer the question: have you done this? what kind of programs have you successfully delivered as "self-contained apps" for use on arbi- trary platforms? From klachemin at comcast.net Fri Jan 7 11:02:23 2005 From: klachemin at comcast.net (Kamilche) Date: 7 Jan 2005 08:02:23 -0800 Subject: Calling Function Without Parentheses! In-Reply-To: <41D8B5F4.1010903@mxm.dk> References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> <41D8B5F4.1010903@mxm.dk> Message-ID: <1105113743.189469.115440@f14g2000cwb.googlegroups.com> Yeah, but still. If they even had the most basic check, like 'an object is being referred to on this line, but you're not doing anything with it' would be handy in catching that. When you use an object like that, usually you're doing something with it, like assigning it to a variable. From sean_mcilroy at yahoo.com Fri Jan 14 15:28:37 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 14 Jan 2005 12:28:37 -0800 Subject: reusing Tkinter Canvases Message-ID: I'd like to save one Tkinter Canvas in order to use it on another Canvas later. The problem is that it gets saved as EPS but it needs to be GIF to be reuseable. How can I convert that format? Peace, STM From aleaxit at yahoo.com Fri Jan 28 04:20:17 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 28 Jan 2005 10:20:17 +0100 Subject: Question about 'None' References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <1gr3gdr.15hwalixjl91xN%aleaxit@yahoo.com> flamesrock wrote: ... > (The reason I ask is sortof unrelated. I wanted to use None as a > variable for which any integer, including negative ones have a greater > value so that I wouldn't need to implement any tests or initializations > for a loop that finds the maximum of a polynomial between certain x > values. Anything is greater than nothing, no?) To have this work reliably across versions of Python (and you mentioned you need it to work on 2.0 as well as 2.3...) you have to make your own sentinel class, such as: class MinusInfinity: def __cmp__(self, other): if isinstance(other, MinusInfinity): return 0 else: return -1 minusInfinity = MinusInfinity() Now, you should be able to use this 'minusInfinity" as ``a variable for which any integer ... has a greater value'', as you wished to use None. (Untested code, as I don't have any 2.0 on which to test it anyway). Alex From peter at engcorp.com Sun Jan 9 13:51:59 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 13:51:59 -0500 Subject: read numbers from file and covert to integer In-Reply-To: References: Message-ID: ?ystein Western wrote: > I got a file with a lot blocks of numbers that are strings. I'd like to read > all > this numbers and convert them to numbers for futher compareation. How can I > convert all this numbers to integer? Do I have to put all numbers into a > list? It would help immensely if you could post some kind of example of the sorts of data you are talking about, perhaps a hex representation of the bytes (if it's a binary file). Otherwise we are just guessing how you are using the terms "block", "number", "string", and even "integer". -Peter From itsme at yahoo.com Mon Jan 10 19:11:01 2005 From: itsme at yahoo.com (It's me) Date: Tue, 11 Jan 2005 00:11:01 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: For those of us that works with complex numbers, having complex number as a natively supported data type is a big advantage. Non-native add-ons are not sufficient and lead to very awkward program code. "J?rgen Exner" wrote in message news:Fm6Ed.3556$u47.321 at trnddc09... > xah at xahlee.org wrote: > > #python supports complex numbers. > [...] > > So? > The world would come to a halt if all of a sudden nobody understands complex numbers anymore. :-) > > # Perl doesn't support complex numbers. But there are packages that > > supports it. > > The Math::Complex module is part of the standard installation already, no > need for any "packages" (whatever that might be). > Did you check "perldoc Math::Complex" > > NAME > Math::Complex - complex numbers and associated mathematical functions > [...] > > jue > > From http Sun Jan 9 20:49:19 2005 From: http (Paul Rubin) Date: 09 Jan 2005 17:49:19 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> Message-ID: <7xllb2f3z4.fsf@ruckus.brouhaha.com> "Carl Banks" writes: > And a suite, be it a def statement, a where block, or whatever, belongs > in a statement, not an expression. So do you approve of the movement to get rid of the print statement? From db3l at fitlinxx.com Mon Jan 17 17:34:35 2005 From: db3l at fitlinxx.com (David Bolen) Date: 17 Jan 2005 17:34:35 -0500 Subject: extension module, thread safety? References: Message-ID: Torsten Mohr writes: > The question came up if this is by itself thread safe, > if some two or more threads try to change these data types, > are the C functions by themselves are "atomic" or can they > be interrupted be the perl interpreter and then (data types > are in some inconsistent half-changed state) another function > that works on these data is called? I presume you mean "Python" and not "perl"... If the threads under discussion are all Python threads, then by default yes, the extension module C functions will appear to be atomic from the perspective of the Python code. When the Python code calls into the extension module, the GIL (global interpreter lock) is still being held. Unless the extension module code explicitly releases the GIL, no other Python threads can execute (even though those threads are in fact implemented as native platform threads). So in general, if you write an extension module where none of its functions ever release the GIL, there's no way for two of its functions to be run from different Python threads simultaneously. Note that this restriction won't necessarily hold if there are other ways (at the C level, or from other extension modules) to trigger code in the extension module, since that's outside of the control of the Python GIL. Nor will it necessarily hold true if your extension module calls back out into Python (as a callback, or whatever) since once the interpreter is back in Python code the interpreter itself will periodically release the GIL, or some other extension code that the callback code runs may release it. To the extent possible, it's considered good practice to release the GIL in an extension module whenever you are doing lengthy processing so as to permit other Python threads (that may have nothing to do with using your extension module) to execute. For short routines this really isn't an issue, but if your extension module will be spending some time managing its data, you may wish to add some internal thread protection around that data, so that you can use your own locks rather than depending on the GIL. -- David From boomberschloss at yahoo.com Fri Jan 14 10:46:48 2005 From: boomberschloss at yahoo.com (Joachim Boomberschloss) Date: Fri, 14 Jan 2005 07:46:48 -0800 (PST) Subject: Integration with java In-Reply-To: Message-ID: <20050114154648.70925.qmail@web53103.mail.yahoo.com> Hello, I am working on a project in Python, and I"m currently looking into the possibiliy of writing some of the project"s modules in Java. Given that a large part of the code is already written in Python, using the standard libraries and several extension modules, I am trying to gauge the viability of integration with Java via Jython with minimal impact on present code, on the complexity of future code, and on deadlines! I need to know in general how dirty it will be to combine the two languages, and what the costs I should take into account are. I"m also interested to know if there are any commonly accepted strategies to fully switch project languages (I"m considering, in the extreme case, to change it all into Java), and if writing some modules in Java and replacing the rest gradually makes sense. Three more specific questions I thought of: 1. Is is possible to pack a Jython/Java program in a py2exe-like fashion? Is it possible to pack in such a way both Python, Jython and Java code? 2. Does transferring large data structures between Java and Python code running by Jython have a significant effect on memory? For example, would passing the result of a large database query from Java to Jython, for further processing, cause the entire data to be duplicated or something similar? 3. Did I miss anything fundemental? Thanks! Joe. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From reinhold-birkenfeld-nospam at wolke7.net Fri Jan 21 14:26:36 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 21 Jan 2005 20:26:36 +0100 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> Message-ID: <35d3bcF4k9t5mU1@individual.net> A.M. Kuchling wrote: > On Fri, 21 Jan 2005 18:54:50 +0100, > Fredrik Lundh wrote: >> judging from http://yaml.org/spec/current.html (750k), the YAML designers are >> clearly insane. that's the most absurd software specification I've ever seen. they >> need help, not users. > > IMHO that's a bit extreme. Specifications are written to be detailed, so > consequently they're torture to read. Seen the ReStructured Text spec > lately? Agreed. If you just want to use it, you don't need the spec anyway. > The basic idea -- a data dumping format that's human-readable -- isn't a bad > one. OTOH, I can't recall wanting such a thing -- when I want readable > output I'm happy using > unreadable pickle files, unpickling the object and calling a .dump() or > .as_text() method.) > > But YAML seems to have started out with the goal of being human-writable, > something you would write in Emacs, Exactly. I use it as a format for config files the user can edit directly without much thinking (the explanation on top of the file are 3 lines). > and that seems to have gotten lost; the > format is now just as complicated as Restructured Text, but more cryptic > (the URI namespacing for tags, for example), not really simpler than > XML and in some ways weaker (e.g. only two encodings supported, more > complicated escaping rules). In most cases you don't need the complicated things, and the http://www.yaml.org/refcard.html isn't very complex either. Reinhold From pierre.barbier at cirad.fr Fri Jan 14 02:36:46 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri, 14 Jan 2005 08:36:46 +0100 Subject: Unclear On Class Variables In-Reply-To: References: Message-ID: <41e77621$0$19576$636a15ce@news.free.fr> Antoon Pardon a ?crit : >>Well I find this a confusing behaviour on python's part. The fact >>that instance.field can mean something different, depending on >>where in a statement you find it, makes the behaviour inconsistent. >> >>I know people in general here are against declarations, but declarations >>could IMO provide more consistency here and thus more obvious behaviour. > > > Well just to show how confusing python can be, the following piece of > code. > > | class Spam: > | eggs = [2, 3] > | > | > | sp1 = Spam() > | sp2 = Spam() > | > | print sp1.eggs, id(sp1.eggs) > | print sp2.eggs, id(sp2.eggs) > | print '--------------------' > | > | sp1.eggs += [4,] > | > | print sp1.eggs, id(sp1.eggs) > | print sp2.eggs, id(sp2.eggs) > | print '--------------------' > | > | Spam.eggs = [3,5] > | > | print sp1.eggs, id(sp1.eggs) > | print sp2.eggs, id(sp2.eggs) > | print '--------------------' > > Which produces: > > [2, 3] 1075958860 > [2, 3] 1075958860 > -------------------- > [2, 3, 4] 1075958860 > [2, 3, 4] 1075958860 > -------------------- > [2, 3, 4] 1075958860 > [3, 5] 1075959084 > -------------------- > Well ... and could someone explain this behaviour ? I don't catch it ! Pierre From invalidemail at aerojockey.com Sun Jan 9 00:44:47 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 8 Jan 2005 21:44:47 -0800 Subject: python3: accessing the result of 'if' In-Reply-To: References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> <1105236383.521393.40680@c13g2000cwb.googlegroups.com> Message-ID: <1105249487.644698.309100@c13g2000cwb.googlegroups.com> Nick Coghlan wrote: > Carl Banks wrote: > > What if the condition you wanted to test wasn't the same as the thing > > you want to save? In other words, how would you convert this? > > > > . where: > > . m = something() > > . if m > 20: > > . do_something_with(m) > > Yeah, this problem eventually occurred to me as well. However, I think a little > utility function can help solve it: > > def test(val, condition): > if condition(val): > return val > else: > return None > > if test(something(), lambda x: x < 10) as m: > print "Case 1:", m > elif test(something(), lambda x: x > 20) as m: > print "Case 2:", m > else: > print "No case at all!" I'm sorry, I really can't agree that this helper function "solves" it. IMO, it's a workaround, not a solution. And, if I may be frank, it's a pretty ugly one. Not only that, but it still doesn't work. What if the object itself is false? -- CARL BANKS From tjreedy at udel.edu Tue Jan 4 16:53:08 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 4 Jan 2005 16:53:08 -0500 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl><1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> Message-ID: "Bulba!" wrote in message > E.g. right now I would kill for a standard, built-in matrix > type The array types of Numerical Python (NumPy) and now Numarray are, defacto, Python's standard 1 to n dimensional array types. Once installed, they are as builtin as anything else. Several other packages build on top of them. > that would be as flexible as lists and dictionaries are > in Python, so that I could slurp the whole CSV file or some > other table in one instruction into a matrix that could > accomodate data types likes strings and floats (just like > dictionaries do - just, say, declare, "column 1 of matrix > contains strings, and please convert the values in column 2 > into floats"), and then easily do some fancy matrix > transformations. Numarray has a record array type. If there is not one publicly available, perhaps you could write a CSV file to record-array slurper and contribute it to the Recipes site or maybe even the CSV module. Terry J. Reedy From hodmann at lycos.nl Wed Jan 26 07:56:10 2005 From: hodmann at lycos.nl (robert) Date: 26 Jan 2005 04:56:10 -0800 Subject: execute python code from db Message-ID: Hello, Anybody knows if it's possible to execute python code from an db. db=MySQLdb.connect(host="localhost",user="r",passwd="j",db="v") c=db.cursor() c.execute("""SELECT * FROM table WHERE id = %s""", (id,)) for python_code in c.fetchall(): execute (python_code) Maybe feed python with stdin??. robert. From xah at xahlee.org Thu Jan 13 07:41:38 2005 From: xah at xahlee.org (Xah Lee) Date: 13 Jan 2005 04:41:38 -0800 Subject: how to stop google from messing Python code Message-ID: <1105620098.878376.110250@z14g2000cwz.googlegroups.com> i'm using groups-beta.google.com to post python code. Is there a way to stop google from messing with my format? it seems to have eaten the spaces in my python code. thanks. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From dbickett at gmail.com Sun Jan 16 13:27:57 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 16 Jan 2005 13:27:57 -0500 Subject: threading and sockets ? In-Reply-To: References: Message-ID: <1d6cdae3050116102711c5c041@mail.gmail.com> http://www.twistedmatrix.com/ Daniel Bickett From harold.fellermann at upf.edu Tue Jan 18 14:54:42 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 18 Jan 2005 20:54:42 +0100 Subject: pickling extension class In-Reply-To: <1gqlpxp.g66j8sl6zkutN%aleaxit@yahoo.com> References: <1gqlpxp.g66j8sl6zkutN%aleaxit@yahoo.com> Message-ID: On 18.01.2005, at 20:31, Alex Martelli wrote: > harold fellermann wrote: > >> File "/sw/lib/python2.4/pickle.py", line 760, in save_global >> raise PicklingError( >> pickle.PicklingError: Can't pickle : it's >> not found as hyper.PeriodicGrid >>>>> dir(hyper) >> ['Dir', 'Neighbors', 'PeriodicGrid', 'PeriodicPos', '__doc__', >> '__file__', '__name__', 'refcount'] >>>>> hyper.PeriodicGrid >> >> >> So pickle complains about the class PeriodicGrid not being found in >> the >> module hyper, but a dir() >> proves that python can find it. Has anyone an idea what's going wrong >> here? > > These symptomps are pretty weird -- let's try to pin things down a bit > more. The relevant few lines of pickle.py are: > > try: > __import__(module) > mod = sys.modules[module] > klass = getattr(mod, name) > except (ImportError, KeyError, AttributeError): > raise PicklingError( > > so, could you please edit your pickle.py to provide VASTLY more info, [...] > and let us know exactly what his modified pickle.py outputs...? Here it goes...: OOPS, error (exceptions.ImportError): No module named hyper Traceback (most recent call last): File "pickle_test.py", line 5, in ? pickle.dump(g,file("test","w")) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 1387, in dump Pickler(file, protocol, bin).dump(obj) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 231, in dump self.save(obj) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 338, in save self.save_reduce(obj=obj, *rv) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 414, in save_reduce save(func) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 765, in save_global raise PicklingError( pickle.PicklingError: Can't pickle : it's not found as hyper.PeriodicGrid I have noticed that the error does not occur, when the imported module ('hyper') is in the same directory as the script that pickles. When it is imported from a subpackage (like in the code I sent you) it goes wrong. - harold - -- Reality is for people who lack imagination. From http Sun Jan 2 00:08:58 2005 From: http (Paul Rubin) Date: 01 Jan 2005 21:08:58 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <7xd5woa045.fsf@ruckus.brouhaha.com> Tim Churches writes: > Can you give some URL for publicly accessible examples of what you > mean by a "NON CONTENT-ORIENTED WEB APPLICATIONS", so we can get a > better idea of what you mean? I don't think there was anything unclear about it. A spreadsheet might be a good example. From ianb at colorstudy.com Fri Jan 7 15:39:01 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Fri, 07 Jan 2005 14:39:01 -0600 Subject: Exception report library Message-ID: <41DEF365.4030209@colorstudy.com> I've been using one of several systems to catch unexpected exceptions and log them (e.g., write to a file, display on web page, email me, etc). But many are built into a particular system, or have an interesting but incomplete set of features. E.g., many web frameworks have exception reporters (and the stdlib includes cgitb), but I want to handle non-web exceptions in the same way as exceptions from web requests, and that's not generally easy. So, I'm figuring there should be some generic library that does this. Does anyone have experience with one they could recommend? PyCrash comes to mind: http://pycrash.sourceforge.net/, though the XML output doesn't excite me (but the post-mortem debugging data is nice). py.test makes nice tracebacks with extra data as well, and cgitb is another option, though I've found the code to be poorly factored for reusability when I've looked at it in the past. Zope includes an otherwise-Zope-neutral ExceptionFormatter, which isn't terribly exciting, except that it does look for __traceback_info__ local variables and create reports with those inlined. Maybe there's something better that's packaged as part of a larger framework? Does anyone have good or bad experience with PyCrash? Localized application extensibility is really useful to me as well; for instance, in a web application I like to know who the logged-in user is, and all sorts of environment information, and there's no way to do that that is common to all the environments I'd like this to work in. On the reporting end configuration and hooks are also really useful; e.g., there's no general way to display an exception report on a web page, so a web framework would have to hook into it in some way as well. I feel like there must be something out there, since every Python programmer has to deal with this sort of thing to some degree...? -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From macrocosm at fastmail.fm Thu Jan 6 18:37:29 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Thu, 06 Jan 2005 18:37:29 -0500 Subject: Python Operating System??? In-Reply-To: <10trb0mgiflcj4f@corp.supernews.com> References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <41DDCBB9.9020202@fastmail.fm> David Brown wrote: >Hello. I recently came across a free operating system called Unununium (or >something like that) and it was developed in Python and Assembly. > >Now, I have been looking for a way to make an operating system for a long >long time and the only possibilities I could find were C++ and assembly. I >don't mind assembly so much if I don't have to use it very often. But C++ is >so complicated and errors are pretty much impossible to find in the code for >me. > >So, I was wondering if it would be possible to find a bootloader that loads >a python file at startup or something... > >Is there an example somewhere of a Python OS? > >Thanks! > > > > People don't make Python OSs because it's a serious pain in the Deng-Xiao-ping. J/k, I am half kidding. Go to google groups, and search for Python OS. You will find that this topic has been discussed numerous times. There was another project other than Unununium which was Python based, but it is not being developed any longer and I fail to remember what it was called. So search away, you will find many results! Alternatively you could contact the Unununium folks for help. Note also that there are Java OSs as well (and probably others). But then again, if you don't like C++, you probably won't like Java. They can be very different languages, but in my experience, the reasons why one does not like C++ is usually due to a quality/flaw that can also be found in Java. From jbperez808 at wahoo.com Wed Jan 12 17:06:30 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Thu, 13 Jan 2005 06:06:30 +0800 Subject: "Architecture of Python" was removed ? In-Reply-To: References: <004801c4f7cb$f62d1d30$1d02a8c0@cr> Message-ID: <34llb0F4apou6U1@individual.net> Skip Montanaro wrote: > Yes, perhaps. Note that it doesn't appear that the Wayback Machine contains > the meat of the essay, just the front page. It came from a wiki. Perhaps Most of the text seems to be there, but there are some critical diagrams (images) which the Wayback Machine did not archive. From stephen.thorne at gmail.com Wed Jan 12 22:07:12 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 13:07:12 +1000 Subject: Octal notation: severe deprecation In-Reply-To: <1105575689.335040.174490@c13g2000cwb.googlegroups.com> References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105575689.335040.174490@c13g2000cwb.googlegroups.com> Message-ID: <3e8ca5c805011219073b98cb64@mail.gmail.com> On 12 Jan 2005 16:21:29 -0800, PJDM wrote: > Maybe P3K will have an integer literal like "n_b" for "the integer n in > base b". I would actually like to see pychecker pick up conceptual errors like this: import datetime datetime.datetime(2005, 04,04) Regards, Stephen Thorne From jeff at ccvcorp.com Fri Jan 7 15:06:42 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 07 Jan 2005 12:06:42 -0800 Subject: The Industry choice In-Reply-To: References: <10trej2fl8dip65@corp.supernews.com> Message-ID: <10ttqk8k1e64495@corp.supernews.com> Bulba! wrote: > On 6 Jan 2005 19:01:46 -0500, aahz at pythoncraft.com (Aahz) wrote: > > >>>Note that the so-called 'viral' nature of GPL code only applies to >>>*modifications you make* to the GPL software. The *only* way in which >>>your code can be 'infected' by the GPL is if you copy GPL source. > > >>That's not true -- consider linking to a GPL library. > > > Will someone please explain to me in simple terms what's > the difference between linking to LGPLed library and linking > to GPLed library - obviously in terms of consequences of > what happens to _your_ source code? > > Because if there isn't any, why bother with distinguishing > between the two? Releasing a product in which your code is linked together with GPL'ed code requires that your code also be GPL'ed. The GPL goes to some lengths to define what exactly "linked together" means. Releasing a product in which your code is linked together with LGPL'ed code does *not* require that your code also be (L)GPL'ed. Changes to the core library must still be released under (L)GPL, but application code which merely *uses* the library does not. (I've forgotten, now, exactly how LGPL defines this distinction...) Jeff Shannon Technician/Programmer Credit International From jstroud at mbi.ucla.edu Mon Jan 24 19:31:13 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 24 Jan 2005 16:31:13 -0800 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <41f589f9$0$3357$9b622d9e@news.freenet.de> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> Message-ID: <1106613073.2400.104.camel@lipscomb.mbi.ucla.edu> Martin v. L?wi said > Hmm. Most applications don't have any crypto needs. Any program where one stores data would have crypto needs. Here are some examples: Database, wordprocessor, spreadsheet, address book, mail program, (should I go on?). What would be the alternative to encryption to satisfy the functionality encryption provides...memorization? But I believe this may be a case of things being so obvious people forget their importance (e.g. breathing). I have written a class that goes something like this (highly simplified) class encryptFilter: def __init__(acipher): self.mycipher = acipher def open(self, filename): self.myfile = open(filename,"w") def write(data): encrypted_data = self.encrypt(data) self.myfile.write(encrypted_data) etc... Now what if acipher and this class could be made from part of the core distro? Any application could have the option of encryption with only a few lines of code: import std_crypt # other code here if get_user_pref("do_encryption"): password = my_get_password() acipher = std_crypt.AES(password) outfile = std_crypt.encryptFilter(acipher) outfile.open(filename) else: outfile = open(filename,"w") # all other code doesn't change... outfile.write(buncha_data) This could be even more simpler, but that's the general idea. The usefulness would be tremendous. From me at yahoo.com Sun Jan 2 18:02:26 2005 From: me at yahoo.com (it's me) Date: Sun, 2 Jan 2005 15:02:26 -0800 Subject: arbitrary number of arguments in a function declaration References: Message-ID: And in case it's not obvious already, you get the number of arguments that got passed down from: len(args) "Nick Coghlan" wrote in message news:mailman.65.1104694009.22381.python-list at python.org... > rbt wrote: > > How do I set up a function so that it can take an arbitrary number of > > arguments? For example, I have a bunch of expenses which may grow or > > shrink depending on the client's circumstance and a function that sums > > them up... hard coding them is tedious. How might I make this dynamic so > > that it can handle any amount of expenses? > > > > def tot_expenses(self, e0, e1, e2, e3): > > pass > > The Python Tutorial is a wonderful thing. . . > > Anyway, you can either set up your function to take a proper list, and then > discover that the sum function already exists to add up the contents of a list: > > def tot_expenses(self, expenses): > self.total_expenses = sum(expenses) > > Or, have the function take a variable number of arguments, and do the same thing: > > def tot_expenses(self, *args): > self.total_expenses = sum(args) > > Cheers, > Nick. > > -- > Nick Coghlan | ncoghlan at email.com | Brisbane, Australia > --------------------------------------------------------------- > http://boredomandlaziness.skystorm.net From sesquile at gmail.com Mon Jan 31 16:17:39 2005 From: sesquile at gmail.com (mh) Date: 31 Jan 2005 13:17:39 -0800 Subject: [ANN] Spike Asset Manager release 0.13 In-Reply-To: References: <1107196878.026930.154270@c13g2000cwb.googlegroups.com> <16894.36152.345508.583247@montanaro.dyndns.org> Message-ID: <1107206259.910842.111840@f14g2000cwb.googlegroups.com> 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? From ncoghlan at iinet.net.au Sat Jan 8 01:38:04 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 16:38:04 +1000 Subject: switching an instance variable between a property and a normal value In-Reply-To: References: Message-ID: <41DF7FCC.8070503@iinet.net.au> Steven Bethard wrote: > I'd like to be able to have an instance variable that can sometimes be > accessed as a property, and sometimes as a regular value, e.g. something > like: If you want the behaviour to be switchable per-instance, you have to go the route of always running through the property machinery, since property() creates a descriptor on the class, not the instance. On the other hand, if you want to switch the behaviour of every instance, then making usevalue and usefunc class methods may give you some mileage. I'm rather curious about your use case, though. . . Here's a different way of using the property machinery, too: Py> class C(object): ... def __init__(self): ... self._use_val = None ... def useval(self, x): ... self._val = x ... self._use_val = True ... def usefunc(self, func, *args, **kwds): ... self._func, self._args, self._kwds = (func, args, kwds) ... def _get(self): ... use_val = self._use_val ... if use_val is None: ... raise AttributeError('x') ... if use_val: ... return self._val ... else: ... return self._func(*self._args, **self._kwds) ... x = property(_get) ... Py> c = C() Py> c.useval(4) Py> c.x 4 Py> c.usefunc(list) Py> c.x [] -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From janeaustine50 at hotmail.com Sat Jan 8 23:13:49 2005 From: janeaustine50 at hotmail.com (Jane Austine) Date: 8 Jan 2005 20:13:49 -0800 Subject: time module precision Message-ID: What is the precision (and accuracy) of time module on a Windows XP machine? threading module depends on time module so it's precision(and accuracy) is up to time module's. | for i in xrange(1000): | time.sleep(0.001) This sleeps for awhile, which means 0.001 sec is not ignored. On the other hand, | for i in xrange(10000): | time.sleep(0.0001) This returns right away. 0.0001 sec is ignored and lost in the air. So can I tell the time.sleep's precision is 1ms? Any other way to increase the precision? (Using busy waiting -- spinning loop -- is not a good option, it makes over 90% cpu usage) Jane From ptmcg at austin.rr._bogus_.com Tue Jan 11 18:28:54 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 11 Jan 2005 23:28:54 GMT Subject: Time script help sought! References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> <1105477084.525279.312970@f14g2000cwb.googlegroups.com> <1105479292.689762.155510@f14g2000cwb.googlegroups.com> <1105480151.431987.327080@c13g2000cwb.googlegroups.com> <1105485509.346577.292130@f14g2000cwb.googlegroups.com> Message-ID: wrote in message news:1105485509.346577.292130 at f14g2000cwb.googlegroups.com... > man, now that is beautifully done. Paul, I wish I knew about pyparsing > a while ago. I could have used it in a few projects. :) > Thanks for the compliment! I'll be the first to admit that pyparsing can be a bit persnickety in some applications, especially when you have to trap on end-of-line, or have some columnar-dependent syntax. pyparsing really works best with data that has some syntactic structure to it, but is not whitespace sensitive (pyparsing's default behavior is to skip over whitespace). I don't recommend it when the data is well-formed - regexp's or even just string.split() will blow it away from a performance (and simplicity) standpoint. For instance, if the OP knew that all his data was itemId, tapeId, recordNum, startTime, endTime, comment, he could have most easily parsed it with item, tape, recordNum, startTime, endTime, comment = dataline.split(None,5) It's just those optional and variable-formatted fields that getcha. :) -- Paul pyparsing can be downloaded at http://pyparsing.sourceforge.net. From jerf at jerf.org Mon Jan 31 00:00:22 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 31 Jan 2005 00:00:22 -0500 Subject: python and gpl References: Message-ID: On Sun, 30 Jan 2005 22:25:10 -0600, John Hunter wrote: > The question is: does shipping a backend which imports a module that > links with GPL code make some or all of the library GPL. This > question is complicated, in my mind at least, by several factors. I believe the best and most honest answer right now is, "Nobody knows." In fact, a careful reading of at least the LGPL (which I recently carefully read before putting a project under it, so I can speak to it where I can't speak to the GPL with quite as much confidence) shows that it is almost hopelessly based on the C way of doing things, with "linking" and "executables", that not only doesn't apply to Python, but doesn't apply to a lot of other modern languages as well. (I am fairly confident that the GPL has identical shortcomings, I just haven't read it as recently.) Specifically, I put a Javascript project under the LGPL and felt compelled to augment it with an appendix of just under 3K, just to make the LGPL make sense. I had to redefine "library", clarify the "work based on the library" and "work using the library" distinction in a context where there is no "linking" occurring, and correctly apply my Appendix to the clause that allows you to use future versions of the LGPL. And my problem is much simpler than yours. (I'm in control of the license, so I was able to simply clarify it, but there would still be the problem of what the raw LGPL would mean to someone had I not amended it, so from a certain point of view there is some similarity despite the difference in our positions; it is the user dilemma that prompted my solution.) Right now, when it comes down to it, I don't think we can even define "program" in a legal sense that is clear and useful; without that, trying to *deeply* understand the (L)GPL is probably a hopeless affair. From fredrik at pythonware.com Wed Jan 26 11:49:35 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Jan 2005 17:49:35 +0100 Subject: Help With Python References: Message-ID: Peter Maas wrote: > > Can anybody help me get started? I am completely new to programming! > Online: > > - http://www.python.org/moin/BeginnersGuide (Beginner, Advanced) > - http://www.freenetpages.co.uk/hp/alan.gauld/ (Beginner) > - http://docs.python.org/tut/tut.html (Beginner) > - http://diveintopython.org/ (Advanced) also: http://www.byteofpython.info/ > Books (Look for most recent editions): > > - Mark Lutz, Learning Python (Beginner) > - Alex Martelli, Python in a Nutshell (Beginner, Advanced) > - Frederik Lundh, Python Standard Library (Beginner, Advanced) on-line here: http://effbot.org/librarybook on-line here: http://effbot.org/zone/librarybook.htm (pdf version) > - Alex Martelli, Python Cookbook (Beginner, Advanced) > - Mark Pilgrim Dive Into Python (Advanced) on-line here: http://diveintopython.org From michele.simionato at gmail.com Thu Jan 27 06:40:24 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 27 Jan 2005 03:40:24 -0800 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106814263.835719.181360@z14g2000cwz.googlegroups.com> Message-ID: <1106826024.655143.227050@c13g2000cwb.googlegroups.com> Peter Maas: >michele.simion... at gmail.com schrieb: >> Davor is right: even if >> you do not want to use it, the stuff is *there* and somebody in your >> team will. So definitely there is an audience of programmers that just >> do not have an use for all the sophistication and actually are >> penalized by it. >No, because Python does not enforce using advanced concepts. You >can write programs that are as simple as in 1991. A group of developers >always has to find some kind of common style with a chance that some >are penalized. This can happen with every language. No. In theory C++ could be kept as simple as C but in practice it is not. >> There is not much than can be done at the Python level. But I would >> see with interest a Python spinoff geared towards simplicity. >I think this would be useless because advanced concepts exist for >a reason. A simplified spin-off would aquire advanced concepts >over time and would just become a clone of Python. And then we will need another simplified spinoff ;) There is always a fight between simplificity and complexity. Some complexity is not needed, and I am sure even in Python something could be dropped. But it is difficult to find what can be removed. Remember that Saint-Exupery quote? Something like "a work of art is finished when there is nothing left to remove?" M.S. From jeff at ccvcorp.com Tue Jan 11 15:41:44 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 11 Jan 2005 12:41:44 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <10u5fu3o7v4h9e3@corp.supernews.com> Message-ID: <10u8e65lju3atbd@corp.supernews.com> Jacek Generowicz wrote: > Given a population with previous exposure to computer programming, my > money is on the map-lambda version. But this last point is mostly > irrelevant. The fact is that you cannot program computers without > doing a bit of learning ... and the lambda, map and friends really do > not take any significant learning. I guess we'll have to agree to disagree, because given the same conditions, I *still* think that a list comprehension expresses its semantics more clearly than map/lambda. I'd also point out that not all Python programmers will have significant prior exposure to programming ideas, and even those who do will not necessarily have prior exposure to lambdas. It's true that programming requires learning, and that map/lambda aren't a tremendous burden to learn. Still, to my mind they make a program a tiny increment more complicated. (I find that reading a lambda requires mentally pushing a stack frame to parse the lambda and another to translate map() into a loop, whereas a list comp's expression doesn't require such a shift, and a function name works as a good placeholder that makes reading easier.) It's not a big difference in any individual case, but incremental differences build up. From the sounds of it, you may have the opposite experience with reading map/lambda vs. reading list comps, though, so we could go back and forth on this all week without convincing the other. :) >>Speaking for *this* laboratory rat, at least, map/lambda was always a >>nasty puzzle for me and difficult to sort out. But when list comps >>were introduced, after reading just a sentence or two on how they >>worked, they were completely clear and understandable -- much more so >>than map/lambda after many months of exposure. > > Forgetting about lambda, map, filter and reduce, do you find that you > pass callables around in your Python programs, or is this not > typically done in your programs? Sure, I pass callables around quite a bit. Usually they're GUI callbacks or the like. Usually they're also either complex enough that lambda would be undesireable if not impossible, or they're simple and numerous (e.g. calling a function with different parameters) such that it's easy to write a factory function that returns closures rather than feed the parameter in with a lambda. Jeff Shannon Technician/Programmer Credit International From tim at pollenation.net Sat Jan 29 09:41:05 2005 From: tim at pollenation.net (Tim Parkin) Date: Sat, 29 Jan 2005 14:41:05 +0000 Subject: Textual markup languages (was Re: What YAML engine do you use?) In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> Message-ID: <1107009665.5655.19.camel@localhost.localdomain> On Sun, 2005-01-23 at 13:41 +0100, Fredrik Lundh wrote: > Alan Kennedy wrote: > > If I can't find such a markup language, then I might instead end up using a WYSIWYG editing > > component that gives the user a GUI and generates (x)html. > > > > htmlArea: http://www.htmlarea.com/ > > Editlet: http://www.editlet.com/ > > > > But I'd prefer a markup solution. > > some of these are amazingly usable. have you asked your users what they > prefer? (or maybe you are your user? ;-) Most users prefer to write documents in word and then paste them into textareas. Not surprisingly means no semantic content, little chance of restyling, horrible encoding problems and far too long spent on the phone trying to explain why it's not a good idea. Giving users a wysiwyg textarea creates the problems that users start to spend time trying to create a 'styled' document, inevitably sacrificing semantics (many is the user that has applied a header style to make things bold or a quote sytle to indent a paragraph). Using text based layouts reinforces the perception that you aren't creating a styled document and that the semantic structure is important. People who have used non-wysiwyg editors have found that their initial reticence has been quickly overtaken by their joy at not having to fight with 'style' and the reassurance that their content is now 'redesign proof'. Tim Parkin http://www.pollenation.net From tjreedy at udel.edu Mon Jan 24 20:36:56 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Jan 2005 20:36:56 -0500 Subject: Another scripting language implemented into Python itself? References: Message-ID: "Roy Smith" wrote in message news:roy-97DBC5.19403124012005 at reader1.panix.com... > In article , > Quest Master wrote: > >> So, my question is simply this: is there an implementation of another >> scripting language into Python? > > Python *is* a scripting language. Why not just let your users write > Python modules which you them import and execute via some defined API? That was my thought also, with the note that you only need to document as much users will need, including specific modules (if any) to import. Terry J. Reedy From wittempj at hotmail.com Mon Jan 17 06:25:21 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 03:25:21 -0800 Subject: getting a class attribute using a keyword argument In-Reply-To: References: Message-ID: <1105961121.277992.105630@f14g2000cwb.googlegroups.com> Guy Robinson wrote: > Hello, > > I have a list of class instances. I wish to get the appropriate class attribute > in each class instance depending on a SINGLE keyword in the calling class. > > How do I get the calling method to correctly recognise the keyword as a keyword > and not a class attribute? See example code below (which doesn't work). > > class tocall: > def __init__(self): > self.title = "test" > self.name = "name" > > def callingmethod(self,**kw): > for key in kw: > if tocall.key == kw[key]: > return tocall.key > > which should work as such(but doesn't): > > print callmethod(title = "test") > print callmethod(name = "name") > > Regards, > > Guy You probably want something like this: class tocall: def __init__(self): self.title = "test" self.name = "name" x = tocall() print getattr(x, 'title') print getattr(x, 'name') print getattr(x, 'bogus') From john.abel at pa.press.net Wed Jan 26 08:18:36 2005 From: john.abel at pa.press.net (John Abel) Date: Wed, 26 Jan 2005 13:18:36 +0000 Subject: FTP Server In-Reply-To: <1106743852.600769.72820@c13g2000cwb.googlegroups.com> References: <1106743852.600769.72820@c13g2000cwb.googlegroups.com> Message-ID: <41F798AC.3010305@pa.press.net> If you're after a simple FTP server, have a look at medusa. Regards John michele.simionato at gmail.com wrote: >What's the simplest way to write an FTP Server in Python? >A short research on the newsgroup and on the Cookbook did not >bring out anything relevant (but I hear a little voice in the >back of my head saying Twisted, Twisted! ...) >Michele Simionato > > > From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Tue Jan 25 06:15:03 2005 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Tue, 25 Jan 2005 12:15:03 +0100 Subject: Right place for third party modules (here: fixedpoint) In-Reply-To: References: <35kj2iF4n6sokU1@news.dfncis.de> Message-ID: <35mo1gF4oqib4U1@news.dfncis.de> Fredrik Lundh schrieb: > > ah, forget what I said. you need to put the fixedpoint.py *file* under site-packages, > not the entire directory. as that "python -v -v" would have told you: > Thank you (and Steve Holden), that did it. > >>more out > > ... > # trying C:\python24\lib\site-packages\fixedpoint.pyd > # trying C:\python24\lib\site-packages\fixedpoint.dll > # trying C:\python24\lib\site-packages\fixedpoint.py > # trying C:\python24\lib\site-packages\fixedpoint.pyw > # trying C:\python24\lib\site-packages\fixedpoint.pyc > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named fixedpoint > ... > > > Very helpful, not only directories, but full module names. I hope I'll remember (or find) "python -v -v" next time around. Python is nice, but Python + c.l.p. is a Really Good Thing. Koczian -- Dr. Sibylle Koczian Universitaetsbibliothek, Abt. Naturwiss. D-86135 Augsburg Tel.: (0821) 598-2400, Fax : (0821) 598-2410 e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From stephen.thorne at gmail.com Sun Jan 9 05:45:16 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Sun, 9 Jan 2005 20:45:16 +1000 Subject: Pre/Postconditions with decorators In-Reply-To: <7x1xcvwkdj.fsf@ruckus.brouhaha.com> References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> <34814fF43bm4cU1@individual.net> <7x1xcvwkdj.fsf@ruckus.brouhaha.com> Message-ID: <3e8ca5c805010902455ef60947@mail.gmail.com> On 08 Jan 2005 15:50:48 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Stephen Thorne writes: > > Unresolved Problems: > > 1) How do you handle duck types, i.e. a method that accepts StringIO, > > cStringIO or any other object that has a .readlines(), .seek() and > > .read() method? > > That should really be done through having those classes inherit a > file-operations mixin, or else through interfaces (which might get > added to Python). Working under the assumption we cannot change the existing standard library. > > 2) How do you turn off the type checking for production code? > > It should be left on. Leaving it in for development and turning it > off for production is like wearing a parachute during ground training > and taking it off once you're in the air. So we can't use this for a case where we have an extremely large list then ;). Its an O(n) operation to just call a function that takes a list of a specific type. Stephen. From python-url at phaseit.net Sun Jan 9 12:11:09 2005 From: python-url at phaseit.net (Josiah Carlson) Date: Sun, 09 Jan 2005 17:11:09 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 9) Message-ID: QOTW: Jim Fulton: "[What's] duck typing?" Andrew Koenig: "That's the Australian pronunciation of 'duct taping'." "I'm thinking that the I-Ching is a vast untapped resource for programming wisdom, plus it makes it funny." -- Mark Carter Nick Coghlan brings up the 'lambdas are going away in 3.0' topic, which has been discussed before: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/81e17b1d3ccba538 A user asks about a non-generator-based method for iteration using class __iter__ and next() methods: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/6336a00ad217888a Daniel Bickett asks about getting Twisted and wxPython working together, and receives both a threaded and non-threaded version: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/73f1e7758225afc3 A question about iterating over floats...be careful! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1278866159ac4429 A Boogieman asks whether Python is easily learned and what can be done with it. Quick answer: yes, and anything you are capable of doing: This Boogieman later asks about GUI toolkits: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e67b776df72eb336 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d502698b4adacd01 Erik Bethke writes Majong game after using Python for a month. Ahh, will the wonders of Python never cease? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/6d710e35007f0f32 Kamilche asks about getting warnings when not calling a function, and gets pointed to pychecker, something more of us should be using: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/dff810b7dacd247c Are people allowed to build commercial applications in Python? YES! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/aa953388db68b196 Questions about asyncore brings up a web server in asyncore from _Python Web Programming_, and a pointer to Twisted. Alternatively, one could look at the asynchat or smtpd modules in the standard library as sources of inspiration: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/81360ec06013e36d ======================================================================== 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 pythongnome at hotmail.com Thu Jan 6 17:10:33 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Thu, 06 Jan 2005 22:10:33 GMT Subject: Python Operating System??? In-Reply-To: <10trb0mgiflcj4f@corp.supernews.com> References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: David Brown wrote: > Hello. I recently came across a free operating system called Unununium (or > something like that) and it was developed in Python and Assembly. > > Now, I have been looking for a way to make an operating system for a long > long time and the only possibilities I could find were C++ and assembly. I > don't mind assembly so much if I don't have to use it very often. But C++ is > so complicated and errors are pretty much impossible to find in the code for > me. > > So, I was wondering if it would be possible to find a bootloader that loads > a python file at startup or something... > > Is there an example somewhere of a Python OS? > > Thanks! > > Hasn't there been numerous discussions about this in the past?? From lbates at syscononline.com Wed Jan 19 11:01:43 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 19 Jan 2005 10:01:43 -0600 Subject: Accessing MDB files on Windows In-Reply-To: <1635068.ZTfiooUzB4@strongwill.g2ctech> References: <1635068.ZTfiooUzB4@strongwill.g2ctech> Message-ID: I'm assuming the application will be run on Windows. You can use ODBC or DAO. An DAO solution that I wrote (and use) can be found at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303349 For ODBC you would just use the standard library module. Larry Bates Syscon, Inc. Jorge Luiz Godoy Filho wrote: > Hi, > > > What is the best way to deal with MDB files? I was thinking on using > ODBC... I'll need to read and write some information to it. The load > won't be so high, but there might be a lot of data. > > Any advices? Will my approach work? I'm not a Windows guy... :-) > From b_b at net.hr Sat Jan 15 11:29:57 2005 From: b_b at net.hr (Brane) Date: Sat, 15 Jan 2005 17:29:57 +0100 Subject: python to mssql References: Message-ID: <19womotgpx7sg.qru1ognhkyt7.dlg@40tude.net> On Fri, 14 Jan 2005 15:22:44 -0500, Richards Noah (IFR LIT MET) wrote: > "Robert Brewer" wrote in message > news:mailman.722.1105724341.22381.python-list at python.org... > Brane wrote: >> can someone please give me some info regarding subject >> >>http://sourceforge.net/projects/mysql-python >> >>Ask a broad question... >> >> >>Robert Brewer > > Robert, the question was about 'mssql', not 'mysql'. As for mssql, a search > on google will give you the following as the first result: > http://pymssql.sourceforge.net/ > > with others on the page that include: > http://www.object-craft.com.au/projects/mssql/ > http://www.egenix.com/files/python/eGenix-mx-Extensions.html > > > Don't be lazy, Brane. Your first point of reference should _always_ be > google. The fact that "I'm Feeling Lucky" points you to pymssql shows that > you didn't do any research before posting here. > > -Noah well i wonted to hear frome someone who already used it because there is lots of topics about subject anyway thnks for info brane From enleverlesO.OmcO at OmclaveauO.com Mon Jan 24 17:52:19 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Mon, 24 Jan 2005 23:52:19 +0100 Subject: add indexes on the fly to lists References: Message-ID: <41f69f0b$0$6606$8fcfb975@news.wanadoo.fr> Hi ! If you want only "search and found" element, look dictionnary ; if you want also to have the order, see the module set. Good night -- Michel Claveau From smitsky at mindspring.com Sat Jan 8 19:37:50 2005 From: smitsky at mindspring.com (Smitsky) Date: Sun, 09 Jan 2005 00:37:50 GMT Subject: Windows XP Installation Message-ID: Hi. I am a newbie to Python. I am running Win XP and want to know what the best course is for installing Python on my system. Could someone kindly direct me to some related resources? Thanks in advance, Steve From sjmachin at lexicon.net Tue Jan 18 02:41:31 2005 From: sjmachin at lexicon.net (John Machin) Date: 17 Jan 2005 23:41:31 -0800 Subject: Fuzzy matching of postal addresses References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <1106034091.153664.309670@z14g2000cwz.googlegroups.com> You can't even get anywhere near 100% accuracy when comparing "authoritative sources" e.g. postal authority and the body charged with maintaining a database of which streets are in which electoral district -- no, not AUS, but close :-) From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 12:27:15 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Mon, 10 Jan 2005 18:27:15 +0100 Subject: Writing huge Sets() to disk In-Reply-To: References: Message-ID: <41E2BAF3.9070106@ribosome.natur.cuni.cz> Paul McGuire wrote: > "Martin MOKREJ?" wrote in message > news:mailman.448.1105373471.22381.python-list at python.org... > >>Hi, >> I have sets.Set() objects having up to 20E20 items, >>each is composed of up to 20 characters. Keeping >>them in memory on !GB machine put's me quickly into swap. >>I don't want to use dictionary approach, as I don't see a sense >>to store None as a value. The items in a set are unique. >> >> How can I write them efficiently to disk? To be more exact, >>I have 20 sets. _set1 has 1E20 keys of size 1 character. >> >>alphabet = ('G', 'A', 'V', 'L', 'I', 'P', 'S', 'T', 'C', 'M', 'A', 'Q', > > 'F', 'Y', 'W', 'K', 'R', 'H', 'D', 'E') > >>for aa1 in alphabet: >> # l = [aa1] >> #_set1.add(aa1) >> for aa2 in alphabet: >> # l.append(aa2) >> #_set2.add(''.join(l)) >>[cut] >> >> The reason I went for sets instead of lists is the speed, >>availability of unique, common and other methods. >>What would you propose as an elegant solution? >>Actually, even those nested for loops take ages. :( >>M. > > > _set1 only has 19 keys of size 1 character - 'A' is duplicated. Ahh, you are right. That's a typo, yet I have to figure out which char I have to use. But 'Z' will do for the tests anyway. > > Assuming you replace 'A' with another character (say 'Z'), then here is what > you get: > _set1 - 20 elements (20**1) > _set2 - 400 elements (20**2) > _set3 - 8000 elements (20**3) > ... > _set20 - 20**20 ~ 10 ^ (1.301*20) or 1E26 > > If you have no duplicates in your alphabet, then you wont need to use sets, > every combination will be unique. In this case, just use a generator. As I noted in later response, actually I will compare these ideal sets to some real world examples. I have no expectation how many entries will be common and how many unique. The only thing I know even in real world, I might be in size ranges of 2E6 or perhaps 2E8? > Here's a recursive generator approach that may save you a bunch of nested > editing (set maxDepth as high as you dare): > > alphabet = ('G', 'A', 'V', 'L', 'I', 'P', 'S', 'T', 'C', 'M', 'Z', 'Q', 'F', > 'Y', 'W', 'K', 'R', 'H', 'D', 'E') > > maxDepth = 3 > > def genNextCombo(root=list(),depth=1): > for a in alphabet: > thisRoot = root + [a] > yield "".join( thisRoot ) > if depth < maxDepth: > for c in genNextCombo(thisRoot, depth+1): > yield c > > for c in genNextCombo(): > print c # or write to file, or whatever Works nice, but http://www.python.org/doc/2.3.4/ref/yield.html doesn't really tell what happens here. :( But is quite fast and definitely saves those the stupid recursively hand-written for loops. Thanks Paul! M. From pierre.barbier at cirad.fr Wed Jan 19 03:07:59 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Wed, 19 Jan 2005 09:07:59 +0100 Subject: extension module, thread safety? In-Reply-To: References: <41ecbaae$0$1046$626a14ce@news.free.fr> <41eccfe4$0$16621$636a15ce@news.free.fr> Message-ID: <41ee14f7$0$26194$626a14ce@news.free.fr> David Bolen a ?crit : > Nick Coghlan writes: > > And even before that it was certainly possible to call into the Python > interpreter from a native thread using existing functions, albeit the > newer functions are more convenient (and perhaps more robust, I don't > know). > > My earliest interaction with Python (~1999, while writing a module > that extended and embedded Python 1.5.2) used PyEval_AcquireThread() > and PyEval_ReleaseThread() to get access to a thread state from a > native C application thread (not initiated by the Python interpreter) > to allow me to call safely into an executing Python script upon > asynchronous data reception by the C code. > > -- David Yes, now you mention this I remember trying to use these functions ! But there is two problems with them (and only one is solved by the new functions) ! The first problem is the dead lock is you try to acquire the same thread twice. This implies a very low level use of these function, and it can be a real pain to find where to put them without risking this dead lock. This is no more a problem with the new functions. But the second (and not solved) problem is: these functions block the current thread when you try to get the GIL ! This is an issue if you don't want your GUI thread to be blocked when a buggy module does not release the GIL during long computations. I didn't find any function like "test the state of the GIL and if it's free, then acquire it" ! And, IMO, it's missing ... Then, if python goes to a model where critical sections are identified and the GIL acquired only there, all these problems will disappear ! That's why I really hope Python 3 will include this kind of thread support ... Pierre From dw at botanicus.net Sun Jan 9 18:23:58 2005 From: dw at botanicus.net (David Wilson) Date: Sun, 09 Jan 2005 23:23:58 +0000 Subject: vi and python In-Reply-To: <20050110032348.GA1960@mrna.tn.nic.in> References: <20050110032348.GA1960@mrna.tn.nic.in> Message-ID: <41E1BD0E.1010805@botanicus.net> km wrote: >Is there a way to display inbuilt function syntax as the user starts typing a function name with 'Vi' editor in console mode? > > Hi there, Unfortunately due to the highly dynamic nature of Python, this is difficult to do reliably. It is one benefit that static typing, to a certain extent, would bring to the language. Sadly we don't have that, yet. :) David. From bokr at oz.net Wed Jan 5 15:07:43 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 05 Jan 2005 20:07:43 GMT Subject: Deferred expressions (was Re: Lambda as declarative idiom) References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: <41dc4099.75876003@news.oz.net> On Tue, 04 Jan 2005 19:31:37 +1000, Nick Coghlan wrote: >Steven Bethard wrote: >> Nick Coghlan: def-from syntax [4] >> (def f(a) + o(b) - o(c) from (a, b, c)) >> (def x * x from (x)) >> (def x from ()) >> (def x.bar(*a, **k) from (*a, **k)) >> ((def x(*a, **k) from ()) for x, a, k in funcs_and_args_list) > >After a bit more musing, this is definitely my preferred syntax. I'd call it a >'deferred expression' rather than an anonymous function, though. The name change >may seem minor, but it changes the emphasis of the feature from how it's >implemented to what it is useful for (i.e. deferring evaluation of an expression >until call time). I like the fact that 'def' can serve as a mnemonic for 'defer' or 'deferred' ;-) OTOH, I like concise notation for expressions, and the def and from aren't really necessary if you can tag the first expression with some syntax marker. I suggested (: rather than (def since (: is illegal now and won't break anything. But all this is just a rewrite of lambda params:expr as (def expr from params). What is the point again? (Not that my rewrite to (:expr)(params) is any more than a lambda rewrite either). If backticks could be used, `(expr:params) might be an interesting spelling of lambda params:expr. I do like being able to leave out the from clause. `(expr) would let you do that too, just as well as (:expr). > >It's also conducive to a clean no-argument syntax - simply make the 'from' claus >optional when the argument list is empty. That is an advantage of having it inside the outer parens, which my (:expr)(params) couldn't benefit from -- unless I just take your format and substitute ':' for both def and from: (: f(a) + o(b) - o(c) : (a, b, c)) (: x * x : (x)) (: x) # empty arg list (: x.bar(*a, **k) : (*a, **k)) ((: x(*a, **k) : (x=x, a=a, k=k) for x, a, k in funcs_and_args_list) > >'def' and 'from' are already keywords, so there shouldn't be any compatibility >problems. > >Michael Spencer's idea of using 'for' instead of 'from' was quite interesting, >but the use of 'for' without a corresponding 'in' feels a bit misleading :) What was the point of all this again? Pretending lambda goes away without really killing it? ;-) Regards, Bengt Richter From kent3737 at yahoo.com Wed Jan 26 11:21:40 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Wed, 26 Jan 2005 11:21:40 -0500 Subject: re.search - just skip it In-Reply-To: <1106754436.876675.144290@c13g2000cwb.googlegroups.com> References: <1106754436.876675.144290@c13g2000cwb.googlegroups.com> Message-ID: <41f7c10b$1_1@newspeer2.tds.net> rasdj at frontiernet.net wrote: > Input is this: > > SET1_S_W CHAR(1) NOT NULL, > SET2_S_W CHAR(1) NOT NULL, > SET3_S_W CHAR(1) NOT NULL, > SET4_S_W CHAR(1) NOT NULL, > ; > > .py says: > > import re, string, sys > s_ora = re.compile('.*S_W.*') > lines = open("y.sql").readlines() > for i in range(len(lines)): > try: > if s_ora.search(lines[i]): del lines[i] When you delete for example lines[0], the indices of the following lines change. So the former lines[1] is now lines[0] and will not be checked. The simplest way to do this is with a list comprehension: lines = [ line for line in lines if not s_ora.search(line) ] Even better, there is no need to make the intermediate list of all lines, you can say lines = [ line for line in open("y.sql") if not s_ora.search(line) ] In Python 2.4 you don't have to make a list at all, you can just say open("z.sql","w").writelines(line for line in open("y.sql") if not s_ora.search(line)) ;) Kent > except IndexError: > open("z.sql","w").writelines(lines) > > but output is: > > SET2_S_W CHAR(1) NOT NULL, > SET4_S_W CHAR(1) NOT NULL, > ; > > It should delete every, not every other! > > thx, > > RasDJ > From http Sat Jan 29 07:11:41 2005 From: http (Paul Rubin) Date: 29 Jan 2005 04:11:41 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> Message-ID: <7xacqsbfk2.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > Indeed, if it was a single new function to an existing module, I would > not require that this be delivered to users first. It is entire new > libraries that I worry about. Why is it different if a single new function is added to an existing module, or if the single new function has the boilerplate of a new module wrapped around it? Look at the sha and md5 modules. They are very similar in both interface and implementation. The only internal function that's really different is the update operation; they actually might have been combined into one module that did the other operations with the same code. But, it's also reasonable to have them as separate modules. If users start needing sha256, it could be done the same way, one new update operation and the rest boilerplate, but in practice it would probably be a separate module. Are you saying if there was user demand for an sha256 module and someone wrote one, you'd still require a year of separate distribution? > A module *is* typically more complex than a single function. If > your new module has only a single new function, we should discuss > whether it really needs to be a separate module. I previously had the mistaken belief that urandom was a new module rather than a function inserted into an existing module. Note that the urandom's implementation is not ultra-trivial. An AES or DES addition to an existing module that implements just one call: ECB(key, data, direction) would be a huge improvement over what we have now. A more complete crypto module would have some additional operations, but ECB is the only one that's really essential. I already have a pure-Python module that does all the other operations using ECB as a subroutine. It's speed isn't great but it's useable in some real applications. It's only the ECB operation that's intolerably slow in Python. If you think a function like that could be added to some existing module with less hassle than adding a new module, then I can write one and submit it. > > Well, if he indicates that it's not a policy and that the question is > > still open, then I could see getting interested again in writing an > > AES module. At the moment I continue to see his python-dev post as > > quite discouraging. > > And, again, I consider this perfectly fine. This would be a volunteer > effort, and volunteers are free to work on whatever they please. Well, volunteers are more likely to work on modules that are mentioned as being welcome by the developers, than modules affected by explicit prior developers' public decisions that cast a chill over the hope of ever getting such a module accepted. > Furthermore, people who want an AES module for Python could get one from Come on, you're being deliberately obtuse, we've discussed this over and over. There are plenty of AES modules that people can get from somewhere. The topic is what it takes to have an AES module that people don't NEED to get from anywhere, because they already have it from having Python installed. Do I have to keep repeating "batteries included" until you understand what it means? > http://sourceforge.net/projects/cryptkit/ > > Maybe Bryan Mongeau will contribute this code to Python some day. Well, that code has been around for over a year, people are using it, etc. Are you saying you'll support its inclusion if Bryan offers to contribute it? I've examined that module, I wouldn't consider it ideal for the core (besides AES, it has some complicated additional functions that aren't useful to most people), but it would certainly take care of my AES needs (it's apparently missing DES though). > I did not say that. I said we don't normally invite people to work > on anything - I said not that we *should* not invite them. I would say that inviting people to work on a module for the stdlib means the developers have thought about whether such a module would be useful and worth including, and are indicating that they're favorable to the idea. However, you wrote: In Message-ID: <41f4324a$0$1547$9b622d9e at news.freenet.de> So if the module was primarily written to be included in the core, I would initially reject it for that very reason. After one year or so in its life, and a recognizable user base, inclusion can be considered. The context was new modules in general, not specifically an AES module. Since "considered" means "thought about", so you said inclusion shouldn't even be thought about until the module is already done. That's completely in conflict with the idea of inviting anyone to work on a new module, since inviting means that there's been some thought. > Now that you mention it, I find that there is an important exception > from my factual statement: I do regularly ask people reporting bugs > or requesting features to work fixing the bugs or implementing the > features. It is perfectly fine if they say "no" then. If they say > yes, there is an implied promise that I'll review their code when > they are done. I would say there's an implied promise of something more than a code review. There's an implied statement that you agree that the proposed new functionality is useful, which means the patch has a good chance of being accepted to the stdlib if it's not too messy or cumbersome. That's a heck of a lot different from saying "why don't you write that patch and distribute it independently for a year on a purely speculative basis, and then I'll think about whether it's worthwhile to include it or not". > As it appears to be clear that you are not going to implement an AES > module in the foreseeable future, The reason for that is as far as I can tell, even if I follow 100% of your prescription of writing the module, releasing it independently and supporting it for a year, and then offering to contribute it complete with favorable user reviews and a promise of two years of further support, the probability of it being accepted and included is still close to zero. In more recent messages you've suggested that my reading of that probability is wrong and that it's actually higher than zero. So let me just ask you one final question: suppose I do all that stuff. The question: in your personal opinion, based on the best information you have, what is the your own subjective estimate of the probability? I won't say I'd immediately replace my estimate with yours, but if you name a reasonably high number and tell me that you really believe that number, then I could get interested again. > and as it also seems to be clear that you cannot talk me into > changing my views on how Python should be developed, I think further > discussing this entire thing is pointless. Well, you can have whatever views you want, but one I've thing I've realized from this thread is that many of the frustrations I often encounter with Python are a direct result of a development process that's successful in some ways but dysfunctional in others. From itsme at yahoo.com Thu Jan 6 20:58:51 2005 From: itsme at yahoo.com (It's me) Date: Fri, 07 Jan 2005 01:58:51 GMT Subject: Another PythonWin Excel question References: <41ddb59e$0$8338$afc38c87@news.optusnet.com.au> Message-ID: Yes, Mike, Others pointed that out as well. The difficulty is that they are all in VBAs. Most of them can be translated to Python fairly easily, and some I can get from looking at the recorded macro - but some requires quite a bit of head scratching. For instance, I wanted to figure out how create a new window. So, I went through the record macro process and looked at the VBA code, it says: ActiveWindow.NewWindow Okay. Now what??? And for switching window, it says: Windows("Book1:1").Activate Okay. ??? So, I look through the online information on msdn and viola! No mentioning of that anwhere.... Would be nice if there's a Python specific of it....but just dreaming... Back to reading MSDN..... Thanks, "Mike Thompson" wrote in message news:41ddb59e$0$8338$afc38c87 at news.optusnet.com.au... > It's me wrote: > > I followed the example in > > http://stompstompstomp.com/weblog/technical/2004-05-20 and learned that to > > add a new worksheet to an Excel workbook, you would use the > > workbook.Worksheets.Add() method. That works. However, the new worksheet > > got added *in front* of the last worksheet I was at. How can I get it to > > add *after*? > > > > Thanks, > > > > -- > > Me > > > > > > Does this help? > > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrtskhowtomoveworksheetswithinworkbooks.asp > > -- > Mike From kbk at shore.net Sun Jan 23 15:15:45 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Sun, 23 Jan 2005 15:15:45 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200501232015.j0NKFjhi001559@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 273 open ( +1) / 2746 closed ( +9) / 3019 total (+10) Bugs : 797 open ( +4) / 4789 closed (+12) / 5586 total (+16) RFE : 166 open ( +1) / 141 closed ( +0) / 307 total ( +1) New / Reopened Patches ______________________ fix distutils.install.dump_dirs() with negated options (2005-01-17) CLOSED http://python.org/sf/1103844 opened by Wummel Add O_SHLOCK/O_EXLOCK to posix (2005-01-17) http://python.org/sf/1103951 opened by Skip Montanaro setup.py --help and --help-commands altered. (2005-01-17) http://python.org/sf/1104111 opened by Titus Brown new-style exceptions (2005-01-18) http://python.org/sf/1104669 opened by Michael Hudson misc doc typos (2005-01-18) CLOSED http://python.org/sf/1104868 opened by DSM chr, ord, unichr documentation updates (2004-10-31) http://python.org/sf/1057588 reopened by mike_j_brown Faster commonprefix in macpath, ntpath, etc. (2005-01-19) http://python.org/sf/1105730 opened by Jimmy Retzlaff get rid of unbound methods (mostly) (2005-01-17) CLOSED http://python.org/sf/1103689 opened by Guido van Rossum Updated "Working on Cygwin" section (2005-01-22) http://python.org/sf/1107221 opened by Alan Green Add Thread.isActive() (2005-01-23) http://python.org/sf/1107656 opened by Alan Green Speed up function calls/can add more introspection info (2005-01-23) http://python.org/sf/1107887 opened by Neal Norwitz Patches Closed ______________ fix distutils.install.dump_dirs() with negated options (2005-01-17) http://python.org/sf/1103844 closed by theller ast-branch: fix for coredump from new import grammar (2005-01-11) http://python.org/sf/1100563 closed by kbk Shadow Password Support Module (2002-07-10) http://python.org/sf/579435 closed by loewis misc doc typos (2005-01-18) http://python.org/sf/1104868 closed by fdrake extending readline functionality (2003-02-11) http://python.org/sf/684500 closed by fdrake self.button.pack() in tkinter.tex example (2005-01-03) http://python.org/sf/1094815 closed by fdrake Clean up discussion of new C thread idiom (2004-09-20) http://python.org/sf/1031233 closed by fdrake Description of args to IMAP4.store() in imaplib (2004-12-12) http://python.org/sf/1084092 closed by fdrake get rid of unbound methods (mostly) (2005-01-17) http://python.org/sf/1103689 closed by gvanrossum New / Reopened Bugs ___________________ email.base64MIME.header_encode vs RFC 1522 (2005-01-17) http://python.org/sf/1103926 opened by Ucho wishlist: os.feed_urandom(input) (2005-01-17) http://python.org/sf/1104021 opened by Zooko O'Whielacronx configure doesn't set up CFLAGS properly (2005-01-17) http://python.org/sf/1104249 opened by Bryan O'Sullivan Bugs in _csv module - lineterminator (2004-11-24) http://python.org/sf/1072404 reopened by fresh Wrong expression with \w+? (2005-01-18) CLOSED http://python.org/sf/1104608 opened by rengel Bug in String rstrip method (2005-01-18) CLOSED http://python.org/sf/1104923 opened by Rick Coupland Undocumented implicit strip() in split(None) string method (2005-01-19) http://python.org/sf/1105286 opened by YoHell Warnings in Python.h with gcc 4.0.0 (2005-01-19) http://python.org/sf/1105699 opened by Bob Ippolito incorrect constant names in curses window objects page (2005-01-19) http://python.org/sf/1105706 opened by dcrosta null source chars handled oddly (2005-01-19) http://python.org/sf/1105770 opened by Reginald B. Charney bug with idle's stdout when executing load_source (2005-01-20) http://python.org/sf/1105950 opened by imperialfists os.stat int/float oddity (2005-01-20) CLOSED http://python.org/sf/1105998 opened by George Yoshida README of 2.4 source download says 2.4a3 (2005-01-20) http://python.org/sf/1106057 opened by Roger Erens semaphore errors from Python 2.3.x on AIX 5.2 (2005-01-20) http://python.org/sf/1106262 opened by The Written Word slightly easier way to debug from the exception handler (2005-01-20) http://python.org/sf/1106316 opened by Leonardo Rochael Almeida os.makedirs() ignores mode parameter (2005-01-21) http://python.org/sf/1106572 opened by Andreas Jung split() takes no keyword arguments (2005-01-21) http://python.org/sf/1106694 opened by Vinz os.pathsep is wrong on Mac OS X (2005-01-22) CLOSED http://python.org/sf/1107258 opened by Mac-arena the Bored Zo Bugs Closed ___________ --without-cxx flag of configure isn't documented. (2003-03-12) http://python.org/sf/702147 closed by bcannon presentation typo in lib: 6.21.4.2 How callbacks are called (2004-12-22) http://python.org/sf/1090139 closed by gward rfc822 Deprecated since release 2.3? (2005-01-15) http://python.org/sf/1102469 closed by anthonybaxter codecs.open and iterators (2003-03-20) http://python.org/sf/706595 closed by doerwalter Wrong expression with \w+? (2005-01-18) http://python.org/sf/1104608 closed by niemeyer Wrong expression with \w+? (2005-01-18) http://python.org/sf/1104608 closed by effbot Bug in String rstrip method (2005-01-18) http://python.org/sf/1104923 closed by tim_one No documentation for zipimport module (2003-12-03) http://python.org/sf/853800 closed by fdrake distutils/tests not installed (2004-12-30) http://python.org/sf/1093173 closed by fdrake urllib2 doesn't handle urls without a scheme (2005-01-07) http://python.org/sf/1097834 closed by fdrake vertical bar typeset horizontal in docs (2004-08-13) http://python.org/sf/1008998 closed by fdrake write failure ignored in Py_Finalize() (2004-11-27) http://python.org/sf/1074011 closed by loewis os.stat int/float oddity (2005-01-20) http://python.org/sf/1105998 closed by loewis os.pathsep is wrong on Mac OS X (2005-01-22) http://python.org/sf/1107258 closed by bcannon From wyojustin at hotmail.com Sun Jan 30 21:41:53 2005 From: wyojustin at hotmail.com (Justin Shaw) Date: Sun, 30 Jan 2005 21:41:53 -0500 Subject: tkSnack pitch() for frequency estimation Message-ID: <4MOdnfuccsdhB2DcRVn-jg@comcast.com> I am using the tkSnack library to estimate the frequency from a sound file. The pitch seems to drop down an octave at 400 Hertz. For example A~440 Hertz comes out at 220 Hertz. When I use the maxpitch and minpitch options to limit the response to say 380 - 460 the result is all zeros. Any ideas on how I can estimate the pitch of a sound up to 880 Hertz (with tkSnack or not)? Thanks Justin Shaw From sp1d3rx at gmail.com Tue Jan 25 15:50:10 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 25 Jan 2005 12:50:10 -0800 Subject: Question Regarding SocketServer In-Reply-To: <1106684900.771730.218060@f14g2000cwb.googlegroups.com> References: <1106684900.771730.218060@f14g2000cwb.googlegroups.com> Message-ID: <1106686210.372444.314020@f14g2000cwb.googlegroups.com> you are missing quotes in "socketserver.py". Make sure the comments at the top are quoted out. In "IDLE" they should be green. From daniel at bowettsolutions.com Wed Jan 26 13:42:14 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Wed, 26 Jan 2005 18:42:14 +0000 Subject: MySQLdb executemany Message-ID: I seem to have found a bug/limitation of executemany in MySQLdb. I am inserting 3100 records into a database. It works fine and adds them in about 1 second. I went back to the program today and realised i'd missed a field so added it to the insert statement. This seems to break it if I try to add all the records in one go. Through trial and error I have realised the limit is 2786 records in one go. Any more than that I get two different errors on the executemany statement: "MySQL server has gone away" - This occurs if I try to add all 3100 records in one go. "Lost Connection to MySQL server during query" - This happens if I am near the 2786 threshold. Is there a known limit with this function??? From fuzzyman at gmail.com Wed Jan 5 07:06:31 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2005 04:06:31 -0800 Subject: Cookbook 2nd ed Credits In-Reply-To: <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> Message-ID: <1104926791.222640.183770@z14g2000cwz.googlegroups.com> Hmm... I'd love to see a list... just to know if I'm on it. Permission was sought for several of my recipes, but I don't know if any were actually used. I'm very curious... Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From rbt at athop1.ath.vt.edu Wed Jan 26 17:32:47 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Wed, 26 Jan 2005 17:32:47 -0500 Subject: exclude binary files from os.walk In-Reply-To: <41f8167b$0$8648$a1866201@visi.com> References: <41f8167b$0$8648$a1866201@visi.com> Message-ID: Grant Edwards wrote: > On 2005-01-26, rbt wrote: > > >>Is there an easy way to exclude binary files (I'm working on >>Windows XP) from the file list returned by os.walk()? > > > Sure, assuming you can provide a rigorous definition of 'binary > files'. :) non-ascii From grahamd at dscpl.com.au Wed Jan 5 17:25:28 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 5 Jan 2005 14:25:28 -0800 Subject: modpython, apache and windows References: <41DB3F0A.2010706@tiscali.co.uk> Message-ID: <1104963928.944830.39170@c13g2000cwb.googlegroups.com> Bob Van Zant wrote: > Fortunately most of the Python-for-the-web implementations do not follow > closely to the PHP paradigm of web-based programming. There are some, > like PSP, that more closely model what PHP does. > > It is not uncommon to have something like index.py which does hardly > anything except fire up a framework that takes care of parsing the rest > of the URI and passing control over to the proper script. Using some > relatively cryptic features of Apache you can hide the fact that > everything goes through index.py (mod_rewrite). I have never really liked how all these different mod_python extensions insist on using their own special file extensions, eg., .psp, .mps etc. All it does is to expose what you are using to implement a site and makes it hard for you to convert to a different implementation mechanism as all your URLs then need to change. As you point out, the only way around it is to use mod_rewrite rules. Overall, from what I have seen all it does is make configuration files harder to understand and spawn lots of newbie questions as to why they can't get anything to work. To me it is more sensible to use REST principles and not use file type extensions at all, or use an extension which reflects the type of content being delivered up and not the mechanism used to generate it. FWIW, the Vampire package tries to address this problem in mod_python by providing a simple mechanism as an extension to mod_python which gives one greater control over the file extension used in a URL and what handler that then maps to. To set it up, one has a single directive in your httpd.conf or htaccess file of the form: PythonHandler vampire You can then place in your directory any number of content handler .py files. Eg. you might have index.py, about.py, report.py etc. In the first instance, no matter what the file type extension on the URL, if the basename in the URL request matches the basename of the content handler file, then it is that file which is the target of the request. Thus, if you used the following URLs, they would map as shown: index.html --> index.py about.html --> about.py report.pdf --> report.py report.csv --> report.py feedback --> feedback.py Now normally the content handler would be called "handler()". Using vampire though, you extend the name with the file type, thus: index.html --> will call handler_html() in index.py about.html --> will call handler_html() in about.py report.pdf --> will call handler_pdf() in report.py report.csv --> will call handler_csv() in report.py feedback --> will call handler() in feedback.py Thus, you can use a more sensible file type in the URL without having to resort to mod_rewrite rules. Further, where a specific resource can be represented in multiple formats which are both generated on the fly, you can have a handler for each in the same content handler .py file, eg., as in .pdf and .csv case. You can also follow REST princinples and have no extension at all. You aren't restricted to just having content handlers in a directory though. You can still have other files such .html and .jpg files. If Vampire determines that there is no content handler corresponding to a request, it will decline to service it and pass it back to Apache which will then serve up the raw .html or .jpg file directly. I should point out that Vampire is not a framework in the sense that it doesn't dictate how your pages are rendered. That handler function which is called is basically the same as a stock standard mod_python handler method. Inside that function you still need to provide the code which creates the response, although there is no reason why you can't on a per resource case trigger off a different system such as PSP, mpservlets or HTMLTemplate to generate the HTML. More could be said, but best to check out: http://www.dscpl.com.au/projects/vampire -- Graham Dumpleton From sxanth at ceid.upatras.gr Fri Jan 7 13:25:16 2005 From: sxanth at ceid.upatras.gr (Stelios Xanthakis) Date: Fri, 07 Jan 2005 10:25:16 -0800 Subject: python-dev Summary for 2004-11-16 through 2004-11-30 In-Reply-To: <1105002357.261642.292880@f14g2000cwb.googlegroups.com> References: <1105002357.261642.292880@f14g2000cwb.googlegroups.com> Message-ID: <41DED40C.3030000@ceid.upatras.gr> michele.simionato at gmail.com wrote: >>Would you like the source with your function? > > > Yes, since I asked for this feature something like two years ago ;-) Well, the main objection seemed to be that we can get the source of a function one way or another. For functions with a file (1) with "inspect" , for functions defined dynamically with "exec"(2), by "knowing what we pass to exec and storing it", and for functions defined in the interactive prompt (3), by using a higher level IDE/shell that is not the pure raw_input, but does sophisticated analysis of code fed to it and which will be responsible for storing functions (!!). Still I believe it's the job of the core python parser to get this info and attach it to function objects. The other problem was whether the source attribute should be saved to pyc files (or more generally marhsaled together with the function object). Logically it should. OTOH, for the application I had using this, I didn't need marshalling source because it stored all the code (initial functions + functions defined while the application was running) in python source form. So, I think that in practice one will use either bytecode or the __source__ feature and not both, but I can't prove it. 8) There's a PEP and an --ugly- patch for 2.3.4 +10 ? Stelios From skip at pobox.com Fri Jan 28 16:03:34 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 28 Jan 2005 15:03:34 -0600 Subject: debugging os.spawn*() calls In-Reply-To: References: <16890.22749.899414.324589@montanaro.dyndns.org> Message-ID: <16890.43174.16771.956147@montanaro.dyndns.org> Nick> If using 2.4 the subprocess module is a good solution too. It Nick> lets you catch stdout/stderr easily. Yeah, thought of that already. Currently not an option though. Thx, Skip From alan.gauld at btinternet.com Sun Jan 2 03:47:52 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Jan 2005 08:47:52 +0000 (UTC) Subject: Frameworks for "Non-Content Oriented Web Apps" References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <36dft0h1v561ejq8u9gnp37063ljjna3rc@4ax.com> On 1 Jan 2005 20:51:06 -0800, mirnazim at gmail.com wrote: > Is there something that can ease the development of application that > are not content oriented(I call them "NON CONTENT-ORIENTED WEB > APPLICATIONS" because I don't know what else to call them). I mean the > applications like, accounting, high volume data entry apps, where > normally GUI clients have ruled. I know very high quality ERP I don;t know of any such frameworks. The Siebel CRM system may be the kind of thing you mean I think, but it uses standard technology. IT just puts up a form then uses client side Javascript to detect changes and send the data requests to/from the data server... No special frameworks as such... HTH, Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From elephantum at dezcom.mephi.ru Sun Jan 9 06:10:04 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 14:10:04 +0300 Subject: python3: 'where' keyword In-Reply-To: <7x3bxbe97m.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> Message-ID: <34choeF48qugdU1@individual.net> Paul Rubin wrote: >>What would be the advantage of that over this? >> >>. x = sqrt(a) + sqrt(b) where: >>. a = 2.0 >>. b = 3.0 > The idea of "where" is to allow re-using variable names instead of > having to keep track of which ones are in use. I just tried to give a > very simple example of how you might do that more than once in a > statement. then I'd write something like this: x = a + b where: a = sqrt(n) where: n = 2. b = sqrt(n) where: n = 3. From jelle.feringa at ezct.net Tue Jan 11 12:18:18 2005 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Tue, 11 Jan 2005 18:18:18 +0100 Subject: os.spawn & stdOUT trouble Message-ID: <20050111171736.D43EC1C0025D@mwinf0101.wanadoo.fr> Yikes, how painful, I meant stdOUT > trouble instead of stdin... Awefully sorry Cheers, Jelle ##thanks for pointing that out Denis! From ssaeed1973 at yahoo.com Sun Jan 30 02:49:00 2005 From: ssaeed1973 at yahoo.com (ssaeed1973 at yahoo.com) Date: 29 Jan 2005 23:49:00 -0800 Subject: Need programming tip Message-ID: <1107071340.486489.146580@f14g2000cwb.googlegroups.com> I am trying to write a program in python (brand new to Python) that would create a database of posts made to binary groups so the user can search for a certain file and have a nzb file returned. I am planning on using the XOVER command to get the list of posts and then dump those into a database. The part I am stuck at now is that some file posts consist of multiple parts as below (abbreviated XOVER reply) 1511156 As Requested 2000 adv server -2000AdvSrv.vol001+02.PAR2 (1/4) - 21/27 1511157 As Requested 2000 adv server -2000AdvSrv.vol001+02.PAR2 (2/4) - 21/27 1511158 As Requested 2000 adv server -2000AdvSrv.vol001+02.PAR2 (3/4) - 21/27 1511159 As Requested 2000 adv server -2000AdvSrv.vol001+02.PAR2 (4/4) - 21/27 I am trying to detect how many segments make up this post. One solution would be to look for (1/ in the subject string then find the denominator and loop thru as many times as the denominator to create the part of the nzb file. Is this the best way or is there an easier method? Also what would be the best way to search for the (1/ using string searches or RegExp? If REgExp could someone provide me with the RegExp for searching for this string? Thanks Salman From lee at example.com Sun Jan 2 10:32:58 2005 From: lee at example.com (Lee Harr) Date: Sun, 02 Jan 2005 15:32:58 GMT Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> <1gpqhbl.125l3evz09uefN%aleaxit@yahoo.com> Message-ID: On 2005-01-02, Brian Beck wrote: > Alex Martelli wrote: >> You _gotta_ be kidding, right...? The Beginner's Guide link takes you >> right to the BeginnersGuide page which starts with the reassurance that >> Python is easy to learn even if you're new to programming and continues >> with a zillion useful links. The Python Books link takes you to a huge > > While I agree that there is much useful content on the official Python > site, I particularly hate the BeginnersGuide and much of the resulting > introduction pages. Often when I happily refer Python to someone who > wants to learn a simple language, I go to the Python site and imagine > where I would start if I were them. Once I get to the BeginnersGuide I > don't see anything immediately useful, and when I look for it I get > frustrated. > I think it looks pretty good. The only problem I see is section 5 where it says: 5. Did we miss your concern? Please add a comment to this page. but the page is immutable. From tjreedy at udel.edu Thu Jan 6 19:16:06 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Jan 2005 19:16:06 -0500 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com><7xvfach813.fsf@ruckus.brouhaha.com><344l83F45rstqU1@individual.net> Message-ID: "Bulba!" wrote in message news:nocrt0119cncjco13l63l9d5nfeimk5820 at 4ax.com... > Which I find again wrong: suppose this developer used GPL-ed > library A, developed patches B and C. He provided you with > the source code of publicly available library A and a patch > C, but he doesn't want to release patch B. Then he does not have to. As I understand the GPL, as long as he does not release (distribute) the patch in any form (in particular, binary), then the GPL has no effect. What strikes me as funny about GPL sniping is that many programmers, including I am sure some of the snipers, sign Terms of Employment contracts far more restrictive of their freedom than one could possibly accuse the GPL of being. But I have seen little or no discussion of this (at least on clp). In fact, I wonder if the GPL might be a substitute target. Terry J. Reedy From irmen at -nospam-remove-this-xs4all.nl Sun Jan 16 17:29:05 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 16 Jan 2005 23:29:05 +0100 Subject: threading and sockets ? In-Reply-To: References: Message-ID: <41eaeaae$0$6203$e4fe514c@news.xs4all.nl> ionel wrote: > how to make a efficient server.. please point me to some good and clear examples I nominate SocketServer.ThreadingTCPServer from the standard library. --Irmen From P at draigBrady.com Thu Jan 6 08:56:04 2005 From: P at draigBrady.com (P at draigBrady.com) Date: Thu, 06 Jan 2005 13:56:04 +0000 Subject: get the IP address of a host In-Reply-To: References: Message-ID: J Berends wrote: > def getipaddr(hostname='default'): [snip] > > It returns the IP address with which it connects to the world (not lo), > might be a pvt LAN address or an internet routed IP. Depend on where the > host is. > > I hate the google trick actually, so any suggestions to something better > is always welcome. Yes your IP is determined really by what you connect to. So I did essentially the same as you. For reference see getMyIPAddress() at the following: http://www.pixelbeat.org/libs/PadSocket.c P?draig From hcslmf at texlife.com Mon Jan 10 12:49:12 2005 From: hcslmf at texlife.com (brolewis) Date: 10 Jan 2005 09:49:12 -0800 Subject: Importing Problem on Windows Message-ID: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> I have a directory that has two files in it: parse.py parser.py parse.py imports a function from parser.py and uses it to parse out the needed information. On Linux, the following code works without a problem: parse.py, line 1: from parser import regexsearch However, when I run the same command in Windows, I get the following error: ImportError: cannot import name regexsearch Any suggestions on why this would work on Linux but not on Windows? From beliavsky at aol.com Sun Jan 30 17:40:32 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 30 Jan 2005 14:40:32 -0800 Subject: Fortran pros and cons (was Re: Coding style article with interesting section on white space) References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> <1107105022.827941.114510@c13g2000cwb.googlegroups.com> Message-ID: <1107124832.327010.181490@f14g2000cwb.googlegroups.com> Michael Tobis wrote: > > Fortran programmers are generally happy with the portability of the > > language. > > Until they try to port something...? Honestly, I can't imagine where > anyone would get this impression. >From the fact that Fortran has been used on hundreds of platforms and that many portable libraries like LAPACK exist. Fortran 90+ allows one to write even more portable code using the KIND mechanism and the selected_int_kind and selected_real_kind functions, which let you specify the ranges of basic data types. > Now, about the terseness and expressiveness? Fortran 90/95 is more expressive than Fortran 77 in many ways, as described in (for example) pages 7-8 of the essay "Numerical Recipes: Does This Paradigm Have a Future?", available at http://www.nr.com/CiP97.pdf . Quoting that paper: "This, for us, was the revelation of parallel programming in Fortran 90. The use of parallel and higher-level constructions -- wholly independently of whether they are executed on tomorrow's parallel machines or today's ordinary workstations -- expresses more science per line of code and per programming workday. Based on our own experience, we think that productivity, or achievable complexity of project, is increased a factor of 2 or 3 in going from Fortran 77 to Fortran 90 -- if one makes the investment of mastering Fortran 90's higher level constructs." > > For scientific computation, consider the case of Numeric > > and Numarray. > > I'm not happy with these, because they either make temporary arrays > with wild abandon Some early Fortran 90 compilers did this but have improved significantly in this respect. > or enforce an unnatural style of expression. I wonder what this means. > I do not suggest that Python is currently competitive with C++ or > Fortran. I simply agree with > http://www.fortranstatement.com that something new ought to be > designed, that a backward compatible Fortran2003 cannot possibly be it, > and that attention to fortran diverts resources from [the sort] of > genuine progress that ought to be possible. You have not given specifics about what "genuine progress" in a scientific programming language would be. > Performance portability has nothing to do with what I'm talking about. > > The answer belies the attitude that programmers are there to put in > time and expend effort, because the only resource worth considering is > production cycles on a big machine. Nonsense. Fortran was originally created to make PROGRAMMERS more efficient by letting them code algebraic expressions instead of machine code. > This attitude explains why working with Fortran is so unpleasant an > experience for anyone who has been exposed to other languages. "Anyone"? Since I have been exposed to Python and C++ and still find Fortran 90+ enjoyable, your statement is demonstrably false. Have you ever used a version of Fortran past F77? The free Fortran 95 compiler called g95 http://www.g95.org is available. > Getting a python package working usually amounts to an install command > to the OS and an import command to the interpreter. Then you can get > down to work. Getting a Fortran package working involves not only an > endless dance with obscure compiler flags and library links, but then a > set of workarounds for codes that produce expected results on one > compiler and compile failures or even different results on another. If one writes standard-conforming code it does not. At least with Fortran one has multiple independent implementations of an ISO standardized language, about 10 each on Intel Windows or Linux, and 4 for Mac OS X. Links are at http://dmoz.org/Computers/Programming/Languages/Fortran/Compilers/ . If one Fortran compiler leaks memory when multiplying matrices, one can use another. If Python Numarray does, the only alternative I know of is Numeric, which is no longer supported according to http://www.pfdubois.com/numpy/ . I have found it extremely useful to work with multiple compilers and compiler options. A good compiler such as Lahey/Fujitsu has debugging options that aid programmer productivity by finding bugs, both at compile and run time, at some cost in speed. I gave a few examples in a previous thread. The existence of such compilers refutes your assertion that Fortran programmers think only machine time is important. From fperez.net at gmail.com Thu Jan 27 19:23:24 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 27 Jan 2005 17:23:24 -0700 Subject: gnuplot on Canvas widget References: <1106852695.371569.234820@f14g2000cwb.googlegroups.com> <1106865871.537454.128830@c13g2000cwb.googlegroups.com> Message-ID: Jonathan Ellis wrote: > Blues wrote: >> I have used two great models - Tkinter and Gnuplot.py - for a while. > I >> can display an image on a Canvas widget using Tkinter and I can also >> generate a gnuplot from Python on the fly in a separate window. Does >> anyone know how to display such a gnuplot on the Canvas widget with > an >> image in it? Thanks. > >>From my experience, the Gnuplot module isn't designed to be used in > "headless" mode -- it can save to the usual formats, but you have to > render everything in an x11 window interactively first. > It might not be hard to modify this, though. That's not correct. I have tons of Gnuplot.py based scripts which write directly to EPS output, without ever opening a gui window. Note that Gnuplot still tries to initialize the X11 terminal at startup, so they would require modifications to run over ssh without X forwarding. The default plot() command in Gnuplot.py doesn't make it too convenient to do this, but it's possible. The Gnuplot support in ipython (http://ipython.scipy.org) extends the syntax of the plot() command to make it trivial to render to EPS without a terminal. It shouldn't be hard to modify this to render to other formats, while avoiding opening an X11 window. Best, f From gsakkis at rutgers.edu Mon Jan 24 17:42:55 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Mon, 24 Jan 2005 17:42:55 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> <35l5d9F4licj2U1@individual.net> Message-ID: <35lbvdF4k3ss4U1@individual.net> "Peter Hansen" wrote in message news:A9OdnRotCdqJ-2jcRVn-jA at powergate.ca... > George Sakkis wrote: > > Fair enough. So perhaps the question is whether such cases are more regular than something like: > > a = give_me_a_huge_tuple() > > slices = [a[i:j] for i in xrange(len(a)) for j in xrange(i+1, len(a)+1)] > > I believe the general usage of tuples tends to mean that > "give_me_a_huge_tuple()" just doesn't happen except with > those who insist on using tuples as though they were nothing > other than read-only lists. > > If you use a tuple the way it was apparently intended, you > are extraordinarily unlikely to find yourself with a > huge one requiring slicing in such a way that you care > whether it is a "view" or a new object. > > -Peter Actually my initial motivation was not a huge tuple I had to slice many times. It was something much less extraordinarily unlikely, a recursive function with a sequence parameter: def foo(sequence): # base_case # do_stuff() combine(foo(sequence[:n]), foo(sequence[n:])) Having each slice be a view of the original sequence instead of a fresh copy would be a Good Thing (tm). George From ncoghlan at iinet.net.au Tue Jan 18 07:42:21 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 18 Jan 2005 22:42:21 +1000 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: <41ED042D.2000004@iinet.net.au> Antoon Pardon wrote: > More specific the Decimal class is mutable and usable as dict key. It's *meant* to be immutable though. The fact that we used __slots__ instead of __setattr__ to implement the immutability, so you *can* overwrite the slot variables if you really want to is merely an artifact of the current Python implementation. The limited mutability bug will disappear in Python 2.5, so it's not a good example of a 'mutable' dict key (especially given that the only way to mutate it is to modify private variables directly). And, as I've stated previously, if the issue of sane mutable keys in dictionaries and sets really bugs you so much - implement identity_dict and identity_set in C and lobby for their inclusion in the collections module. On the more general point of "don't use mutable objects with non-identity based comparisons as dictionary keys", try teaching students for a while (or listen to those who have): When stating useful general principles, it is never, ever worth it to get into the quibbly little details about exceptions to the principle. If students ask, admit that they exist, but point out that the exceptions are rare, and not worth worrying about at that point in their learning. Only when one is aware of the reasons for a principle, can one be aware of good reasons not to follow it :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jepler at unpythonic.net Sat Jan 29 23:00:51 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 29 Jan 2005 22:00:51 -0600 Subject: [Tkinter] problem In-Reply-To: References: Message-ID: <20050130040049.GB20609@unpythonic.net> These lines > if __name__ == '__main__': > OptionsWindow() mean "if this source code is the main program (not an imported module), call OptionsWindow()". So the behavior should be different when the source code is the main program ('python opt_newlogin.py') and when it's imported ('python -c "import opt_newlogin"') Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tom at dtsam.com Wed Jan 26 10:39:31 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Wed, 26 Jan 2005 09:39:31 -0600 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: "Davor" wrote in message news:ct6kvm$edg$1 at rumours.uwaterloo.ca... > > On the other hand, this does beggar for a reason to bother with Python at > > all. It seems you could be happy doing BASH scripts for Linux or DOS batch > > files for Windows. Both are "nice&simple" scripting languages free of > > object oriented contamination. > > not really, what I need that Python has and bash&dos don't is: > > 1. portability (interpreter runs quite a bit architectures) > 2. good basic library (already there) > 3. modules for structuring the application (objects unnecessary) > 4. high-level data structures (dictionaries & lists) > 5. no strong static type checking > 6. very nice syntax > > so initially I was hoping this is all what Python is about, ... The irony here is that the OO approach woven into the warp and woof of Python is what make 1-6 possible. > but when I > started looking into it it has a huge amount of additional (mainly OO) > stuff which makes it in my view quite bloated now... Again, there is nothing "additional" about the OO in Python. It is the very foundation upon which it is built. > ... anyhow, I guess > I'll have to constrain what can be included in the code through > different policies rather than language limitations... It would be reasonable to decide that Python is not what you are looking for. I'm not sure that castrating it in this manner would be quite so reasonable. Thomas Bartkus From philippecmartin at sbcglobal.net Fri Jan 7 07:16:49 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Fri, 07 Jan 2005 13:16:49 +0100 Subject: Tkinter: passing parameters to menu commands Message-ID: <1105100209.6909.6.camel@localhost> Hi, I have he following need and do not find an easy way out: I have many menu items and would like them all to call the same method -However, I need the method called to react differently depending on the menu item selected. Since the menu command functions do not seem to receive any type of event style object, is there some type of Tkinter call that would let my method know the menu id selected ? Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From snacktime at gmail.com Sun Jan 23 18:50:50 2005 From: snacktime at gmail.com (snacktime) Date: Sun, 23 Jan 2005 15:50:50 -0800 Subject: Set parity of a string In-Reply-To: References: <1f060c4c050123140310e6f887@mail.gmail.com> Message-ID: <1f060c4c05012315506a2c9cb4@mail.gmail.com> On Sun, 23 Jan 2005 23:52:29 +0100, Fredrik Lundh wrote: > "snacktime" wrote: > > > Is there a module that sets the parity of a string? I have an > > application that needs to communicate with a host using even parity > > So what I need is before sending the message, convert it from space to > > even parity. And when I get the response I need to convert that from > > even to space parity. > > umm. shouldn't the communication library do this for you? > The communication is an https post, but the host needs the data in even parity before sending it into their internal systems (this is a large bank network) and it's up to the client to do the transformation. Chris From rkern at ucsd.edu Sat Jan 15 15:12:26 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 15 Jan 2005 12:12:26 -0800 Subject: hash patent by AltNet; Python is prior art? In-Reply-To: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> References: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> Message-ID: GerritM wrote: > ZDnet features an article about the had patent at AltNet > http://news.zdnet.com/2100-9588_22-5534087.html . Apparantly this issue > plays already for some time, now the p2p companies are threatened, becuase > they use hashing to recognize files. > > As far as I know hasing is a very old technique used to quickly look up > information. The use of hashing always requires an idnetity check, because > the lookup is not unique (mapping a very big amount of possibilities on a > limited amount of entries). This is a fast and robust way of finding > information, if the right hashing function is used. I don't know the details, but I'm willing to bet that the kind of hashes being disputed here are cryptographic hashes, not the kind that Python uses for dictionaries. I'm also willing to bet that the patent won't hold up in court because there's quite a lot of prior art with respect to cryptographic hashes, too. -- 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 sjmachin at lexicon.net Tue Jan 11 17:16:07 2005 From: sjmachin at lexicon.net (John Machin) Date: 11 Jan 2005 14:16:07 -0800 Subject: Octal notation: severe deprecation References: Message-ID: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> Some poster wrote (in connexion with another topic): > ... unicode("\347", "iso-8859-1") ... Well, I haven't had a good rant for quite a while, so here goes: I'm a bit of a retro specimen, being able (inter alia) to recall octal opcodes from the ICT 1900 series (070=call, 072=exit, 074=branch, ...) but nowadays I regard continued usage of octal as a pox and a pestilence. 1. Octal notation is of use to systems programmers on computers where the number of bits in a word is a multiple of 3. Are there any still in production use? AFAIK word sizes were 12, 24, 36, 48, and 60 bits -- all multiples of 4, so hexadecimal could be used. 2. Consider the effect on the newbie who's never even heard of "octal": >>> import datetime >>> datetime.date(2005,01,01) datetime.date(2005, 1, 1) >>> datetime.date(2005,09,09) File "", line 1 datetime.date(2005,09,09) ^ SyntaxError: invalid token [straight out of the "BOFH Manual of Po-faced Error Messages"] 3. Consider this extract from the docs for the re module: """ \number Matches the contents of the group of the same number. Groups are numbered starting from 1. For example, (.+) \1 matches 'the the' or '55 55', but not 'the end' (note the space after the group). This special sequence can only be used to match one of the first 99 groups. If the first digit of number is 0, or number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value number. Inside the "[" and "]" of a character class, all numeric escapes are treated as characters. """ I helped to straighten out this description a few years ago, but I fear it's still not 100% accurate. Worse, take a peek at the code necessary to implement this. === We (un-Pythonically) implicitly take a leading zero (or even just \[0-7]) as meaning octal, instead of requiring something explicit as with hexadecimal. The variable length idea in strings doesn't help: "\18", "\128" and "\1238" are all strings of length 2. I don't see any mention of octal in GvR's "Python Regrets" or AMK's "PEP 3000". Why not? Is it not regretted? From rmemmons at member.fsf.org Thu Jan 13 20:59:57 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Thu, 13 Jan 2005 19:59:57 -0600 Subject: Newbie: module structure and import question References: <8fb821f9.0501120706.499dd04c@posting.google.com> Message-ID: > hi all, > i have question on how to design a module structure. > for example, i have 3 files. > [somewhere]/main.py > [somewhere]/myLib/Base/BaseA.py > [somewhere]/myLib/ClassA.py > .... > ..... > It's fine when i run main.py. > however when i run ClassA.py individually, it would fail in import > statment since the import path is incorrect. > I would like to know is something wrong in my design, or something i > missed. I think your issue is your module search path. Take a look at the doc for sys.path in the library reference. These are the directories that python searchies for modules. Usually the "." directory is included in this which makes python search the current working directory. Your example fails because your working directories are probably different when you ran the two modules. In any case always consider how you've setup sys.path and your libraries and modules. > Also, in practical usage, is that one class in one py file? I'm not exactly clear what your asking -- but I think yor asking if you'd normally only put one class in one py file. My answer is no -- generally you'd put many functions and classes in each py file. Modules are high level and should be used to create libraries essentailly -- this means many fucntions and classes per module. Rob From iseestars at gate.net Thu Jan 27 21:14:07 2005 From: iseestars at gate.net (inhahe) Date: Thu, 27 Jan 2005 21:14:07 -0500 Subject: Why do look-ahead and look-behind have to be fixed-width patterns? Message-ID: Hi i'm a newbie at this and probably always will be, so don't be surprised if I don't know what i'm talking about. but I don't understand why regex look-behinds (and look-aheads) have to be fixed-width patterns. i'm getting the impression that it's supposed to make searching exponentially slower otherwise but i just don't see how. say i have the expression (?<=.*?:.*?:).* all the engine has to do is search for .*?:.*?:.*, and then in each result, find .*?:.*?: and return the string starting at the point just after the length of the match. no exponential time there, and even that is probably more inefficient than it has to be. From shalabh at cafepy.com Sun Jan 23 17:39:08 2005 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Sun, 23 Jan 2005 14:39:08 -0800 Subject: Solutions for data storage? In-Reply-To: <356c7tF4g3f64U1@individual.net> References: <356c7tF4g3f64U1@individual.net> Message-ID: <41F4278C.8000206@cafepy.com> Leif K-Brooks wrote: > I'm writing a relatively simple multi-user public Web application with > Python. It's a rewrite of a similar application which used PHP+MySQL > (not particularly clean code, either). My opinions on various Web > frameworks tends to vary with the phase of the moon, but currently, I'm > planning to use Quixote. Good choice, IMO! And while you're using Quixote, you might want to look at QLime [1] for all your data storage needs :) > I've looked at SQLObject, and it's very nice, but it doesn't provide > certain features I really want, like the ability to store lists of > strings or integers directly in the database (using commas in a varchar > column or something). In any mapper that lets you set attributes for storing columns (such as QLime), this should be fairly simple using properties. > My ideal solution would be an object database (or object-relational > mapper, I guess) which provided total transparency in all but a few > places, built-in indexing, built-in features for handling schema > changes, the ability to create attributes which are required to be > unique among other instances, and built-in querying with pretty syntax. Briefly, QLime uses RDBMS indexing, automatically handles schema changes (in fact you don't define the schema in Python at all, you just create the table). For uniqueness you'd have to set the constraint on the table. To look at the query syntax avaialable, (and OR mapping features) see http://www.qlime.org/0.5.1/qlime_or_mapping.html. Cheers, Shalabh [1] http://www.qlime.org/ From devries at idolstarastronomer.com Mon Jan 3 20:52:40 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: 3 Jan 2005 17:52:40 -0800 Subject: How do I make Windows Application with Python ? In-Reply-To: <1104802115.543884.96150@z14g2000cwz.googlegroups.com> References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> <1104802115.543884.96150@z14g2000cwz.googlegroups.com> Message-ID: <1104803560.244274.251150@c13g2000cwb.googlegroups.com> I should learn to type faster. You beat me to the response. Chris From http Sun Jan 30 06:43:26 2005 From: http (Paul Rubin) Date: 30 Jan 2005 03:43:26 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> <7xacqsbfk2.fsf@ruckus.brouhaha.com> <41fbcb11$0$12030$9b622d9e@news.freenet.de> <7xsm4j1wbe.fsf@ruckus.brouhaha.com> Message-ID: <7xpszngn1d.fsf@ruckus.brouhaha.com> Nick Craig-Wood writes: > There is a PEP about this... > > API for Block Encryption Algorithms v1.0 > http://www.python.org/peps/pep-0272.html Yes, I know about that and have been in contact with its author. He and I are in agreement (or at least were in agreement some time ago) that the proposed API of the new module is an improvement, at least for a generic module. PEP 272 seems to document the interface of something that had been implemented for some particular application. From zuerich at hebeler.net Thu Jan 27 11:20:21 2005 From: zuerich at hebeler.net (Felix Hebeler) Date: Thu, 27 Jan 2005 17:20:21 +0100 Subject: how to pass attribute name via sys.argv In-Reply-To: References: <41f8e31a$1@idnews.unizh.ch> Message-ID: <41f914c3$1@idnews.unizh.ch> Wolfram Kraus wrote: > Felix Hebeler wrote: > >> >> I need to call an object attribute: >> >> value = object.attrName[0] >> > > Use getattr: > value = getattr(object, attrName)[0] > > > > HTH, > Wolfram Thanks so much! Had I known earlier. Looks so easy... Now, why did I not find this in the online tutorial, the reference manual, or google? Not that I didn't try... I mean, I would find 'getattr' if I searched, but if you don't know what you're looking for.. I find the reference manual extremely (== too) compact to look things up. A couple of colleages and me agreed that it is much more difficult to find solutions and _useful_ tips for Python than e.g. for Java (where there's Javadoc for example). The syntax doc in the reference manual to me looks like computer linguists might understand, but unfortunately not me. And Python code IS really easy to read, I agree, but what if I can't find out how to write it? I'd appreciate any link to online resources or recommendations for books (english/german)! Chances are I'm a silly/lazy/deprived/stupid bugger, but I try to think there's still hope! again, thank you so much for your quick response (thanks Gilles Lenfant too!), I really DO like the Python community ;-) Cheers Felix From jerf at jerf.org Sat Jan 15 18:13:04 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 15 Jan 2005 18:13:04 -0500 Subject: threading and sockets ? References: Message-ID: On Sun, 16 Jan 2005 05:30:37 +0200, ionel wrote: > how to make a efficient server.. please point me to some good and clear examples Your question is too broad. There is no such thing as "a server", the server must *do* something and it is generally named for what it does.. Please read http://www.catb.org/~esr/faqs/smart-questions.html and try again. That said, Twisted is a likely good first stop. http://twistedmatrix.com/ But I have no way of knowing that, only a guess. From steven.bethard at gmail.com Thu Jan 27 13:06:18 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 11:06:18 -0700 Subject: Help With Python In-Reply-To: References: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Nick Craig-Wood wrote: > Steven Bethard wrote: >> py> orders = [Viking().order()] * 7 >> py> ', '.join(orders) >> 'Spam, Spam, Spam, Spam, Spam, Spam, Spam' > > Thats still one Viking making 7 orders surely? > > So you want this... > >>>>orders = [ Viking().order() for _ in range(7) ] Right, right. Thanks for the correction! This is why I never use the * operator on lists. ;) Steve From phil at riverbankcomputing.co.uk Mon Jan 10 07:30:04 2005 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Mon, 10 Jan 2005 12:30:04 -0000 (GMT) Subject: Command line and GUI tools : need a single threading solution In-Reply-To: <41e26e79@duster.adelaide.on.net> References: <41e26e79@duster.adelaide.on.net> Message-ID: <7461.82.68.80.137.1105360204.squirrel@82.68.80.137> > I have a collection of multi-threaded command line tools which I want wrap > a > PyQt gui around. I'm using queues to route messages from the command line > tools to the PyQt gui. The command line tools use python threads to do > their work. The gui uses a QThread object to read incoming messages. > > This does not work consistently - and I've since read that mixing python > threads and QThreads is a bad idea. The command line tools work well > using > python threads. How well mixing the two threading APIs works depends on version numbers. A PyQt generated with SIP v4.x (rather than SIP v3.x) with Python v2.4 should be Ok. > I don't want to maintain two copies of the tools - one for command line > and > another for the PyQt version. > > I'm thinking it may be possible to modify the command line tools to use qt > threads instead of native python threads. Is this the way to go? Are > there other options? Using QThreads only should work - just tell the QApplication ctor that you have a console application. Phil From asda at sdarta.com Sat Jan 8 21:22:54 2005 From: asda at sdarta.com (worzel) Date: Sun, 9 Jan 2005 10:22:54 +0800 Subject: The best way to do web apps with Python? References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41e0957d$0$21086$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Holy Moly - there's quite a few choices out there! I like the look of Karrigel for my immediate needs. Looking forward to the day there is a more 'j2ee' like standard in place for Python - looks like this is in the works. Thanks for all the feedback guys. "worzel" wrote in message news:41dfdc15$0$29387$5a62ac22 at per-qv1-newsreader-01.iinet.net.au... What is the best way to web developemnt with Python? Is there anything close to PHP style in-page script placement that can create and use other Python objects? I am not really interested in Zope (I believe that is more a CMS than anything else?) I am also looking for something a little more structured than a series of CGI Scripts. While on the topic - what is the expectataion of Python for this kind of stuff? Would one use Python for certain other things but turn to PHP for web apps - or would one use their Python skills in place of PHP? TIA From steve at holdenweb.com Thu Jan 6 08:45:21 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 08:45:21 -0500 Subject: Other notes In-Reply-To: References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> Message-ID: <41DD40F1.5030301@holdenweb.com> Timo Virkkala wrote: > bearophileHUGS at lycos.com wrote: > >> Andrew Dalke: >> >>> (BTW, it needs to be 1 .. 12 not 1..12 because 1. will be interpreted >>> as the floating point value "1.0".)< >> >> Uhm, I have to fix my ignorance about parsers. >> Cannot a second "." after the first tell that the first "." isn't in >> the middle of a floating point number? > > > Python uses an LL(1) parser. From Wikipedia: > """ LL(1) grammars, although fairly restrictive, are very popular > because the corresponding LL parsers only need to look at the next token > to make their parsing decisions.""" > Indeed, but if ".." is defined as an acceptable token then there's nothing to stop a strict LL(1) parser from disambiguating the cases in question. "Token" is not the same thing as "character". >>>> This may allow: assert 5 interval 9 == interval(5,9) >>> >>> Maybe you could give an example of when you need this in real life?< >> >> Every time you have a function with 2 parameters, you can choose to use >> it infix. > > > But why would you want to? What advantage does this give over the > standard syntax? Remember, in Python philosophy, there should be one > obvious way to do it, and preferably only one. Adding a whole another > way of calling functions complicates things without adding much > advantage. Especially so because you suggest it is only used for binary, > i.e. two-parameter functions. This part of your comments I completely agree with. However, we are used to people coming along and suggesting changes to Python on comp.lang.python. Ironically it's often those with less experience of Python who suggest it should be changed to be more like some other language. One of the things I like best about c.l.py is its (almost) unfailing politeness to such posters, often despite long stream-of-consciousness posts suggesting fatuous changes (not necessarily the case here, by the way). The level of debate is so high, and so rational, that the change requesters are often educated as to why their suggested changes wouldn't be helpful or acceptable, and having come to jeer they remain to whitewash, to use an analogy from "Tom Sawyer" [1]. All in all a very pleasant change from "F*&% off and die, noob". regards Steve [1]: http://www.cliffsnotes.com/WileyCDA/LitNote/id-2,pageNum-10.html -- 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 fumanchu at amor.org Mon Jan 10 13:14:24 2005 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 10 Jan 2005 10:14:24 -0800 Subject: Writing huge Sets() to disk Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339814F@exchange.hqamor.amorhq.net> Martin MOKREJ? wrote: > Robert Brewer wrote: > > Martin MOKREJ? wrote: > > > >> I have sets.Set() objects having up to 20E20 items, > >>each is composed of up to 20 characters. Keeping > >>them in memory on !GB machine put's me quickly into swap. > >>I don't want to use dictionary approach, as I don't see a sense > >>to store None as a value. The items in a set are unique. > >> > >> How can I write them efficiently to disk? > > > > > > got shelve*? > > I know about shelve, but doesn't it work like a dictionary? > Why should I use shelve for this? Then it's faster to use > bsddb directly and use string as a key and None as a value, I'd guess. If you're using Python 2.3, then a sets.Set *is* implemented with a dictionary, with None values. It simply has some extra methods to make it behave like a set. In addition, the Set class already has builtin methods for pickling and unpickling. So it's probably faster to use bsddb directly, but why not find out by trying 2 lines of code that uses shelve? The time-consuming part of your quest is writing the timed test suite that will indicate which route will be fastest, which you'll have to do regardless. Robert Brewer MIS Amor Ministries fumanchu at amor.org From danperl at rogers.com Fri Jan 28 08:54:28 2005 From: danperl at rogers.com (Dan Perl) Date: Fri, 28 Jan 2005 08:54:28 -0500 Subject: How to test that an exception is raised ? References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> <41fa400b$0$2029$6c56d894@feed0.news.be.easynet.net> Message-ID: "StepH" wrote in message news:41fa400b$0$2029$6c56d894 at feed0.news.be.easynet.net... > > Do you say that it's not possible to test (using unittest) if an exception > is well raised if the tested code catch it ? > How to solve this paradoxe ? How to automaticaly test such code ? Then you need a side-effect in catching the exception. A return code would be such a side-effect. Setting a state variable that can be checked by the invoking code would be another such side-effect. > 1./ Cheking error-return value if not a good idea for me, cause this make > the code less clear. I don't want a code where i've to test each function > return value... > 2./ If I re-raise the exception, then how to not show the traceback. My > user will became crazy if they view such error msg. But then how will the user know if the call did what it is supposed to do? And if the user mis-used the function and used it for a file that does not exist, how is he/she supposed to know what the problem was and why nothing is coming out of calling your function? > It seems that there is 2 school here. I've read a lot on python, and > somed > 'guru' Python say that it's maybe better to use exception even for case > you > can "predict", no ? Or i'm completly wrong ? The IOError is an exception that you can predict and I was saying that you should catch it, but with a "except IOError:" statement instead of the "except:" statement that you used. From jjl at pobox.com Tue Jan 25 18:19:00 2005 From: jjl at pobox.com (John J. Lee) Date: 25 Jan 2005 23:19:00 +0000 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> <7xacr4ewjk.fsf@ruckus.brouhaha.com> <41ef4a7a.1323588509@news.oz.net> <7xwtu8vb17.fsf@ruckus.brouhaha.com> <41EF72DE.5030305@jessikat.fsnet.co.uk> <7xwtu8pgr4.fsf@ruckus.brouhaha.com> <7x7jm5m613.fsf@ruckus.brouhaha.com> Message-ID: <87d5vthzbv.fsf@pobox.com> Paul Rubin writes: > jjl at pobox.com (John J. Lee) writes: > > > Building larger ones seems to > > > have complexity exponential in the number of bits, which is not too > > > > Why? > > The way I understand it, that 7-qubit computer was based on embedding > the qubits on atoms in a large molecule, then running the computation Oh, you mean that particular kind, OK. Doesn't apply to QC in general. > > > It's not even known in theory whether quantum computing is > > > possible on a significant scale. > > > > Discuss. > > The problem is maintaining enough coherence through the whole > calculation that the results aren't turned into garbage. In any > physically realizeable experiment, a certain amount of decoherence > will creep in at every step. So you need to add additional qubits for > error correction, but then those qubits complicate the calculation and > add more decoherence, so you need even more error correcting qubits. Yes, that's much more interesting, dunno what the current state of play is. [...] > I'm not any kind of expert in this stuff but have had some > conversations with people who are into it, and the above is what they > told me, as of a few years ago. I probably have it all somewhat garbled. Me too :-) John From martin at v.loewis.de Mon Jan 24 18:51:24 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 25 Jan 2005 00:51:24 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> Message-ID: <41f589f9$0$3357$9b622d9e@news.freenet.de> phr at localhost.localdomain wrote: > Maybe we're not thinking about the same problems. Say I'm an app > writer and I want to use one of your modules. My development > environment is GNU/Linux, and I want to ship a self-contained app that > anyone can run without having to download additional components. That > includes people wanting to run my app on Windows, Macintosh, Amiga, > and various other Python target platforms that I don't have compilers > for. How do I do it? This is not possible - whether the module is included in Python or not. People *will* have to download something besides your application, namely Python - and in the version your require, too. If they cannot compile Python themselves, they will have to find somebody who did that for them. This is very easy if you are using Windows, Debian, or Mac OS X. It is very difficult if you are using an Amiga, or any of the other Python target platforms that you don't have compilers for. HP-UX users of your application will have a hard time to get it running even if the module was available as a built-in. This does not change much if the module is available separately, and it does not change much whether the separate module is written in Python or in C: Windows, Debian, and OS X users will still find precompiled binaries for the module, and all others will still have to build it themselves. This is very easy, since all they have to do is to use distutils. > So, if your modules are generally useful, I hope you > will try to get them into the core. Right - the critical condition is "if the modules are generally useful". I cannot possibly know whether they are generally useful until a general public has commented that they are. > I can't speak for the authors but I'd personally say that none of > those old modules are really suitable for the core on technical > grounds. That is my impression, too. > The module I'm discussing would simply implement the FIPS standard > block ciphers (AES and DES) and the FIPS operating modes. These are > the basic building blocks that I feel are missing from the core. They > should be enough to fill the crypto needs of most applications. Hmm. Most applications don't have any crypto needs. Those that do typically need TLS, or secure password hashing (crypt(3) specifically). So I somehow doubt that an AES module would be generally useful. >>So if the module was primarily written to be included in the core, I >>would initially reject it for that very reason. After one year or so >>in its life, and a recognizable user base, inclusion can be >>considered. > > > That makes no sense; improving the core is a perfectly valid reason to > write something. If someone wrote a straightforward patch that made > the Python interpreter 3x faster, would you still want to wait a year > before thinking about including it? I would have to apply the "generally useful" test. For an 3x speed improvement, about 100% of the Python users would find that useful. For an AES module with an interface nobody has ever used but yourself, it would be very difficult to argue that the module is generally useful. If the module does not serve a need that people have, in general, I don't see why it should be included (and yes, I wish a few of the modules that were included recently wouldn't have been added so quickly). > I certainly believe that every > contribution needs code review and user testing before entering wide > release, but that doesn't seem to be what you're getting at. I'm primarily looking for the user testing. I require that this happens *outside* the Python distribution. Make a distutils package, and report the user feedback. Then propose inclusion into the core. > I release this "app" and presto, every Python user on every OS > platform can run it with no fuss. That includes CGI authors who > aren't allowed to install C modules at all, without getting their > hosting service to do it. How do I do the same thing if there's no > built-in sha module and all I have is sha.c? It very much depends on the details of the target system. Yes, it is a bit more tricky to install the additional library - but that is the case with any additional library, whether it is C or not. For the CGI user who is not allowed to install binaries into /usr/local, she can still install the module in her home directory, no? > To me, the whole Python notion of "batteries included" expresses > precisely the idea that I'm trying to describe. Commonly-used > functions belong in the core, because making people download or > install them separately is a pain in the neck. See, this is the critical point: "commonly-used functions", not "functions I believe would be commonly used". You must have *existing* users for a function to be commonly-used. Regards, Martin From paul.kooistra at leaseplan.nl Tue Jan 25 09:23:29 2005 From: paul.kooistra at leaseplan.nl (Paul Kooistra) Date: 25 Jan 2005 06:23:29 -0800 Subject: Browsing text ; Python the right tool? Message-ID: I need a tool to browse text files with a size of 10-20 Mb. These files have a fixed record length of 800 bytes (CR/LF), and containt records used to create printed pages by an external company. Each line (record) contains an 2-character identifier, like 'A0' or 'C1'. The identifier identifies the record format for the line, thereby allowing different record formats to be used in a textfile. For example: An A0 record may consist of: recordnumber [1:4] name [5:25] filler [26:800] while a C1 record consists of: recordnumber [1:4] phonenumber [5:15] zipcode [16:20] filler [21:800] As you see, all records have a fixed column format. I would like to build a utility which allows me (in a windows environment) to open a textfile and browse through the records (ideally with a search option), where each recordtype is displayed according to its recordformat ('Attributename: Value' format). This would mean that browsing from a A0 to C1 record results in a different list of attributes + values on the screen, allowing me to analyze the data generated a lot easier then I do now, browsing in a text editor with a stack of printed record formats at hand. This is of course quite a common way of encoding data in textfiles. I've tried to find a generic text-based browser which allows me to do just this, but cannot find anything. Enter Python; I know the language by name, I know it handles text just fine, but I am not really interested in learning Python just now, I just need a tool to do what I want. What I would REALLY like is way to define standard record formats in a separate definition, like: - defining a common record length; - defining the different record formats (attributes, position of the line); - and defining when a specific record format is to be used, dependent on 1 or more identifiers in the record. I CAN probably build something from scratch, but if I can (re)use something that already exists it would be so much better and faster... And a utility to do what I just described would be REALLY usefull in LOTS of environments. This means I have the following questions: 1. Does anybody now of a generic tool (not necessarily Python based) that does the job I've outlined? 2. If not, is there some framework or widget in Python I can adapt to do what I want? 3. If not, should I consider building all this just from scratch in Python - which would probably mean not only learning Python, but some other GUI related modules? 4. Or should I forget about Python and build someting in another environment? Any help would be appreciated. From bokr at oz.net Wed Jan 12 21:45:03 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 02:45:03 GMT Subject: counting items References: Message-ID: <41e5ddc8.705938866@news.oz.net> On Wed, 12 Jan 2005 18:07:47 GMT, "Andrew Koenig" wrote: >"It's me" wrote in message >news:ukdFd.10645$5R.2000 at newssvr21.news.prodigy.com... > >> What's the best way to count number of items in a list? >> >> For instance, >> >> a=[[1,2,4],4,5,[2,3]] >> >> I want to know how many items are there in a (answer should be 7 - I don't >> want it to be 4) > >How about this? > > def totallen(x): > if isinstance(x, (list, tuple, dict)): > return sum(map(totallen, x)) > return 1 Since the requirement is to _count_, not flatten, ISTM your solution is best so far ;-) Regards, Bengt Richter From peter at engcorp.com Sat Jan 8 13:20:23 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 13:20:23 -0500 Subject: windows mem leak In-Reply-To: References: Message-ID: Bob Smith wrote: > Does the Win32 port of Python have a memory leak? I have some code that > runs flawlessly on Linux, but bombs after a few hours on Windows. It's > threaded and uses a lot of memory. Let's see what you're missing: 1. platform specifics 2. versions of things involved 3. any sort of detail about the code 4. how you're noticing/measuring the problem 5. what "bombs" means 6. any mention that you've checked Sourceforge to see whether a similar problem has been reported There have been memory leaks in various past versions of Python, and could easily be in the current version, but they're generally rather specific in terms of the code that can trigger it. Once it was doing some particular work with a socket, once it was trying to append (or extend?) to an empty list, and so on. There are also a few ways you could have written your application to cause memory to leak as a result of your own code, not as a result of Python's. And it's even possible that this would happen only on one platform (though I'm trying hard to think of an example and can't... maybe it's very unlikely.) -Peter From jack at performancedrivers.com Wed Jan 19 16:01:04 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 19 Jan 2005 16:01:04 -0500 Subject: RuntimeError: dictionary changed size during iteration In-Reply-To: References: Message-ID: <20050119210104.GJ26167@performancedrivers.com> On Wed, Jan 19, 2005 at 11:45:15PM +0300, Roman Suzi wrote: > > I think, the behaviour below is misfeature: > > >>> [e for e in vars()] > Traceback (most recent call last): > File "", line 1, in ? > RuntimeError: dictionary changed size during iteration > >>> e = None > >>> [e for e in vars()] > ['e', '__builtins__', 'rlcompleter', '__file__', '_[1]', 'atexit', '__name__', > 'readline', '__doc__'] > Chalk it up as a lesson in the slightly different behavior of genexps 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. >>> list(e for e in vars()) ['__builtins__', '__name__', '__doc__'] >>> [e for e in vars()] Traceback (most recent call last): File "", line 1, in ? RuntimeError: dictionary changed size during iteration -Jack From rschroev_nospam_ml at fastmail.fm Fri Jan 14 13:33:05 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 14 Jan 2005 18:33:05 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <1CSFd.30772$Qv5.2842746@phobos.telenet-ops.be> Message-ID: Antoon Pardon wrote: > Op 2005-01-14, Roel Schroeven schreef : > >>Antoon Pardon wrote: >> >>>IMO we have a: dogs are mamals kind of relationship in Python. >> >>I see what you mean, but I don't think it's true. >> >> >>>Every expression can be used where a statement is expected. >>>(And this can be worded as: every expression is a statement.) >> >>Not really. An expression statement is a statement that looks like an >>expression, but actually it's more than that: not only does it calculate >>the value of the expression, it also prints the value. > > > 1) Only in an interactive environment. True, I wanted to add that but forgot it. Doesn't change what I'm saying though. > 2) That the semantics differ according to where the expression is > used doesn't make a difference. That an expression decides which > branch of an if statement is executed or what object is pass > as an argument in a call are also semantic difference, yet > we still have an expression in both cases. In both cases we have an expression, in both cases we have a statement, in both cases the expression is a part of the statement. In one case the expression is the only statement, in the other case the statement has other parts too. > >>Note that it would be perfectly possible to modify the syntax into >> >>expression_stmt ::= "exprstmt" expression_list >>... > > If you change the syntax, of course you will change the strings > that will be accepted. I could change the syntax to: > > if_stmt ::= "if" "ifexpr" expression ... > > Have I now proved that expressions after an if are not normal > expressions? No, you still have a statement with one or more parts, one of which is an expression. In OOP terms: I think that an expression statement 'has an' expression (I agree that is a very thin wrapper though), not that an expression statement 'is an' expression. >>>Not every statement can be used where an expression is expected. >> >>AFAIK *no* statement can be used where an expression is expected. > > > But that was not the implication of what Guido supposedly had said. > So that this is not the case doesn't counter what I said. Whether statements can be used in the place of expressions is indeed not relevant to the discussion. Regarding what Guido apparently said: Op 2005-01-12, Steve Holden schreef : >> Given that Guido is on record as saying that expressions aren't >> statements because he wants those things to be separate Antoon Pardon wrote: > Well, it seems that Guido is wrong then. The documentation clearly > states that an expression is a statement. I don't think it says that at all. > More specifically, everywhere you can use a statement, you can > simply use an expression according to the python syntax. If you use an expression where a statement is expected, you really write an expression statement that contains the expression (and nothing else, but that doesn't matter). -- "Codito ergo sum" Roel Schroeven From bac at OCF.Berkeley.EDU Sun Jan 23 14:49:06 2005 From: bac at OCF.Berkeley.EDU (Brett C.) Date: Sun, 23 Jan 2005 11:49:06 -0800 Subject: python-dev Summary for 2004-12-01 through 2004-12-15 Message-ID: <41F3FFB2.5070607@ocf.berkeley.edu> This is a summary of traffic on the `python-dev mailing list`_ from December 01, 2004 through December 15, 2004. It is intended to inform the wider Python community of on-going developments on the list. To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! This is the fifty-fourth summary written by Brett Cannon (amazed no one has complained about the lateness of these summaries!). To contact me, please send email to brett at python.org ; I do not have the time to keep up on comp.lang.python and thus do not always catch follow-ups posted there. All summaries are archived at http://www.python.org/dev/summary/ . Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sf.net/rst.html . Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it, although I suggest learning reST; it's simple and is accepted for `PEP markup`_ and gives some perks for the HTML output. Also, because of the wonders of programs that like to reformat text, I cannot guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _PEP Markup: http://www.python.org/peps/pep-0012.html The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation on new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to forward the development and use of Python. But the PSF_ cannot do this without donations. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation (you can donate through PayPal or by check) helps. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. contents:: .. _last summary: http://www.python.org/dev/summary/2004-11-16_2004-11-30.html .. _original text file: http://www.python.org/dev/summary/2004-12-01_2004-12-15.ht ===================== Summary Announcements ===================== PyCon_ 2005 planning is well underway. The schedule has been posted at http://www.python.org/pycon/2005/schedule.html and looks great with a quite the varied topics. And there is still time for the early-bird registration price of $175 ($125 students) before it expires on January 28th. Some day I will be all caught up with the Summaries... .. _PyCon: http://www.pycon.org ========= Summaries ========= ---------------------------------- PEPS: those existing and gestating ---------------------------------- [for emails on PEP updates, subscribe to python-checkins_ and choose the 'PEP' topic] A proto-PEP covering the __source__ proposal from the `last summary`_ has been posted to python-dev. `PEP 338`_ proposes how to modify the '-m' modifier so as to be able to execute modules contained within packages. .. _python-checkins: http://mail.python.org/mailman/listinfo/python-checkins .. _PEP 338: http://www.python.org/peps/pep-0338.html Contributing threads: - `PEP: __source__ proposal `__ - `PEP 338: Executing modules inside packages with '-m' `__ ------------------- Deprecating modules ------------------- The xmllib module was deprecated but not listed in `PEP 4`_. What does one do? Well, this led to a long discussion on how to handle module deprecation. With the 'warning' module now in existence, PEP 4 seemed to be less important. It was generally agreed that listing modules in PEP 4 was no longer needed. It was also agreed that deleting deprecated modules was not needed; it breaks code and disk space is cheap. It seems that no longer listing documentation and adding a deprecation warning is what is needed to properly deprecate a module. By no longer listing documentation new programmers will not use the code since they won't know about it. And adding the warning will let old users know that they should be using something else. .. _PEP 4: http://www.python.org/peps/pep-0004.html Contributing threads: - `Deprecated xmllib module `__ - `Rewriting PEP4 `__ ------------------------------------------ PR to fight the idea that Python is "slow" ------------------------------------------ An article_ in ACM TechNews that covered 2.4 had several mentions that Python was "slow" while justifying the slowness (whether it be flexibility or being fast enough). Guido (rightfully) didn't love all of the "slow" mentions which I am sure we have all heard at some point or another. The suggestions started to pour in on how to combat this. The initial one was to have a native compiler. The thinking was that if we compiled to a native executable that people psychologically would stop the association of Python being interpreted which is supposed to be slow. Some people didn't love this idea since a native compiler is not an easy thing. Others suggested including Pyrex with CPython, but didn't catch on (maintenance issue plus one might say Pyrex is not the most Pythonic solution). This didn't get anywhere in the end beyond the idea of a SIG about the various bundling tools (py2app, py2exe, etc.). The other idea was to just stop worrying about speed and move on stomping out bugs and making Python functionally more useful. With modules in the stdlib being rewritten in C for performance reasons it was suggested we are putting out the perception that performance is important to us. Several other people also suggested that we just not mention speed as a big deal in release notes and such. This also tied into the idea that managers don't worry too much about speed as much as being able to hire a bunch of Python programmers. This led to the suggestion of also emphasizing that Python is very easy to learn and thus is a moot point. There are a good number of Python programmers, though; Stephan Deibel had some rough calculations that put the number at about 750K Python developers worldwide (give or take; rough middle point of two different calculations). .. _article: http://gcn.com/vol1_no1/daily-updates/28026-1.html Contributing threads: - `2.4 news reaches interesting places `__ =============== Skipped Threads =============== - MS VC compiler versions - Any reason why CPPFLAGS not used in compiling? Extension modules now compile with directories specified in the LDFLAGS and CPPFLAGS env vars - adding key argument to min and max min and max now have a 'key' argument like list.sort - Unicode in doctests - SRE bug and notifications - PyInt_FromLong returning NULL - PyOS_InputHook enhancement proposal - The other Py2.4 issue - MinGW And The other Py2.4 issue - Supporting Third Party Modules - Python in education From jurgenex at hotmail.com Tue Jan 18 09:35:57 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Tue, 18 Jan 2005 14:35:57 GMT Subject: [perl-python] 20050118 keyed list References: <1106027360.920787.321590@z14g2000cwz.googlegroups.com> Message-ID: Xah Lee wrote: > ? # in perl, keyed-list is done like this: Just FYI: those thingies are called hashes. The legacy name would be associative array. > ? %a = ('john',3, 'mary', 4, 'jane', 5, 'vicky',7); > ? use Data::Dumper qw(Dumper); > ? print Dumper \%a; Wow, my compliments. The very first time that using Data::Dumper actually may do something useful (formats the data more nicely). Still, why you are passing a reference is beyond me. > ? # the syntax of keyed list in Perl is too complex > ? # to be covered in a short message. Excuse me? If (using the same examples as for your Python section) print "Mary is $a{mary}"; delete $a{vicky}; print %a; print keys(%a); exists $a{mary}; is too complex for your to cover, then I strongly suggest you stop posting your "explanations". > ? # see "perldoc perldata" for an unix-styled course. Excuse me? Do you mind explaining where exactly perldata is "Unix-styled"? jue From Mark.English at liffe.com Fri Jan 21 12:41:11 2005 From: Mark.English at liffe.com (Mark English) Date: Fri, 21 Jan 2005 17:41:11 -0000 Subject: Class introspection and dynamically determining function arguments Message-ID: <40E605146701DE428FAF21286A97D309174511@wphexa02.corp.lh.int> Diez B. Roggisch wrote: > According to this > http://www-106.ibm.com/developerworks/library/l-pyint.html > > not really - and there are no special moduls neccessary, as > everything is at your hands using __dict__ and so on. Thanks for the link. I'd read that article but found it was too introductory (what is help, what is sys, etc.). It didn't even deal with inspect. As such, I didn't think it was definitive about Python's existing introspection code. This was much more the level of sophistication I was looking for, albeit aimed at (static) declared function syntax, rather than (dynamic) instance or class attributes: http://www.sff.net/people/neelk/open-source/Signature.py Also, I know the class __dict__ (which is actually a proxy object) may have class attributes currently, but that seems implementation dependent. At the moment it lists the attributes defined by *this* type, regardless of attributes defined in base types. Again, this happens to be what I want but I don't know that this behaviour is defined anywhere, and therefore it may be subject to change. It would be nice if I could ask a class if there are any attributes defined for it in "tp_getset", although that's just a small step along the path of attribute discovery... (Apologies for interchangeable use of the words type/class) Nick Coghlan wrote > Perhaps the simplest way is to require all such classes to have a "getExample" > class method that produces a fully populated example instance Thanks Nick. This was the kind of approach I've ended up going with (sorta). Still hunting for ideas... ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From asda at sdarta.com Sat Jan 8 10:03:44 2005 From: asda at sdarta.com (worzel) Date: Sat, 8 Jan 2005 23:03:44 +0800 Subject: tuples vs lists References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41dff650$0$29357$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Cheers - thanks for the feedback guys - pretty much answers the question for me. 'Two-Pull' it is then, thanks. "Steve Horsley" wrote in message news:croqtg$qo0$1 at news.freedom2surf.net... > worzel wrote: >> I get what the difference is between a tuple and a list, but why would I >> ever care about the tuple's immuutability? > > Mainly for security and speed. Many library functions return info by > returning > a reference to an internally held tuple, and could be damaged / > compromised > / corrupted if that internal data was modified by malicious code. If > tuples > were mutable (lists) then it would be necessary to return a copy instead. > >> Also, do you say 'too-ple' or 'chu-ple' - if you get my drift. (tomato or >> tomato kind of thing) > > Try 'Two-pull'. > > Steve From benji at zope.com Mon Jan 31 23:19:39 2005 From: benji at zope.com (Benji York) Date: Mon, 31 Jan 2005 23:19:39 -0500 Subject: barchart for webpage needed In-Reply-To: References: Message-ID: <41FF035B.3050900@zope.com> dimitri pater wrote: > I am looking for a Python tool to create graphs and charts on a > webpage. Chartdirector is too expensive for me. A simple script for > creating a barchart should be sufficient as a starting point. If all you want are bar charts, you can get by with simple HTML. Here's one technique: http://www.siteexperts.com/tips/contents/ts13/page1.asp. -- Benji York Sr. Software Engineer Zope Corporation From steve at holdenweb.com Thu Jan 6 09:06:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 09:06:05 -0500 Subject: navigating/changing directories In-Reply-To: References: Message-ID: <8FbDd.68968$Jk5.48112@lakeread01> skip wrote: > A simple script like the one below lets me jump through a directory > structure. However, if I run it from /this/directory and within it to go to > /a/totally/different/directory... I'm still actually going to be in > /this/directory when I exit the script. Is it possible to have a script > that can drop me off into a different directory than where I initiated it > from? > > import os > process = 1 > while (process): > # Display directories > for i in os.listdir(os.getcwd()): > if (os.path.isdir(os.path.join(os.getcwd(),i))): > print i > > # Change directory > goto_dir = raw_input(": ") > if (goto_dir in os.listdir(os.getcwd())): > os.chdir(os.path.join(os.getcwd(),goto_dir)) > else: > process = 0 # Exit > > As has already been reported, under Linux a change to the current working directory won't affect the environment of the parent process. You may find that under some Windows command line interpreters that the change to the working directory made by a program persists into the interactive session that triggered the program. One way to achieve your desired goal, of course, is to call your program using a shell expansion sequence (assuming Unix-like shell environments), as in: cd `myprogram.py` and then if your program outputs the path to a directory your shell's current working directory will be chaged as you require. there's-always-a-way-ly y'rs - 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 aleaxit at yahoo.com Mon Jan 24 04:28:25 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 24 Jan 2005 10:28:25 +0100 Subject: best way to do a series of regexp checks with groups References: <1gqvzm0.htfjsq10h8nruN%aleaxit@yahoo.com> Message-ID: <1gqw1sv.18zhgeqcb46t3N%aleaxit@yahoo.com> Steven Bethard wrote: > I get a bit uneasy from the repeated calls to m.group... If I was going > to build a class around the re, I think I might lean towards something like: > > class ReWithMemory(object): > def search(self, are, aline): > self.mo = re.search(are, aline) > return self.mo > def groups(self, *indices): > return [self.mo.group(i) for i in indices] > > m = ReWithMemory() > > if m.search(r'add (\d+) (\d+)', line): > do_add(*m.groups(1, 2)) > elif m.search(r'mult (\d+) (\d+)', line): > do_mult(*m.groups(1, 2)) > elif m.search(r'help (\w+)', line): > show_help(*m.groups(1)) > > Of course, this is even less general-purpose than yours... I'm not sure what advantage it's supposed to give. Would you have any problems writing, say, somecall(X[1], X[2]) ...? Python normally relies on indexing one thing at a time, and I see calling m.group(1) etc as just the same kind of approach. > (And if I saw myself using this much regex code, I'd probably reconsider > my strategy anyway.) ;) Surely joining all the regexp's into one big one with | would be faster and more compact, but, with variable numbers of groups per sub-regexp, determining which regexp matched can perhaps be tricky (issues with matching mo.lastindex to the correct sub-regexp). So, I can understand the desire to do it sequentially, regexp by regexp. Alex From ncoghlan at iinet.net.au Wed Jan 12 05:32:25 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 12 Jan 2005 20:32:25 +1000 Subject: else condition in list comprehension In-Reply-To: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: <41E4FCB9.4030200@iinet.net.au> Luis M. Gonzalez wrote: > Hi there, > > I'd like to know if there is a way to add and else condition into a > list comprehension. I'm sure that I read somewhere an easy way to do > it, but I forgot it and now I can't find it... > > for example: > z=[i+2 for i in range(10) if i%2==0] > what if I want i to be "i-2" if i%2 is not equal to 0? > Hmm: z = [newval(i) for i in range(10)] using: def newval(x): if x % 2: return x - 2 else: return x + 2 Just some more mental twiddling relating to the thread on statement local namespaces. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ncoghlan at iinet.net.au Tue Jan 25 09:09:10 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 00:09:10 +1000 Subject: Instances of class object not modifiable? In-Reply-To: References: Message-ID: <41F65306.4030008@iinet.net.au> Steven Bethard wrote: > Open Issues > =========== > What should the type be named? Some suggestions include 'Bunch', > 'Record' and 'Struct'. Add 'namespace' to the list of name suggestions :) Cheers, Nick. The name came up in some thread a few weeks back. . . -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From chris.peressotti at utoronto.ca Fri Jan 28 11:13:45 2005 From: chris.peressotti at utoronto.ca (Chris P.) Date: 28 Jan 2005 08:13:45 -0800 Subject: PythonWin (build 203) for Python 2.3 causes Windows 2000 to grind to a halt? References: <3f233389.0501271147.43572416@posting.google.com> <41f9e4a9$1_1@127.0.0.1> Message-ID: <3f233389.0501280813.6be97b74@posting.google.com> AWESOME - my life just got THAT much better. The bug you suggested is exactly the problem that I was having... I had looked through the bugs being tracked, but the title of that one didn't jump out at me as something that would help. Thanks! - Chris P.S. For anyone reading this group who wants to know exactly what I did: 1) Uninstall Pywin32 2) Open the registry editor ('regedit' at the command prompt) 3) Go to HKEY_CURRENT_USER\Software\Python[version]\Python for Win32 You will likely find many many many keys that have the format "ToolbarDefault-Bar#". These keys filling up your registry cause Windows 2000 to become extremely slow/unstable when Python is running (especially if your debugger is running.) 4) Delete the keys... I just deleted it at the "Python[version]" root 5) Reinstall Pywin32 "Roger Upole" wrote in message news:<41f9e4a9$1_1 at 127.0.0.1>... > These look like symptoms of sf bug #1017504 > http://sourceforge.net/tracker/index.php?func=detail&aid=1017504&group_id=78018&atid=551954 > > What version of Pywin32 are you running ? > There's a (semi) fix for this in the latest build. > hth > Roger From aurora00 at gmail.com Mon Jan 31 19:07:41 2005 From: aurora00 at gmail.com (aurora) Date: Mon, 31 Jan 2005 16:07:41 -0800 Subject: Go visit Xah Lee's home page Message-ID: 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." From storchaka at ksf.kiev.ua Tue Jan 11 13:14:01 2005 From: storchaka at ksf.kiev.ua (Serhiy Storchaka1659322541) Date: Tue, 11 Jan 2005 20:14:01 +0200 Subject: else condition in list comprehension In-Reply-To: References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> <1105305000.052714.188980@c13g2000cwb.googlegroups.com> Message-ID: Nick Coghlan wrote: > Dan Bishop wrote: > >> Luis M. Gonzalez wrote: >> >>> Hi there, >>> >>> I'd like to know if there is a way to add and else condition into a >>> list comprehension. I'm sure that I read somewhere an easy way to do >>> it, but I forgot it and now I can't find it... >>> >>> for example: >>> z=[i+2 for i in range(10) if i%2==0] >>> what if I want i [sic] to be "i-2" if i%2 is not equal to 0? >> >> >> >> z = [i + (2, -2)[i % 2] for i in range(10)] > > > For the specific case of +/- a number, (-1) ** x works, too: > > z = [i + 2 * ((-1) ** i) for i in range(10)] > > Not that I'm claiming it's particularly readable or anything. . . just > that it works :) Yet another variant: z = [i + ( (i % 2) and -2 or 2 ) for i in range(10)] -- Serhiy Storchaka From tim.peters at gmail.com Wed Jan 26 20:59:11 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 26 Jan 2005 20:59:11 -0500 Subject: python memory blow out In-Reply-To: <3e8ca5c8050126174444967112@mail.gmail.com> References: <4e4a11f805012617082ebd9b80@mail.gmail.com> <3e8ca5c8050126174444967112@mail.gmail.com> Message-ID: <1f7befae050126175916958afd@mail.gmail.com> [Simon Wittber] >> According to the above post: >> a) If the allocation is > 256 bytes, call the system malloc. >> b) If the allocation is < 256, use its own malloc implementation, which >> allocates memory in 256 kB chunks and never releases it. >> >> I imagine this means that large memory allocations are eventually >> released back to the operating system. However, in my case, this >> appears to be not happening. Large chunks are returned to the platform C when they become unreferenced. More below. [Stephen Thorne] > There was a recent patch posted to python-dev list which allows python > to release memory back to the operating system once the 256kb chunk is > no longer used. Nope, the patch may return such a 256KB chunk to the platform C library's free() function. That's never what someone actually means by the vague "released back to the operating system", and whether the latter might happen is another platform-dependent (OS + C library + specific versions of each) can of worms. > I'm not saying running a bleeding edge CVS HEAD python plus untested > development patches is going to be a solution for you in the short > term, but I just wanted to mention it because I'm excited about this > limitation disappearing in python :). It's a necessary first step, anyway. Alas, there's no way to take a second step without messy platform-specific code (when does your favorite platform C free() "release memory back" to your favorite operating system? to "do something about that", exact knowledge of platform details is necessary). From removethis.kartic.krishnamurthy at gmail.com Sun Jan 30 20:28:59 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Mon, 31 Jan 2005 01:28:59 GMT Subject: Problem with loading textfiles into dictionaries. In-Reply-To: References: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> Message-ID: Kartic said the following on 1/30/2005 8:21 PM: > mercuryprey at gmail.com said the following on 1/30/2005 7:43 PM: > Hi - It looks like your code encountered a blank line when you got this > error. > > You should move "if len(siteline) == 0" part right after your readline. > The way you have done it really does not help. > > def do_load(self, arg): > sitefile = file('sitelist', 'r+', 1) > while True: > siteline = sitefile.readline() > if len(siteline) == 0: > break > site_rawlist = siteline.split() > sitelist[site_rawlist[0]] = site_rawlist[1:] Sorry...siteline = sitefile.readline().strip() From jgrahn-nntq at algonet.se Mon Jan 24 16:51:35 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 24 Jan 2005 21:51:35 GMT Subject: how to ncurses on win32 platform References: <3nkds3kzc9mp.18yfed1y3vo9d$.dlg@40tude.net> Message-ID: On Mon, 24 Jan 2005 20:26:28 +0000 (UTC), Alan Gauld wrote: > On Mon, 24 Jan 2005 17:06:52 +0100, Brane wrote: >> please advice > > You can use ncurses via cygwin. > There are DOS ports too but I couldn't get any of them to > work on my XP box, YMMV... Or, as Alex Martelli wrote in "Python in a nutshell": "The curses package works only on Unix-like platforms (there are persis- tent rumors of Windows ports of it, but I've never found a working one)." /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From tom at livelogix.com Wed Jan 26 01:01:57 2005 From: tom at livelogix.com (Tom) Date: 25 Jan 2005 22:01:57 -0800 Subject: Python with no significant whitespace In-Reply-To: References: <35oh4gF4nvvfoU1@individual.net> Message-ID: <1106719317.609935.38430@f14g2000cwb.googlegroups.com> Just though I'd point out that Logix *does* use whitespace for delimiting blocks. Or rather, it can use whitespace, and the languages that come as standard do. With Logix you could quite easily make a version of Python with, e.g., braces instead of whitespace for delimiting blocks. That's probably what the Stephen was getting at. Tom. From martin at v.loewis.de Sun Jan 23 18:15:29 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 24 Jan 2005 00:15:29 +0100 Subject: rotor replacement In-Reply-To: <7xllalljah.fsf@ruckus.brouhaha.com> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> Message-ID: <41F43011.8020303@v.loewis.de> Paul Rubin wrote: > There's tons of such examples, but python-dev apparently reached > consensus that the Python maintainers were less willing than the > maintainers of those other packages to deal with those issues. As Andrew says, it is not apparent that there was consensus. > Martin, do you know more about this? I'm pretty certain that we (the PSF) sent a message to BXA, reporting the rotor module. While I can't find out exactly when this happened right now, the board meeting on 2002-04-09 decided that this should happen, see http://python.org/psf/records/board/minutes-2002-04-09.html Regards, Martin From elephantum at dezcom.mephi.ru Thu Jan 13 14:41:54 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Thu, 13 Jan 2005 22:41:54 +0300 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> Message-ID: <34o183F4b3in3U1@individual.net> Nick Coghlan wrote: > Nick Coghlan wrote: > >> Semantics >> --------- >> The code:: >> >> with: >> >> >> translates to:: >> >> def unique_name(): >> >> >> unique_name() > I've come to the conclusion that these semantics aren't what I would > expect from the construct. Exactly what I would expect can't really be > expressed in current Python due to the way local name bindings work. The > main thing to consider is what one would expect the following to print: > > def f(): > a = 1 > b = 2 > print 1, locals() > print 3, locals() using: > a = 2 > c = 3 > print 2, locals() > print 4, locals() > > I think the least suprising result would be: > > 1 {'a': 1, 'b': 2} # Outer scope > 2 {'a': 2, 'c': 3} # Inner scope > 3 {'a': 2, 'b': 2, 'c': 3} # Bridging scope > 4 {'a': 1, 'b': 2} # Outer scope as for me, I would expect following: 1 {'a': 1, 'b': 2} 2 {'a': 2, 'b': 2, 'c': 3'} 3 {'a': 2, 'b': 2, 'c': 3'} 4 {'a': 1, 'b': 2} otherwise that would be impossible to do calculations based on scope variables and "using:" would be useless =), consider example of usage: current_position = 1 current_environment # = ... current_a_lot_of_other_parameters # = ... scores = [count_score(move) for move in aviable_moves] using: def count_score(move): #walking through current_environment return score From kosh at aesaeion.com Tue Jan 11 21:23:46 2005 From: kosh at aesaeion.com (kosh) Date: Tue, 11 Jan 2005 19:23:46 -0700 Subject: Python.org, Website of Satan In-Reply-To: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <200501111923.46511.kosh@aesaeion.com> On Tuesday 11 January 2005 7:06 pm, humblythegreatest at usa.com wrote: > python.org = 194.109.137.226 > > 194 + 109 + 137 + 226 = 666 > > What is this website with such a demonic name and IP address? What > evils are the programmers who use this language up to? Geeze did you miss out on the demon summoning rituals last week? Wow that was a great thing you missed out on. I am sorry I can't tell you about the future events though. Only great wizards are allowed to come and they all know when the events are. :) From rbt at athop1.ath.vt.edu Mon Jan 17 10:30:38 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 17 Jan 2005 10:30:38 -0500 Subject: Install Python 2.4 on Fedora 3 Core In-Reply-To: <1105975262.047782.6010@z14g2000cwz.googlegroups.com> References: <1105975262.047782.6010@z14g2000cwz.googlegroups.com> Message-ID: Bill wrote: > I have less than a week experience on linux, so I am a new newbie. > Python 2.3 came preinstalled. I installed version 2.4. All seemed to > go well except it installed to usr/local? > > 1. Was it wrong to install when logged in as 'root'? Does it make a > difference? > > 2. I looked in the package editor and there was no way to uninstall > 2.3? Should I? If so, how can I? If not,what are the problems, if > any, of having both. > > Thank you for your help. > Bill, /usr/local is the path on Unix systems where add-on software is traditionally installed. RH used to use Python heavily for many aspects of their RHL distribution. I suspect they still do this with Fedora. This is probably why the version of Python that came with Fedore cannot be removed (at least not easily). It's OK to have the RH version and the latest Python.org version installed. You'll just have to specify the path to the version you wish to use when running your scripts like this: /usr/local/python There are some more advanced things you could do and I suspect others will give you better advice. But all in all, you're OK. Have fun. From alan.gauld at btinternet.com Thu Jan 6 17:36:00 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 6 Jan 2005 22:36:00 +0000 (UTC) Subject: Securing a future for anonymous functions in Python References: Message-ID: On Thu, 30 Dec 2004 23:28:46 +1000, Nick Coghlan wrote: > GvR has commented that he want to get rid of the lambda keyword for Python 3.0. > Getting rid of lambda seems like a worthy goal, Can I ask what the objection to lambda is? 1) Is it the syntax? 2) Is it the limitation to a single expression? 3) Is it the word itself? I can sympathise with 1 and 2 but the 3rd seems strange since a lambda is a well defined name for an anonymous function used in several programming languages and originating in lambda calculus in math. Lambda therefore seems like a pefectly good name to choose. So why not retain the name lambda but extend or change the syntax to make it more capable rather than invent a wholly new syntax for lambdas? Slightly confused, but since I only have time to read these groups regularly when I'm at home I have probably missed the bulk of the discussion over the years. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From deetsNOSPAM at web.de Fri Jan 28 08:15:36 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 28 Jan 2005 14:15:36 +0100 Subject: Proccess termination References: <1106917700.730538.80320@f14g2000cwb.googlegroups.com> Message-ID: <35us3lF4rqg1oU1@individual.net> alexrait1 wrote: > I use popen.popen2 or popen.popen3 to start a new process and read from > it's stdout/ write to it's stdin. > But I need a way to know when a process terminates. If it closes it's > stdin/stdout, it doesn't mean it has really terminated... You can use the Popen-objects pid to see if a process still runs. > And if possible, I would like to see an exception thrown when that > happens.. Not possible - that exception would be asynchronous to your program flow. The only thing I can think of that would make this possible is to have a second thread waiting for process termination - and sending the own process a signal. If I'm not mistaken, that will be propagated to the main thread. All this is meant to be running on unix - not sure how thinks work out on windows. -- Regards, Diez B. Roggisch From bulba at bulba.com Sat Jan 8 23:01:58 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 09 Jan 2005 05:01:58 +0100 Subject: The Industry choice References: <7xhdluxh4i.fsf@ruckus.brouhaha.com> Message-ID: On 6 Jan 2005 20:07:19 -0500, aahz at pythoncraft.com (Aahz) wrote: >>Nope. That is not what I'm arguing. Really, I think you have >>jumped to conclusion about that: I merely pointed out that >>I don't like what I perceive as end effect of what GPL license >>writers are attempting to achieve: vendor lock-in. >> >>I think I stated that clearly. > >And my counter-argument is that I believe your perception is wrong. If >I agreed with your focus on lock-in, I'd say that what the GPL is trying >to lock in is a specific legal philosophy by subverting the existing >system. If it finally turns out that I'm wrong on this and GPL does not have that kind of economic "vendor lock-in" _effect_ behind it (note: effect, not intent), I will be only happy to see that. Re subverting existing legal philosophy, I could not care less. Obviously the only reason that I argued that way is that given the info that I have it simply looks like that from my viewpoint. -- It's a man's life in a Python Programming Association. From donn at drizzle.com Sun Jan 2 01:26:39 2005 From: donn at drizzle.com (Donn Cave) Date: 2 Jan 2005 00:26:39 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> Message-ID: <41d7941f$1_3@127.0.0.1> Quoth Paul Rubin : | beliavsky at aol.com writes: |> Overall I agree with you and would like to have OPTIONAL static type |> declarations in Python, as has often been discussed. But without |> facilities for generic programming, such as templates in C++, static |> type declarations can force one to duplicate a LOT of code, with one |> sorting routine each for integer, floats, strings, etc. | | I don't see that big a problem. The current Python sorting routine | operates on instances of class "object" and calls the __cmp__ method | to do comparisons. Every class of sortable objects either defines a | __cmp__ method or inherits one from some superclass, and sort calls | those methods. Static type declarations would not require writing any | additional sorting routines. Yes, it would be really weird if Python went that way, and the sort of idle speculations we were reading recently from Guido sure sounded like he knows better. But it's not like there aren't some interesting issues farther on downstream there, in the compare function. cmp(), and str() and so forth, play a really big role in Python's dynamically typed polymorphism. It seems to me they are kind of at odds with static type analysis, especially if you want type inference -- kind of a type laundering system, where you can't tell what was supposed to be there by looking at the code. Some alternatives would be needed, I suppose. Donn Cave, donn at drizzle.com From jzgoda at gazeta.usun.pl Fri Jan 14 15:27:01 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 14 Jan 2005 21:27:01 +0100 Subject: python to mssql In-Reply-To: <1lmwxbtst8x8x$.10hwcoinem3cs.dlg@40tude.net> References: <1lmwxbtst8x8x$.10hwcoinem3cs.dlg@40tude.net> Message-ID: Brane wrote: > can someone please give me some info regarding subject From Windows machine: http://adodbapi.sourceforge.net/ From elsewhere: FreeTDS + unixODBC + mxODBC is one of possible solutions. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From ysharma at catprosystems.com Thu Jan 13 18:09:07 2005 From: ysharma at catprosystems.com (Yogesh Sharma) Date: Thu, 13 Jan 2005 15:09:07 -0800 Subject: Embedding Multiplr Python interpreter in C++ In-Reply-To: References: Message-ID: <41E6FF93.9060406@catprosystems.com> one more question to add: Is there a way to have 2 local copies of python interpreter ? Yogesh Sharma wrote: > Hi, > > I have following setup: > OS Linux Fedora Core 3 > Python 2.3.4 > > How can I embed two python interpreters in one C++ program ? > > Thanks From peter at engcorp.com Thu Jan 13 18:15:21 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 18:15:21 -0500 Subject: newbie ?s In-Reply-To: <1105656971.768148@sj-nntpcache-5> References: <1105656971.768148@sj-nntpcache-5> Message-ID: Venkat B wrote: > Hi folks, > > I'm looking build a CGI-capable SSL-enabled web-server around Python 2.4 on > Linux. > It is to handle ~25 hits possibly arriving "at once". Content is non-static > and built by the execution of py cgi-scripts talking to a few backend > processes. Twisted? I'm not sure what, if anything, it has in the way of CGI support, but that could probably be hacked on pretty darn quick if you needed. At least Twisted has support for server-side SSL (i.e. it can deal with certificates). -Peter From rkern at ucsd.edu Sun Jan 9 11:46:22 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 09 Jan 2005 08:46:22 -0800 Subject: Python3: on removing map, reduce, filter In-Reply-To: <34d3c9F477m01U1@individual.net> References: <34csn1F4a46hqU1@individual.net> <5CcEd.70344$Jk5.19962@lakeread01> <34d3c9F477m01U1@individual.net> Message-ID: Andrey Tatarinov wrote: > Steve Holden wrote: > >> Andrey Tatarinov wrote: >> >>> Hi. >>> >>> How does GvR suggestions on removing map(), reduce(), filter() >>> correlate with the following that he wrote himself (afaik): >>> >>> http://www.python.org/doc/essays/list2str.html > > > > >> And note that the summary in the conclusiogn BEGINS with "Rule number >> one: only optimize when there is a proven speed bottleneck", which >> seems to adequately imply that straightforward code is to be preferred >> unless speed requirements override that. > > > My main question was: "how could be this advices applied, when map, > reduce and filter would be removed?" Since Python 3.0 is currently mythical and will involve a complete rewrite of the language and interpreter, I don't think that you should expect any optimization advice to carry over. -- 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 fredrik at pythonware.com Sat Jan 15 04:31:37 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 15 Jan 2005 10:31:37 +0100 Subject: How to del item of a list in loop? References: Message-ID: "skull" wrote: > Hi everybody, it is my first post in this newsgroup. > I am a newbie for python though I have several years development experience in c++. > recently, I was stumped when I tried to del item of a list when iteration. > > here is the wrong way I did: > > lst = [1, 2, 3] > for i in lst: > print i > if i == 2: > lst.remove(i) > > the result is: > > 1 > 2 >>>> > > as you would see, '3' is missing. this problem is caused by 'lst.remove(i)'. the internal loop counter is incremented whether you remove stuff or not, so when you're moving things around by removing items in the middle, the loop will skip over items. this is basic for-in usage, and any decent tutorial should explain this. to fix this, you can build a new output list, loop backwards, or loop over a copy. the last is easiest to implement: lst = [1, 2, 3] for i in lst[:]: print i if i == 2: lst.remove(i) but the others may have advantages in certain use cases. if you want more details, see the language reference: http://docs.python.org/ref/for.html (note the warning) From aurora00 at gmail.com Fri Jan 28 11:25:29 2005 From: aurora00 at gmail.com (aurora) Date: Fri, 28 Jan 2005 08:25:29 -0800 Subject: Transparent (redirecting) proxy with BaseHTTPServer References: <35sfdaF4hka1hU1@individual.net> <35t9huF4rt829U1@individual.net> Message-ID: It should be very safe to count on the host header. Maybe some really really old browser would not support that. But they probably won't work in today's WWW anyway. Majority of today's web site is likely to be virtually hosted. One Apache maybe hosting for 50 web addresses. If a client strip the host name and not sending the host header either the web server wouldn't what address it is really looking for. If you caught some request that doesn't have host header it is a good idea to redirect them to a browser upgrade page. > > Thanks, aurora ;), > > aurora wrote: >> If you actually want the IP, resolve the host header would give you >> that. > I' m only interested in the hostname. > >> The second form of HTTP request without the host part is for >> compatability of pre-HTTP/1.1 standard. All modern web browser should >> send the Host header. > How safe is the assumtion that the Host header will be there? Is it part > of the HTTP/1.1 spec? And does it mean all "pre 1.1" clients will fail? > Hmm, maybe I should look on the wire whats really happening... > > thanks again > Paul From cdieterich at geosci.uchicago.edu Thu Jan 27 21:02:53 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Thu, 27 Jan 2005 20:02:53 -0600 Subject: inherit without calling parent class constructor? In-Reply-To: <10vj4ovqee29oc9@corp.supernews.com> Message-ID: On D?ardaoin, Ean 27, 2005, at 19:25 America/Chicago, Jeff Shannon wrote: > Okay, so size (and the B object) is effectively a class attribute, > rather than an instance attribute. You can do this explicitly -- Ah, now I'm getting there. That does the trick. > Probably not worth the trouble in this particular case, but maybe in > another case... :) Yeah, maybe not. But I'll remember it as a useful recipe. Cheers, Christian From peter at engcorp.com Thu Jan 6 10:36:28 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jan 2005 10:36:28 -0500 Subject: OT: spacing of code in Google Groups In-Reply-To: References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> Message-ID: <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> Jacek Generowicz wrote: > Peter Hansen writes: >>Why the heck would I ever have to do "rectangle operations" on a >>regular basis? ;-) > > Well, given that all editors are cat equivalent[*], you don't _have_ > to use any of their features :-) This "cat equivalent" thing is a red-herring. I can rarely type more than a line of code without making a typographical error. Sometimes I won't catch that error until a bit later. Using "cat" alone would provide me little opportunity to fix the error, so I would never be able to produce a working program longer than a few lines. You might call this simply "less productive" (though I'd argue it becomes a qualitative difference). But, okay, let's work from there... > But just like Python (particularly in the hands of a skilled Python > programmer) is more productive than a Turing Machine, any featureful > editor (in the hands of an experienced user) is far more productive > than "cat > file". I don't disagree. I do, however, claim that the set of features that are required to make *me* orders of magnitude more productive than "cat" (to use your quantitative comparison) is very, very small. And that I use less than 2% of the features most editors have. And that if a programmer with equal abilities managed to learn to use 98% of the features of such an editor, such that he could readily use whichever such feature was most effective at any given time, he would not be more than 10% more effective than I am. But the whole argument is fairly moot... I've needed a rectangle operation only once in the last ten years, and if I hadn't known at the time that my editor could do it (and spent about half an hour figuring out how it worked), I could have written a utility to do the job faster if I'd been using Python at the time... Cheers, -Peter From martin at v.loewis.de Mon Jan 31 18:20:01 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 01 Feb 2005 00:20:01 +0100 Subject: serializing data structures In-Reply-To: References: Message-ID: <41FEBD21.5030306@v.loewis.de> Philippe C. Martin wrote: > I once wrote something in C to do that, but since python usually has a > solution for me .... If you use arbitrary data structures, you could use pickle or xmlrpclib to marshal the data. If you know the data is restricted to a few well-known data types, you could use XDR (Demo/rpc/xdr.py) or CORBA (e.g. through fnorb.sf.net) to come up with a wire format. Otherwise, if you want to define your own proprietary data format, you can probably use the struct module to generate messages according to this format. However, in any case, you need to define the wire format. Once you made a choice, Python can help implement it - but Python cannot chose a wire format for you (although pickle comes really close, as does Dopy - http://www.mindhog.net/~mmuller/projects/dopy/) Regards, Martin From http Sun Jan 9 00:40:40 2005 From: http (Paul Rubin) Date: 08 Jan 2005 21:40:40 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> Message-ID: <7xsm5b2m93.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > I think having to keep the names unique within the statement you are > currently writing is a reasonable request :) Um, you could say the same thing about the function, the module, etc. ;) From sjmachin at lexicon.net Fri Jan 21 23:34:08 2005 From: sjmachin at lexicon.net (John Machin) Date: 21 Jan 2005 20:34:08 -0800 Subject: why am I getting a segmentation fault? References: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> <1106351339.457714.214940@f14g2000cwb.googlegroups.com> <1106356789.748649.259090@f14g2000cwb.googlegroups.com> Message-ID: <1106368448.725365.37030@f14g2000cwb.googlegroups.com> Jay donnell wrote: > >### Have you looked in your database to see if the >script has > actually > >updated item.goodImage? Do you have a test plan? > > Thank you for the help. Sorry for the messy code. I was under time > constraints. I had class, and I was rushing to get this working before > class. I should waited a day and read over it before I asked. Sorry > again. Apologise to _yourself_ for the messy code. If 'query' had been safely tucked away as a local variable instead of a global, that problem (typing 'query' instead of 'self.q') would have caused an exception on the first time around. A few points: Yes, don't rush. I've-forgotten-whom wrote something like "Don't program standing up". Good advice. Build things a piece at a time. Build your tests at the same time or earlier. In this case, a stand-alone method or function that checked that one file was OK, would have been a reasonable place to start. Then add the code to query the db. Then add the threading stuff, gingerly. If you build and test incrementally, then a segfault or other disaster is highly likely to have been caused by the latest addition. AND SOME MORE CRUFT: def __init__(self, url, filename, id): self.t = time.time() <<<<<<<<<======= never used again threading.Thread.__init__(self) self.db = MySQLdb.connect(host="localhost", user="xxx", passwd="xxx", db="xxx") # create a cursor self.cursor = db.cursor() <<<=== should be self.db.cursor() #### picks up the *GLOBAL* 'db' self.url = url self.filename = filename self.id = id =========================== threadList = [] [snip] threadList.append(imageChecker) ===>>>> that doesn't achieve much! ============================ N.B. You still have two problems: (1) Your script as you said now "seems to work". That doesn't sound like you have a test plan. (2) You have shuffled your code around and the segfault went away; i.e. you waved a dead chicken and the volcano stopped erupting. Most of the changes suggested by others and myself were of a style/clarity nature. The self.q/query thing would have caused a select instead an update; hardly segfault territory. I wouldn't expect that busy-wait loop to cause a segfault. You still don't know what caused the segfault. That means you don't know how to avoid it in the future. You are still living in the shadow of the volcano. Will the chicken trick work next time? Looking forward to the next episode, John From jfine at pytex.org Fri Jan 7 16:57:48 2005 From: jfine at pytex.org (Jonathan Fine) Date: Fri, 07 Jan 2005 21:57:48 +0000 Subject: What could 'f(this:that=other):' mean? References: <41DC52CA.5070104@pytex.org> <10toomjdjcs5v21@corp.supernews.com> <41DCE28B.70806@pytex.org> <10tr8eo5skqo2a3@corp.supernews.com> Message-ID: <41DF05DC.9060004@pytex.org> Jeff Shannon wrote: > Jonathan Fine wrote: > The use of *args and **kwargs allows functions to take a variable number > of arguments. The addition of ***nsargs does not add significantly. I've posted usage examples elsewhere in this thread. I think they show that ***nsargs do provide a benefit. At least in these cases. How significant is another matter. And how often do they occur. > Now, though, we've lost the ability to specify *only* the argname and > not the namespace as well -- that is, you *cannot* call f4 with keywords > but not namespaces. From the caller's vantage point, this means that > they need to know the full namespace spec of the function, which makes > it no different than simply using longer (but unique) keyword names. This is a major point. From the caller's point of view: fn_1(x_aa=1, x_bb=2, y_aa=3) fn_2(x:aa=1, x:bb=2, y:aa=3) are very similar. Replace '_' by ':'. So you are saying, I think, 'what does this buy the caller'. Well, by using ':' the namespacing is explicit. fn_3(my_path, my_file, any_file) Is this an example of implicit namespacing? (Rhetorical question.) Explicit is better than implicit, I'm told (smile). > So, we can see that allowing namespaces and ***nsargs doesn't add any > utility from the caller's perspective. How much does the callee gain > from it? > > Well, the following functions would be equivalent: > > def g1(arg1, arg2, arg3, arg4): > ns1 = {'arg1':arg1, 'arg2':arg2, 'arg3':arg3, 'arg4':arg4} > return ns1 > def g2(ns1:arg1, ns1:arg2, ns1:arg3, ns1:arg4): > return ns1 > > You might say "Wow, look at all that repetetive typing I'm saving!" But > that *only* applies if you need to stuff all of your arguments into > dictionaries. This is a key point. But there's more to it. Namespace arguments are good if you have to divide the arguments into two or more dictionaries. Based on the namespace prefix. > I suspect that this is a rather small subset of > functions. In most cases, it will be more convenient to use your > arguments as local variables than as dictionary entries. This is a matter of usage. If the usage is very, very small, then what's the point. If the usage is very, very large, then the case is very strong. > def gcd1(a, b): > while a: > a, b = b%a, a > return b > > def gcd2(ns1:a, ns1:b): > while ns1['a']: > ns1['a'], ns1['b'] = ns1['b']%ns1['a'], ns1['a'] > return ns1['b'] > > Speaking of repetetive typing.... :P > > Besides, another function equivalent to the above two would be: > > def g3(arg1, arg2, arg3, arg4): > ns1 = locals() > return ns1 > > ....which is quite a bit less repetetive typing than the 'namespace' > version. These are not good examples for the use of namespacing. And the results are horrible. So this is an argument _in favour_ of namespacing. Namely, that it _passes_ "there should be one (and preferably only one) obvious way to do things" test (quoted from your earlier message). > So, you're looking at making the function-calling protocol significantly > more complex, both for caller and callee, for the rather marginal gain > of being able to get arguments prepackaged in a dictionary or two, when > there already exist easy ways of packaging function arguments into a > dict. Given the deliberate bias against adding lots of new features to > Python, one needs a *much* better cost/benefit ratio for a feature to be > considered worthwhile. I believe that we _agree_, that it is a matter of cost/benefit ratio. My opinion is that studying usage examples is a good way of evaluating this ratio. Which is why I have posted some favourable usage examples. > I'd note also that the usage you're drawing from, in XML/XSLT, isn't > really comparable to function parameters. It's a much closer parallel > to object attributes. Python *does* have this concept, but it's spelled > differently, using a '.' instead of a ':'. In other words, the XML > fragment you give, > > > > .... would be more appropriate to render in Python as > > e = Element() > e.this.that = 'other' > > It's quite reasonable to suppose that some object of type Element may > have a set of font attributes and a set of image attributes, and that > some of these may have the same name. Python would use font objects and > image objects instead of 'namespaces' -- > > e.font.size = '14pt' > e.image.size = (640, 480) > > So while these namespaces are probably a great thing for XML, XSLT, > they're not very useful in Python. Which, given the rather different > goals and design philosophies behind the languages, shouldn't really be > much of a surprise. It may be better, in some cases, to write fp = FontParams() fp.size = 14 fp.slope = 0.1 f(this=this, font_params=fp) But not, I think, if the definition of f is something like: def f(this, font_params): fpd = font_params.__dict__ font_function(**fpd) (Assuming that font_function has got it right.) Prompted by your post, the idea of writing f(this.that='other') instead of f(this:that='other') came to my mind. At first I did not like it, but now it is growing on me a little. However, that is a syntactic issue. Which falls if the costs do not justify the benefits. And here, I think, the key question is this: How often do you have to divide the arguments to a function into two or more dictionaries? Which can be answered by studying usage. -- Jonathan http://www.pytex.org From ncoghlan at iinet.net.au Tue Jan 25 09:56:39 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 00:56:39 +1000 Subject: Memory Usage In-Reply-To: References: Message-ID: <41F65E27.5010108@iinet.net.au> Stuart McGarrity wrote: > Do you have a page file? > > The Mem column should be RAM usage and not total working set. Some of it > could be swapped to the page file. A free tool like process explorer can > give you better informaton than the task manager. As Tim pointed out, "View->Select Columns" and activating "VM Size" is enough to find out how much memory that program actually has *mapped* (rather than currently loaded into RAM). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From saint_infidel at hotmail.com Thu Jan 20 11:59:57 2005 From: saint_infidel at hotmail.com (infidel) Date: 20 Jan 2005 08:59:57 -0800 Subject: delay and force in Python In-Reply-To: <1106164457.982053.214970@f14g2000cwb.googlegroups.com> References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> <1106164457.982053.214970@f14g2000cwb.googlegroups.com> Message-ID: <1106240397.513679.107680@z14g2000cwz.googlegroups.com> Of course I meant to put a break out of the loop after the print statement. Duh on me. From steve at holdenweb.com Fri Jan 7 07:23:23 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 07 Jan 2005 07:23:23 -0500 Subject: Securing a future for anonymous functions in Python In-Reply-To: <7xis6930ah.fsf@ruckus.brouhaha.com> References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <7xis6930ah.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Anna" writes: > >>Having taken some calculus (derivatives, limits, some integrals) but >>never even heard of lambda calculus, to me, lambda means absolutely >>NOTHING. Less than nothing. > > > Lambda calculus is from mathematical logic, but more to the point > "lambda" has been the term used in Lisp for this operation since time > immemorial. Since the kinds of programmers who want to use anonymous > functions have probably been exposed to Lisp at one time or another, > "lambda" should not cause any confusion. That's probably not the most enthusiastic evangelical approach to functional programming I've ever heard :-) Perhaps what we really need is a good Lisp subsystem for Python? 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 duncan.booth at invalid.invalid Fri Jan 28 07:50:10 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Jan 2005 12:50:10 GMT Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> <7x3bwlsqnj.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Duncan Booth writes: >> In other words, I'm intrigued how you managed to come up with >> something you consider to be a security issue with Python since >> Python offers no security. Perhaps, without revealing the actual >> issue in question, you could give an example of some other situation >> which, if it came up in Python you would consider to be a security >> issue? > > Until fairly recently, the pickle module was insufficiently documented > as being unsafe to use with hostile data, so people used it that way. > As a result, the Cookie module's default settings allowed remote > attackers to take over Python web apps. See SF bug 467384. SF doesn't seem to know about any such bug any more. Google finds me http://mail.python.org/pipermail/python-bugs-list/2001-October/007669.html which appears to be SF bug 467384, but it says nothing about security or the Cookie module, just that you wanted better documentation. I think its a bit borderline whether this really was a security bug in Python rather than just a problem with the way some people used Python. It was a standard library which if used in the wrong way opens a security hole on your machine, but there are plenty of ways to open security holes. The response seems to have been to document that there is a security concern here, but it is still just as possible to use python to expose your machine to attack as it was before. But thanks anyway, it does give me the sort of example I was asking for. From deetsNOSPAM at web.de Mon Jan 10 08:09:47 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 10 Jan 2005 14:09:47 +0100 Subject: Command line and GUI tools : need a single threading solution References: <41e26e79@duster.adelaide.on.net> Message-ID: <34f9lfF4af717U1@individual.net> > I'm thinking it may be possible to modify the command line tools to use qt > threads instead of native python threads. Is this the way to go? Are > there other options? Why don't you use python threads in qt - I do so and so far it didn't make any troubles for me. And I would strongly advise against using qthreads with your commandline-tools, as these then would only run on machines where pyqt is installed - which opens a small part of "dependency hell" for your users. -- Regards, Diez B. Roggisch From aut_gbarros at uolinc.com Wed Jan 5 11:18:51 2005 From: aut_gbarros at uolinc.com (Gabriel Cosentino de Barros) Date: Wed, 5 Jan 2005 14:18:51 -0200 Subject: tk the python way Message-ID: <2814F26DA6908F41927A81C410C4991A02079C32@siamun.server.bl.corp.intranet> I'm strugling a little with TK, and the docs on the web aren't helping much. I've already rewritten about twelve times a basic class that was supposed to simply draw a window. It's not even close the final draft, but i tought "well, let's start with something easy that can be done in less than an hour"... silly me. But keep reading, it's not just to vent my frustations :) The main issue here is: How to use TK eficiently. I'm already planing another post about the pack/grid/place-power-trio but for now: what's the better, most scalable and less cumbersome way to use Tk? 1. Windows a) hide Tkroot in __main__ and call the class, whom willcreate it's own windows. b) let __main__ pass the root window and make the class always require a parent. c) what's the "industry standandard" for a single or dual window small app? (no, it's not java, wrong topic) 2. Buttons What's the nicer way to pass arguments directly in a button action? I don't know if this one is me just being dumb. but `Button(..., command=doit(1) )` doesn't work for me and i haven't seen it in any doc... I came to the point of writing: btnHd = Button(..., command=self.__fileBrowseH) btnCd = Button(..., command=self.__fileBrowseC) btnFd = Button(..., command=self.__fileBrowseF) and self.__fileBrowse/[CHF]/() being just a wraper for self.__fileBrowse('/[chf]/') ...And don't miss on this same channel: my indignation with Tk's positioning systems :P Thanks! Gabriel -------------- next part -------------- An HTML attachment was scrubbed... URL: From none at none.net Tue Jan 4 06:11:23 2005 From: none at none.net (Iwan van der Kleyn) Date: Tue, 04 Jan 2005 12:11:23 +0100 Subject: Python evolution: Unease In-Reply-To: <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> Message-ID: <41DA79DB.7020507@none.net> > Also, you keep talking about "the core python team" on the basis, it > would appear, of reading one document by Guido. Have you bothered doing > a MINIMUM of homework, such as, looking at > http://www.amk.ca/diary/archives/cat_python.html Well, you being a member of that core team (meaning nog an organisational unit, but the group of people doing the really hard job, getting Python to work. An excellent job at that :-) I can repect you if not branding me a lamer at least admonishing me for not coming up with a thorough factual statement. But like I stated: "ramblings", remember. I'm not completely unknown with the workings of our species myself, though. Especially when discourse and policy is dictated by a select group of people (meaning: the one who actually create python, no criticism there) with final abritary powers for one indidual (again, no criticism), mindset *is* just as important as stated fact. Mindset will dictate future discourse and action. And I do sense (reading planet python/this newsgroup) a mindset or at least a tendency by the people who really matter in these discussion to keep on adding features to the syntax; to add "structure" to Python. My personal preference would be to leave the language alone for a while and to improve its infrastructure. Regards, Iwan From lance-news at augustmail.com Tue Jan 25 17:51:16 2005 From: lance-news at augustmail.com (Lance Hoffmeyer) Date: Tue, 25 Jan 2005 16:51:16 -0600 Subject: script to search ebay? Message-ID: Hi all, Anyone know where I can find a python script to search ebay? I have been looking around but haven't found anything. I know there must be one somewhere so I am probably just looking in the wrong places. Optimally, I would like the script to search ebay and then send an email out with the results. Lance From fu.limin.tao at gmail.com Thu Jan 27 10:13:03 2005 From: fu.limin.tao at gmail.com (Limin Fu) Date: Thu, 27 Jan 2005 16:13:03 +0100 Subject: Tao Scripting Language 0.8.5 beta released! In-Reply-To: <35scaqF4sqpqnU1@individual.net> References: <35scaqF4sqpqnU1@individual.net> Message-ID: Dear Claudio, Thank you for your kind testing, suggestions and encourages. I'm glad that you like it. For that problem in the Lexer, it can be corrected without increasing the size. I will do it soon. Best regards, Limin On Thu, 27 Jan 2005 15:32:13 -0000, Claudio Grondi wrote: > Dear Limin, > > Tao Script with its 300 KByte of code is so small, > that one just must love it forgiving all its baby > troubles. > > After changes (see below) to the code in taoModule.cpp > necessary because my compiler claimed repeated definition > of 'ref' e.g. in the section: > if(TaoReference *ref2a=inNameSpace->findDataShared(name) ){ > myData[name]=ref2a; > outNameSpace->nsData[name]=ref2a; > }else{ > TaoShareRefer*ref2b=new TaoShareRefer(); > myData[name]=ref2b; > outNameSpace->nsDataShared[name]=ref2b; > outNameSpace->nsData[name]=ref2b; > } > I was able to compile the code with > Microsoft Visual C++ .NET 2003 on W2K > (create an empty .NET project, add all source > code files, compile and be happy :-) > > Trying the examples provided on the > homesite of Tao Script which run ok as they > are, I found, that print("### \n") failes due to > the way the Lexer works beeing not able to > proper handle string literals. > One just can't probably use any of "#'" "//" "/*" > in strings because the lexer strips the > comments before it analyses the source > to handle content of the string literals. > > Hope this comment helps you to continue > the well done work on it. > I had fun with it because of its size, so > from my point of view please try to > keep the project as small as possible, so > that it remains easy to check out the entire > code. > Maybe it is even a good idea to keep > the problem with the strings as a "feature" > in order to keep the Lexer as simple as > possible? > > Best regards > > Claudio > > "Limin Fu" schrieb im Newsbeitrag > news:mailman.1426.1106825698.22381.python-list at python.org... > > Dear all, > > > > I am glad to announce in this mailing list that the lastest version > > of a new scripting language has come out. > > > > Welcome to try it out. > > > > Comments are welcome. > > > > Suggestions are appreciated. > > > > ======================= > > Here are some details: > > ======================= > > > > Design Goals: > > 1. Simple and efficient. > > 2. Integrate nice features of other languages whenever possible. > > > > Implementation language: C++ with STL. > > > > Designer: Fu Limin > > Email: fu [dot] limin [dot] tao [at] gmail.com > > > > Key features have been supported: > > > > 1. Dynamic-typing variables, supporting complex data structures > > such as array/list, hash/dictionary and matrix etc. > > > > 2. Object-oriented programming ( multi-inheritance not supported > > yet ). > > > > 3. Basic string regular expression matching. > > > > 4. Automatic garbage collection capable of collecting cyclically > > referenced objects. > > > > 5. Numeric data types: complex number and matrix, and their basic > > operations. > > > > 6. Convenient namespacing and dynamic creation of subroutines and > > classes. > > > > 7. Dynamic loading of C/C++ modules ( not complete, but enough for > > playing with it ^_^ ). > > > > 8. An embedded tiny XML parser. > > > > ToBeDone: > > More string operations, multi-inheritance of classes, improvements > > on C/C++ module loading, more on regular expression matching and > > possible optimizations etc. > > > > Documentation: > > > > http://taoscript.sourceforge.net/brief_tao.php > > > > Sample scripts: > > > > http://taoscript.sourceforge.net/sample.php > > > > Download: > > http://taoscript.sourceforge.net/downloads.php > > > > Best regards, > > > > Limin > > > > -- > > Homepage for Tao Language: > > http://taoscript.sourceforge.net > > > > Tao Language project at sourceforge.net: > > http://sourceforge.net/projects/taoscript > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Homepage for Tao Language: http://taoscript.sourceforge.net Tao Language project at sourceforge.net: http://sourceforge.net/projects/taoscript From alanmk at hotmail.com Sun Jan 23 14:11:30 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 23 Jan 2005 19:11:30 +0000 Subject: Textual markup languages (was Re: What YAML engine do you use?) In-Reply-To: <7xmzv0gw80.fsf@ruckus.brouhaha.com> References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <7xmzv0gw80.fsf@ruckus.brouhaha.com> Message-ID: [Alan Kennedy] >>So, I'm hoping that the learned folks here might be able to give me >>some pointers to a markup language that has the following >>characteristics [Paul Rubin] > I'm a bit biased but I've been using Texinfo for a long time and have > been happy with it. It's reasonably lightweight to implement, fairly > intuitive to use, and doesn't get in the way too much when you're > writing. There are several implementations, none in Python at the > moment but that would be simple enough. It does all the content > semantics you're asking (footnotes etc). It doesn't have an explicit > object model, but is straightforward to convert into a number of > formats including high-quality printed docs (TeX); the original Info > hypertext browser that predates the web; and these days HTML. Thanks Paul, I took a look at texinfo, and it looks powerful and good ....... for programmers. Looks like a very steep learning curve for non-programmers though. It seems to require just a few hundred kilobytes too much documentation ...... regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From ncoghlan at iinet.net.au Fri Jan 14 02:46:35 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 14 Jan 2005 17:46:35 +1000 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: <7xacrcdhzh.fsf@ruckus.brouhaha.com> References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: <41E778DB.2050601@iinet.net.au> Paul Rubin wrote: > Come on, that is vacuous. The claim was "expressions are not > statements". But it turns out that expressions ARE statements. The > explanation is "well, that's because they're expression statements". > And there is no obvious case of an expression that can't be used as a > statement. So it's not inherently obvious that there needs to be any > kind of statement that can't be used as an expression. It's just an > artifact. Whether the artifact is a desirable one is a matter of > discussion. No, it's entirely to do with building a readable language that uses significant whitespace to delineate scope. Simple statements are not allowed to contain other statements, but they are allowed to contain expressions. In their most degenerate form, ALL they contain is a *single* expression (e.g. a function call). That expression itself is still not a statement, though. Think of it as the difference between value and [value]. Suites are sequences of statements. Compound statements are statements which incorporate a suite as part of their syntax. Python allows statements inside suites and suites inside compound statements. It also allows expressions inside statements and expressions inside expressions. The one thing it never ever does is allow a suite or a statement inside an expression, because doing so would utterly destroy the handling of significant white space. And that's why expressions are special in Python - they demarcate the boundary of the significance of whitespace. Within an expression, whitespace is insignificant. At the level of statements and suites, whitespace is extremely significant. So, precisely how should one go about cleanly embedding something that cares about whitespace into a context which doesn't care in the slightest? Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From duncan.booth at invalid.invalid Thu Jan 27 06:57:18 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Jan 2005 11:57:18 GMT Subject: how to comment out a block of code References: <1106767695.572974.98920@z14g2000cwz.googlegroups.com> Message-ID: Xah Lee wrote: > > is there a syntax to comment out a block of code? i.e. like html's > or perhaps put a marker so that all lines from there on are ignored? > thanks. > The simplest way is to select the block of code in your editor and use the 'comment-region' command. If this doesn't work, upgrade your editor. Most editors have a command to do this although obviously the name will vary slightly: Idle calls it 'Comment Out Region', SciTe calls it 'Block Comment', emacs calls it 'comment-region'. From aurora00 at gmail.com Fri Jan 21 23:02:38 2005 From: aurora00 at gmail.com (aurora) Date: Fri, 21 Jan 2005 20:02:38 -0800 Subject: list unpack trick? Message-ID: I find that I use some list unpacking construct very often: name, value = s.split('=',1) So that 'a=1' unpack as name='a' and value='1' and 'a=b=c' unpack as name='a' and value='b=c'. The only issue is when s does not contain the character '=', let's say it is 'xyz', the result list has a len of 1 and the unpacking would fail. Is there some really handy trick to pack the result list into len of 2 so that it unpack as name='xyz' and value=''? So more generally, is there an easy way to pad a list into length of n with filler items appended at the end? From reinhold-birkenfeld-nospam at wolke7.net Tue Jan 18 12:38:09 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 18 Jan 2005 18:38:09 +0100 Subject: [perl-python] 20050118 keyed list In-Reply-To: <41ed0f4d.39606090@news.erols.com> References: <1106027360.920787.321590@z14g2000cwz.googlegroups.com> <41ed0f4d.39606090@news.erols.com> Message-ID: <354vs2F3oehr2U1@individual.net> Jay Tilton wrote: >: # the syntax of keyed list in Perl is too complex >: # to be covered in a short message. JFTR: "keyed lists" are called dictionaries in Python. > > [1]Message-ID: <7fe97cc4.0401242131.22acf485 at posting.google.com> > This guy's wish-wash is starting to be funny, after all! Reinhold From cam.ac.uk at mh391.invalid Fri Jan 14 20:37:53 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 15 Jan 2005 01:37:53 +0000 Subject: query python env In-Reply-To: References: Message-ID: Steve Holden wrote: > I suspect rather that the OP is looking for os.environ, as in: He was using the examples of PYTHONHOME and PYTHONPATH which have specific meanings. Using sys.prefix is better than os.environ["PYTHONHOME"], which is unlikely to be set. -- Michael Hoffman From irmen at -nospam-remove-this-xs4all.nl Fri Jan 14 12:55:19 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Fri, 14 Jan 2005 18:55:19 +0100 Subject: Why 'r' mode anyway? (was: Re: Pickled text file causing ValueError (dos/unix issue)) In-Reply-To: References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> Message-ID: <41e80785$0$6203$e4fe514c@news.xs4all.nl> Tim Peters wrote: > Yes: regardless of platform, always open files used for pickles in > binary mode. That is, pass "rb" to open() when reading a pickle file, > and "wb" to open() when writing a pickle file. Then your pickle files > will work unchanged on all platforms. The same is true of files > containing binary data of any kind (and despite that pickle protocol 0 > was called "text mode" for years, it's still binary data). I've been wondering why there even is the choice between binary mode and text mode. Why can't we just do away with the 'text mode' ? What does it do, anyways? At least, if it does something, I'm sure that it isn't something that can be done in Python itself if really required to do so... --Irmen From francis.girard at free.fr Tue Jan 25 01:27:21 2005 From: francis.girard at free.fr (Francis Girard) Date: Tue, 25 Jan 2005 07:27:21 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <1f7befae05012419297085cdf@mail.gmail.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501241409.25598.francis.girard@free.fr> <1f7befae05012419297085cdf@mail.gmail.com> Message-ID: <200501250727.22371.francis.girard@free.fr> Ok I'll submit the patch with the prose pretty soon. Thank you Francis Girard FRANCE Le mardi 25 Janvier 2005 04:29, Tim Peters a ?crit?: > [Francis Girard] > > > For all the algorithms that run after their tail in an FP way, like the > > Hamming problem, or the Fibonacci sequence, (but unlike Sieve of > > Eratosthene -- there's a subtle difference), i.e. all those algorithms > > that typically rely upon recursion to get the beginning of the generated > > elements in order to generate the next one ... > > > > ... so for this family of algorithms, we have, somehow, to abandon > > recursion, and to explicitely maintain one or many lists of what had been > > generated. > > > > One solution for this is suggested in "test_generators.py". But I think > > that this solution is evil as it looks like recursion is used but it is > > not and it depends heavily on how the m235 function (for example) is > > invoked. > > Well, yes -- "Heh. Here's one way to get a shared list, complete with > an excruciating namespace renaming trick" was intended to warn you in > advance that it wasn't pretty . > > > Furthermore, it is _NOT_ memory efficient as pretended : it leaks ! > > Yes. But there are two solutions to the problem in that file, and the > second one is in fact extremely memory-efficient compared to the first > one. "Efficiency" here was intended in a relative sense. > > > It internally maintains a lists of generated results that grows forever > > while it is useless to maintain results that had been "consumed". Just > > for a gross estimate, on my system, percentage of memory usage for this > > program grows rapidly, reaching 21.6 % after 5 minutes. CPU usage varies > > between 31%-36%. Ugly and inefficient. > > Try the first solution in the file for a better understanding of what > "inefficient" means . > > > The solution of Jeff Epler is far more elegant. The "itertools.tee" > > function does just what we want. It internally maintain a list of what > > had been generated and deletes the "consumed" elements as the algo > > unrolls. To follow with my gross estimate, memory usage grows from 1.2% > > to 1.9% after 5 minutes (probably only affected by the growing size of > > Huge Integer). CPU usage varies between 27%-29%. > > Beautiful and effecient. > > Yes, it is better. tee() didn't exist when generators (and > test_generators.py) were written, so of course nothing in the test > file uses them. > > > You might think that we shouldn't be that fussy about memory usage on > > generating 100 digits numbers but we're talking about a whole family of > > useful FP algorithms ; and the best way to implement them should be > > established. > > Possibly -- there really aren't many Pythonistas who care about this. > > > For this family of algorithms, itertools.tee is the way to go. > > > > I think that the semi-tutorial in "test_generators.py" should be updated > > to use "tee". Or, at least, a severe warning comment should be written. > > Please submit a patch. The purpose of that file is to test > generators, so you should add a third way of doing it, not replace the > two ways already there. It should also contain prose explaining why > the third way is better (just as there's prose now explaining why the > second way is better than the first). From bulba at bulba.com Sat Jan 15 11:40:17 2005 From: bulba at bulba.com (Bulba!) Date: Sat, 15 Jan 2005 17:40:17 +0100 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <1105734450.961150.32980@z14g2000cwz.googlegroups.com> <7xfz13zrb2.fsf@ruckus.brouhaha.com> Message-ID: On 14 Jan 2005 12:30:57 -0800, Paul Rubin wrote: >Mmap lets you treat a disk file as an array, so you can randomly >access the bytes in the file without having to do seek operations Cool! >Just say a[234]='x' and you've changed byte 234 of the file to the >letter x. However.. however.. suppose this element located more or less in the middle of an array occupies more space after changing it, say 2 bytes instead of 1. Will flush() need to rewrite the half of mmaped file just to add that one byte? flush() definitely makes updating less of an issue, I'm just curious about the cost of writing small changes scattered all over the place back to the large file. -- I have come to kick ass, chew bubble gum and do the following: from __future__ import py3k And it doesn't work. From mefjr75 at hotmail.com Sun Jan 30 20:16:07 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 30 Jan 2005 17:16:07 -0800 Subject: Problem with loading textfiles into dictionaries. In-Reply-To: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> References: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> Message-ID: <1107134167.206620.286290@z14g2000cwz.googlegroups.com> mercuryp... at gmail.com wrote: > Hello, > I want to do the following: > > def do_load(self, arg): > sitefile = file('sitelist', 'r+', 1) > while True: > siteline = sitefile.readline() > site_rawlist = siteline.split() > sitelist[site_rawlist[0]] = site_rawlist[1:] > if len(siteline) == 0: > break > > I want to load a textfile into a dictionaries and use the first word on > a line as the key for the list, then take the remaining words of the > line and make them values of the key. This doesn't work: > > File "ftp.py", line 57, in do_load > sitelist[site_rawlist[0]] = site_rawlist[1:] > IndexError: list index out of range Hello again Munin, First i'll start with a spanking! Post your code like this:(or pick your favorite starter) Py> def do_load(self, arg): ... sitefile = file('sitelist', 'r+', 1) ... while True: ... siteline = sitefile.readline() ... site_rawlist = siteline.split() ... sitelist[site_rawlist[0]] = site_rawlist[1:] ... if len(siteline) == 0: ... break See how much nicer that is even if the newsfeed gets mangled it comes out ok(mostly). If I guess right it looks like you are trying disect a line that was empty or only had one element. If you check for line length first you might do better. Py> def do_load(self, arg): ... sitefile = file('sitelist', 'r+', 1) ... while True: ... if len(siteline) == 0: ... break ... siteline = sitefile.readline() ... site_rawlist = siteline.split() ... sitelist[site_rawlist[0]] = site_rawlist[1:] Ok next thing is this smells like you really are trying to reinvent a sort of pickle. If you don't know search for 'python pickle module'. examples abound but here it is anyway: Py> import pickle Py> # Pickle a dictionary Py> f = open('/tmp/mydata', 'wb') Py> f.write(pickle.dumps(yourdict) Py> f.close() Py> # and it is easy to get back as well Py> f = open('tmp/mydata', rb') Py> pdata = f.read() Py> f.close() Py> yourdict = pickle.load(pdata) hth, M.E.Farmer From wuwei23 at gmail.com Sun Jan 23 20:57:04 2005 From: wuwei23 at gmail.com (alex23) Date: 23 Jan 2005 17:57:04 -0800 Subject: how to write a tutorial In-Reply-To: <1106472508.591411.40140@c13g2000cwb.googlegroups.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: <1106531824.833549.28720@c13g2000cwb.googlegroups.com> > the first paragraph of 9.1 "A Word About Terminology" is > epitome of masturbation. I'm tempted to concede this point to you given the sheer overwhelming testament to onanism that is your website but this is just nonsense. Defining terms is *always* necessary, it ensures that participants in whatever dialogue are at least partially using the terms with the same intent > For 99% of readers, it is incomprehensible and irrelevant. You're not 99% of the readers, so I find that remark difficult to swallow. Having read your comments on women, the whole idea that you have a superior insight into would-be python coders is just obscenely ludicrous. - alex23 From just at xs4all.nl Mon Jan 3 04:08:46 2005 From: just at xs4all.nl (Just) Date: Mon, 03 Jan 2005 10:08:46 +0100 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: In article , JanC wrote: > Something like this: > > py> import cStringIO > py> import sys > py> > py> def foo(): > ... print "test" > ... > py> f = cStringIO.StringIO() > py> sys.stdout = f > py> foo() > py> s = f.getvalue() > py> sys.stdout = sys.__stdout__ You should always save stdout instead of using __stdout__. It may not be the same! I don't think anyone should *ever* use __stdout__ except when debugging. See also: http://mail.python.org/pipermail/python-dev/2000-October/010144.html > py> f.close() > py> print s.capitalize() > Test Just From fredrik at pythonware.com Tue Jan 25 02:51:21 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 Jan 2005 08:51:21 +0100 Subject: What's so funny? WAS Re: rotor replacement References: <200501241906.39865.hancock@anansispaceworks.com> Message-ID: Terry Hancock wrote: > And, well, I'm sorry Mr. Lundh, but your PIL module actually is something > of a pain to install still. The OP is right about that. Usually worth it, but I don't > like the fact that that pain is being passed on to the end-user of my software. > > The fact that you got all snide and refused to work with me when I asked > for a copy of the autoconf sources to try to fix the problem didn't make me > too happy, either. ah, you're the guy who flamed me and called me names because PIL didn't fit some hypothetical GNU-inspired definition of "open source software." it's always sad when people have to attack those who don't share their religion, but it's not that much I can do about that. > So, naturally, I just dropped it. which means that you have no idea how easy or hard it is to install PIL today (hint: things have changed) From ncoghlan at iinet.net.au Tue Jan 11 08:04:50 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 11 Jan 2005 23:04:50 +1000 Subject: else condition in list comprehension In-Reply-To: <1105305000.052714.188980@c13g2000cwb.googlegroups.com> References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> <1105305000.052714.188980@c13g2000cwb.googlegroups.com> Message-ID: <41E3CEF2.4070807@iinet.net.au> Dan Bishop wrote: > Luis M. Gonzalez wrote: > >>Hi there, >> >>I'd like to know if there is a way to add and else condition into a >>list comprehension. I'm sure that I read somewhere an easy way to do >>it, but I forgot it and now I can't find it... >> >>for example: >>z=[i+2 for i in range(10) if i%2==0] >>what if I want i [sic] to be "i-2" if i%2 is not equal to 0? > > > z = [i + (2, -2)[i % 2] for i in range(10)] For the specific case of +/- a number, (-1) ** x works, too: z = [i + 2 * ((-1) ** i) for i in range(10)] Not that I'm claiming it's particularly readable or anything. . . just that it works :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From danperl at rogers.com Sun Jan 30 19:24:06 2005 From: danperl at rogers.com (Dan Perl) Date: Sun, 30 Jan 2005 19:24:06 -0500 Subject: Regarding exception handling References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> Message-ID: "Aggelos I. Orfanakos" wrote in message news:1107127179.863445.55310 at c13g2000cwb.googlegroups.com... > Thanks. This should now be OK: > > #try: > # try: > # s = ... # socket opens > # > # # various code ... > # except socket.error, x: > # # exception handling > #finally: > # s.close() # socket closes > Why the nested try's? If I understand your intention correctly this should do the same thing: try: s = ... # socket opens # various code ... except socket.error, x: # exception handling s.close() # socket closes You would need the try-finally statement only if you expect it to handle other exceptions than socket.error or if the socket.error is re-raised in the "except" clause. Otherwise, the try-finally statement is redundant because no socket.error are getting out of the try-except statement. Dan From guettli at thomas-guettler.de Wed Jan 26 11:15:48 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 26 Jan 2005 17:15:48 +0100 Subject: Help With Python References: Message-ID: Am Wed, 26 Jan 2005 15:55:28 +0000 schrieb Judi Keplar: > > I am currently taking a course to learn Python and was looking for > some help. I need to write a Python statement to print a comma- > separated repetition of the word, "Spam", written 511 times ("Spam, > Spam, Spam"). > > Can anybody help me get started? I am completely new to programming! Hi, # This way, there is a comma after the last: import sys for i in range(511): sys.stdout.write("Spam, ") # No comma at the end: mylist=[] for i in range(511): mylist.append("Spam") print ", ".join(mylist) Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From tomi.hasa at gmail.com Mon Jan 10 08:46:32 2005 From: tomi.hasa at gmail.com (=?iso-8859-1?B?VG9taSBI5HPk?=) Date: 10 Jan 2005 05:46:32 -0800 Subject: OT: google groups bug, or worse? In-Reply-To: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> References: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> Message-ID: <1105364792.404039.65190@c13g2000cwb.googlegroups.com> aaronwmail-usenet at yahoo.com wrote: > I'm concerned that google groups is not correctly reflecting > the python lists. > [...] > Is it a google bug? Yes, Google Groups Beta is missing messages: http://groups-beta.google.com/group/google-labs-groups2/browse_thread/thread/c4108ad41c189d34?tvc=2 http://tinyurl.com/6vybw http://groups-beta.google.com/group/google-labs-groups2/msg/dc745c7784c81890 http://tinyurl.com/4keqh http://groups-beta.google.com/group/google-labs-groups2/msg/b54c12517c75eb24 From tjreedy at udel.edu Thu Jan 20 13:40:12 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 20 Jan 2005 13:40:12 -0500 Subject: RuntimeError: dictionary changed size during iteration References: Message-ID: RE: RuntimeError: dictionary changed size during iteration "Batista, Facundo" wrote [Robert Brewer] #- But not unexpected, since vars() returns a dictionary, and #- binding 'e' #- changes that dictionary while you are iterating over it. >For me, the point is: vars() returns the local variables > as a list or is a generator? As the OP said, it returns a *dictionary*. In particular: >>> help(vars) Help on built-in function vars: vars(...) vars([object]) -> dictionary Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__. >In the docs don't say nothing about this. You must be having a bad day ;-). From Lib Ref 2.1 Built-in Functions: vars( [object]) Without arguments, return a dictionary corresponding to the current local symbol table. With a module, class or class instance object as argument (or anything else that has a __dict__ attribute), returns a dictionary corresponding to the object's symbol table. The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined Terry J. Reedy From drewc at rift.com Fri Jan 21 08:23:08 2005 From: drewc at rift.com (drewc) Date: Fri, 21 Jan 2005 13:23:08 GMT Subject: how to write a tutorial In-Reply-To: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: <0n7Id.135415$Xk.80179@pd7tw3no> You should not be giving such advice! (and the crosspost ... WTF?). I've been trying to follow along with your perl/python yahoo group, but your posts are terrible. Perhaps you should provide the output of the code you post. Then i'd actually know what i'm trying to achieve. As it is i have to cut/paste your code into an interpreter just to figure out what it does. What does this have to do with Lisp? (i'm in c.l.l). drewc Xah Lee wrote: > i've started to read python tutorial recently. > http://python.org/doc/2.3.4/tut/tut.html > > Here are some quick critique: > > quick example: > If the input string is too long, they don't truncate it, but return it > unchanged; this will mess up your column lay-out but that's usually > better than the alternative, which would be lying about a value. (If > you really want truncation you can always add a slice operation, as in > "x.ljust( n)[:n]". > > better: > If the input string is too long, they don't truncate it, but return it > unchanged; > ----------------- > delete: Reverse quotes (``) are equivalent to repr(), but their use is > discouraged. > ----------------- > similarly, many places mentioning uncritical info such as warning or > reference to other languages should be deleted. > > the tutorial should be simple, concise, to the point, stand along. > Perhaps 1/5th length of the tutorial should be deleted for better. > Follow the above principles. > > at places often a whole paragraph on some so called computer science > jargons should be deleted. They are there more to showcase inane > technicality than do help the reader. (related, many passages with > jargons should be rewritten sans inane jargon. e.g. mutable object.) > > one easy way to understand these principles is to compare perl's > documentation or unix man pages to Python's. The formers are often > irrelevant, rambling on, not stand-along (it is written such that it > unnecessarily requires the reader to be knowledgable of lots of other > things). Python docs are much better, but like many computer language > manuals, also suffers from verbiage of tech jargons. (these jargons or > passages about them are usually there to please the authors > themselves). > > A exemplary writing in this direction is the Mathematica manual by > Stephen Wolfram. Any intelligent layman sans computer science degree > can read it straightforwardly, and learn unhindered a language that is > tantamount to features of lisp languages. Such documentation is not > difficult to write at all. (contrary to the lot of "computer > scientists" or IT pundits morons.) All it take is some simple > principles outlined above. > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html > From frans.englich at telia.com Mon Jan 17 13:45:46 2005 From: frans.englich at telia.com (Frans Englich) Date: Mon, 17 Jan 2005 18:45:46 +0000 Subject: Assigning to self Message-ID: <200501171845.46766.frans.englich@telia.com> Hello, I am having trouble with throwing class instances around. Perhaps I'm approaching my goals with the wrong solution, but here's nevertheless a stripped down example which demonstrates my scenario: #------------------------------------------------------------------------------------------ class foo: tests = {} def __init__( self, id ): try: me = self.__class__.tests[ id ] except KeyError: print "Did not exist, initializing myself.." self.attr = "exists" self.__class__.tests[ id ] = self else: print "Already exists! Re-using existing instance" self = me print "Me", self.attr + "!" # line 18 def yo(self): return self.attr # line 21 def main(): a = foo( "test" ) print "ATTR:", a.yo() b = foo( "test" ) print "ATTR:", b.yo() if __name__ == "__main__": main() #------------------------------------------------------------------------------------------ This is the output: Did not exist, initializing myself.. Me exists! ATTR: exists Already exists! Re-using existing instance Me exists! ATTR: Traceback (most recent call last): File "cpClass.py", line 32, in ? main() File "cpClass.py", line 29, in main print "ATTR:", b.yo() File "cpClass.py", line 21, in yo return self.attr # line 21 AttributeError: foo instance has no attribute 'attr' #------------------------------------------------------------------------------------------ What the code attempts to do is implementing a, to the API user, transparent memory-saver by ensuring that no more than one instance of the class foo exists for a particular id. E.g, the user can simply "create" an instance and if one not already exists, it is created. First of all; am I approaching the goal with the right solution? The way I do fails, obviously. The line 'self = me'(scary..) doesn't really work for the attribute attr; the attribute exists on line 21, but it fails when yo() tries to access it. What have failed? Is it a namespace scope issue? Do 'self = me' do what I think it should? Cheers, Frans From allen at cis.ohio-state.edu Tue Jan 4 17:37:20 2005 From: allen at cis.ohio-state.edu (Nick Allen) Date: Tue, 04 Jan 2005 17:37:20 -0500 Subject: Restore a unified diff Message-ID: After using ndiff from difflib, the function restore would return the sequence that generated the delta. Unfortunately, restore does not do the same for unified_diff. I do not see any similar function that is intended for unified_diff. Does anyone know how to "restore" from a unified diff generated delta? Thanks for all your help in advance. Best Regards, Nick Nick Allen From francis.girard at free.fr Wed Jan 26 18:19:39 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 27 Jan 2005 00:19:39 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <6PKdnVpD-4f3CGvcRVn-gQ@comcast.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> <6PKdnVpD-4f3CGvcRVn-gQ@comcast.com> Message-ID: <200501270019.39611.francis.girard@free.fr> Le mardi 25 Janvier 2005 19:52, Steven Bethard a ?crit?: Thank you Nick and Steven for the idea of a more generic imerge. To work with the Hamming problem, the imerge function _must_not_ allow duplicates and we can assume all of the specified iteratables are of the same size, i.e. infinite ! Therefore, Nick's solution fulfills the need. But it is admittedly confusing to call the function "imerge" when it doesn't merge everything (including duplicates). Anyway both solution sheds new light and brings us a bit farther. That's the beauty of many brains from all over the world collabarating. Really, it makes me emotive thinking about it. For the imerge function, what we really need to make the formulation clear is a way to look at the next element of an iteratable without consuming it. Or else, a way to put back "consumed" elements in the front an iteration flow, much like the list constructors in FP languages like Haskell. It is simple to encapsulate an iterator inside another iterator class that would do just that. Here's one. The additional "fst" method returns the next element to consume without consuming it and the "isBottom" checks if there is something left to consume from the iteration flow, without actually consuming anything. I named the class "IteratorDeiterator" for lack of imagination : -- BEGIN SNAP class IteratorDeiterator: def __init__(self, iterator): self._iterator = iterator.__iter__() self._firstVal = None ## Avoid consuming if not requested from outside ## Works only if iterator itself can't return None def __iter__(self): return self def next(self): valReturn = self._firstVal if valReturn is None: valReturn = self._iterator.next() self._firstVal = None return valReturn def fst(self): if self._firstVal is None: self._firstVal = self._iterator.next() return self._firstVal def isBottom(self): if self._firstVal is None: try: self._firstVal = self._iterator.next() except StopIteration: return True return False -- END SNAP Now the imerge_infinite which merges infinite lists, while allowing duplicates, is quite straightforward : -- BEGIN SNAP def imerge_infinite(*iterators): vItTopable = [IteratorDeiterator(it) for it in iterators] while vItTopable: yield reduce(lambda itSmallest, it: itSmallest.fst() > it.fst() and it or itSmallest, vItTopable).next() -- END SNAP To merge finite lists of possibly different lengths is a bit more work as you have to eliminate iterators that reached the bottom before the others. This is quite easily done by simply filtering them out. The imerge_finite function below merges "lists" of possibly different sizes. -- BEGIN SNAP def imerge_finite(*iterators): vItDeit = [IteratorDeiterator(it) for it in iterators] vItDeit = filter(lambda it: not it.isBottom(), vItDeit) while vItDeit: yield reduce(lambda itSmallest, it: itSmallest.fst() > it.fst() and it or itSmallest, vItDeit).next() vItDeit = filter(lambda it: not it.isBottom(), vItDeit) -- END SNAP Now, we want versions of these two merge functions that do not allow duplicates. Building upon what we've already done in a semi FP way, we just filter out the duplicates from the iteration streams returned by the above functions. The job is the same for the infinite and finite versions, hence the imerge_nodup generic function. -- BEGIN SNAP def imerge_nodup(fImerge, *iterators): it = fImerge(*iterators) el = it.next() yield el while True: el = dropwhile(lambda _next: _next == el, it).next() yield el imerge_inf_nodup = \ lambda *iterators: imerge_nodup(imerge_infinite, *iterators) imerge_finite_nodup = \ lambda *iterators: imerge_nodup(imerge_finite, *iterators) -- END SNAP I used the lambda notation for imerge_inf_nodup and imerge_finite_nodup to avoid another useless for-yield loop. Here the notation really just express function equivalence with a bounded argument (it would be great to have a notation for this in Python, i.e. binding a function argument to yield a new function). The merge function to use with hamming() is imerge_inf_nodup. Regards, Francis Girard FRANCE > Nick Craig-Wood wrote: > > Steven Bethard wrote: > >> Nick Craig-Wood wrote: > >>>Thinking about this some more leads me to believe a general purpose > >>>imerge taking any number of arguments will look neater, eg > >>> > >>>def imerge(*generators): > >>> values = [ g.next() for g in generators ] > >>> while True: > >>> x = min(values) > >>> yield x > >>> for i in range(len(values)): > >>> if values[i] == x: > >>> values[i] = generators[i].next() > >> > >> This kinda looks like it dies after the first generator is exhausted, > >> but I'm not certain. > > > > Yes it will stop iterating then (rather like zip() on lists of unequal > > size). Not sure what the specification should be! It works for the > > hamming problem though. > > Actually, it stops iterating on lists of equal size too: > > py> def imerge(*iterators): > ... iterators = [iter(i) for i in iterators] > ... values = [i.next() for i in iterators] > ... while True: > ... x = min(values) > ... yield x > ... for i, val in enumerate(values): > ... if val == x: > ... values[i] = iterators[i].next() > ... > py> list(imerge([1, 4, 7], [2, 5, 8], [3, 6, 9])) > [1, 2, 3, 4, 5, 6, 7] > > Note that 8 and 9 are not in the list. > > Steve From gsakkis at rutgers.edu Mon Jan 24 15:50:52 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Mon, 24 Jan 2005 15:50:52 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> Message-ID: <35l5d9F4licj2U1@individual.net> "Fredrik Lundh" wrote in message news:mailman.1214.1106591959.22381.python-list at python.org... > Steven Bethard wrote: > > >>>>>a = 1, 2, 3 > >>>>>b = a[:] > >>>>>a is b > >> True > > > > My impression was that full tuple copies didn't actually copy, but that slicing a subset of a > > tuple might. Not exactly sure how to test this, but: > > > > py> a = 1, 2, 3 > > py> a[:2] is a[:2] > > False > > yup. and to figure out why things are done this way, consider this case: > > >>> a = give_me_a_huge_tuple() > >>> len(a) > (a rather large number) > >>> b = a[:2] > >>> del a > > (IIRC, I proposed to add "substrings" when I implemented the Unicode string > type, but that idea was rejected, for the very same "and how do you get rid of > the original object" reason) > > Fair enough. So perhaps the question is whether such cases are more regular than something like: a = give_me_a_huge_tuple() slices = [a[i:j] for i in xrange(len(a)) for j in xrange(i+1, len(a)+1)] George From tmohr at s.netic.de Wed Jan 12 16:40:13 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Wed, 12 Jan 2005 22:40:13 +0100 Subject: reference or pointer to some object? References: Message-ID: Hi, thank you all for your explanations. I still wonder why a concept like "references" was not implemented in Python. I think it is (even if small) an overhead to wrap an object in a list or a dictionary. Isn't it possible to extend Python in a way to use real references? Or isn't that regarded as necessary? Thanks for any hints, Torsten. From ionel.mc at gmail.com Thu Jan 20 22:14:31 2005 From: ionel.mc at gmail.com (ionel) Date: Fri, 21 Jan 2005 05:14:31 +0200 Subject: What's the best python web-developer's editor In-Reply-To: <41EFFCD9.7060302@wild-flower.co.uk> References: <41EFFCD9.7060302@wild-flower.co.uk> Message-ID: how about editplus ? imho it's excelent On Thu, 20 Jan 2005 18:47:53 +0000, andy wrote: > Anybody like to comment on which editor they use for python web app > development - for both discrete and mixed python and html code, and why? > > I'm comfortable with IDLE (used it for years) but of course it lacks ftp > or webDAV abilities, obviously because it's not intended for that type > of use. > > I've had a look at Screem - and that seems to do python syntax > highlighting, but it dosn't seem to be python syntax aware (unless > there's a hidden option somewhere). Although I can live without auto > indent, I'd rather not... > > I'm sure emacs, xemacs, vi, elvis and so on can do the same, but I have > no experience with them for heavy python or html coding, nor the time > to trip off down a blind-alley to find out! I know Enough Vi To Get > By(tm) but it's by no means my favourite editor. Emacs is a complete > mystery to me. > > I guess I *could* use IDLE and Screem together, but that's a clunky > solution! > > all opinions greatfully received, > -andyj > -- > http://mail.python.org/mailman/listinfo/python-list > -- ionel. From ark at acm.org Sat Jan 22 12:33:49 2005 From: ark at acm.org (Andrew Koenig) Date: Sat, 22 Jan 2005 17:33:49 GMT Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <7xu0p9lk4h.fsf@ruckus.brouhaha.com> <7x8y6l8k6l.fsf@ruckus.brouhaha.com> Message-ID: <18wId.68007$w62.25250@bgtnsc05-news.ops.worldnet.att.net> "Paul Rubin" wrote in message news:7x8y6l8k6l.fsf at ruckus.brouhaha.com... > It's not obvious to me how the compiler can tell. Consider: > > x = 3 > if frob(): > frobbed = True > squares = [x*x for x in range(9)] > if blob(): > z = x > > Should the compiler issue a warning saying the program should be taken > out and shot? With lexical comprehensions, the program is perfectly > valid and sets z to 3 if blob() is true. The whole point of lexical > comprhensions is to make Python safe for such programs. > > Without lexical comprehensions, the program still doesn't depend on > the listcomp leakage if frob() and blob() aren't simultaneously true > (envision "assert not frobbed" before the "z = x"). So "should be > taken out and shot" is maybe a little bit extreme. Actually, I don't think so. If you intend for it to be impossible for "z = x" to refer to the x in the list comprehension, you shouldn't mind putting in "from __future__ import lexical_comprehensions." If you don't intend for it to be impossible, then the program *should* be taken out and shot. From spam-trap-095 at at-andros.demon.co.uk Sun Jan 23 19:45:34 2005 From: spam-trap-095 at at-andros.demon.co.uk (Andrew McLean) Date: Mon, 24 Jan 2005 00:45:34 +0000 Subject: Fuzzy matching of postal addresses [1/1] References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> <1106517571.768306.23430@f14g2000cwb.googlegroups.com> Message-ID: <5jDnWqluUE9BFwTg@at-andros.demon.co.uk> In article <1106517571.768306.23430 at f14g2000cwb.googlegroups.com>, John Machin writes >Andrew McLean wrote: >> In case anyone is interested, here is the latest. > >> def insCost(tokenList, indx, pos): >> """The cost of inserting a specific token at a specific >normalised position along the sequence.""" >> if containsNumber(tokenList[indx]): >> return INSERT_TOKEN_WITH_NUMBER + POSITION_WEIGHT * (1 - pos) >> elif indx > 0 and containsNumber(tokenList[indx-1]): >> return INSERT_TOKEN_AFTER_NUMBER + POSITION_WEIGHT * (1 - >pos) >> elif tokenList[indx][0] in minorTokenList: >> return INSERT_MINOR_TOKEN >> else: >> return INSERT_TOKEN + POSITION_WEIGHT * (1 - pos) >> >> def delCost(tokenList, indx, pos): >> """The cost of deleting a specific token at a specific normalised >position along the sequence. >> This is exactly the same cost as inserting a token.""" >> return insCost(tokenList, indx, pos) > >Functions are first-class citizens of Pythonia -- so just do this: > >delCost = insCost > Actually, the code used to look like that. I think I changed it so that it would look clearer. But perhaps that was a bad idea. >Re speed generally: (1) How many addresses in each list and how long is >it taking? On what sort of configuration? (2) Have you considered using >pysco -- if not running on x86 architecture, consider exporting your >files to a grunty PC and doing the match there. (3) Have you considered >some relatively fast filter to pre-qualify pairs of addresses before >you pass the pair to your relatively slow routine? There are approx. 50,000 addresses in each list. At the moment the processing assumes all the postcodes are correct, and only compares addresses with matching postcodes. This makes it a lot faster. But may miss some cases of mismatched postcodes. Also it does two passes. One looking for exact matches of token sequences. This deals with about half the cases. Only then do I employ the, more expensive, edit distance technique. Overall, the program runs in less than half an hour. Specifically it takes about 60s per thousand addresses, which requires an average of about 8 calls to editDistance per address. Psyco.full() reduced the 60s to 45s. I'll only try optimisation if I need to use it much more. >Soundex?? To put it bluntly, the _only_ problem to which soundex is the >preferred solution is genealogy searching in the US census records, and >even then one needs to know what varieties of the algorithm were in use >at what times. I thought you said your addresses came from >authoritative sources. You have phonetic errors? Can you give some >examples of pairs of tokens that illustrate the problem you are trying >to overcome with soundex? I'm sure that in retrospect Soundex might not be a good choice. The misspellings tend to be minor, e.g. Kitwhistle and KITTWHISTLE Tythe and TITHE I was tempted by an edit distance technique on the tokens, but would prefer a hash based method for efficiency reasons. >Back to speed again: When you look carefully at the dynamic programming >algorithm for edit distance, you will note that it is _not_ necessary >to instantiate the whole NxM matrix -- it only ever refers to the >current row and the previous row. What does space saving have to do >with speed, you ask? Well, Python is not FORTRAN; it takes considerable >effort to evaluate d[i][j]. A relatively simple trick is to keep 2 rows >and swap (the pointers to) them each time around the outer loop. At the >expense of a little more complexity, one can reduce this to one row and >3 variables (north, northwest, and west) corresponding to d[i-1][j], >d[i-1][j-1], and d[i][j-1] -- but I'd suggest the simple way first. >Hope some of this helps, Thanks for that. The first edit distance algorithm I looked at did it that way. But I based my code on a version of the algorithm I could actually follow ;-). Getting the concatenation bit right was non-trivial and it was useful to store all of "d" for debugging purposes. As to Python not being Fortran. You've found me out. The three languages I am most comfortable with are Fortran, Matlab and Python. It did occur to me that numarray might be a more efficient way of dealing with a 4-dimensional array, but the arrays aren't very big, so the overhead in setting them up might be significant. The simplest optimisation would be to replace the two indices used to deal with concatenation by four explicit variables. And then, as you said, I could just store the three last rows, and avoid any multiple indexing. As with all these potential optimisations, you don't know until you try them. -- Andrew McLean From whereU at now.com Tue Jan 11 00:54:33 2005 From: whereU at now.com (Eric Pederson) Date: Mon, 10 Jan 2005 21:54:33 -0800 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: <7x6524d6pv.fsf@ruckus.brouhaha.com> References: <7x6524d6pv.fsf@ruckus.brouhaha.com> Message-ID: <20050110215433.792683707.whereU@now.com> Paul Rubin wrote: > What I'm getting at is I might like to install MoinMoin now and > migrate to Mediawiki sometime later. Anyone have any thoughts about > whether that's a crazy plan? Disclaimer, I am neither using Moinmoin nor Mediawiki, and don't really have your answer. >From what I read, Mediawiki stores each page as "wikitext" in a MySQL database; wikitext "is a mixture of content, markup, and metadata." It seems essentially what you'd need for migration is a mapping function and I do not know how complex the mapping between the systems would be. I could imagine migrating from Moinmoin to Mediawiki via a script looping through the Moinmoin files in a directory, modifying a copy of each, and storing them in MySQL. I suspect it's less painful to just start with the wiki you want to end up with, but if you're going to migrate between the two, won't Python come in handy! ;-) 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 xah at xahlee.org Mon Jan 31 14:02:17 2005 From: xah at xahlee.org (Xah Lee) Date: 31 Jan 2005 11:02:17 -0800 Subject: Q: quoting string without escapes Message-ID: <1107198137.141990.246880@c13g2000cwb.googlegroups.com> in Python, is there a way to quote a string as to avoid escaping ' or " inside the string? i.e. like Perl's q or qq. thanks. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From g.brandl-2005-01 at gmx.net Sun Jan 23 15:11:32 2005 From: g.brandl-2005-01 at gmx.net (Georg Brandl) Date: Sun, 23 Jan 2005 21:11:32 +0100 Subject: Help on project, anyone? Message-ID: <35ienhF4lu88lU1@individual.net> Hello, to train my Python skills I am looking for some project I can contribute to. I learned Python about one year ago, and had already some programming background behind (I contributed to SharpDevelop for instance), so I'm not the complete newbie. About myself: I'm a 20 year old German with strong interests in programming and, of course, especially in Python (I love it...). Does anyone run, or participate in, a project looking for fellow programmers? I don't have a special area of interest, well, perhaps web programming... Thanks, Georg From ed at leafe.com Thu Jan 13 08:05:54 2005 From: ed at leafe.com (Ed Leafe) Date: Thu, 13 Jan 2005 08:05:54 -0500 Subject: wxPython and CheckListBox In-Reply-To: <1105613647.610479.13280@z14g2000cwz.googlegroups.com> References: <1105613647.610479.13280@z14g2000cwz.googlegroups.com> Message-ID: On Jan 13, 2005, at 5:54 AM, ncookson at networkusa.net wrote: > I am trying to add a caption or title to the box drawn around a > checklistbox and having no luck. Is there a way to do this? > I am using python 2.3.4 and wxPython 2.5 on a windows platform. I don't think you can do it directly. What you might want to try is to create a StaticBoxSizer with the label you want, and add the checkbox to that sizer. Then add the StaticBoxSizer to the panel's layout instead of the checkbox. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From http Wed Jan 19 04:42:00 2005 From: http (Paul Rubin) Date: 19 Jan 2005 01:42:00 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> Message-ID: <7x1xchlpqv.fsf@ruckus.brouhaha.com> Robin Becker writes: > What exactly are/were the political reasons for rotor removal? Some countries have laws about cryptography software (against some combination of export, import, or use). The Python maintainers didn't want to deal with imagined legal hassles that might develop from including good crypto functions in the distribution. Then it became obvious that the same imagined hassles could also befall the rotor module, so that was removed. > I might add that the source for rotormodule is still easily obtainable > and can be compiled trivially as an extension for Python-2.4. Does the > Python community take a position on the sources of removed modules? Those are still free to distribute, but I'd advise against doing so with the rotor module unless you absolutely need it for some interoperability purpose. Otherwise, it's insecure and should not be used. The routine I posted was intended as a straightforward replacement for the rotor module that doesn't depend on C compilers and is reasonably secure. If you don't mind using C extensions, there's various AES modules available, plus fancier packages like mxCrypto. From philippe at philippecmartin.com Mon Jan 24 17:30:38 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 24 Jan 2005 22:30:38 GMT Subject: Why I use private variables (WAS: RE:"private" variables a.k.a. name mangling?) References: Message-ID: I used double underscore because I thought it was the correct way to name private variables/methods - I will have to change those to single underscore since that it the current methodology. A private variable to me: 1) is internal to the processing of a class and needs not be accessed by external or derivated objects. (I won't get into the potential need of "protected" variables/methods - Python creators have not made those distinctions for reasons that they believe are good and I'm not the one to discuss them) 2) Must not be documented to library users as they're using it would go againts 'law' 1). 3) I wish I had one, but there is only one Isaac Asimov after all :-) Regards, Philippe On Mon, 24 Jan 2005 11:45:34 -0500, Jeremy Bowers wrote: > On Mon, 24 Jan 2005 15:35:11 -0600, Philippe C. Martin wrote: > >> The real reason behind my using private variables is so they do not appear >> in the epydoc generated documentation and confuse my users. > > You mean single or double underscores? I just checked and at least epydoc > 2.1 doesn't include single-underscore values, but those aren't "private" > in sense we're talking in this thread (some form of compiler enforcement). From invalidemail at aerojockey.com Fri Jan 14 06:22:23 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 14 Jan 2005 03:22:23 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: <1105701743.706951.257970@c13g2000cwb.googlegroups.com> Skip Montanaro wrote: > Fredrik> no, expressions CAN BE USED as statements. that doesn't mean > Fredrik> that they ARE statements, unless you're applying belgian logic. > > Hmmm... I'd never heard the term "belgian logic" before. Googling provided > a few uses, but no formal definition (maybe it's a European phrase so > searching for it in English is futile). The closest thing I found was > > Or is it another case of Belgian logic, where you believe it because > theres no evidence or motive whatsoever? Maybe it's Belgain logic, as opposed to Dutch logic. -- CARL BANKS From maxm at mxm.dk Mon Jan 17 10:01:23 2005 From: maxm at mxm.dk (Max M) Date: Mon, 17 Jan 2005 16:01:23 +0100 Subject: [ANN] iCalendar package 0.9 Message-ID: <41ebd292$0$253$edfadb0f@dread12.news.tele.dk> I have written a package that can parse and generate files according to RFC 2445 (iCalender). That should be any file ending with .ics :-) It is not quite polished yet, but fully functional, and choke full of doctest. It does support the full spec and all datatypes and parameter values. The Api is pretty stable, and will probably not change much. I would like anybody interrested to give it a test drive before I finish it off and make it a 1.0. http://www.mxm.dk/products/public/ical/ Any feedback would be welcome. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From reinhold-birkenfeld-nospam at wolke7.net Fri Jan 14 17:06:43 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 14 Jan 2005 23:06:43 +0100 Subject: Why would I get a TypeEror? In-Reply-To: References: <34ql1vF4dqd9pU1@individual.net> Message-ID: <34qu3jF4br3iqU2@individual.net> Steven Bethard wrote: > It's me wrote: >> Say again??? > > Please stop top-posting -- it makes it hard to reply in context. > >> "Reinhold Birkenfeld" wrote... >>>It's me wrote: >>>>If this is true, I would run into trouble real quick if I do a: >>>> >>>>(1/x,1.0e99)[x==0] >>> >>>Lazy evaluation: use the (x==0 and 1e99 or 1/x) form! > > If you want short-circuting behavior, where only one of the two branches > gets executed, you should use Python's short-circuiting boolean > operators. For example, > > (x == 0 and 1.0e99 or 1/x) > > says something like: > > Check if x == 0. > If so, check if 1.0e99 is non-zero. It is, so return it. > If x != 0, see if 1/x is non-zero. It is, so return it. > > Note that if you're not comfortable with short-circuiting behavior, you > can also code this using lazy evaluation: > > (lambda: 1/x, lambda: 1.0e99)[x==0]() Or even (x==0 and lambda: 1e99 or lambda: 1/x)() Or ... Reinhold From tjreedy at udel.edu Fri Jan 28 18:00:44 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Jan 2005 18:00:44 -0500 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com><1106911061.429966.303510@f14g2000cwb.googlegroups.com> Message-ID: OP: >>I find this response a bit dissappointing frankly. Open Source people >>make such a big deal about having lots of people being able to look at >>source code and from that discover security problems, thus making it >>somehow making it better than proprietary source code. OP: Did you discover this supposed security hole from black-box observation of behavior or by being one of the 'lots of people being able to look at source code', thereby giving evidence to the point? Everyone: I say 'supposed' because a) The OP has provided no info about his/her claim. b) The OP's original post is a classical troll: blast volunteer developers for not having anticipated and planned for a novel situation; argue against things not said, at least now here, not recently; imply that volunteers own him something. Most people with the expertise to detect a security hole would know better. c) The noise generated because of b) has alerted any malware writers monitering c.l.p for hints about exploitable security holes that there might be one in one of the few modules where such could reasonably be. OP: If my doubts are wrong and you really do have something to quietly report to the 'authority', then do so, and quit making a noise about it. Terry J. Reedy From hcslmf at texlife.com Mon Jan 31 16:35:04 2005 From: hcslmf at texlife.com (brolewis) Date: 31 Jan 2005 13:35:04 -0800 Subject: Spawning, and Killing, a Process Message-ID: <1107207304.586338.270080@c13g2000cwb.googlegroups.com> I am writing a program on Windows (XP Pro) that as part of the application takes advantage of rsync's ability to synchronize a client and server computer. However, because of the nature of our company's policies and our proxy, I must connect using SSH and use it as a tunnel to get to the location I need on the inside. My delimma is that I need to be able to spawn a process that uses the SSH, runs rsync, and then I need to be able to kill the SSH process and do not know a way to do that in Windows. I also would prefer to have SSH run invisible to the end user (no new window) which I get when using spawnl The commands I am running are as follows: SSH Tunnel: ssh ssh_user at proxy.example.com -i file_name -L 873:200.200.60.60:7000 -N Rsync Command: rsync -azv rsync_user at 127.0.0.1::package . I am aware that you should be able to run ssh inside of rsync but there seems to be a problem with the port of rsync that prevents me from accomplishing this. I thank you in advance for any assistance you are able to give. From gmanbauer at gmail.com Fri Jan 7 15:47:17 2005 From: gmanbauer at gmail.com (Gavin Bauer) Date: Fri, 7 Jan 2005 20:47:17 +0000 Subject: DOS problem (simple fix??) Message-ID: My DOS window (running in windows ME) closes the second it finishes running my programs. As you can imagine, this makes it hard to see the results. I've gotten in the habit of putting raw_input("Press enter to exit") at the end of every program, and in addition to being pain in the butt, it often fails to work. Being new to programming in general, I make more mistakes than most people. My programs often have errors before they get to my raw_input command. They then display the error and immediately close. It is naturally a lot easier to fix an error when you know what the error is. This makes debugging even more annoying than it ordinarily would be, if you can imagine that. I've heard that it should be a simple preference fix, but I've asked around and no one seems to know how. Thank you, and please make all answers simple enough to be understood by a highschool student and his father :) . From wcarus at comcast.net Wed Jan 12 08:45:12 2005 From: wcarus at comcast.net (Win) Date: 12 Jan 2005 05:45:12 -0800 Subject: Help Optimizing Word Search In-Reply-To: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: <1105537512.711823.225530@f14g2000cwb.googlegroups.com> Hi Case. Just in case you're really, truly looking for a fast Scrabble word-search algorithm, the classic AI/CS article here is: Andrew W. Appel and Guy J. Jacobson, The world's fastest Scrabble program, Communications of the ACM, 31(5), pp 572--578, May 1988. You can find a copy of this article at, for example: http://counties.csc.calpoly.edu/~team12fk/F02/acm_worlds_fastest_scrabble_program.pdf This algorithm uses a "dawg" (Directed Acyclic Word Graph). You can find a well-documented example of this data structure implemented in Python in the the WordUtils package: http://cedar-solutions.com/software/wordutils/ Regards, Win From ncoghlan at iinet.net.au Mon Jan 17 05:27:47 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 17 Jan 2005 20:27:47 +1000 Subject: Executing a script created by the end user In-Reply-To: <41EAC49E.70209@earthlink.net> References: <41EAC49E.70209@earthlink.net> Message-ID: <41EB9323.3020805@iinet.net.au> Craig Howard wrote: > I am working on a python project where an object will have a script that > can be edited by the end user: object.script > > If the script is a simple one with no functions, I can easily execute it > using: > exec object.script Take a look at the execfile builtin. > But if the object script is a bit more complicated, such as the example > below, my approach does not work: Alternatively: Py> exec """ ... def main(): ... hello1() ... hello2() ... ... def hello1(): ... print 'hello1' ... ... def hello2(): ... print 'hello2' ... """ Py> main() hello1 hello2 'exec' is quite happy to deal with newlines and indenting. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jelle.feringa at ezct.net Mon Jan 17 04:53:14 2005 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Mon, 17 Jan 2005 10:53:14 +0100 Subject: OCAMl a more natural extension language for python? Message-ID: <20050117095248.90B8F1C015CF@mwinf0507.wanadoo.fr> After reading about extending python with C/Fortran in the excellent Python Scripting for Computational Science book by Hans Langtangen, I'm wondering whether there's not a more pythonic way of extending python. And frankly I think there is: OCAML Fortunately there is already a project up and running allowing you to extend python with OCAMl: http://pycaml.sourceforge.net/ Since I haven't got actual experience programming CAML I'd like to speculate that OCAML would be a very pythonic way of extending python: its open-source, object oriented, as fast as C, and ! garbage collecting! Would making an effort integrating python & CAML not be very worthwhile? I think an effort such as Joe Strouts python2c would be more relevant to a language as CAMl since its conceptually more closer to python (how could you automate programming memory allocation for instance) So my question is: wouldn't there be some serious synergy in bringing python & CAML closer together? ##of course this is speculation, I'm not informed well ##enough to make an educated guess Interested in hearing your thoughts about this matter! Cheers, Jelle. From fredrik at pythonware.com Sat Jan 22 13:55:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 19:55:36 +0100 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com><41EE24F7.7030303@jessikat.fsnet.co.uk><7x1xchlpqv.fsf@ruckus.brouhaha.com><41efeb82$0$27807$9b622d9e@news.freenet.de><41f1a70b$0$25959$9b622d9e@news.freenet.de><7xbrbiqdhk.fsf@ruckus.brouhaha.com><7xllalljah.fsf@ruckus.brouhaha.com><7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Excellent. I hope you will re-read it several times a day. Doing > that might improve your attitude. you really don't have a fucking clue about anything, do you? From beliavsky at aol.com Fri Jan 7 12:38:21 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 7 Jan 2005 09:38:21 -0800 Subject: how to extract columns like awk $1 $5 References: Message-ID: <1105119501.289155.264740@z14g2000cwz.googlegroups.com> It takes a few more lines in Python, but you can do something like for text in open("file.txt","r"): words = text.split() print words[4],words[5] (assuming that awk starts counting from zero -- I forget). From lcatalin at siadv.com Wed Jan 5 10:23:50 2005 From: lcatalin at siadv.com (Catalin Lungu) Date: Wed, 5 Jan 2005 16:23:50 +0100 Subject: Image capture Message-ID: Hi, Can anybody help me to implement the following VB code in Python. Thanks in advance. Private Declare Function SendMessage Lib "user32.dll" Alias _ "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, _ ByVal wParam As Long, ByVal lParam As Long) As Long Private Const WM_PAINT = &HF Private Const WM_PRINT = &H317 Private Const PRF_CLIENT = &H4& Private Const PRF_CHILDREN = &H10& Private Const PRF_OWNED = &H20& Private Sub Command1_Click() SendMessage grid.hwnd, WM_PAINT, picture.hDC, 0 SendMessage grid.hwnd, WM_PRINT, picture.hDC, PRF_CHILDREN Or PRF_CLIENT Or PRF_OWNED picture.Picture = picture.Image picture.Refresh End Sub Catalin lcatalin at siadv.com From http Sat Jan 8 04:55:03 2005 From: http (Paul Rubin) Date: 08 Jan 2005 01:55:03 -0800 Subject: python3: accessing the result of 'if' References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> Message-ID: <7xd5wgs0so.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > So let's use it for expression naming in 'if' statements, too. > > if someregexp.match(s) as m: > # blah using m > elif someotherregexp.match(s) as m: > # blah using m Certainly an improvement over what we have now. From jacek.generowicz at cern.ch Mon Jan 10 03:59:18 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Jan 2005 09:59:18 +0100 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> Message-ID: "Anna" writes: > With class and def, I at least have a *name* to start with - class > Square pretty obviously is going to have something to do with > geometric shapes, I would hope (or maybe with boring people...). Or maybe with multiplying something by itself. Or maybe the author made some changes in his program, and forgot to rename the class sensibly, and the class' functionality has nothing to do with squares of any sort any more. Or maybe he felt the name "Square" was very appropriate for something else in his program and inadvertently gave the same name to two different entities thereby clobbering the one whose use was intended at this point. > def getfoo() tells me I'm the function is likely to go elsewhere and > get something. It's a *start*, All too often a start in the wrong direction. > a handle, to deciphering whatever the following statements are > doing. (Yes, I realize that often class and function names suck Yup. I waste quite some time because of crappily chosen names. > - but more often than not, they give *some* clue). > > Whereas, with lambda - I have *nothing* to go on. Aaah. OK, you object to lambda because it gives you no clue as to what the function does, rather than with the word "lambda" itself? Is that it? So, IIUC, you consider def add_one(x): return x+1 map(add_one, seq) to be clearer than map(lambda x:x+1, seq) ? > With lambdas, all I know is that the programmer wanted to hide > whatever it is the program is doing behind the curtain... I find this a strange way of looking at it, given that, with lambda, what the program is doing is right there in front of your very eyes at the very point at which it is doing it. Were there a name, _then_ you could argue that the functionality is hidden ... and you would have to look the name up, to make sure that it really represents what you inferred it meant (and, to be absolutely sure, you'd have to double check that it hasn't been rebound by some other part of the program in some nasty way). None of these problems arise with lambda. > IMHO, YMMV, etc etc Of course. Same here. > Personally, I like lambdas less than regular expressions (of which > I'm particularly UNfond but understand their usefulness at > times). At least with regular expressions - I know that the > gibberish I need to decipher (probably) has to do with text > parsing... Hmm, that tells you about as much as lambda does. With lambda you know that the gibberish you need to decipher has to do with functions :-) From skip at pobox.com Wed Jan 26 22:03:07 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 26 Jan 2005 21:03:07 -0600 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: <16888.23019.818401.742296@montanaro.dyndns.org> phr> I don't see why you can't make up your mind enough to issue simple phr> statements like "the Python lib should have a module that does phr> so-and-so, and it should meet such-and-such requirements, so if phr> someone submits one that meets the requirements and passes code phr> review and testing and doesn't have unexpected issues or otherwise phr> fail to meet reasonable expectations, we'll use it". Because good requirements specification is difficult and testing improves the breed. Better to have the major API changes and bugs taken care of, and to have its popularity demonstrated *before* it gets into the Python distribution. The best way to do something isn't always obvious at the outset. If multiple solutions exist in the community, everyone benefits. The best survive. The worst don't. If one implementation is prematurely chosen for inclusion in the Python distribution, it stifles the vetting process. Finally, what if, saints be preserved, your whizbang new module is included in the core distribution and it's just not as popular as was first thought? It just winds up as a weight around the maintainers' necks. Once included in the distribution it's difficult to remove. Even rexec and Bastion, which are both known to be inadequate from a security standpoint, are still in the distribution. So, feel free to implement whatever it is you propose. Register it with PyPI, announce it on comp.lang.python.announce, etc. Support it for awhile. Run it through a couple revisions to fix API warts and bugs. When it's the category king and there is substantial community support for inclusion, it will be considered. Python is popular in part because of its fairly conservative development strategy. That goes for the libraries as well as the language itself. Skip From steven.bethard at gmail.com Thu Jan 27 12:58:23 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 10:58:23 -0700 Subject: String Fomat Conversion In-Reply-To: References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Message-ID: Stephen Thorne wrote: > I did all I did in the name of clarity, considering the OP was on his > first day with python. How I would actually write it would be: > > inputfile = file('input','r') > inputfile.readline() > data = [map(float, line.split()) for line in inputfile] > > Notice how you don't have to call iter() on it, you can treat it as an > iterable to begin with. Beware of mixing iterator methods and readline: http://docs.python.org/lib/bltin-file-objects.html next( ) ...In order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right. I haven't tested your code in particular, but this warning was enough to make me generally avoid mixing iter methods and other methods. Steve From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Tue Jan 11 17:57:08 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Tue, 11 Jan 2005 23:57:08 +0100 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> <1105434532.132061.24030@f14g2000cwb.googlegroups.com> <1105434900.511862.54740@f14g2000cwb.googlegroups.com> Message-ID: <41e459e5$0$8025$8fcfb975@news.wanadoo.fr> ;o) Python ==. limits ,===> \________/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ncoghlan at iinet.net.au Sun Jan 2 00:32:33 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 02 Jan 2005 15:32:33 +1000 Subject: when wxPython update to python2.4? In-Reply-To: <41B930B7.4040600@163.com> References: <41B930B7.4040600@163.com> Message-ID: <41D78771.8000404@iinet.net.au> alang_yl wrote: > i can't wait. > wxPython 2.5 already has a version which works with Python 2.4 (grab it from www.wxpython.org). For the wxPython 2.4 series, I understand Robin is planning a release which will both integrate the 2.4 series into the new wxPython versioning scheme, and also include a Python 2.4 compatible version. The timeframe for that isn't entirely clear, though. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From pierre.barbier at cirad.fr Wed Jan 12 08:36:35 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Wed, 12 Jan 2005 14:36:35 +0100 Subject: how to visualize symbol table? In-Reply-To: <41e5220c$0$15240$91cee783@newsreader01.highway.telekom.at> References: <41e5220c$0$15240$91cee783@newsreader01.highway.telekom.at> Message-ID: <41e52772$0$7880$626a14ce@news.free.fr> Thomas Korimort a ?crit : > Hi, > > how can i visualize the content of the symbol table in Python? > Sometimes i want to know which symbols are imported from apackage and > such kind of things > > Greetings, THomas Korimort Do you mean something like : dir(module) ??? Pierre From christian_stengel at yahoo.de Wed Jan 26 11:29:31 2005 From: christian_stengel at yahoo.de (christian_stengel) Date: Wed, 26 Jan 2005 16:29:31 -0000 Subject: unknown protocol error when connecting to an server via ssl Message-ID: Hi *, I have just started to learn python and I am having a problem with an python client connecting to a perl server using ssl (I tried this with pyOpenSSL and with the build in SSL Module). I don't want to check a cerificate, so i simply tried a from OpenSSL import SSL s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("127.0.0.1", 2000) s.sendall("100 Hello\n") ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.set_verify(SSL_VERIFY_NONE,self.verify_cb) ss = SSL.Connection(ctx,s) ss.set_connect_state() ss.sendall("101 User\n") when writeing the 101 I'll get an SSL23_GET_SERVER_HELLO unknown protocol error. If I don't do the ssl stuff, everything works. I also tried this with the socket.ssl(s,None, None) to get a secure socket - but I got the same error. The server is not written by me - so I can't change that to python. The problem is, that there is first an unencrypted socket, that is converted to a secure socket. the perl (server) code is something like this: # creating a socket $socket = IO::Socket::INET->new(Listen => 5, LocalPort => 2000, Timeout => 15, Resue => 1, Proto => 'tcp'); # some more code # accepting a remote connection $session = $socket->accept; # some more code # convert the Socket to an ssl socket $sslsocket = IO::Socket::SSL::socket_to_SSL($session, SSL_verify_mode => 0x00) # some more code Does anybody know, where the UNKNOWN PROTOCOL error comes from? I have changed the connection Mode to SSLv2_METHOD but this gave me an GET_SERVER_HELLO read wrong packet type error. I have done this with python 2.3.4 under linux - and the perl stuff is done via the IO-Socket-SSL package. Thx, Chris From http Sun Jan 30 17:50:42 2005 From: http (Paul Rubin) Date: 30 Jan 2005 14:50:42 -0800 Subject: ANNOUNCE: KirbyBase 1.7 References: Message-ID: <7xy8ea1qgt.fsf@ruckus.brouhaha.com> Jamey Cribbs writes: > 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. That's cute, especially the part about using Python expressions instead of SQL to express queries. I don't see anything in the info page about what happens when you have multiple clients updating the db concurrently. Do you make any attempt to handle that? From morphex at gmail.com Wed Jan 12 23:49:56 2005 From: morphex at gmail.com (morphex) Date: 12 Jan 2005 20:49:56 -0800 Subject: Creating text on images Message-ID: <1105591796.422252.190990@f14g2000cwb.googlegroups.com> Hi all, I'm trying to create a script that will superimpose text on an image. I didn't find any great examples out there on how this can be done (I presume using PIL is necessary), do you know of any examples? Thanks, Morten From peter at engcorp.com Thu Jan 13 08:37:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 08:37:50 -0500 Subject: pyserial and com port interrupts In-Reply-To: <24lbu0htudrc9ir4b0na3r1m6g09qlbck4@4ax.com> References: <24lbu0htudrc9ir4b0na3r1m6g09qlbck4@4ax.com> Message-ID: engsol wrote: > I'm working on a s/w test program using python > code. Com1 and com2 play a part. The problem is that the python code > has a lot of work to do...and the results from the hardware under test can > come from either com1 or com2...at any time. It may be a few milliseconds, > or several seconds, sometimes minutes, before a response is expected. > I'm not sure what timeout value I'd use. Using threads, and re-loading the > timeout values on the fly may be a solution, but I'm not experienced with > threads....and was hoping to avoid them. I'm with Grant on this: threads in Python are really easy. If you can describe a little more about what you need/would like to do with the serial data when it *does* arrive, and how that relates to the "lot of work" that the rest of the code is doing, I'm sure there are a number of helpful replies just waiting to be written to convince you how easy it really is. For example, if you need to retrieve the data from the serial ports right away, so the sending device doesn't block or lose data, but can afford to just store it for later processing when the main thread has time, that's only a few lines of code. If you actually want to reply immediately, then the only real question is how you come up with the reply. If it needs data from the main thread, we can show you several easy and appropriate ways to do that with no thread safety issues. If you're not experienced with threads, there's almost no place better to start learning than with Python and c.l.p. :-) -Peter From michele.simionato at gmail.com Wed Jan 5 22:42:08 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 5 Jan 2005 19:42:08 -0800 Subject: Python evolution: Unease In-Reply-To: <7xzmzo6qk0.fsf@ruckus.brouhaha.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <1104910363.381748.105670@z14g2000cwz.googlegroups.com> <7xzmzo6qk0.fsf@ruckus.brouhaha.com> Message-ID: <1104982928.527510.29630@z14g2000cwz.googlegroups.com> Did you used Tkinter and Tix? Most of my problems were there. Of course, I also got in trouble when upgrading to Python 2.2 from 1.5.2 Finally they switched to Python 2.2, but at that moment Python 2.3 came out and I got tired. I switched to Mandrake 1.5 and I am happy with it. Never had any serious trouble with urpmi and lots of Python packages are available. Michele Simionato From woetzel at AUTO Wed Jan 19 05:08:18 2005 From: woetzel at AUTO (Gerd Woetzel) Date: 19 Jan 2005 12:08:18 +0200 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> Message-ID: <41ee3fa2$1@news.fhg.de> Robin Becker writes: >Paul Rubin wrote: >.....I'm also missing the rotor module and regret that something useful >was warned about and now removed with no plugin replacement. Hm, yes. Here is a (rather slow) replacement: """This module is derived from Modules/rotormodule.c and translated into Python. I have appended the Copyright by Lance Ellinghouse below. The rotor module has been removed from the Python 2.4 distribution because the rotor module uses an insecure algorithm and is deprecated. ============================================================== Of course, this does still hold. However, I think this module might be used and adapted for demonstration purposes and might help some poor users who have encrypted (or obfuscated) some old stuff with the rotor module and have no access to older Python versions any more. Documentation can be found in Python Library Reference, Guido van Rossum, Fred L. Drake, Jr., editor, PythonLabs, Release 2.3.4 May 20, 2004 ##################################################################### Copyright 1994 by Lance Ellinghouse, Cathedral City, California Republic, United States of America. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Lance Ellinghouse not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ##################################################################### """ class newrotor(object): def __init__(self, key, n_rotors=6): self.n_rotors = n_rotors self.setkey(key) def setkey(self, key): self.key = key self.rotors = None self.positions = [None, None] def encrypt(self, buf): # Reset (encrypt) positions and encryptmore self.positions[0] = None return self.cryptmore(buf, 0) def encryptmore(self, buf): return self.cryptmore(buf, 0) def decrypt(self, buf): # Reset decrypt positions and decryptmore self.positions[1] = None return self.cryptmore(buf, 1) def decryptmore(self, buf): return self.cryptmore(buf, 1) def cryptmore(self, buf, do_decrypt): size, nr, rotors, pos = self.get_rotors(do_decrypt) outbuf = [] append = outbuf.append for c in map(ord, buf): if do_decrypt: # Apply decrypt rotors and xor in reverse order for i in xrange(nr-1,-1,-1): c = pos[i] ^ rotors[i][c] else: # Apply xor and ecrypt rotors for i in xrange(nr): c = rotors[i][c ^ pos[i]] append(c) # Advance rotors, i.e. add the (fixed) rotor increments to the # variable rotor positions with carry. # Note: In the C-implementation, the result of the carry addition # was stored to an "unsigned char". Hence the next carry # is lost if pos[i] == size-1 and pnew >= size. # Masking with 0xff simulates this behavior. # pnew = 0 # (pnew >= size) works as "carry bit" for i in xrange(nr): pnew = ((pos[i] + (pnew >= size)) & 0xff) + rotors[i][size] pos[i] = pnew % size return ''.join(map(chr, outbuf)) def get_rotors(self, do_decrypt): # Return a tuple (size, nr, rotors, positions) where # - size is the rotor size (== 256, because of 8-bit bytes) # - nr is the number of rotors. # - rotors is a tuple of nr encrypt or nr decrypt rotors # for do_decrypt == 0 or do_decrypt == 1 respectively. # - postions is a list of nr "rotor positions". # # The rotors represent the static aspect of the rotor machine which # is initially computed from key and fixed during en/decryption. # A rotor is a random permutation of range(size) extended # by an "increment value" in range(size). # # The followng statements hold for a tuple of encrypt rotors E and # and the corresponding tuple of decrypt rotors D. # # D[i][E[i][j]] == j for i in range(nr) for j in range(size) # # E[i][D[i][j]] == j for i in range(nr) for j in range(size) # # This means that the corresponding rotors E[i] and D[i] are # inverse permutations. # The increments are equal for the corresponding encrypt and # decrypt rotors and have an odd value: # # D[i][size] == E[i][size] and E[i][size] == 1 mod 2 and # 0 < E[i][size] < size for i in range(nr) # # The position vector represents the dynamic aspect. # It changes after each en/decrypted character (the rotors # are "advanced"). The initial position vector is also computed # from the key # nr = self.n_rotors rotors = self.rotors positions = self.positions[do_decrypt] if positions is None: if rotors: positions = list(rotors[3]) else: # Generate identity permutation for 8-bit bytes plus an # (unused) increment value self.size = size = 256 id_rotor = range(size+1) # Generate nr "random" initial positions and "random" # en/decrypt rotors from id_rotor. # rand = random_func(self.key) E = [] D = [] positions = [] for i in xrange(nr): i = size positions.append(rand(i)) erotor = id_rotor[:] drotor = id_rotor[:] drotor[i] = erotor[i] = 1 + 2*rand(i/2) # increment while i > 1: r = rand(i) i -= 1 er = erotor[r] erotor[r] = erotor[i] erotor[i] = er drotor[er] = i drotor[erotor[0]] = 0 E.append(tuple(erotor)) D.append(tuple(drotor)) self.rotors = rotors = ( tuple(E), tuple(D), size, tuple(positions)) self.positions[do_decrypt] = positions return rotors[2], nr, rotors[do_decrypt], positions def random_func(key): # Generate a random number generator that is "seeded" from key. # This algorithm is copied from Python2.3 randommodule.c. # mask = 0xffff x=995 y=576 z=767 for c in map(ord, key): x = (((x<<3 | x>>13) + c) & mask) y = (((y<<3 | y>>13) ^ c) & mask) z = (((z<<3 | z>>13) - c) & mask) # Emulate (unintended?) cast to short maxpos = mask >> 1 mask += 1 if x > maxpos: x -= mask if y > maxpos: y -= mask if z > maxpos: z -= mask y |= 1 # avoid very bad seed, why not for x and z too? # Oh, dear, for compatibility, we must evaluate the first seed transition # the hard way, later it becomes much simpler x = 171 * (x % 177) - 2 * (x/177) y = 172 * (y % 176) - 35 * (y/176) z = 170 * (z % 178) - 63 * (z/178) if x < 0: x += 30269 if y < 0: y += 30307 if z < 0: z += 30323 # At least all values are > 0 by now but may be greater than expected .. def rand(n, seed=[(x, y, z)]): # Return a random number 0 <= r < n # x, y, z = seed[0] seed[0] = ((171*x) % 30269, (172*y) % 30307, (170*z) % 30323) return int((x/30269.0 + y/30307.0 + z/30323.0) * n) % n # Original code was like this: # from math import floor # val = x/30269.0 + y/30307.0 + z/30323.0 # val = val - floor(val) # if val >= 1.0: # val = 0.0 # n = int(val*n) % n return rand From aahz at pythoncraft.com Sun Jan 9 19:26:59 2005 From: aahz at pythoncraft.com (Aahz) Date: 9 Jan 2005 19:26:59 -0500 Subject: Old Paranoia Game in Python References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> Message-ID: In article , Lucas Raab wrote: >Aahz wrote: >> In article <5JcEd.1988$KJ2.907 at newsread3.news.atl.earthlink.net>, >> Lucas Raab wrote: >>>Sean P. Kane wrote: >>>> >>>>Equipment: Red Reflec Armour, Laser Pistol, Laser Barrel (red), >>>> Notebook & Stylus, Knife, Com Unit 1, Jump suit, >>>> Secret Illuminati Eye-In-The-Pyramid(tm) Decoder ring, >>>> Utility Belt & Pouches >>> >>>The Illuminati really have infiltrated our society. >> >> Stay alert! >> Trust no one! >> Keep your laser handy! > >Well, I really meant "Secret Illuminati Eye-In-The-Pyramid(tm) Decoder >ring", but if you wanted to go in another direction... Trust the computer, the computer is your friend. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From tmohr at s.netic.de Fri Jan 14 01:23:53 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Fri, 14 Jan 2005 07:23:53 +0100 Subject: reference or pointer to some object? References: Message-ID: Hi, thank you all for your explanations. That's really great and helps me a lot. Thanks, Torsten. From toop82 at comcast.net Tue Jan 25 00:01:08 2005 From: toop82 at comcast.net (Robert Toop) Date: Tue, 25 Jan 2005 00:01:08 -0500 Subject: error References: Message-ID: http://www.python.org/2.4/bugs.html ...suggests that firewall running on python host (read Windows software firewall) may block the localhost TCP connection required between IDLE parent and child processes. I don't think this problem is specific to python 2.4. IDLE should work if you change firewall config to allow local (i.e. intramural) TCP connections. HTH /old goat/ "me" wrote in message news:RAfJd.37$587.2870 at news.uswest.net... > whenever i try and run my Python GUI, my computer thinks for a sec, then > drops the process, without ever displaying the window. the command prompt > window seems to work fine, but the IDLE GUI won't start. > > i'm running Windows 2K professional and python 2.4, so any advice help would > be appreciated. i've already tried reinstalling and use a thread response, > as the e-mail on this account is bogus. > > From petite.abeille at gmail.com Fri Jan 28 18:21:16 2005 From: petite.abeille at gmail.com (PA) Date: Sat, 29 Jan 2005 00:21:16 +0100 Subject: what's OOP's jargons and complexities? In-Reply-To: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: On Jan 29, 2005, at 00:10, Xah Lee wrote: > Tomorrow i shall cover more manmade jargons and complexities arising > out of the OOP hype, in particular Java. Good read. Keep them coming :) Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From tundra at tundraware.com Fri Jan 7 05:28:31 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 07 Jan 2005 05:28:31 EST Subject: Tkinter Puzzler Message-ID: I am trying to initialize a menu in the following manner: for entry in [("Up", KeyUpDir), ("Back", KeyBackDir), ("Home", KeyHomeDir), ("Startdir", KeyStartDir), ("Root", KeyRootDir)]: func = entry[1] UI.ShortBtn.menu.add_command(label=entry[0], command=lambda: func(None)) However, at runtime, each of the menu options binds to the *last* function named in the list (KeyStartDir). Explicitly loading each entry on its own line works fine: UI........command=lambda:KeyWHATEVERDir(None) Any ideas why the first form does not fly? TIA, ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From apardon at forel.vub.ac.be Wed Jan 19 09:40:24 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Jan 2005 14:40:24 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> <41ed8c13.1209309354@news.oz.net> Message-ID: Op 2005-01-19, Nick Coghlan schreef : > Antoon Pardon wrote: > > I can be wrong, but until now I have seen no indication that I was >> using mutable and immutable differently than other people. AFAICT >> we all refer to whether an object belongs to a mutable or immutable >> class. > > The difference is that when you take a copy of the key and stick it in the > dictionary, such that the dictionary now holds the *sole* reference to that key, > you have made that key *effectively* immutable. > > This is why no-one really batted an eyelid when you mentioned that mutable keys > can be used safely by making a copy - doing so makes the key *effectively* > immutable, and means that modifying the original key object (i.e. the > application's copy, not the dict's copy), and reusing it to look up in the > dictionary is likely to give a KeyError. > > These semantics would be understandably surprising to many users, and hence, are > not supplied by default. This seems like circle reasoning. The reason why these semantics would be surprising is that those are not the semantics supplied. > Additionally, a dictionary's keys are accessible via its API. Accordingly, to > preserve this 'effective immutability', making a copy on key input is > insufficient - keys must be copied on *output* as well (that is, dict.keys, > dict.items etc must return *copies* of the key objects, not the key objects > themselves). Yes I haven been thinking about this too. I also think not making a copy on output is less dangerous than not making a copy on input. > Since there is no reliable way in Python to tell if an object is mutable or not > (the closest equivalent is the presence of __hash__, which clearly can't be used > in this example), this copying would need to be done for *every* object. > > Alternately, the dictionary can say to the API clients, "make an immutable copy > and supply that instead. It is left to API clients to decide how best to make > the immutable version". The API client copies the key once (to make the > immutable version), and everyone lives happily ever after. > > For example: > > Py> class mylist(list): > ... def __init__(self, arg): > ... super(mylist, self).__init__(arg) > ... self._tuple = None > ... def frozen(self): > ... if self._tuple is None: > ... self._tuple = tuple(self) > ... return self._tuple > ... def unfreeze(self): > ... self._tuple = None > ... > Py> x = mylist(range(10)) > Py> x > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > Py> x.frozen() > (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) > Py> x.append(10) > Py> x.frozen() > (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) > Py> x.unfreeze() > Py> x.frozen() > (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) > > This is much safer than having a list subclass that implements __hash__, and > still lets you avoid redundant copy operations. > > Nicely, so long as you don't unfreeze the object you used to key the dictionary, > reusing the same object will always get you the correct dictionary entry, and > two lists that compare equal at the time they are frozen will also get you the > same dictionary entry. The equivalent tuples can be used for the lookup, too. Interesting idea. But I think you are wrong when you say that two lists that compare equal at the time they are frozen, will get the same dictionary entry. The problem is an object must compare equal to the key in the dictionary to get at the same entry. So if you freeze a list and its copy but then mutate them differently, they no longer are equal and so wont get you at the same entry. [ Rest snipped, this is getting into a semantic debate on what 'mutable' means. This may be interesting enough on its own but I feel it detracts too much from what I consider the more important issue. ] -- Antoon Pardon From john at grulic.org.ar Mon Jan 17 14:23:27 2005 From: john at grulic.org.ar (John Lenton) Date: Mon, 17 Jan 2005 16:23:27 -0300 Subject: strange note in fcntl docs In-Reply-To: <16875.54085.712019.524951@montanaro.dyndns.org> References: <20050117053949.GA28456@grulic.org.ar> <16875.54085.712019.524951@montanaro.dyndns.org> Message-ID: <20050117192327.GA4723@grulic.org.ar> On Mon, Jan 17, 2005 at 09:01:25AM -0600, Skip Montanaro wrote: > > I could have sworn that os.open supported the O_SHLOCK and O_EXLOCK flags. > I'm pretty sure I've used them in the past, but don't see them now. (They > aren't in 2.2 either.) > > If you try this: > > O_SHLOCK = 0x0010 > O_EXLOCK = 0x0020 > > (those are the definitions on my Mac - YMMV) does > > os.open("somefile", O_SHLOCK|) > > work? I grepped for O_..LOCK in /usr/include on my linux computer and came up barehanded. The flags you mention are not, AFAIK, part of POSIX (the open(3posix) manpage does not list them). And, even if they were, the note is *still* wrong and misleading: fcntl is available on Windows, and os.open's flags won't be. from http://www.daemon-systems.org/man/open.2.html, I gather that O_..LOCK are a BSD extension, which is why you have then on the Mac. But they do *not* belong in posix; they belong in os for your platform, and the note in fcntl should be removed. The only way this wouldn't be true is if os.open is extended to understand O_..LOCK, and call out to flock as needed. That would go against what I understand is the essence of os.open (i.e., a direct road to open(2)). Hmm, if the above sounds a little harsh, sprinkle :)s in. I've had too little sleep. -- John Lenton (john at grulic.org.ar) -- Random fortune: If you're right 90% of the time, why quibble about the remaining 3%? -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From fperez.net at gmail.com Tue Jan 25 12:37:34 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Tue, 25 Jan 2005 10:37:34 -0700 Subject: Installer made with bdist_wininst segfaulting... References: Message-ID: Hi Thomas, Thomas Heller wrote: > Fernando Perez writes: >> Here is a brief summary: if the installer file is run from a windows drive >> which is different from the one where python resides (and hence where >> ipython will >> end up), the installer segfaults. No traceback, nothing, just a segfault >> (well, one of those Windows dialogs asking me to send a binary traceback to >> Redmond, but not a proper Python traceback). > > There are a couple of known bugs in bdist_wininst, and you just reported > another one. All these bugs are related to using the > post_install_script, and show up when either (thats what I currently > remember): [...] many thanks for following up on this. In my case, I realized I could avoid the chdir() call and things were then OK. But it's good to see the bug fixed. Best regards, f From roy at panix.com Fri Jan 7 20:43:03 2005 From: roy at panix.com (Roy Smith) Date: Fri, 07 Jan 2005 20:43:03 -0500 Subject: EOF for binary? References: <1105147072.909665.242360@z14g2000cwz.googlegroups.com> Message-ID: In article <1105147072.909665.242360 at z14g2000cwz.googlegroups.com>, "flamesrock" wrote: > Hi, > > So if I understand correctly, there are NO eof characters in any binary > file. If so, is there an easier way to check for the end of the file > than: > > os.path.getsize(infile) <= infile.tell() How you detect EOF depends on how you're reading the file. For example, read() indicates EOF by returning fewer characters than you asked for (possibly zero). Checking the length of a file is perilous. Files change size. File sizes don't have much meaning on things like network sockets to begin with. From mahs at telcopartners.com Tue Jan 25 19:03:11 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 25 Jan 2005 16:03:11 -0800 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: Message-ID: Cameron Laird wrote: > In article , > Michael Spencer wrote: > . > . > . > >>Right - the crux of the problem is how to identify dangerous objects. My point >>is that if such as test is possible, then safe exec is very easily implemented >>within current Python. If it is not, then it is essentially impossible. >> > > > > I'll suggest yet another perspective: add another indirection. > As the virtual machine becomes more available to introspection, > it might become natural to define a *very* restricted interpreter > which we can all agree is safe, PLUS a means to extend that > specific instance of the VM with, say, new definitions of bindings > for particular AST nodes. Then the developer has the means to > "build out" his own VM in a way he can judge useful and safe for > his own situation. Rather than the Java there-is-one-"safe"-for- > all approach, Pythoneers would have the tools to create safety. That does sound good. And evolutionary, because the very restricted VM could be implemented today (in Python), and subsequently PyPy (or whatever) could optimize it. The safe eval recipe I referred to earlier in the thread is IMO a trivial example of of this approach. Of course, its restrictions are extreme - only constant expressions, but it is straightforwardly extensible to any subset of the language. The limitation that I see with this approach is that it is not, in general, syntax that is safe or unsafe (with the notable exception of 'import' and its relatives). Rather, it the library objects, especially the built-ins, that present the main source of risk. So, if I understand your suggestion, it would require assessing the safety of the built-in objects, as well as providing an interpreter that could control access to them, possibly with fine-grain control at the attribute level. M From timj at tolisgroup.com Mon Jan 17 14:22:44 2005 From: timj at tolisgroup.com (brucoder) Date: 17 Jan 2005 11:22:44 -0800 Subject: Adjusting the 1024 byte stdin buffer limit References: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> Message-ID: <1105989764.168794.113430@z14g2000cwz.googlegroups.com> Currently, when sending a data stream that exceeds 1024 bytes via stdin, the stream blocks at the 1024th byte. This precludes completion of the submission of the data stream. Tim From klapotec at chello.at Thu Jan 6 19:27:33 2005 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 07 Jan 2005 00:27:33 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <1105056774.393244.199250@f14g2000cwb.googlegroups.com> Message-ID: On Thu, 06 Jan 2005 16:12:54 -0800, Carl Banks wrote: > Arich Chanachai wrote: >> But >> then again, if you don't like C++, you probably won't like Java. > They >> can be very different languages, but in my experience, the reasons > why >> one does not like C++ is usually due to a quality/flaw that can also > be >> found in Java. > > Oh, brother. > > The Zen of Python says that "simple is better than complex" and > "complex is better than complicated". Java does pretty well here. C++ > didn't even get "complicated is better than convoluted" right. There's > are a ton of flaws in C++ not found in Java. Still, Java feels like C++ done right, while being more wrong >:-[ -- Christopher If there was a scheme for Lisp world domination... From michele.simionato at gmail.com Wed Jan 5 22:31:53 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 5 Jan 2005 19:31:53 -0800 Subject: Python evolution: Unease In-Reply-To: <10to8qulnc3vke1@news.supernews.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> Message-ID: <1104982313.217034.308760@z14g2000cwz.googlegroups.com> John Roth: > The bottom line is that I'm not going to be writing any > extensive pieces of Python documentation. My time > is better spent elsewhere. Well, a couple of years ago I realized that some documentation on the MRO was missing. I wrote a document in reST, posted here, and Guido put it on python.org. It was as easy as it sounds. So I don't see your problem. Dave Kulhman wrote some utility to convert reST in latex using the same style of the standard library docs; I haven't used it myself, but you may check with him: http://www.rexx.com/~dkuhlman/ P.S. since you cite descriptors, what's wrong with Raimond Hetting documentation? http://users.rcn.com/python/download/Descriptor.htm The only problem I see is that it is not integrated with the official docs, but this is a minor issue, I think. Michele Simionato From rnd at onego.ru Tue Jan 4 09:06:45 2005 From: rnd at onego.ru (Roman Suzi) Date: Tue, 4 Jan 2005 17:06:45 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: References: Message-ID: On Tue, 4 Jan 2005, Batista, Facundo wrote: Maybe OP doesn't yet fully comprehend the ways of Python universe? As for his claims, I am quite surprised that Python lacks something in the docs. Concerning better hierarchy in the standard library, it is interesting that there are some movements in this direction: xml package, email package, etc. Probably Iwan thinks that letting more "hierachiesness" into std lib Python will be "cleaner". Yes, it will probably look "more organized" this way, but I do not like the idea: import time.time import time.calendar ... import web.url.openers import net.http ... import datatypes.string import textprocessing.re etc. > [Iwan van der Kleyn] > > #- need: a better standard ide, an integrated db interface with > #- a proper > #- set of db drivers (!!), a better debugger, a standard widget/windows > #- toolkit, something akin to a standard for web programming, better > #- documentation, a standard lib which is better organized, a > #- formalized > #- set of protocols and patterns for program construction. And an > #- interpreter which is fast enough to avoid using C or Pyrex in most > #- obvious cases. > > Let's take one by one: > > - IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than Pythonwin? > > - Integrated DB interface with a proper set of db drivers (what means the > "!!"?): What do you mean with an integrated db interface? An standard API to > access different DB engines? Something like the Database API specification > (http://www.python.org/topics/database/DatabaseAPI-2.0.html)? There's a SIG > on DB at http://www.python.org/sigs/db-sig/ you may want to look at. > Regarding drivers, to what DB do you miss one? > > - Debugger: Again, better than what? I use the debugger in IDLE and it's > pretty ok. > > - Standard widget/windows toolkit: More standard than Tk? > > - Something akin to a standard for web programming: specifically? > > - Better documentation: Did you find *any* issue in the docs? And why you > didn't post a bug on that? > > - Better organization of the std lib: What do you propose (specifically)? > Please, in your proposal, take in consideration migration plans and how the > migration affect actual systems. And of course, why the new organization is > better than the old one. BTW, I also think that it should be better > organized, but don't know how. > > - a formalized set of protocols and patterns for program construction: a > what? > > - an interpreter which is fast enough to avoid using C or Pyrex in most > obvious cases: CPython is More Than Fast Enough. In which obvious cases it's > not enough for you? > > Don't misinterpret this response. I know it was a rambling. But *maybe* you > have something to contribute to Python development, even good ideas only and > no work. > > . Facundo Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From zathras at thwackety.com Sun Jan 2 20:13:04 2005 From: zathras at thwackety.com (Michael Sparks) Date: Mon, 3 Jan 2005 01:13:04 +0000 (GMT) Subject: PEP 288 ponderings In-Reply-To: <41D794BA.8090408@colorstudy.com> Message-ID: On Sun, 2 Jan 2005, Ian Bicking wrote: > Steven Bethard wrote: > > PEP 288 was mentioned in one of the lambda threads and so I ended up > > reading it for the first time recently. I definitely don't like the > > idea of a magical __self__ variable that isn't declared anywhere. It > > also seemed to me like generator attributes don't really solve the > > problem very cleanly. An example from the PEP[1]: > > > > def mygen(): > > while True: > > print __self__.data > > yield None > > > > g = mygen() > > g.data = 1 > > g.next() # prints 1 > > g.data = 2 > > g.next() # prints 2 > > I don't get why this isn't good enough: > > def mygen(data): > while True: > print data[0] > yield None It's OK, but rather limited. IMHO a nicer approach is to use decorators to decorate a generator with extra attributes. Specifically to embed the generator inside an iterator inside an anonymous class. (We're exploring this as a alternative approach to the system we currently use at work) (Hmm... Now I describe it that sounds rather hideous, but the result is nice) First of all the decorator: import copy def wrapgenerator(bases=object, **attrs): def decorate(func): class statefulgenerator(bases): __doc__ = func.__doc__ def __init__(self,*args): super(statefulgenerator, self).__init__(*args) self.func=func(self,*args) for k in attrs.keys(): self.__dict__[k] = copy.deepcopy(attrs[k]) self.next=self.__iter__().next def __iter__(self): return iter(self.func) return statefulgenerator return decorate This would be used thus: @wrapgenerator(component) def forwarder(self): # The generator, note the explicit self for local state # for this generator "Simple data forwarding generator" while 1: if self.dataReady("inbox"): self.send("outbox",self.recv("inbox")) elif self.dataReady("control"): if self.recv("control") == "shutdown": break yield 1 self.send("signal","shutdown") yield 0 This clearly assumes a set of attributes, local methods etc. In this case our local methods, attribute etc are from this class: class component(object): def __init__(self, *args): # Default queues self.queues = {"inbox":[],"control":[],"outbox":[],"signal":[]} def send(self, box, object): self.queues[box].append(object) def dataReady(self,box): return len(self.queues[box])>0 def recv(self, box): # NB. Exceptions aren't caught X=self.queues[box][0] del self.queues[box][0] return X This then gets used in the usual way: >>> f = forwarder() >>> f <__main__.statefulgenerator object at 0x402dcccc> >>> f.send("inbox", "some data") >>> f.send("inbox", "some more data") >>> f.next() 1 >>> f.next() 1 >>> f.recv("outbox") 'some data' >>> f.recv("outbox") 'some more data' If you "just" want (arbitrary) generator attributes, then that's a lot easier (since we don't need to support an arbitrary base class): import copy def add_attrs_to_generator(**attrs): def decorate(func): class statefulgenerator: __doc__ = func.__doc__ def __init__(self,*args): self.func=func(self,*args) for k in attrs.keys(): self.__dict__[k] = copy.deepcopy(attrs[k]) self.next=self.__iter__().next def __iter__(self): return iter(self.func) return statefulgenerator return decorate @add_attrs_to_generator() def simpleGen(self): while True: print dir(self) yield None We can also add default attributes: @add_attrs_to_generator(test=1,simple=2) def simpleGen(self): while True: print dir(self) yield None >>> g=simpleGen() >>> g.next() ['__doc__', '__init__', '__iter__', '__module__', 'func', 'next', 'simple', 'test'] We've been using this general approach of giving generators local state for communications for a while now, and it's been rather interesting/fun to use. However we've been using explicit declaration of a class, and then a standard fixed name for the generator (main) instead. (we've been thinking about using decorators as syntactic sugar) Being able to pass exception in would be very nice, however we've used a "control" attribute, queue in practice, to allow for need to be able to shutdown an arbitrary generator. However, I don't think the __self__ part of the PEP is explicitly required - since you can build that onto generators using python quite happily now (@add_attrs_to_generator). The code for the stuff we're playing with (in case anyone's interested :) is at http://kamaelia.sourceforge.net/. The specific subsystem that uses this approach has been released as a separate download (Axon[1]) on the sourceforge project page[2], and the main system (obviously) uses this heavily and can be browsed via viewcvs. [3] [1] http://kamaelia.sourceforge.net/Docs/Axon.html [2] http://sourceforge.net/projects/kamaelia [3] http://cvs.sourceforge.net/viewcvs.py/kamaelia/Code/Python/Kamaelia/Kamaelia/ Best Regards, Michael. From peter at engcorp.com Mon Jan 10 19:32:48 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Jan 2005 19:32:48 -0500 Subject: exceptions and items in a list In-Reply-To: References: <34g8i6F4ad39oU1@individual.net> Message-ID: <3r-dnftx4-syg37cRVn-uQ@powergate.ca> rbt wrote: > Andrey Tatarinov wrote: >> # skip bad object and continue with others >> for object in objects: >> try: >> #do something to object >> except Exception: >> pass > > Thanks Andrey. That's a great example of how to do it. Actually, it's not really a "great" example, since it catches _all_ exceptions that might happen, and quietly ignores them. For example, in the following code, you might not realize that you've made a typo and none of the items in the list are actually being checked, even though there is obviously no problem with any of these simple items (integers from 0 to 9). def fornat_value(val): return '-- %5d --' % val L = range(10) for val in L: try: print format_value(val) except Exception: pass It's almost always better to identify the *specific* exceptions which you are expecting and to catch those, or not do a simple "pass". See Vincent's response, for example, where he explicitly asks only for ValueErrors and lets others propagate upwards, to be reported. (I realize these were contrived examples, but examples that don't mention this important issue risk the propagation of buggy code...) -Peter From ncoghlan at iinet.net.au Thu Jan 20 05:32:12 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 20 Jan 2005 20:32:12 +1000 Subject: Zen of Python In-Reply-To: <7xekggbrns.fsf@ruckus.brouhaha.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> Message-ID: <41EF88AC.9030703@iinet.net.au> Paul Rubin wrote: > But it's often predictable at the > beginning what the final destination is going to be. So once we can > see where it's going, why not proceed to the finish line immediately > instead of bothering with the intermediate steps? Because getting there incrementally helps to make sure you end up with the features you need, without the irrelevant baggage an overengineered solution may bring with it. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From gurpreet.sachdeva at gmail.com Thu Jan 6 04:15:24 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Thu, 6 Jan 2005 14:45:24 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: <2b7d8b420501060057270f1878@mail.gmail.com> References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> <003801c4f3b9$af17fa20$0800a8c0@vishnu> <2b7d8b42050105232546083758@mail.gmail.com> <2b7d8b420501060057270f1878@mail.gmail.com> Message-ID: On Thu, 6 Jan 2005 14:27:40 +0530, Binu K S wrote: > I'm sorry, I didn't get what you trying to say here. Where do you see > a read altering the file? An example might help. Please try: logfile=file(r'test.txt','w+') logfile.write('datetime') Check the contents of test.txt, you will get what ever was required... Now Run: logfile=file(r'test.txt','w+') logfile.write('datetime') logfile.readlines() and check the contents of test.txt??? My doubt is that logfile.write('datetime') will write datetime that is universaly accepted but why all that junk is appending to that when I add logfile.readlines() Strange or Am I on drugs??? :o) Please Comment... Garry From bokr at oz.net Thu Jan 6 13:58:59 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 06 Jan 2005 18:58:59 GMT Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> Message-ID: <41dcf582.122188317@news.oz.net> On 05 Jan 2005 23:19:39 -0800, Paul Rubin wrote: >bokr at oz.net (Bengt Richter) writes: >> What do you think of automated secure importing/installing from a >> remote server? You know, you try to import something and it imports >> a stub that was included as a battery-place-holder and that has >> basic help info and will give you reasonable options in directing >> the installation of the full thing (or subset you are interested in). > >You mean for Python modules, in ordinary operation? I'd hate that. >For things like apt-get, used for installing nonstandard programs or >getting security updates, I guess it's about as good as one can hope >for. The user has to activate it explicitly though. I definitely >don't want my computer opening internet connections unless I >specifically ask it to. Doing otherwise is almost spyware. I agree 1000% !! Importing a stub should get you an imported stub that prints info as it imports, so you know its not functional. And just gives you the options to type help(themodule) or if you know you want to go ahead, themodule.install() -- and nothing would touch the internet until you gave a final "yes" to an "Are you sure" at the end of a what-will-happen-if-you-say-yes summary. I didn't mean any activity that you don't control. Just activity that you can control easily. > >This may sound a little extreme but my distribution philosophy is I'd >like to get closer to an environment where users normally never >install any software of any type, ever. Microsoft cornered the OS >market cornered by acheiving something pretty close to this: they >deliver Windows with no installation needed. When people buy new >computers, Windows is already on the hard drive, so the user just >turns the computer on and Windows is there. It makes a lot of sense for a "core" plus a delivered specific application base, but IMO if you try to cover the world with a monolith you will inevitably still have the problem of getting the latest version of particular packages for bug fixes or enhancements. The more you have in your giant collection the more that will be true. > >Fedora Core (what I'm running now) isn't shipped that way by any >computer makers that I know of, but it makes up for it by having lots >of applications included. So I buy a new computer, put in the >bootable Fedora DVD-ROM, and sit back for half an hour while a >one-time installation runs. That's about as close as I can get to >just turning on the new computer and having Fedora already there. > >> I don't see why every gee whiz thing has to be on your hard disk >> from the first. And for those that want a big grabbag, the stubs >> ought to be designed to to be runnable from a configured script, so >> you can turn it loose and see what's up IRL. > >If I have a 400 gig hard drive, I don't see why I need 99.99% of it >empty instead of 99.0% after I do my OS install. I don't want to >hassle over downloading stuff for hours or days at a time, or about >what components depend on other components, if the distro can just >include it. I just tried to install a Python program that uses >wxPython, except that meant I had to download both wxPython and >wxWidgets, and the installations failed because of some version >mismatch between the current wxWidgets distro and the version of GTK >included with FC3. I spent an hour or so messing with it and then >said screw it and gave up on the GUI part of that program. I'm more >technical than most users (I'm a programmer) yet this installation >stuff is too much hassle even for me. So I'd really rather that all >that stuff be pre-configured. There are several parts to those frustrations. But you are presuming that they would have been solved for you and put on a DVD with all dependency problems resolved. Ok, let's assume that. In that case, an installation stub module could just as well have the solution built into it as to what versions etc are needed to make the module work. With a large collection, you may need several versions of some support libs. To bring a large collection into version-alignment ISTM you need a version freeze across too many libraries of different kinds with different development schedules and resources to make it reliable. So you're still going to need the ability to add updates and new modules and more. I'd rather see effort going into making that process simple and reliable (and fully controlled by the user -- i.e. no unauthorized hidden internet activity!!) than to solve the same version problems for some mega DVD make file where you don't have the script and config info in a concise single-problem stub form, and can't ask here for help finding an updated stub. It's a matter of being able to limit the problem you need to solve when something particular doesn't work. When your wxPython-using program didn't work, wouldn't it have been nice to have downloaded a standard stub program (with older stub versions still available if you have an older system) and have it tell you what was missing that it needed before you decided to let it continue and get those things? Or choose not to? With broadband most apps will be ready before you can make fresh coffee, or maybe watch the Simpsons. Otherwise what? Send for a new DVD? Yes, core stuff + plenty of compatible goodies in a distro is a good idea, but problems are inevitable, and IMO it's more important to have a standard reliable way to solve problems than to have them "solved" on periodic monoliths DVDs that can't ever be problem free. > >If a system has N downloadable components that are supposedly >independent, there are 2**N combinations of them that anyone might >have installed. In reality the indepdence is never that complete, so >something can easily go wrong if you pick a combination that hasn't >been tested and debugged by someone, and there's no way to test more >than a few of the possibilities. So I'd rather that all N components >already be included with the OS so that the combination will have been >tested by the distro maintainers before the end user has to deal with You are asking a lot from these distro maintainers if you expect recent versions of everything, and for them to watch for new stuff to evaluate and include after researching compatibility problems. They aren't in the best position to do that. The author/s of the new stuff is/are. And if such authors had a standard stub module they could prepare, then distros could include those, and you would find version updates for those rather than trying to solve the integration problems yourself. And if there were still bugs, a new version would likely be posted here after some discussion. And then everyone could have an easy download of the new stub, and be able to go for coffee. I think if python.org had a trusted-software registry that could be a flat CSV text file of names, versions, urls, sizes, and md5 digests and maybe some trust level, then the stubs could access that for a standard way of finding components. Or course for a DVD distro, stubs could access the DVD rather than the internet for things at the DVD's version level. I realize this problem has been "solved" with various RPM and app-loading methods, but I think python could wrap its solution nicely. I don't think distutils and setup.py is easy enough to create (at least I have been somewhat frustrated in using it effectively), though it deals with a lot of what has to be done. >it. Hard drives and distro media (DVD) are big enough now that it's >quite reasonable for distros to include just about everything that >most users could want. Agreed for some "core" set. How shall we define what belongs in the "core?" ;-) Regards, Bengt Richter From marklists at mceahern.com Wed Jan 12 13:23:30 2005 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 12 Jan 2005 12:23:30 -0600 Subject: counting items In-Reply-To: References: Message-ID: <41E56B22.6020708@mceahern.com> It's me wrote: >Okay, I give up. > >What's the best way to count number of items in a list [that may contain lists]? > > a = [[1,2,4],4,5,[2,3]] def iterall(seq): for item in seq: try: for subitem in iterall(item): yield subitem except TypeError: yield item all = [x for x in iterall(a)] print len(all) From bokr at oz.net Mon Jan 24 23:52:12 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 25 Jan 2005 04:52:12 GMT Subject: Another scripting language implemented into Python itself? References: <1106624803.825442.73870@f14g2000cwb.googlegroups.com> Message-ID: <41f5cf0f.1750685172@news.oz.net> On 24 Jan 2005 19:46:43 -0800, "Carl Banks" wrote: [...] >> Imbed > >EMBED. > >This spelling error wouldn't bother me if I didn't work with people >whose own job title is embedded control engineer, yet who still >misspell it "imbedded." > wordnet seems to accept it as an alternative spelling (not too recent): [20:44] C:\pywk\sovm>wn imbed -over Overview of verb imbed The verb imbed has 1 sense (first 1 from tagged texts) 1. implant, engraft, embed, imbed, plant -- (to fix or set securely or deeply: "Kneeling, Cobb p lanted a sturdy knee in the small of his back,") funny that googling define:imbed gets nothing. Nor define:embed ?? I've had a number of misses in that kind of search. I wonder if it's temporarily broken (or maybe it hit a licensing snag with the various online dictionaries?) Regards, Bengt Richter From jlenton at gmail.com Wed Jan 12 12:05:14 2005 From: jlenton at gmail.com (John Lenton) Date: 12 Jan 2005 09:05:14 -0800 Subject: Iteration over two sequences In-Reply-To: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> Message-ID: <1105549514.563799.307030@z14g2000cwz.googlegroups.com> > Quite frequently, I find the need to iterate over two sequences at the > same time, and I have a bit of a hard time finding a way to do this in a > "pythonic" fashion. One example is a dot product. The straight-ahead > C-like way of doing it would be: > > def dotproduct(a, b): > psum = 0 > for i in range(len(a)): > psum += a[i]*b[i] > return psum for this particular example, the most pythonic way is to do nothing at all, or, if you must call it dotproduct, >>> from Numeric import dot as dotproduct From elbertlev at hotmail.com Mon Jan 31 15:03:49 2005 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 31 Jan 2005 12:03:49 -0800 Subject: py-xmlrpc postpone question Message-ID: <1107201829.674563.79000@z14g2000cwz.googlegroups.com> Hi! I'm trying to use py-xmlrpc. All works fine (and very fast) in one-threaded case, but I really have to serve many clients. As advertised, py-xmlrpc supports non-blocking calls (via select). When request is received the handler is called with proper parameters. As I understood from reading the source, if rpc call can't be executed immediately (or takes long time) respond can be postponed by raising postpone exception and when respond is ready, calling queueResponse() . I wanted to have a pool of worker threads listening on a queue. In the "lengthy command handlers", post data on the queue and raise postpone. Threads from the pool respond by calling queueResponse() when rpc is done. Server trace tells me that postpone was received, but client reacts as if socket was closed (got EOS while reading). I tryed to supress default error handling on the client side by returning from OnErr() xmlrpc.ONERR_KEEP_WORK, but this kills the interpreter! What am I doing wrong? From paul at prescod.net Mon Jan 31 21:27:04 2005 From: paul at prescod.net (Paul Prescod) Date: Mon, 31 Jan 2005 18:27:04 -0800 Subject: Vancouver Python/Zope/Plone: Creating OS X Cocoa Applications Using XML and Python Message-ID: <41FEE8F8.9000906@prescod.net> February 1, 2005 Creating OS X Cocoa Applications Using XML and Python, Dethe Elza This talk will cover the use of Renaissance and Python to develop programs for OS X, focussing on both rapid application development, and ease of maintenance. Renaissance is an XML dialect for describing Cocoa (or GNUstep) user interfaces, which can be used as an alternative to Apple's binary NIB format. It grew out of the GNUstep? project and is intended for use with Objective-C, but works seamlessly from Python with the PyObjC bridge. Hosted by ActiveState ("a division of Sophos") at 580 Granville St., Vancouver From me at privacy.net Fri Jan 28 16:19:36 2005 From: me at privacy.net (JanC) Date: 28 Jan 2005 21:19:36 GMT Subject: Where can I find sample "beginner" programs to study? References: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> Message-ID: Todd_Calhoun schreef: > I'm trying to learn Python (and programming), and I'm wondering if > there are any places where I can find small, simple programs to study. Try: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From tjreedy at udel.edu Sat Jan 1 04:51:27 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 1 Jan 2005 04:51:27 -0500 Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> Message-ID: "JanC" wrote in message news:Xns95D132B172343JanC at 213.118.32.224... > I don't know if gmane keeps formating of messages intact when posting? > That could be an alternative too... Reading posts via gmane with Outlook Express preserves leading spaces just fine. However, OE deletes tabs regardless of what newsgroup does. The funny thing is that typing a tab gets converted to 4 spaces. Terry J. Reedy From jason at tishler.net Mon Jan 17 16:27:48 2005 From: jason at tishler.net (Jason Tishler) Date: Mon, 17 Jan 2005 16:27:48 -0500 Subject: Cygwin Popen object In-Reply-To: <1105994485.770313.141910@f14g2000cwb.googlegroups.com> References: <1105994485.770313.141910@f14g2000cwb.googlegroups.com> Message-ID: <20050117212748.GB2388@tishler.net> On Mon, Jan 17, 2005 at 12:41:25PM -0800, christiancoder wrote: > Is anybody else getting the following error with the Popen object in > cygwin? The code works fine in windows and linux. > > File "d:\atg\personal\python\buildroot\util.py", line 100, in System > pipe = subprocess.Popen( command, shell=True, > stdout=subprocess.PIPE, stderr=subprocess.STDOUT, > universal_newlines=True ) > File "/usr/local/lib/python2.4/subprocess.py", line 554, in __init__ > errread, errwrite) > File "/usr/local/lib/python2.4/subprocess.py", line 914, in > _execute_child > self.pid = os.fork() > OSError: [Errno 11] Resource temporarily unavailable Try rebasing your Cygwin installation. See the README: /usr/share/doc/Cygwin/python-2.4.README for more information. Does it solve your problem? 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 invalidemail at aerojockey.com Fri Jan 14 11:02:19 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 14 Jan 2005 08:02:19 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: <34q69pF4dvkhqU1@individual.net> References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> <34q69pF4dvkhqU1@individual.net> Message-ID: <1105718539.916246.174950@z14g2000cwz.googlegroups.com> Tim Jarman wrote: > IANA French person, but I believe that Belgians are traditionally > regarded as stupid in French culture, so "Belgian logic" would be > similar to "Irish logic" for an English person. (Feel free to insert > your own cultural stereotypes as required. :) Ok. http://www.urbandictionary.com/define.php?term=belgian&r=f -- CARL BANKS From jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com Sun Jan 9 17:25:19 2005 From: jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com (Miklós P) Date: Sun, 9 Jan 2005 23:25:19 +0100 Subject: Guild of Python consultants? References: Message-ID: "Peter Hansen" wrote in message news:rtednbVd1tsF4XzcRVn-oQ at powergate.ca... > I also know of many people (myself included) who restrict the term > to those who have a deep expertise in one or more areas and who > look for projects where they can be brought in to apply that > expertise, usually by telling the customer what to do (or what > not to do any more, perhaps). This sort of work can be hourly, > or quite often daily or even at a fixed price (say, for specialized > "emergency" troubleshooting, or for a design task). > > (The second type will take on jobs that the former would take, > often grudgingly if work is scarce, while the former are rarely > qualified to take on the sort of work that interests the latter.) > > Which type do you mean? Well, I consider myself a consultant of the second kind. Using Python for maths/stats (often meaning decision support systems) or science related custom software is what I prefer to do .. But I also tend to enjoy "firefighting" web projects because they pay well and they are never boring.. rather on the contrary.. :-) ...and I second what you said in parenthesis. So my interest follows. Though one could surely have two divisions of a huge guild. :-)) Best, Mikl?s From steve at holdenweb.com Mon Jan 31 14:20:10 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 14:20:10 -0500 Subject: Relocatable binary installs.... In-Reply-To: References: <1107195180.462949.222980@z14g2000cwz.googlegroups.com> <41FE7F26.1090209@holdenweb.com> Message-ID: <41FE84EA.3030501@holdenweb.com> Fredrik Lundh wrote: > Steve Holden wrote: > > >>>>Is there a way to make a relocateable python binary... that is... a >>>>python installation that won't care where it is on the machine... and >>>>won't care if it gets put somewhere else besides / ? >>> >>> >>>the standard CPython interpreter is 100% "relocatable". If you think >>>it isn't, you have to be a bit more specific. >>> >> >>Is it possible that you are using "relocatable" in the standard sense of "code can be located >>anywhere in physical memory", where the OP is using the same term to mean "can live anywhere in >>the filestore"? > > > nope. > > >>I suspect the problem the OP is seeing is because the --prefix configuration parameter will cause >>an interpreter to look in a specific place for standard libraries. Clearly if you "relocate" the >>libraries to another directory entirely then an interpreter without any further nouse (and no >>symbolic links to help it) is going to crap out badly. > > > clearly? > > [fredrik at brain build] mv python2.3 /tmp > [fredrik at brain build] mkdir /tmp/lib > [fredrik at brain build] mv lib /tmp/lib/python2.3 > [fredrik at brain build] cd /tmp > [fredrik at brain tmp]$ ./python2.3 > >>>>import sys >>>>sys.prefix > > '/tmp' > >>>>sys.path > > ['', '/tmp/lib/python23.zip', '/tmp/lib/python2.3', ...] > > [fredrik at brain tmp]$ mkdir spam > [fredrik at brain tmp]$ mv python2.3 spam > [fredrik at brain tmp]$ mv lib spam > [fredrik at brain tmp]$ cd spam/ > [fredrik at brain spam]$ ./python2.3 > >>>>import sys >>>>sys.prefix > > '/tmp/spam' > >>>>sys.path > > ['', '/tmp/spam/lib/python23.zip', '/tmp/spam/lib/python2.3', ...] > > > [fredrik at brain spam]$ mkdir bin > [fredrik at brain spam]$ mv python2.3 bin > [fredrik at brain spam]$ bin/python2.3 > >>>>import sys >>>>sys.prefix > > '/tmp/spam' > > > [fredrik at brain spam]$ cd bin > [fredrik at brain bin]$ ./python2.3 > >>>>import sys >>>>sys.prefix > > '/tmp/spam' > > [fredrik at brain fredrik]$ export PATH=/tmp/spam/bin:$PATH > [fredrik at brain bin]$ cd > [fredrik at brain fredrik]$ python2.3 > >>>>import sys >>>>sys.prefix > > '/tmp/spam' > > > and so on... > Well, OK, maybe it's not quite as clear as I thought :-) 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 bokr at oz.net Mon Jan 24 15:35:09 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 24 Jan 2005 20:35:09 GMT Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) References: <41f325b5.1576259210@news.oz.net> <6I2dnYLoXdcTmGncRVn-vw@comcast.com> <41f490e8.1669238027@news.oz.net> Message-ID: <41f5568c.1719834331@news.oz.net> On Mon, 24 Jan 2005 00:31:17 -0700, Steven Bethard wrote: >Bengt Richter wrote: >> So, e.g., for >> >> >>> presets = dict(a=1, b=2, deftime=__import__('time').ctime()) >> >> in the decorator args, the next version will act as if the decorated >> function had the source code >> >> >>> print '%s = __frompresets__' % ', '.join(sorted(presets)) >> a, b, deftime = __frompresets__ >> >> for the current version, except that it will be hidden. > >Cool! Keep us posted. I assume you'll put this into the Cookbook? > Not ready for prime time, I guess, but I made a module that does presets and also adjusts parameters and count to do currying without nested function calling in the curried function. >>> from presets import presets, curry >>> @presets(verbose=True, a=1, b=2, deftime=__import__('time').ctime()) ... def foo(): ... print (a, b) ... print deftime ... presets: -- "name(?)" means name may be unused a = 1 b = 2 deftime = 'Mon Jan 24 12:16:07 2005' >>> foo() (1, 2) Mon Jan 24 12:16:07 2005 >>> @curry(verbose=True, y=444) ... def bar(x=3, y=4): ... return x*y ... presets: -- "name(?)" means name may be unused y = 444 >>> bar(2) 888 >>> bar(2, 3) Traceback (most recent call last): File "", line 1, in ? TypeError: bar() takes at most 1 argument (2 given) >>> bar() 1332 >>> import dis >>> dis.dis(bar) 1 0 LOAD_CONST 1 (444) 3 STORE_FAST 1 (y) 3 6 LOAD_FAST 0 (x) 9 LOAD_FAST 1 (y) 12 BINARY_MULTIPLY 13 RETURN_VALUE >>> dis.dis(foo) 1 0 LOAD_CONST 1 ((1, 2, 'Mon Jan 24 12:16:07 2005')) 3 UNPACK_SEQUENCE 3 6 STORE_FAST 0 (a) 9 STORE_FAST 1 (b) 12 STORE_FAST 2 (deftime) 3 15 LOAD_FAST 0 (a) 18 LOAD_FAST 1 (b) 21 BUILD_TUPLE 2 24 PRINT_ITEM 25 PRINT_NEWLINE 4 26 LOAD_FAST 2 (deftime) 29 PRINT_ITEM 30 PRINT_NEWLINE 31 LOAD_CONST 0 (None) 34 RETURN_VALUE Now I have to see whether I can optimize the result with Raymond's make_constants as two decorators in a row... (pre without keyword args is an alias for Raymond's make_constants, just handy for the moment) >>> from pre import pre >>> @pre(verbose=True) ... @presets(verbose=True, a=1, b=2, deftime=__import__('time').ctime()) ... def foo(): ... print (a, b) ... print deftime ... print __name__ ... presets: -- "name(?)" means name may be unused a = 1 b = 2 deftime = 'Mon Jan 24 12:29:21 2005' __name__ --> __main__ >>> foo() (1, 2) Mon Jan 24 12:29:21 2005 __main__ >>> dis.dis(foo) 1 0 LOAD_CONST 1 ((1, 2, 'Mon Jan 24 12:29:21 2005')) 3 UNPACK_SEQUENCE 3 6 STORE_FAST 0 (a) 9 STORE_FAST 1 (b) 12 STORE_FAST 2 (deftime) 3 15 LOAD_FAST 0 (a) 18 LOAD_FAST 1 (b) 21 BUILD_TUPLE 2 24 PRINT_ITEM 25 PRINT_NEWLINE 4 26 LOAD_FAST 2 (deftime) 29 PRINT_ITEM 30 PRINT_NEWLINE 5 31 LOAD_CONST 2 ('__main__') 34 PRINT_ITEM 35 PRINT_NEWLINE 36 LOAD_CONST 0 (None) 39 RETURN_VALUE Regards, Bengt Richter From steve at holdenweb.com Sun Jan 9 17:19:31 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 17:19:31 -0500 Subject: Python serial data aquisition In-Reply-To: References: Message-ID: Flavio codeco coelho wrote: > Hi, > > I am using pyserial to acquire data from an A/D converter plugged to > my serial port. > > my hardware represents analog voltages as 12bit numbers. So, according > to the manufacturer, this number will be stored in two bytes like > this; > |-------------bits(1-8)-----------| > Byte1: x x x n1 n2 n3 n4 n5 > Byte2: x n6 n7 n8 n9 n10 n11 n12 > > where x is some other information, and nx are the digits of my number. > > My problem is to how to recover my reading from these bytes, since > pyserial gives me a character (string) from each byte... I dont know > how to throw away the unneeded bits and concatenate the remaining > bits to form a number... > > > Fl?vio Code?o Coelho Try something like (here I'm assuming that n12 is the least-significant bit) (untested): ((ord(byte1) & 31) << 7 ) + (ord(byte2) & 127) This takes the rightmost five bits from the first byte's integer value, shifts them up seven bits, and then adds the rightmost seven bits of the second byte's integer value. 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 aaronwmail-usenet at yahoo.com Thu Jan 27 09:19:22 2005 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 27 Jan 2005 06:19:22 -0800 Subject: On benchmarks, heaps, priority queues References: Message-ID: <1106835562.598569.211370@c13g2000cwb.googlegroups.com> me> PQPython23 - the Lib implementation me> PQ0 - my insertion sort based variant me> PQueue - my "heap" based variant me> (like PQPython23, but different). Tim D: > First of all, you should be running these benchmarks using Python 2.4. > heapq is considerably faster there ... (Raymond Hettinger rewrote it all > in C). > http://www.python.org/2.4/highlights.html > Tim Delaney WHOOPS. Okay after getting past my initial embarassment I tried this, and it turns out it doesn't make much of a difference. In particular PQ0 is still always better if you intersperse many deletes with inserts or in all cases of size <10000. Of course other machines will probably have different characteristics (and yes my py24 contains the _heapq extension module). The nasty behavior of PQ0 for insertBench at >100000 I think has to do with large list reallocation. Hmmm. This makes me wonder if my bplustree implementation(s) are faster than the bsddb modules too... -- Aaron Watters === SOMETHING WENT WRONG IN AIRLINE CRASH, EXPERT SAYS -- a "real life headline" (that'll be $50,000, please) ENCLOSURE: Python 2.4 run of http://xsdb.sourceforge.net/bench/pq3.py on my machine. ======================= BENCHMARKS FOR 1000 insertBench __main__.PQPython23 on 1000 elapsed 0.0199999809265 got 1000 __main__.PQ0 on 1000 elapsed 0.00999999046326 got 1000 __main__.PQueue on 1000 elapsed 0.0300002098083 got 1000 mixBench __main__.PQPython23 on 1000 elapsed 0.0 got 502 __main__.PQ0 on 1000 elapsed 0.00999999046326 got 502 __main__.PQueue on 1000 elapsed 0.0 got 502 BENCHMARKS FOR 10000 insertBench __main__.PQPython23 on 10000 elapsed 0.260999917984 got 10000 __main__.PQ0 on 10000 elapsed 0.210000038147 got 10000 __main__.PQueue on 10000 elapsed 0.359999895096 got 10000 mixBench __main__.PQPython23 on 10000 elapsed 0.0700001716614 got 5003 __main__.PQ0 on 10000 elapsed 0.050999879837 got 5003 __main__.PQueue on 10000 elapsed 0.0699999332428 got 5003 BENCHMARKS FOR 100000 insertBench __main__.PQPython23 on 100000 elapsed 3.26499986649 got 100000 __main__.PQ0 on 100000 elapsed 7.88100004196 got 100000 __main__.PQueue on 100000 elapsed 4.81699991226 got 100000 mixBench __main__.PQPython23 on 100000 elapsed 0.65099978447 got 50000 __main__.PQ0 on 100000 elapsed 0.461000204086 got 50000 __main__.PQueue on 100000 elapsed 0.661000013351 got 50000 BENCHMARKS FOR 200000 insertBench __main__.PQPython23 on 200000 elapsed 6.99000000954 got 200000 __main__.PQ0 on 200000 elapsed 28.5010001659 got 200000 __main__.PQueue on 200000 elapsed 10.3849999905 got 200000 mixBench __main__.PQPython23 on 200000 elapsed 1.29099988937 got 100001 __main__.PQ0 on 200000 elapsed 0.922000169754 got 100001 __main__.PQueue on 200000 elapsed 1.34200000763 got 100001 BENCHMARKS FOR 300000 insertBench __main__.PQPython23 on 300000 elapsed 11.6970000267 got 300000 __main__.PQ0 on 300000 elapsed 70.3009998798 got 300000 __main__.PQueue on 300000 elapsed 16.8840000629 got 300000 mixBench __main__.PQPython23 on 300000 elapsed 1.93300008774 got 150000 __main__.PQ0 on 300000 elapsed 1.39199995995 got 150000 __main__.PQueue on 300000 elapsed 1.96300005913 got 150000 BENCHMARKS FOR 400000 insertBench __main__.PQPython23 on 400000 elapsed 15.5419998169 got 400000 __main__.PQ0 on 400000 elapsed 127.253000021 got 400000 __main__.PQueue on 400000 elapsed 23.0629999638 got 400000 mixBench __main__.PQPython23 on 400000 elapsed 2.64399981499 got 200000 __main__.PQ0 on 400000 elapsed 1.95300006866 got 200000 __main__.PQueue on 400000 elapsed 2.73399996758 got 200000 BENCHMARKS FOR 500000 insertBench __main__.PQPython23 on 500000 elapsed 20.8800001144 got 500000 __main__.PQ0 on 500000 elapsed 246.954999924 got 500000 __main__.PQueue on 500000 elapsed 35.9609999657 got 500000 mixBench __main__.PQPython23 on 500000 elapsed 3.55599999428 got 250000 __main__.PQ0 on 500000 elapsed 2.48300004005 got 250000 __main__.PQueue on 500000 elapsed 3.48500013351 got 250000 BENCHMARKS FOR 1000000 insertBench __main__.PQPython23 on 1000000 elapsed 44.6940000057 got 1000000 __main__.PQ0 on 1000000 elapsed 1400.5940001 got 1000000 __main__.PQueue on 1000000 elapsed 70.6619999409 got 1000000 mixBench __main__.PQPython23 on 1000000 elapsed 6.63000011444 got 500001 __main__.PQ0 on 1000000 elapsed 4.73600006104 got 500001 __main__.PQueue on 1000000 elapsed 6.82999992371 got 500001 From cpl.19.ghum at spamgourmet.com Thu Jan 27 04:07:09 2005 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Thu, 27 Jan 2005 09:07:09 +0000 (UTC) Subject: py2exe problem References: <41f7213c$0$2343$a1866201@visi.com> Message-ID: Thomas, > Would the above (include all encodings stuff by default) be a good > solution, or do you have other ideas? I assume a good solution would involve switching pythons default from "ASCII" to "UNICODE" :) But ... as far as py2exe is concerned, yeah, I think it would be helpfull to include all encoding by default (undefaultable, of course), or at least provide in the very very first simple setup.py example the include encodings.* stuff. Harald Armin From mcfletch at rogers.com Sat Jan 22 13:44:06 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 22 Jan 2005 13:44:06 -0500 Subject: Class introspection and dynamically determining function arguments In-Reply-To: <41f2212f.1509565800@news.oz.net> References: <41f18d10.1471646806@news.oz.net> <41f2212f.1509565800@news.oz.net> Message-ID: <41F29EF6.7030909@rogers.com> Bengt Richter wrote: >On Fri, 21 Jan 2005 20:23:58 -0500, "Mike C. Fletcher" wrote: > > > >>>On Thu, 20 Jan 2005 11:24:12 -0000, "Mark English" wrote: >>> >>> ... >Does the BasicProperty base class effectively register itself as an observer >of subclass properties and automatically update widgets etc., a la Delphi >data-driven visual components? I've thought of doing a light-weight form >extension class that would use a text (maybe CSV) definition to control >contruction, and easy programmatic manipulation by python of the definition >parameters, like a stripped-down version of the text view of Delphi forms. >It could also be done via Tkinter, to prototype it. It would be interesting >to allow dragging widgets and edges around in Tkinter and round-trip the parameter >changes automatically into the text representation. A little (well, ok, a fair amount ;-) >further and you'd have a drag-n-drop GUI design tool. But don't hold your breath ;-) > > BasicProperty itself doesn't register as an observable/observer, BasicProperty is the lowest-level of the software stack, so it allows you to override and provide notification (e.g. using PyDispatcher) on property-setting. ConflictSolver (old project to create a room scheduler) used that to do automatic updating of widgets in the wxPython UI based on Model changes (though I don't remember if it was per-property or per-object). My goal for the wxoo project was to provide hooks in the wxPython GUI designers for dropping in property sheets and/or property-aware controls such that you would have the equivalent of "data aware" controls in VB or Access (keeping in mind that BasicProperty properties can also represent fields in database rows). Aside: The VRML97 field class in OpenGLContext does notifications for every set (using PyDispatcher), btw. It's a little more limited in its scope (focus on 3D data-types), but the effect is what allows the scenegraph to cache and then rebuild its internal rendering structures with very low overhead. ... >>Anyway, if you aren't interested in BasicProperty for this task; another >>project on which I work, PyDispatcher provides fairly robust mechanism >>(called robustApply) for providing a set of possible arguments and using >>inspect to pick out which names match the parameters for a function in >>order to pass them in to the function/method/callable object. That >>said, doing this for __init__'s with attribute values from an object's >>dictionary doesn't really seem like the proper way to approach the problem. >> >> >Sounds like a workaround for parameter passing that maybe should have been >keyword-based? > > Not as such, that is, not a workaround, and it shouldn't be keyword based ;) . The problem with using keyword-based passing is that every method needs to be written with this awareness of the keyword-handling structures. You spread pointless implementation details throughout your codebase. PyDispatcher lets you write very natural functions for dealing with events without having every function use **named parameters. I've now written quite a few such systems, and I'm currently balanced between two approaches; that taken in PyDispatcher (define only natural parameters, have the system figure out how to deliver them to you), and that taken in OpenGLContext (define an event-class hierarchy which encapsulates all information about the events). The PyDispatcher approach is nice in that it makes simple things very simple. You want access to the "lastValue" parameter in the "environment" of the event and nothing else, you define your function like so: def handler( lastValue ): print 'got last value', lastValue which works very nicely when you're early in the development of a system, or are linking multiple systems. There's no need to do all sorts of extra work defining event hierarchies, you can often leave given handlers entirely alone during refactoring if they aren't dealing with the changed properties in the event-environment. The OpenGLContext approach is more appropriate when you have a large system (such as OpenGLContext), where defining an event class is a trivial task compared to the total system expenditure. It allows for such things as putting methods on the event objects to make debugging easy, and providing common functionality. It starts to show it's worth when you start needing to reason about the phenomena of events themselves, rather than just about the phenomena the events represent (e.g. when you need to cache, delay, or reorder events). The named argument passing approach has the disadvantage that every function must be written with knowledge of that use of named arguments: def handler( lastValue, **named ): print 'got last value', lastValue when using such systems in the past I've often wound up with errors deep in an application where some seldom-called callback didn't have a **named parameter, so the system would abort (well, log an error) trying to call it. Is it a huge overhead? No. But its unnecessary if you've got a tool that takes care of that "implementation-level" detail for you. Compared to robustApply, the difference is pretty minimal. If you define a **named parameter, for instance, you will get the remainder of the robustApply environment passed in. In another lifetime, you could imagine these systems being written as wrappers that added a nested scope around the definition of the function such that the scope forwarded unresolved name references to the environment of the event (non-lexical scoping), but that would lack the explicitness of passing in the arguments from the environment and would, I suppose be evil in a quite non-trivial way. Peace, and have fun, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From itsme at yahoo.com Wed Jan 5 17:29:31 2005 From: itsme at yahoo.com (It's me) Date: Wed, 05 Jan 2005 22:29:31 GMT Subject: Python 2.4 on Windows XP References: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> <10toje56oiebq24@corp.supernews.com> <10ton02dur41v0b@corp.supernews.com> Message-ID: Thanks, Jeff. That works. "Jeff Shannon" wrote in message news:10ton02dur41v0b at corp.supernews.com... > It's me wrote: > > > In my case, there is *no* error message of any kind. When I run pythonw.exe > > from the python23 directory, the screen blinked slightly and goes back to > > the command prompt. > > Right -- pythonw.exe is a console-less interpreter. Having no > console, it doesn't have an interactive mode, and since you didn't > give it a script to run, it simply started, found nothing to do, and > then terminated itself. > > You need to run idle.pyw, *not* pythonw.exe. The idle.pyw script runs > inside the pythonw.exe interpreter, but the latter can't do anything > without instructions. > > Jeff Shannon > Technician/Programmer > Credit International > From miki.tebeka at zoran.com Sun Jan 16 06:44:27 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 16 Jan 2005 13:44:27 +0200 Subject: video analysis with python In-Reply-To: References: Message-ID: <20050116114407.GE3276@zoran.com> Hello Ashot, > I need to write a video analysis tool which extracts statistics from > microsocope video. Essentially what I need is to translate the video data > into numerical matrices. I have been using Python for the past 1.5 years > anytime I could for absolutely everything, because it has every library > imaginable... Alas, I can not find a library for decoding video/using > codecs. The only solution I have been able to come up with is to create > an image sequence and load those in with PIL, however this is not really > feasible as the images are too large (nor is it proffessional). > > Is there a library or project that I have missed, or is there a way > to incorporate something like vfw.lib directly? If there isn't I think > this would be a pretty large whole in Python's arsenal. Thanks in advance > for any help. 1. There is PyMedia (http://pymedia.org/) 2. Maybe you can use the code from VLC (http://www.videolan.org/vlc/) (using SWIG/PyBoost/Pyrex ...) HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From jzgoda at gazeta.usun.pl Thu Jan 20 15:10:35 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 20 Jan 2005 21:10:35 +0100 Subject: ElementTree cannot parse UTF-8 Unicode? In-Reply-To: <1106233137.588111.216480@z14g2000cwz.googlegroups.com> References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106230846.455765.7310@c13g2000cwb.googlegroups.com> <1106233137.588111.216480@z14g2000cwz.googlegroups.com> Message-ID: Erik Bethke wrote: > So why are there non-UNICODE versions of wxPython??? To save memory or > something??? Win95, Win98, WinME have problems with unicode. GTK1 does not support unicode at all. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From steve at holdenweb.com Mon Jan 17 10:33:07 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 10:33:07 -0500 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Antoon Pardon wrote: > Op 2005-01-17, Steve Holden schreef : > >>Antoon Pardon wrote: >> >> >>>I don't see a big difference between these principles >>>and the hash key principle, so in the end may be we >>>should just stick with the more general principle: >>> >>> Don't use mutables! >>> >>> >>>and be done with it. >>> >> >>http://redwing.hutman.net/~mreed/warriorshtm/tirelessrebutter.htm >> >>regards >> Steve > > > I you want to play it like this > > http://redwing.hutman.net/~mreed/warriorshtm/crybaby.htm > Hey, I'm not crying, or trying to play it any particular way. It's a free Internet, and you are (more than) welcome to your opinions. Personally I'd say I'm actually more of a combination of http://redwing.hutman.net/~mreed/warriorshtm/diplomat.htm and http://redwing.hutman.net/~mreed/warriorshtm/evilclown.htm, with added touches of http://redwing.hutman.net/~mreed/warriorshtm/garble.htm and possibly http://redwing.hutman.net/~mreed/warriorshtm/toxicgranny.htm Whereas I also detect touches of http://redwing.hutman.net/~mreed/warriorshtm/ferouscranus.htm in your posts. It must be nice to *never* be wrong :-). Your resemblance to http://redwing.hutman.net/~mreed/warriorshtm/filibuster.htm, however, makes me wish you could be right rather more succinctly. Mostly, though, I was trying to say that I found your nitpicking insistence on terminological exactitude, even when giving advice to those new to the language, both inappropriate and tedious in the extreme. Have a nice day :-) 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 Serge.Orlov at gmail.com Fri Jan 14 17:45:49 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: Fri, 14 Jan 2005 22:45:49 +0000 (UTC) Subject: oddities in the datetime module References: <41e79a1a$0$264$edfadb0f@dread12.news.tele.dk> <41e84175$0$258$edfadb0f@dread12.news.tele.dk> Message-ID: Max M wrote: > Serge Orlov wrote: >> Max M wrote: > >> Yes, you did. datetime.timetuple is those who want *time module* >> format, you should use datetime.data, datetime.time, datetime.year >> and so on... As they say, if the only tool you have is timetuple, everything >> looks like tuple Try this: >> >>>>> dt = datetime(2005, 1, 1, 12, 0, 0) >>>>> dt.date() >> >> datetime.date(2005, 1, 1) > > This doesn't solve it. I don't think you understand my issue. I understand, but I don't think it's something that should be solved. Especially date(*dt.timetuple()[:3]) > class my_datetime(datetime): > > def __add__(self, other): > result = datetime.__add__(self, other) > return my_datetime(result.timetuple()[:6]) > What about: def __add__(self, other): result = datetime.__add__(self, other) return my_datetime.fromdatetime(result) Serge. From jjl at pobox.com Sat Jan 29 07:07:19 2005 From: jjl at pobox.com (John J. Lee) Date: 29 Jan 2005 12:07:19 +0000 Subject: cookielib and urllib2: thread-safe? References: Message-ID: <87vf9gv3pk.fsf@pobox.com> Alex Hunsley writes: > I'm writing a test script in python for pulling web pages from a web > server using urllib2 and cookielib. Since the main thing I am testing > is what happens when concurrent requests are made to the web server, I > need to make several requests concurrently, which I'll do from > different threads in my python script. So the important question is: > are cookielib and urllib2 thread safe? Are there any precautions that > apply to using these libs in a multi-threaded context? urllib2: For HTTP, yes, AFAIK. For other protocols, eg. FTP, perhaps not. cookielib: No. It's currently thread-broken, simply because I've never had reason to do threaded stuff with it. There is thread synchronization code in there, but I have little doubt that it's broken, because it's untested (I should have removed the synchronization code entirely, in fact, since nobody volunteered to test & fix before release: unfortunately the first beta caught me by surprise...). I won't be making it threadsafe, so don't wait for me to do it. I'm happy to help others do so. Nothing especially hard for somebody with plenty of thread experience to do, AFAIK. I had thought part of a patch had gone in which stated this thread-unsafety very prominently in the cookielib module docs, but it seems that never happened, or at least not in time for 2.4.0 -- eek! John From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Jan 13 07:26:23 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Thu, 13 Jan 2005 13:26:23 +0100 Subject: Free python server. References: Message-ID: <41e66aa0$0$25801$8fcfb975@news.wanadoo.fr> Hi ! Server, web ? Files server ? Web-services server ? XML-RPC server ? Mail-server ? Newsgroups server ? SGBD server ? Object server ? Persistance server ? Restaurant server ? or ALL ? From http Fri Jan 14 01:19:17 2005 From: http (Paul Rubin) Date: 13 Jan 2005 22:19:17 -0800 Subject: Pickled text file causing ValueError (dos/unix issue) References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> Message-ID: <7xk6qga5y2.fsf@ruckus.brouhaha.com> Open the file on windows for writing with "wb" mode, the b is for binary. From dave.benjamin at gmail.com Thu Jan 27 11:30:41 2005 From: dave.benjamin at gmail.com (Dave Benjamin) Date: Thu, 27 Jan 2005 09:30:41 -0700 Subject: python without OO In-Reply-To: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: Davor wrote: > Is it possible to write purely procedural code in Python, or the OO > constructs in both language and supporting libraries have got so > embedded that it's impossible to avoid them? Also, is anyone aware of > any scripting language that could be considered as "Python minus OO > stuff"? (As you can see I'm completely new to Python and initially > believed it's a nice&simple scripting language before seeing all this > OO stuff that was added in over time) Many people have answered your question already, but I thought I would share my opinion as well, since I think I understand where you are coming from. What attracted me to Python was not OO at all but the fact that it was somewhat similar to PHP (which I was using heavily at the time) but allowed me to encode certain higher-order programming techniques that PHP simply could not express. In short, I had become interested in functional programming after reading David Mertz's "Charming Python" tutorials, and after x attempts at trying to port the ideas to PHP, I finally gave up in frustration and started learning Python. At the time, I was decidedly anti-OO. I grew up around a very liberal, punk-rock, nonconformist culture, and the amount of hype around OO made it too easy to hate (and, I suppose, it still does). PHP at the time was 90% procedural; the prevaling attitude (which seems to have changed with the advent of PHP5) was that procedural code is all you need to solve most problems. With web scripting, it kind of makes sense, because (IMHO) objects really don't have much value unless you can hold onto them long enough for them to be useful, and many web scripts just pipe data from one place to another. Packing the data into objects is kind of like putting your possessions into boxes so that you can move them from one room to another and immediately unpack. So, I guess you could say, I learned Python in spite of its rich support for OO. =) It wasn't until I had to implement a large (to me), complex, graphical user interface, that I finally had to get off of my soapbox and realize that I had no better way to create sophisticated GUIs than OO. There are surely non-OO ways to build fancy GUIs, like functional-reactive programming, but a) I don't understand them, and b) I had to get my project done, and used the tools I had and the techniques I knew. At that time, I started learning about Smalltalk and Alan Kay's emphasis on the "messaging" aspect of OO, and it started making a lot more sense. One of the most difficult tasks sometimes is getting various parts of the screen to update when the user changes a field or clicks a button--in a way that is manageable and doesn't devolve into spaghetti. Aside from GUIs, however, I am rarely confronted with a task where I *need* OO. As a method for encoding abstract data types, it works, but it seems like more fashion than substance. As many have pointed out, the difference between "method(obj, args)" and "obj.method(args)" is subtle, and often inconsequential. In Python, you can program with just modules and functions/procedures, and never bother with the fact that you are using objects. Sure, a module is an object, and so is a procedure, but it's not all up in your face like, say, Java's arcane restriction that everything belong to some class. It has been said of Perl programmers that they often dislike abstraction. Sometimes, I really sympathize with this viewpoint. I hate having to use a class that offers no value to the problem whatsoever, merely because an API is hard-wired to use instances of that class. No abstraction can often be better than a bad abstraction, and when it comes to debugging, the last thing you want is a bunch of black boxes. These days, I do use classes and objects in Python, but mainly as a code organization technique, and only when I actually want my code organized that way. I tend to start with the problem at hand, building procedures to remove redundancy and keep my code small and simple. If I start noticing that a lot of procedures revolve around a particular data structure, I refactor them into a class. This way, I avoid creating abstractions that don't fit. It's much more mechanical than any feigned attempt at "modeling the real world". I think that functional programming (FP) is a very powerful methodology that can solve a lot of the same problems as OO, and does some things a lot better. FP and OO can live in harmony to some extent, but there are some places where they contradict each other. For instance, FP offers a mind-blowingly powerful tool called pattern matching, which is like a switch/case statement on steroids. OO dogma insists that this "violates encapsulation", and that any form of switch/case is evil... replace conditional with polymorphism... replace conditional with polymorphism... replace conditional with polymorphism... repl On the other hand, implementing something as seemingly simple as a "__str__" method in functional languages can be surprisingly non-trivial. The lesson to be learned here is that each methodology (including strctures/procedural) has its strong points and weak points, and there are always tradeoffs to be made. OO's biggest strong point is that a lot of people grok it, so it's a fashionable and friendly user interface for a programmer. Python in particular emphasizes this point with its no-nonsense, lightweight approach to defining classes and using objects. However, and this really the main point I wanted to make: *no* paradigm is sufficient to solve any interesting problem. I have gotten sucked into coutless language and paradigm pissing matches only to go back to my desk and try to finish a project I'm working on and realize that (gasp!) programming is still hard. It never stopped being hard! And sometimes the methodologies just create additional work (cf. jwz's comment on regular expressions: "now you have two problems"). The best way to crack through tough problems is to learn as many methods and techniques as you can, and develop an intuition for "the right tool for the job". What matters most is that you solve the problem at hand, in a way that people can hopefully understand and maintain later. Good luck, Dave From klachemin at comcast.net Sat Jan 22 01:08:59 2005 From: klachemin at comcast.net (Kamilche) Date: 21 Jan 2005 22:08:59 -0800 Subject: Reload Tricks In-Reply-To: References: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> Message-ID: <1106374139.853129.73310@z14g2000cwz.googlegroups.com> Would it be possible to just not copy any attribute that starts and ends with '__'? Or are there some important attributes being copied? From merkosh at hadiko.de Fri Jan 28 07:30:20 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 28 Jan 2005 13:30:20 +0100 Subject: example needed: sip + Qt Message-ID: Hi, can someone provide me with a running example for subclassing QWidget (or something similarly simple) in C++ and then creating SIP (4.x+) bindings for in for Python (2.3+)? I am looking for something I can start of with and work my way towards more complicated stuff (with Qt). The QLabel example in the SIP reference manual yields syntax errors for me. Same with: http://www.pegasus.rutgers.edu/~elflord/unix/siptute/subclass_example.tgz thanks, Uwe From ehenriqu at gmail.com Thu Jan 20 10:52:27 2005 From: ehenriqu at gmail.com (Eduardo Henriquez A.) Date: Thu, 20 Jan 2005 11:52:27 -0400 Subject: Python-list Digest, Vol 16, Issue 324 In-Reply-To: <20050120144143.7F2DB1E4011@bag.python.org> References: <20050120144143.7F2DB1E4011@bag.python.org> Message-ID: <810c6a5805012007521ea04edf@mail.gmail.com> On Thu, 20 Jan 2005 15:41:43 +0100 (CET), python-list-request at python.org wrote: > Send Python-list mailing list submissions to > python-list at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > python-list-request at python.org > > You can reach the person managing the list at > python-list-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." > > > Today's Topics: > > 1. Re: Class introspection and dynamically determining function > arguments (Diez B. Roggisch) > 2. Re: xml parsing escape characters (Luis P. Mendes) > 3. Problem in importing MySQLdb (Gurpreet Sachdeva) > 4. Re: Problem in importing MySQLdb (deelan) > 5. Re: mod_python friendly isps in europe (Daniel Bowett) > 6. Re: xml parsing escape characters (Kent Johnson) > 7. Re: Zen of Python (Steve Holden) > 8. Re: Freezing a mutable (was Re: lambda) (Antoon Pardon) > 9. Re: iteritems() and enumerate() (Steve Holden) > 10. Re: ElementTree cannot parse UTF-8 Unicode? (Erik Bethke) > 11. Re: ElementTree cannot parse UTF-8 Unicode? (Fredrik Lundh) > > > > ---------- Forwarded message ---------- > From: "Diez B. Roggisch" > To: python-list at python.org > Date: Thu, 20 Jan 2005 13:50:37 +0100 > Subject: Re: Class introspection and dynamically determining function arguments > Nick Coghlan wrote: > > > > If this only has to work for classes created for the purpose (rather than > > for an arbitrary class): > > > > Certainly a step into the direction I meant - but still missing type > declarations. And that's what at least I'd like to see - as otherwise you > don't know what kind of editing widget to use for a property. > -- > Regards, > > Diez B. Roggisch > > > > ---------- Forwarded message ---------- > From: "Luis P. Mendes" > To: python-list at python.org > Date: Thu, 20 Jan 2005 13:05:59 +0000 > Subject: Re: xml parsing escape characters > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > this is the xml document: > > > <DataSet> > ~ <Order> > ~ <Customer>439</Customer> > (... others ...) > ~ </Order> > </DataSet> > > When I do: > > print xmldoc.toxml() > > it prints: > > <DataSet> > ~ <Order> > ~ <Customer>439</Customer> > > ~ </Order> > </DataSet> > > __________________________________________________________ > with: stringNode = xmldoc.childNodes[0] > print stringNode.toxml() > I get: > <DataSet> > ~ <Order> > ~ <Customer>439</Customer> > > ~ </Order> > </DataSet> > ______________________________________________________________________ > > with: DataSetNode = stringNode.childNodes[0] > print DataSetNode.toxml() > > I get: > > <DataSet> > ~ <Order> > ~ <Customer>439</Customer> > > ~ </Order> > </DataSet> > _______________________________________________________________- > > so far so good, but when I issue the command: > > print DataSetNode.childNodes[0] > > I get: > IndexError: tuple index out of range > > Why the error, and why does it return a tuple? > Why doesn't it return: > <Order> > <Customer>439</Customer> > > </Order> > ?? > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.2.4 (GNU/Linux) > Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org > > iD8DBQFB76y3Hn4UHCY8rB8RAvQsAKCFD/hps8ybQli8HAs3iSCvRjwqjACfS/12 > 5gctpB91S5cy299e/TVLGQk= > =XR2a > -----END PGP SIGNATURE----- > > > > ---------- Forwarded message ---------- > From: Gurpreet Sachdeva > To: python-list at python.org > Date: Thu, 20 Jan 2005 18:53:06 +0530 > Subject: Problem in importing MySQLdb > I am using Mysql version 5.0.2-alpha on RedHat 9.0 (python2.2) > > When I try to import MySQldb > > I get: > Python 2.2.2 (#1, Feb 24 2003, 19:13:11) > [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import MySQLdb > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/site-packages/MySQLdb/__init__.py", line 27, in ? > import _mysql > ImportError: /usr/lib/libmysqlclient.so.10: symbol errno, version > GLIBC_2.0 not defined in file libc.so.6 with link time reference > > Is there any problem in library files?? Do I need to install anything > I have installed MySQL-shared-3.23.54a-1.i386.rpm, > MySQL-devel-5.0.2-0.i386.rpm, MySQL-client-5.0.2-0.i386.rpm, > MySQL-server-5.0.2-0.i386.rpm > > Please help, > Garry > > > > ---------- Forwarded message ---------- > From: deelan > To: python-list at python.org > Date: Thu, 20 Jan 2005 14:43:01 +0100 > Subject: Re: Problem in importing MySQLdb > Gurpreet Sachdeva wrote: > > I am using Mysql version 5.0.2-alpha on RedHat 9.0 (python2.2) > > > > When I try to import MySQldb > > i' not completely sure mysqldb works with mysql 5.0 and its > bundled client libraries. > > to be more precise: > > '' MySQL-5.0 and newer are not currently supported, > but might work.'' > > from: > > > > Is there any problem in library files?? Do I need to install anything > > I have installed MySQL-shared-3.23.54a-1.i386.rpm, > > MySQL-devel-5.0.2-0.i386.rpm, MySQL-client-5.0.2-0.i386.rpm, > > MySQL-server-5.0.2-0.i386.rpm > > are u sure you have compiled mysqldb against 5.0 > client libs? > > you may want to post on the mysqldb forum of ask > for help there: > > > > HTH, > deelan > > -- > @prefix foaf: . > <#me> a foaf:Person ; foaf:nick "deelan" ; > foaf:weblog . > > > > ---------- Forwarded message ---------- > From: Daniel Bowett > To: python-list at python.org > Date: Thu, 20 Jan 2005 08:48:37 +0000 > Subject: Re: mod_python friendly isps in europe > paulo.jpinto at gmail.com wrote: > > Hello everybody > > > > I'm thinking about improving my web site scripts > > and would like to use Python instead of PHP/Perl. > > > > Does anyone know of mod_python friendly ISPs in > > europe? With prices around 10? ? > > > > Thanks in advance, > > Paulo > > > > I would doubt you will find any commercial python ISP's out there. If > you do could you post them here? > > > > ---------- Forwarded message ---------- > From: Kent Johnson > To: python-list at python.org > Date: Thu, 20 Jan 2005 09:01:01 -0500 > Subject: Re: xml parsing escape characters > Luis P. Mendes wrote: > > -----BEGIN PGP SIGNED MESSAGE----- > > Hash: SHA1 > > > > this is the xml document: > > > > > > > > ~ > > ~ 439 > > (... others ...) > > ~ > > > > This is an XML document containing a single tag, , whose content is text containing > entity-escaped XML. > > This is *not* an XML document containing tags , , , etc. > > All the behaviour you are seeing is a consequence of this. You need to unescape the contents of the > tag to be able to treat it as structured XML. > > Kent > > > > ---------- Forwarded message ---------- > From: Steve Holden > To: python-list at python.org > Date: Thu, 20 Jan 2005 09:04:00 -0500 > Subject: Re: Zen of Python > Paul Rubin wrote: > > > Tim Peters writes: > > > >>>Huh? [1,2,[3,4,5],[6,[[[[7]],8]]]] is a perfectly valid Python list. > >> > >>You're claiming not to know any relevant difference between Python > >>lists and Lisp lists? Heh. > > > > > > Python doesn't provide syntactic sugar for [1,[2,[3,[4,[]]]]] if > > that's what you mean. In Lisp you'd say (1 2 3 4). It's still > > a perfectly valid list in Python. Python by convention uses > > multi-element arrays instead of lists of conses. > > > But how, in Lisp, would you transliterate the Python list [1, 2, 3, 4]? > Clearly the Python list *is* different, and the tradeoff was to obtain > speed of random access, presumably (I wasn't taking an interest in > Python in its early days) anticipating that non-recursive algorithms > would be the norm. > > > >>>And you can break out of a containing loop from a nested loop > >>>with try/raise. > >> > >>Heh heh. Yes, you can. I've never seen a real Python program that > >>did, but there's nothing to stop you. > > > > > I do that on a fairly routine basis. I won't say "often", but it's a > > standard technique that finds a use now and then. > > > Well, I blush to say I have done that (once, if my memory serves me > correctly), but it was an ugly program, and I did eventually refactor > the code so that the loops were in separate scopes, which made it much > cleaner. > > [...] > > > > There's a technique in numerical analysis called Richardson > > extrapolation, where you compute an integral by [...] > > Wow. Anyone who feels the need to explain numerical analysis techniques > to Tim Peters is wasting keystrokes big-time. Anyway, Richardson > extrapolation is merely one of many successive approximation techniques, > which is what you are talking about, no? > > > > > I see the same thing happening in Python. It's going through > > successively better approximations to get closer to a limit. Python > > has it harder than some other languages, because it tries to serve the > > needs of both throwaway scripts and large-scale development projects. > > The result is that feature after feature starts out with an > > implementation sufficient for small scripts, and then edges towards > > the needs of large-scale projects. But it's often predictable at the > > beginning what the final destination is going to be. So once we can > > see where it's going, why not proceed to the finish line immediately > > instead of bothering with the intermediate steps? > > Perhaps because we don't all have your psychic powers? > > 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 > > > > ---------- Forwarded message ---------- > From: Antoon Pardon > To: python-list at python.org > Date: 20 Jan 2005 14:07:57 GMT > Subject: Re: Freezing a mutable (was Re: lambda) > Op 2005-01-20, Nick Coghlan schreef : > > Antoon Pardon wrote: > >> I missed that you would use it with the idiom: dct[x.frozen()] > > > > The list itself isn't hashable with this approach, so you don't have much > > choice. I wasn't particularly clear about that point, though. > > > >> I have two problems with this approach. > >> > >> 1) It doesn't work when you get your keys via the keys/items > >> methods. > > > > True - the frozen object has no link back to the original object. That could be > > added though (by returning a tuple subtype with the extra attribute) > > > >> 2) This is rather minor, but a user could still unfreeze > >> untimely > > > > True - doing that is less likely than mutating a hashable list though :) > > > > I'm just noting this as a way to avoid copying data more than once when storing > > immutable copies of mutable data in a dictionary. You're quite right that there > > isn't a really clean idiom for doing that in Python (aside from moving to a > > different data structure that works natively as a dict key, naturally). > > The problem here is IMO is the, we are all consenting adults (which we > are not but I wont start on this now), approach. > > I have been thinking a bit in your freeze direction, but more thorough. > The idea i had was that freeze would replace all mutating methods > with methods that would throw an exception. a thaw method would inverse > the proces. It would then be the responsibilty of the dictionary to > freeze an object on entry and thaw it when removed. However this > wouldn't work with ordinary python objects, since there is no easy way > to have readonly or private variables. > > -- > Antoon Pardon > > > > ---------- Forwarded message ---------- > From: Steve Holden > To: python-list at python.org > Date: Thu, 20 Jan 2005 09:07:39 -0500 > Subject: Re: iteritems() and enumerate() > Xah Lee wrote: > > > Python has iteritems() and enumerate() to be used in for loops. > > > > can anyone tell me what these are by themselves, if anything? > > > > are they just for idiom? > > No, anyone can use them, not just idioms like you. > > 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 > > > > ---------- Forwarded message ---------- > From: "Erik Bethke" > To: python-list at python.org > Date: 20 Jan 2005 06:20:46 -0800 > Subject: Re: ElementTree cannot parse UTF-8 Unicode? > There is something wrong with the physical file... I d/l a trial > version of XML Spy home edition and built an equivalent of the korean > test file, and tried it and it got past the element tree error and now > I am stuck with the wxEditCtrl error. > > To build the xml file in the first place I had code that looked like > this: > > d=wxFileDialog( self, message="Choose a file", > defaultDir=os.getcwd(), defaultFile="", wildcard="*.xml", style=wx.SAVE > | wxOVERWRITE_PROMPT | wx.CHANGE_DIR) > if d.ShowModal() == wx.ID_OK: > # This returns a Python list of files that were selected. > paths = d.GetPaths() > layout = '\n' > L1Word = self.t1.GetValue() > L2Word = 'undefined' > > layout += '\n' > layout += ' \n' > layout += '' > open( paths[0], 'w' ).write(layout) > d.Destroy() > > So apprantly there is something wrong with physically constructing the > file in this manner? > > Thank you, > -Erik > > > > ---------- Forwarded message ---------- > From: "Fredrik Lundh" > To: python-list at python.org > Date: Thu, 20 Jan 2005 15:40:35 +0100 > Subject: Re: ElementTree cannot parse UTF-8 Unicode? > Erik Bethke wrote: > > > layout += '\n' > > layout += ' \n' > > what does "print repr(L1Word)" print (that is, what does wxPython return?). > it should be a Unicode string, but that would give you an error when you write > it out: > > >>> f = open("file.txt", "w") > >>> f.write(u'\uc5b4\ub155\ud558\uc138\uc694!') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode characters > in position 0-4: ordinal not in range(128) > > have you hacked the default encoding in site/sitecustomize? > > what happens if you replace the L1Word term with L1Word.encode("utf-8") > > can you post the repr() (either of what's in your file or of the thing, whatever > it is, that wxPython returns...) > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Atte, Eduardo Henr?quez A. 9-6975236 From kartic.krishnamurthy at gmail.com Wed Jan 26 16:55:52 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 26 Jan 2005 13:55:52 -0800 Subject: wx.Image: Couldn't add an image to the image list. References: Message-ID: <1106776552.518189.147400@c13g2000cwb.googlegroups.com> Laszlo, If you are using PIL just for scaling, you can do away with PIL. Even if you do other things with PIL, you can use the Rescale method of the wx.Image instance to resize. Here is the code (adapted from the Demo): data = open('C:/TEMP/test.bmp'), "rb").read() stream = cStringIO.StringIO(data) img = wx.ImageFromStream( stream ) img.Rescale(32, 32) # Resize your image to 32x32 bmp = wx.BitmapFromImage( img ) # Convert Image to Bitmap # Now display Bitmap in Panel wx.StaticBitmap(self, -1, bmp, (bmp.GetWidth(), bmp.GetHeight())) Try this and see if this works for you. Thank you, --Kartic From support at convertzone.com Tue Jan 4 11:22:08 2005 From: support at convertzone.com (support at convertzone.com) Date: 4 Jan 2005 08:22:08 -0800 Subject: Using python to convert PDF document to MSWord documents In-Reply-To: References: <20040928161317.88987.qmail@web8401.mail.in.yahoo.com> Message-ID: <1104855728.542769.220760@c13g2000cwb.googlegroups.com> You can use "pdf to word", it can help you to batch convert pdf to word or text at one time, keeping source layout, and Standalone software, MS Word, Adobe Acrobat and Reader NOT required! and you can get more information from http://www.convertzone.com/net/cz-PDF%20to%20Word-1-1.htm. ConvertZone Support team ConvertZone Software Co,.ltd http://www.convertzone.com support at convertzone.com ************************************************************ ConvertZone provides office(PDF, Word, Excel, PowerPoint, AutoCAD etc), video(DVD, VCD, SVCD etc), audio(MP3, WAV, MIDI etc), image(JPG, GIF, TIF, BMP etc) file converter. ************************************************************ From klachemin at comcast.net Fri Jan 21 23:29:37 2005 From: klachemin at comcast.net (Kamilche) Date: 21 Jan 2005 20:29:37 -0800 Subject: Reload Tricks Message-ID: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> I want my program to be able to reload its code dynamically. I have a large hierarchy of objects in memory. The inheritance hierarchy of these objects are scattered over several files. I find that after reloading the appropriate files, and overwriting the __class__ of object instances, one more thing is necessary: reloading the __bases__ of each reloaded class. If I don't do this, the modules reloaded first point to old versions of the classes from later modules, and when the later module is reloaded, it doesn't update the inheritance hierarchy of classes already loaded. This appears to be working... but now I'm wondering, what else did it not change? Can I expect more toes to be blown off? --Kamilche From dave at pythonapocrypha.com Sun Jan 23 23:17:09 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sun, 23 Jan 2005 21:17:09 -0700 Subject: Determining if a client PC has an Internet connection In-Reply-To: <1106364768.871474.92810@z14g2000cwz.googlegroups.com> References: <1095578301.31957.263.camel@devilbox.devilnet.internal> <1106364768.871474.92810@z14g2000cwz.googlegroups.com> Message-ID: <41F476C5.6020007@pythonapocrypha.com> torment wrote: [snip] > Have you tried just parsing the output from the command "ipconfig"? > > It's pretty obvious from the output that might give you if a connection > is availible. It's tempting to use ipconfig's output, but the info it gives you is unreliable - you can incorrectly infer the presence of an net connection when you don't really have one (if you also run VMWare, if you have installed a loopback adapter, if you have a static public IP, etc.). -Dave From michele.simionato at gmail.com Mon Jan 31 00:42:22 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 30 Jan 2005 21:42:22 -0800 Subject: future of computing languages In-Reply-To: <1107003465.707681.161950@f14g2000cwb.googlegroups.com> References: <1107003465.707681.161950@f14g2000cwb.googlegroups.com> Message-ID: <1107150142.589225.85200@z14g2000cwz.googlegroups.com> I found that page very shallow and superficial. What they call "the language of the future" is actually the language of the present. Python (but also, Ruby, Perl, Smalltalk, Lisp, Scheme, ...) have already most of the features they list. Then they claim "the language of the future will be so different from the languages we have now that we cannot imagine how it will be". This is pretty naive. A Lisper would say that nothing new happened in the last 40 years. Actually, I think that something new happened, but not that much. The progress was more in the technology than in the programming paradigms. I mean, OO was already there in Simula. It this very possible that the language of 2045 will not be very different from the current dynamic languages. The all page reminds me of the excitation of 60's about the space program (affirmations such "in the year 2000 we will have colonies on Mars") We all know how it ended :-( Michele Simionato From aleaxit at yahoo.com Fri Jan 7 05:55:08 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 11:55:08 +0100 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> Message-ID: <1gq0odo.1x1uyr2kgdgiyN%aleaxit@yahoo.com> Paul Rubin wrote: > Really, I just want to buy a new > computer, turn it on, and have everything there. That's generally > impossible without running satanware from Redmond The princes of insufficient light from Cupertino will in fact be very happy to sell you such computers, and _their_ definition of "everything" includes a bit more than the Redmonders' (e.g., Python is there, perl is there, gcc is there, so is Apache, a good development GUI-based IDE, emacs, a solid firewall, a _usable_ Terminal/commandline program to run bash or tcsh on, ...), though it's no doubt still missing many pieces that you or I might want as parts of *our* "everything" (gvim rather than just vim, GUI/IDEs for Python, Python add-ons such as numarray, gmpy, ctypes, ...) -- all of those you still have to download and install, just as you would for the satanware. Alex From fredrik at pythonware.com Fri Jan 21 12:17:11 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 21 Jan 2005 18:17:11 +0100 Subject: circular iteration References: Message-ID: "Flavio codeco coelho" wrote: > is there a faster way to build a circular iterator in python that by doing this: > > c=['r','g','b','c','m','y','k'] > > for i in range(30): > print c[i%len(c)] have you benchmarked this, and found it lacking, or are you just trying to optimize prematurely? From Serge.Orlov at gmail.com Fri Jan 14 16:23:27 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: Fri, 14 Jan 2005 21:23:27 +0000 (UTC) Subject: oddities in the datetime module References: <41e79a1a$0$264$edfadb0f@dread12.news.tele.dk> Message-ID: Max M wrote: > # -*- coding: latin-1 -*- > > """ > > I am currently using the datetime package, but I find that the design > is oddly > asymmetric. I would like to know why. Or perhaps I have misunderstood > how it should be used? Yes, you did. datetime.timetuple is those who want *time module* format, you should use datetime.data, datetime.time, datetime.year and so on... [snip a lot of timetuple wrestling] > The other way around is also easy. > >>>> dt = datetime(2005, 1, 1, 12, 0, 0) >>>> date(*dt.timetuple()[:3]) > datetime.date(2005, 1, 1) As they say, if the only tool you have is timetuple, everything looks like tuple Try this: >>> dt = datetime(2005, 1, 1, 12, 0, 0) >>> dt.date() datetime.date(2005, 1, 1) Serge. From aahz at pythoncraft.com Fri Jan 7 16:05:43 2005 From: aahz at pythoncraft.com (Aahz) Date: 7 Jan 2005 16:05:43 -0500 Subject: Software archeology (was Re: Developing Commercial Applications in Python) References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> <87pt0iegga.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: In article , Stephen Waterbury wrote: >> eeykay at gmail.com writes: >>> >>>Can somebody there to point me any good commercial applications >>>developed using python ? > >Also see Python Success Stories: http://pythonology.org/success > >A notable example is Verity's search engine -- see >http://python.oreilly.com/news/PythonSS.pdf Actually, your statement is slightly inaccurate. The Verity search engine is more than fifteen years old in its core technology; it was started as a LISP project at IIRC MIT. (At one point I was much amused to look at the C source code and find car() and cdr() functions.) As of my last information, Python isn't used at all in or with the Verity search engine. What you're referring to is the Verity Ultraseek engine, originally written and owned by Infoseek before getting transferred to Verity through a series of dot-bomb transactions. The Ultraseek engine doesn't use Python, but Python is used to control the engine, and I think much of the spider is written in Python. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From __peter__ at web.de Sat Jan 22 03:56:45 2005 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Jan 2005 09:56:45 +0100 Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: Paul McGuire wrote: >> Is there an elegant way to assign to a list from a list of unknown >> size? For example, how could you do something like: >> >> >>> a, b, c = (line.split(':')) >> if line could have less than three fields? > I asked a very similar question a few weeks ago, and from the various > suggestions, I came up with this: > > line = "AAAA:BBB" > expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen] > a,b,c = expand( line.split(":"), "", 3 ) Here is an expand() variant that is not restricted to lists but works with arbitrary iterables: from itertools import chain, repeat, islice def expand(iterable, length, default=None): return islice(chain(iterable, repeat(default)), length) Peter From lee at example.com Tue Jan 25 17:57:16 2005 From: lee at example.com (Lee Harr) Date: Tue, 25 Jan 2005 22:57:16 GMT Subject: Another scripting language implemented into Python itself? References: <10vb8cve125v0b0@corp.supernews.com> Message-ID: >> That approach creates a sort of fragility, though. >> Python includes, along with much else, os.unlink(). >> Suppose our original poster doesn't want end-users >> to be able to delete files (or directories ...). > > I don't remember if the OP specified *where* the scripted application is to > be run. If on a server, then *any* language with loops is vulnerable to > malicious users. If on a person's own desktop machine, where one can run > 'diskformat' or the equivalent, or pick up and drop the machine, then > worrying about Python security seems superfluous. Why worry, for instance, > about os.unlink when the user can just do the same much easier in a text or > gui shell? > What if you were creating a program that used programmable modules and wanted to let people safely share modules over the internet. It would be nice to be able to say "downloaded modules are safe to use. They can only do these things: x, y, z. They will not be able to access or damage anything outside of the application" From reinhold-birkenfeld-nospam at wolke7.net Sun Jan 2 15:14:01 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 02 Jan 2005 21:14:01 +0100 Subject: What can I do with Python ?? In-Reply-To: <33qk47F41507nU1@individual.net> References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> <33oir1F40vpumU2@individual.net> <33qk47F41507nU1@individual.net> Message-ID: <33r309F44620gU1@individual.net> Jabaru wrote: >> BTW, I don't know of >> a way to write fullscreen games in C#... >> > > Directx, Opengl, Gdi+, win32api, SDL... the list goes on Yes, that's right, but most of those you can use in Python, too. I should have inserted the word "specific" at the right point in my sentence Reinhold From rff_rff at remove-yahoo.it Wed Jan 5 06:27:37 2005 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Wed, 05 Jan 2005 11:27:37 GMT Subject: Cookbook 2nd ed Credits (was Re: The Industry choice) In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> Message-ID: Jacek Generowicz ha scritto: > aleaxit at yahoo.com (Alex Martelli) writes: > > >>...but each still gets ONE free copy...!-) > > > Who gets Luther Blissett's copy ? :-) > > And are all the Luther Blissetts the same Luther Blisset ? no, some of them are Wu Ming http://www.wumingfoundation.com/ (from http://www.lutherblissett.net/indexes/bibliography_it.html) From beliavsky at aol.com Mon Jan 31 00:16:11 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 30 Jan 2005 21:16:11 -0800 Subject: Fortran pros and cons (was Re: Coding style article with interesting section on white space) In-Reply-To: <1107144265.980844.9830@z14g2000cwz.googlegroups.com> References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> <1107105022.827941.114510@c13g2000cwb.googlegroups.com> <1107124832.327010.181490@f14g2000cwb.googlegroups.com> <1107144265.980844.9830@z14g2000cwz.googlegroups.com> Message-ID: <1107148571.179315.305970@z14g2000cwz.googlegroups.com> Michael Tobis wrote: > beliavsky at aol.com wrote: > > Michael Tobis wrote: > > > Fortran 90/95 is more expressive than Fortran 77 in many ways, as > > described in ... > > http://www.nr.com/CiP97.pdf . > > > > > ... expresses more science per > > line of code and per programming workday. > > The example shown on p 10 illustrates a shorter piece of code in f90 > than in f77, but it is not obviously more expressive or less complex. > Arguably the f77 code is easier to write and maintain, even though it > has more linefeeds in it, so I find the example far from compelling. Ok, here are some simple examples of the greater expressiveness of Fortran 95 compared to F77 or C for calculations involving arrays. (1) To compute the sum of squares for each column of a matrix of the positive elements, one can write in F90 just isum = sum(imat**2,dim=1,mask=imat>0) compared to do j=1,ncol isum(j) = 0 do i=1,nrows if (imat(i,j) > 0) isum(j) = isum(j) + imat(i,j)**2 end do end do I think there is a similar Numeric Python one-liner using the sum and compress functions. Array operations are not revolutionary (APL had them in 1960s), but they are faster to write and later read. (2) Suppose x and y are matrices of the same size and one wants to set each element y(i,j) = f(x(i,j)) for some elemental (no side-effects) function f. In Fortran 95, one can just write y = f(x) compared to do j=1,ncol do i=1,nrow y(i,j) = f(x(i,j)) end do end do The ufunc of Numeric Python and the map of basic Python offer similar functionality. With Fortran 95 one can code numerical algorithms involving arrays in a high-level manner similar to Python with Numeric/Numarray or Matlab, while retaining the advantages (better performance, stand-alone executables) and disadvantages (explicit variable declarations, no scripting ability) of a compiled language with static typing. That's all I am claiming. From fredrik at pythonware.com Fri Jan 14 03:26:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 14 Jan 2005 09:26:59 +0100 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com><7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> > Huh? Expressions are not statements except when they're "expression >> > statements"? What kind of expression is not an expression statement? >> >> any expression that is used in a content that is not an expression statement, >> of course. > > Come on, that is vacuous. The claim was "expressions are not > statements". But it turns out that expressions ARE statements. no, expressions CAN BE USED as statements. that doesn't mean that they ARE statements, unless you're applying belgian logic. (if you have a problem figuring this out, try substituting other things for "expressions" and "statements", and see if you still think that "can be used as" and "are" are always the same thing. try "fish" and "pillow", for example). > It's just an artifact. Whether the artifact is a desirable one is a matter > of discussion. no, it's Python, and it's designed this way on purpose. go read the language reference. From aleaxit at yahoo.com Thu Jan 27 10:09:57 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Jan 2005 16:09:57 +0100 Subject: exclude binary files from os.walk References: <41f8167b$0$8648$a1866201@visi.com> Message-ID: <1gr21db.19k3er3jlvz31N%aleaxit@yahoo.com> rbt wrote: > Grant Edwards wrote: > > On 2005-01-26, rbt wrote: > > > >>Is there an easy way to exclude binary files (I'm working on > >>Windows XP) from the file list returned by os.walk()? > > > > Sure, assuming you can provide a rigorous definition of 'binary > > files'. :) > > non-ascii The only way to tell for sure if a file contains only ASCII characters is to read the whole file and check. You _are_, however, using a very strange definition of "binary". A file of text in German, French or Italian, for example, is likely to be one you'll define as "binary" -- just as soon as it contains a vowel with accent or diaeresis, for example. On the other hand, you want to consider "non-binary" a file chock full of hardly-ever-used control characters, just because the American Standard Code for Information Interchange happened to standardize them once upon a time? Most people's intuitive sense of what "binary" means would rebel against both of these choices, I think; calling a file "binary" because its contents are, say, the string 'El perro de aguas espa?ol.\n' (the n-with-tilde in "espa?ol" disqualifies it from being ASCII), while another whose contents are 32 bytes all made up of 8 zero bits each (ASCII 'NUL' characters) is to be considered "non-binary". In any case, since you need to open and read all the files to check them for "being binary", either by your definition or whatever heuristics you might prefer, you would really not ``excluded them from os.walk'', but rather filter os.walk's results by these criteria. Alex From fumanchu at amor.org Tue Jan 18 12:33:29 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 18 Jan 2005 09:33:29 -0800 Subject: simultaneous multiple requests to very simple database Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33981ED@exchange.hqamor.amorhq.net> Eric S. Johansson wrote: > I have an application where I need a very simple database, > effectively a very large dictionary. The very large > dictionary must be accessed from multiple processes > simultaneously. I need to be able to lock records within > the very large dictionary when records are written to. Just to clarify, you want shared-read until a write, at which point you want to lock just the item being written? Or would page or table locking be acceptable at that point? Robert Brewer MIS Amor Ministries fumanchu at amor.org From erikbethke at gmail.com Tue Jan 18 00:36:39 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 17 Jan 2005 21:36:39 -0800 Subject: wxPython and PyGame - do they play well together? Message-ID: <1106026599.092269.292170@c13g2000cwb.googlegroups.com> Hello All, I am having a great time with python and pygame, and last night I took a long look at the wxPython demo. I think that rocks as well. So now, my question is do wxPython and PyGame work together? How is the windows event loop managed? How is the display window managed? Is it possible to have some sort of master/slave relationship between the two? Is it possible that either could be dominant? Does this sound too weird? I appreciate any fingers pointing in any directions... Thank you, -Erik From roy at panix.com Sun Jan 16 09:18:57 2005 From: roy at panix.com (Roy Smith) Date: Sun, 16 Jan 2005 09:18:57 -0500 Subject: why are some types immutable? References: Message-ID: Torsten Mohr wrote: > reading the documentation (and also from a hint from this NG) > i know now that there are some types that are not mutable. > > But why is it this way? > > From an overhead point of view i think it is not optimal, > for example for a large string it could be much faster to > have it changed in place, not generating a new one for > every step in a change. There has been a huge amount written about immutable types recently. A search of the Google news archives should turn up tons of articles. But, in a nutshell, the biggest reason for immutable types (tuples and strings) is that this lets they be dictionary keys. If you want to know why dictionary keys have to be immutable, do that google search; there was a huge thread on exactly that subject just in the path month or two. Making strings immutable has some good points (in addition to making them usable as dictionary keys) and bad points. On the good side, it lets you intern strings and share memory. For example: >>> a = "fred" >>> b = "fred" >>> id (a) 3587520 >>> id (b) 3587520 when the interpreter saw the string "fred" in the second assignment statement, it looked it up and discovered that it already had a string with the value "fred", so it just re-used the same string (which is why they both have the same id). This saves memory (which can become important when you have a lot of strings). It also makes string comparison more efficient, since a test for equality can often be satisfied by just comparing id's. The bad side is that, as you mentioned, things like: s = "" for c in getCharacters(): s = s + c become very inefficient: O(n^2). Fortunately, there is an easy idiom to avoid that quadratic behavior. You just accumulate the characters in a list, O(n), and then convert the list to a string with join(), also O(n). Two O(n) passes is a heck of a lot better than a single O(n^2). l = [] for c in getCharacters(): l.append (c) s = "".join (l) Other types of in-place string manipulation could use the same trick. From bulba at bulba.com Thu Jan 6 19:29:17 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 01:29:17 +0100 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> <7xzmzmurte.fsf@ruckus.brouhaha.com> Message-ID: <8tlrt058dpe40naqj3pid3icptjnjg3p0d@4ax.com> On 06 Jan 2005 14:16:13 -0800, Paul Rubin wrote: >> Yes, apart from libraries and similar cases (frameworks etc), it's no >> doubt rare for closed-source "end-user packages" to be sold with >> licenses that include source and allow you to "do anything with it". >> >> However, allowing customization (at least for internal use within the >> customer organization), while rare, is far from unheard of. >There's no obstacle to doing that with GPL'd software either. Which is absolutely true, but generally it's not the main _expected effect_ that license writers aim to achieve.. -- It's a man's life in a Python Programming Association. From me at privacy.net Wed Jan 26 00:10:11 2005 From: me at privacy.net (JanC) Date: 26 Jan 2005 05:10:11 GMT Subject: Another scripting language implemented into Python itself? References: <1106624803.825442.73870@f14g2000cwb.googlegroups.com> Message-ID: Francis Girard schreef: > I'm really not sure but there might be some way to embed Java Script > within Jython. You can embed JavaScript in CPython, but I don't know how secure or stable it is: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From itsme at yahoo.com Wed Jan 5 17:39:27 2005 From: itsme at yahoo.com (It's me) Date: Wed, 05 Jan 2005 22:39:27 GMT Subject: Another PythonWin Excel question Message-ID: I followed the example in http://stompstompstomp.com/weblog/technical/2004-05-20 and learned that to add a new worksheet to an Excel workbook, you would use the workbook.Worksheets.Add() method. That works. However, the new worksheet got added *in front* of the last worksheet I was at. How can I get it to add *after*? Thanks, -- Me From duncan.booth at invalid.invalid Fri Jan 21 11:40:35 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Jan 2005 16:40:35 GMT Subject: circular iteration References: Message-ID: Flavio codeco coelho wrote: > hi, > > is there a faster way to build a circular iterator in python that by > doing this: > > c=['r','g','b','c','m','y','k'] > > for i in range(30): > print c[i%len(c)] > > thanks, > > Fl?vio > >>> import itertools >>> c=['r','g','b','c','m','y','k'] >>> circ = itertools.cycle(c) >>> for i in range(30): print circ.next(), r g b c m y k r g b c m y k r g b c m y k r g b c m y k r g >>> From peter at engcorp.com Mon Jan 24 08:59:03 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jan 2005 08:59:03 -0500 Subject: compile python to binary In-Reply-To: References: <1d6cdae3050123080242bf8994@mail.gmail.com> Message-ID: <4e6dnUp7mvK7YmncRVn-vA@powergate.ca> sam wrote: > Peter Hansen wrote: >> After all, source code is stored in binary too... >> > Sorry for the vagues terms. I meant compile a python script into a > binary program. As I said, "binary" is a very ambiguous term, so your clarification by itself wouldn't have helped. (That is, while the defined meaning is fairly precise, many people use "binary" to mean something different.) Anyway, the phrase you were actually looking for is "stand-alone executable". That's what py2exe and the like produce, and that's what distinguishes what you want from, for example, what some suggested in the first place. (In a Windows-only environment, asking "how do I create an EXE" would pretty much mean the same thing.) -Peter From aahz at pythoncraft.com Sat Jan 29 06:43:26 2005 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2005 06:43:26 -0500 Subject: Textual markup languages (was Re: What YAML engine do you use?) References: <35a6tpF4gmat2U1@individual.net> Message-ID: In article , Alan Kennedy wrote: > >I think that is where a lot of markup languages fall down, in that they >end trying to develop a sophisticated metadata model that can capture >that kind of information, and re-engineering the markup to support it. >This co-evolution of the markup and model can go horribly awry, if the >designers are inexperienced or don't know where they're headed. Ayup. Fortunately, David Goodger (the primary architect of reST) has plenty of experience in this area; reST was written as a reaction to the, er, organic nature of some other experiments. Nobody involved with the reST project claims it's perfect, but most of us do think we've made good tradeoffs (just like Python ;-). Like Guido, David's also pretty comfortable saying "no".... One more thing: reST does make it fairly easy to write "self-documenting" forms -- give your users boilerplate plus some simple instructions, and they should find it very easy to write their content. (I'm particularly referring to using bibliographic fields in reST -- that's easier to do with boilerplate than explain how to do correctly.) The one thing I forgot to mention in my first post is that the biggest downside to reST for non-technical users is that it's possible to write incorrect documents. With a GUI interface, you can write butt-ugly junk, but it'll never generate a syntax error. However, given your requirements, it sounds more like you're using "non-technical" to mean "not computer experts" -- those people are probably more likely to feel comfortable with getting error messages. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From philippecmartin at sbcglobal.net Mon Jan 24 16:35:11 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 24 Jan 2005 15:35:11 -0600 Subject: Why I use private variables (WAS: RE:"private" variables a.k.a. name mangling?) Message-ID: <1106602511.15475.18.camel@localhost> The real reason behind my using private variables is so they do not appear in the epydoc generated documentation and confuse my users. Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From simon.brunning at gmail.com Wed Jan 12 08:54:49 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 12 Jan 2005 13:54:49 +0000 Subject: Excel module for Python In-Reply-To: References: Message-ID: <8c7f10c605011205541b561d93@mail.gmail.com> On Wed, 12 Jan 2005 15:18:09 +0800, sam wrote: > I m wondering which Excel module is good to be used by Python? If you are on Windows, and you have Excel, then the Python for Windows extensions[1] are all you need to drive Excel via COM. O'Reilly's "Python Programming on Win32" covers COM scripting extensively - and by good fortune, driving Excel is the example they use, and the COM scripting chapter is on-line[2]. You'll also need to know the objects and methods that Excel exposes. These are documented on Microsoft's web site[3], or in the Excel VBA help, which is an optional part of they Office installation. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ [1] http://starship.python.net/crew/mhammond/ [2] http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html [3] http://msdn.microsoft.com/library/en-us/modcore/html/deovrWorkingWithMicrosoftExcelObjects.asp From gh at ghaering.de Thu Jan 6 10:53:23 2005 From: gh at ghaering.de (Gerhard Haering) Date: Thu, 6 Jan 2005 16:53:23 +0100 Subject: Embedding a restricted python interpreter In-Reply-To: <7xbrc2a7zq.fsf@ruckus.brouhaha.com> References: <7xbrc2a7zq.fsf@ruckus.brouhaha.com> Message-ID: <20050106155323.GA11145@mylene.ghaering.de> On Thu, Jan 06, 2005 at 07:32:25AM -0800, Paul Rubin wrote: > Jp Calderone writes: > > A Python sandbox would be useful, but the hosting provider's excuse > > for not allowing you to use mod_python is completely bogus. All the > > necessary security tools for that situation are provided by the > > platform in the form of process and user separation. > > But mod_python is an apache module and runs in the same apache process > with other users' scripts. Which is why it's a good idea for each customer to have it's own system user and their virtual hosts running under this uid. Which was the idea for the perchild MPM for Apache 2 - which is abandoned now :-( muxmpm is a replacement project in beta. This really sucks when you use Apache2. I myself did make the switch some time ago, then noticed that this (for me) important feature was missing. It now works, somehow, but to make it work properly I'd need to either: - go back to Apache 1.3.x, missing some nice improvements - use different webservers per user, put them together with mod_proxy (yuck!) -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From ken at switchboard.ericsson.se Thu Jan 27 17:14:15 2005 From: ken at switchboard.ericsson.se (Kenneth Johansson) Date: Thu, 27 Jan 2005 23:14:15 +0100 Subject: Profiling python 2.3 Message-ID: I wonder what would be a good way to profile a python program where the main thread starts two worker threads that do all the work. I get no infomation at all from the threads. I tried to use profile.run as the first thing in the new thread and the thread starts and works fine but when it exits I get this error File "/usr/lib/python2.3/profile.py", line 71, in run prof = prof.run(statement) File "/usr/lib/python2.3/profile.py", line 403, in run return self.runctx(cmd, dict, dict) File "/usr/lib/python2.3/profile.py", line 409, in runctx exec cmd in globals, locals TypeError: exec: arg 1 must be a string, file, or code object The main problem I have is that when I add a small function to a program the resulting code takes longer than it should. The program takes about 80% normally and end up taking more than 100%. I did a small test of the new funtions and when I run that alone it only takes 20%-25% so the result sould not take more than 50% and now I need to know where the time is spent. From usenet_spam at janc.invalid Fri Jan 21 22:25:47 2005 From: usenet_spam at janc.invalid (JanC) Date: Sat, 22 Jan 2005 03:25:47 GMT Subject: Free NNTP (was Re: how to stop google from messing Python code) References: <5339b60d.0501160809.2eda8b23@posting.google.com> Message-ID: Paul Boddie schreef: > JanC wrote: >> Aahz schreef: >> >>> You also have access to the free netnews server >>> http://news.cis.dfn.de/ >> >> That address is now for DFN internal use only. >> >> Their public service moved to . > > To me, that seems to be the general problem with public NNTP services > - you have to play a game of following them around the net. The "http://news.cis.dfn.de/" address has worked for 1 year after they announced this change. DFN stands for the "German Science and Research Network" and is a government funded organisation, and they wanted/needed separate servers for public and member usage, so they had to find a new name for their public service: "individual.net". -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From peter at somewhere.com Sun Jan 16 15:15:35 2005 From: peter at somewhere.com (Peter Maas) Date: Sun, 16 Jan 2005 21:15:35 +0100 Subject: why are some types immutable? In-Reply-To: References: Message-ID: <3500epF4g7e38U1@individual.net> Torsten Mohr schrieb: > reading the documentation (and also from a hint from this NG) > i know now that there are some types that are not mutable. > > But why is it this way? Immutable types (e.g. strings, tuples) allow for code optimization in some situations and can be used as dictionary keys. For the latter reason see: http://www.python.org/moin/DictionaryKeys -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From roy at panix.com Sun Jan 16 12:41:02 2005 From: roy at panix.com (Roy Smith) Date: Sun, 16 Jan 2005 12:41:02 -0500 Subject: why are some types immutable? References: <1105896839.966379.220890@z14g2000cwz.googlegroups.com> Message-ID: In article <1105896839.966379.220890 at z14g2000cwz.googlegroups.com>, "Dan Bishop" wrote: > Roy Smith wrote: > > Torsten Mohr wrote: > > > reading the documentation (and also from a hint from this NG) > > > i know now that there are some types that are not mutable. > > > > > > But why is it this way? > > > > > > From an overhead point of view i think it is not optimal, > > > for example for a large string it could be much faster to > > > have it changed in place, not generating a new one for > > > every step in a change. > > > > There has been a huge amount written about immutable types recently. > A > > search of the Google news archives should turn up tons of articles. > > > > But, in a nutshell, the biggest reason for immutable types (tuples > and > > strings) is that this lets they be dictionary keys. If you want to > know > > why dictionary keys have to be immutable, > > More precisely, dictionary keys can't be mutable in any way that > affects the result of the hash function or the == or != operators. Yes, this is true. In fact, I spent a fair amount of time in the referenced thread arguing exactly that point. I was hoping people would take my hint, read the thread, and find that out :-) From john.hsu at clear.net.nz Wed Jan 19 18:01:25 2005 From: john.hsu at clear.net.nz (John Hsu) Date: Thu, 20 Jan 2005 12:01:25 +1300 Subject: getting a class attribute using a keyword argument In-Reply-To: References: Message-ID: <41eee75e@clear.net.nz> Guy Robinson wrote: > Hello, > > I have a list of class instances. I wish to get the appropriate class > attribute in each class instance depending on a SINGLE keyword in the > calling class. > > How do I get the calling method to correctly recognise the keyword as a > keyword and not a class attribute? See example code below (which doesn't > work). > > class tocall: > def __init__(self): > self.title = "test" > self.name = "name" > > def callingmethod(self,**kw): > for key in kw: > if tocall.key == kw[key]: > return tocall.key > > which should work as such(but doesn't): > > print callmethod(title = "test") > print callmethod(name = "name") > > Regards, > > Guy Hi, This may be more like you want. class tocall: def __init__(self): self.title = "test" self.name = "name" def callmethod(**kw): for key in kw: if hasattr(tocall(), key): return getattr(tocall(), key) print callmethod(title = "test") print callmethod(name = "name") From fuzzyman at gmail.com Mon Jan 17 08:52:11 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 17 Jan 2005 05:52:11 -0800 Subject: Executing a script created by the end user In-Reply-To: References: Message-ID: <1105969931.707580.20790@f14g2000cwb.googlegroups.com> compile and eval is a good way to go. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From pythongnome at hotmail.com Thu Jan 13 17:58:16 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Thu, 13 Jan 2005 22:58:16 GMT Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: Arich Chanachai wrote: > Jane wrote: > >> "Lucas Raab" wrote in message >> news:UsuFd.5434$KJ2.1253 at newsread3.news.atl.earthlink.net... >> >> >>> Jane wrote: >>> >>> >>>> wrote in message >>>> news:1105495569.479185.166340 at z14g2000cwz.googlegroups.com... >>>> >>>> >>>> >>>>> python.org = 194.109.137.226 >>>>> >>>>> 194 + 109 + 137 + 226 = 666 >>>>> >>>>> What is this website with such a demonic name and IP address? What >>>>> evils are the programmers who use this language up to? >>>>> >>>>> >>>> >>>> Some people have too much time on their hands... >>>> >>>> Jane >>>> >>>> >>>> >>> >>> Better get some ointment for that burn!! >>> >> >> >> Huh??? >> >> Jane >> >> >> >> > You said that people have too much "time" on their "hands", so he > suggested ointment to prevent the irritation etc... He was probably > also getting at the topic of this thread (hint: Satan = Hell = Fire), so > the ointment puts out the burn. > Have fun folks! > > - Arich I'd also like to add that the term "burn" means to be made look stupid or be insulted. From jepler at unpythonic.net Mon Jan 24 15:41:35 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 24 Jan 2005 14:41:35 -0600 Subject: Tuple slices In-Reply-To: <35kn4mF4o44ufU1@individual.net> References: <35kn4mF4o44ufU1@individual.net> Message-ID: <20050124204135.GB14448@unpythonic.net> The cpython implementation stores tuples in memory like this: [common fields for all Python objects] [common fields for all variable-size python objects, including tuple size] [fields specific to tuple objects, if any] [array of PyObject*, one for each item in the tuple] This way of storing variable-size Python objects was chosen in part because it reuqires only one allocation for an object, not two. However, there is no way for one tuple to point to a slice of another tuple. there's no reason that some other python implementation couldn't make a different choice. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ncoghlan at iinet.net.au Tue Jan 18 03:52:38 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 18 Jan 2005 18:52:38 +1000 Subject: extension module, thread safety? In-Reply-To: <41ecbaae$0$1046$626a14ce@news.free.fr> References: <41ecbaae$0$1046$626a14ce@news.free.fr> Message-ID: <41ECCE56.9060200@iinet.net.au> Pierre Barbier de Reuille wrote: > With the current CPython, it's very hard to mix Python and C in a > multithreading application (with C-threads, not Python-threads). In fact > I never really succeeded in that task because of that GIL ! I have a > multi-thread application but every bit of Python code must be run into a > Python thread. To be more precise, I wanted to be able to call Python > code in response to some GUI events, and I didn't want to instanciate a > new interpreter for I wanted to be able to access the environment of my > main Python interpreter. I don't understand. This is what PyGILState_Ensure and PyGILState_Release are for - so C code can leave the GIL unlocked by default, and only grab it when they want to call into the C/Python API. Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jbperez808 at wahoo.com Wed Jan 12 03:09:54 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Wed, 12 Jan 2005 16:09:54 +0800 Subject: Windows GUIs from Python In-Reply-To: References: Message-ID: <34k4aiF4bqr4vU1@individual.net> Still, what I think would appeal to a lot of people (although they might not know it yet) as a GUI solution for Python is Mozilla XUL with all the RDF and XPCOM crap surgically removed from it. If you've ever tried a couple of basic XUL tutorials, I think you would be convinced that XUL is an even better way to develop GUIs than visual RAD tools. After years of doing web apps, I feel the DHTML/DOM approach as applied to GUI creation is superior in terms of learning curve, productivity and ease of code maintenance to imperative language, event-driven, IDE-coupled frameworks like Delphi, Windows Forms or Swing... except for the fact that the HTML widgets (if you could even call them that) are very primitive. XUL essentially gives you full fledged GUI widgets and allows you to script them from Javascript the same way you script HTML elements via DOM or DHTML (very easily, in other words). Now, imagine being able to use Python instead of Javascript... sounds like a match made in heaven to me. Unfortunately, the Mozilla developers are too enamoured with Javascript and RDF and XPCOM to realize that XUL (which is really shaping up beautifully if you look at Firefox and Thunderbird) is the real star in their stable and many people would like to use it without being forced to deal with the other complicated, overengineered technologies surrounding it. From apardon at forel.vub.ac.be Mon Jan 17 09:58:32 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2005 14:58:32 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-17, Steve Holden schreef : > Antoon Pardon wrote: > >> I don't see a big difference between these principles >> and the hash key principle, so in the end may be we >> should just stick with the more general principle: >> >> Don't use mutables! >> >> >> and be done with it. >> > http://redwing.hutman.net/~mreed/warriorshtm/tirelessrebutter.htm > > regards > Steve I you want to play it like this http://redwing.hutman.net/~mreed/warriorshtm/crybaby.htm -- Antoon Pardon From sross at connectmail.carleton.ca Fri Jan 7 17:09:32 2005 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 7 Jan 2005 17:09:32 -0500 Subject: Getting rid of "self." References: <740c3aec05010705393048a374@mail.gmail.com><1105114214.359029.152240@f14g2000cwb.googlegroups.com> Message-ID: "BJ?rn Lindqvist" wrote in message news:mailman.306.1105116676.22381.python-list at python.org... Thank you for your replies. But they don't deal with my original question. :) I have read the thousands of posts all saying "self is good" and they are right. But this time I want to be different m-kay? I figure that there might be some way to solve my problem by doing this: [snip ...] But beyond that, I have no idea and I would be grateful if someone would like to help me with it. http://starship.python.net/crew/mwh/hacks/selfless.py From elephantum at dezcom.mephi.ru Sun Jan 9 09:32:55 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 17:32:55 +0300 Subject: Python3: on removing map, reduce, filter In-Reply-To: <7xekguof4a.fsf@ruckus.brouhaha.com> References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> Message-ID: <34ctkpF4b9ijlU1@individual.net> Paul Rubin wrote: >>How does GvR suggestions on removing map(), reduce(), filter() >>correlate with the following that he wrote himself (afaik): >>http://www.python.org/doc/essays/list2str.html > > I think that article was written before list comprehensions were added > to Python. anyway list comprehensions are just syntaxic sugar for >>> for var in list: >>> smth = ... >>> res.append(smth) (is that correct?) so there will be no speed gain, while map etc. are C-implemented From garyr at fidalgo.net Tue Jan 4 19:38:06 2005 From: garyr at fidalgo.net (Gary Richardson) Date: Tue, 4 Jan 2005 16:38:06 -0800 Subject: Reaching the real world References: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: <10tmdnnjl7djaad@corp.supernews.com> "Fuzzyman" wrote in message news:1104850540.610295.152240 at f14g2000cwb.googlegroups.com... > I have a friend who would like to move and program lights and other > electric/electro-mechanical devices by computer. I would like to help - > and needless to say Python would be an ideal language for the > 'programmers interface'. > > What I'd like is an electronic interface that connects to several > relays and a python extension module to switch on and off the relays. > I've had a quick google and can't see anything too similar to what I > want. pyro (python robotics) seems to require expensive (relatively) > robotic equipment. > > Does anyone know anything *similar* to what I have in mind, or have > alternative suggestions ? > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml > Take a look at: http://www.geocities.com/hagtronics/pic_das/index.html Very easy to interface to Python. From ola.natvig at infosense.no Tue Jan 18 08:03:26 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Tue, 18 Jan 2005 14:03:26 +0100 Subject: generator expressions: performance anomaly? In-Reply-To: References: <377Hd.77904$Jk5.30235@lakeread01> Message-ID: Antoon Pardon wrote: > Op 2005-01-18, Steve Holden schreef : > >>Antoon Pardon wrote: >> >> >>>Op 2005-01-18, Nick Coghlan schreef : >>> >>> >>>>Raymond Hettinger wrote: >>>> >>>> >>>>>[Delaney, Timothy C] >>>>> >>>>> >>>>> >>>>>>Nick's other suggestion - that genexps propagate __len__ - might >>>>>>still be interesting. Of course, it would only be applicable for >>>>>>unconditional genexps(i.e. no if clause). >>>>> >>>>>Length transparency for iterators is not as general as one would expect. I once >>>>>spent a good deal of effort exploring where it made sense, and I was surprised >>>>>to find that it only rarely works out. Length transparency is an unexpectedly >>>>>thorny subject with many dead-ends which precludes a fully general solution such >>>>>as that proposed by Nick. >>>>> >>>>>For a recap of my research, see the docstring for Lib/test/test_iterlen.py . >>>> >>>>"""The situation slightly more involved whenever an object allows length >>>>mutation during iteration. """ >>>> >>>>Ouch. Nice understatement. >>>> >>>>It's rather unfortunate that we can't make use of the length information even >>>>when the source *doesn't* mutate, though. I'll have to think some more to see if >>>>I can come up with any concrete ideas for you to shoot down :) >>> >>> >>>Something else I was thinking about. I think it would be nice if the >>>python compilor could figure out whether a genexp in a list or tuple >>>expression always generates the same list or tuple and then instead >>>of generating code would generate the list or tuple in place. >>> >> >>Since it doesn't yet optimize 2+5 to a constant-folded 7 you should >>realize that you are suggesting a large increase in the compiler's >>analytical powers. > > > Well I can dream, cant I? > > >>I agree it would be nice under certain circumstances, but don't forget >>that unlike list comprehensions (for which it would be even nicer) the >>whole point of generator expressions is often to defer the generation of >>the individual items until they are required and thereby relieve stress >>on memory. >> >>As an edge case to demonstrate the point, what about a constant but >>infinite sequence? > > > Maybe I was not clear enough. I meant to limit it to cases such as > > lst = list(genexp) > tpl = tuple(genexp) > > > Since in such cases the object is build in memory any way, I don't > think it would be a problem of having them prebuilt in memory, or am > I missing something? > Perhaps it had been better if that kind of functionality were implemented with a different syntax, I don't know enough about how the python interpreter works but perhaps it should be possible to execute some expressions with genexp syntax when compiling to bytecode. That should be a quite trivial extension. examples using '<' list-comp/genexp syntax '>': lst = or perhaps lst = list() Would result in the same bytecode as this expression lst = [0, 1, 2, 3, ..., 98, 99] It could be called static list comprehensions. But if it is a usefull extension is another dicussion. ola From newsgroups at jhrothjr.com Wed Jan 12 23:03:55 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 12 Jan 2005 22:03:55 -0600 Subject: why are people still using classic classes? References: Message-ID: <10ubsq4lii1dac7@news.supernews.com> "Simon Wittber" wrote in message news:mailman.605.1105586518.22381.python-list at python.org... > I've noticed that a few ASPN cookbook recipes, which are recent > additions, use classic classes. > > I've also noticed classic classes are used in many places in the > standard library. > > I've been using new-style classes since Python 2.2, and am suprised > people are still using the classic classes. > > Is there a legitimate use for classic classes that I am not aware of? > Is there a project to specifically migrate standard library classes to > new-style classes? Part of it is simply that it's a bit easier: you don't have to inherit from object. AFAIK, there's no project to migrate the standard library, and I'm not at all sure that would be a good idea since existing programs that asssume classic class behavior would be affected when classes they inherited from suddenly changed. Classic classes will go away sometime in the future, currently planned for the semi-mythical 3.0 release. John Roth > > Sw. From Noah.Richards at infineon.com Fri Jan 14 15:22:44 2005 From: Noah.Richards at infineon.com (Richards Noah (IFR LIT MET)) Date: Fri, 14 Jan 2005 15:22:44 -0500 Subject: python to mssql References: Message-ID: "Robert Brewer" wrote in message news:mailman.722.1105724341.22381.python-list at python.org... Brane wrote: > can someone please give me some info regarding subject > >http://sourceforge.net/projects/mysql-python > >Ask a broad question... > > >Robert Brewer Robert, the question was about 'mssql', not 'mysql'. As for mssql, a search on google will give you the following as the first result: http://pymssql.sourceforge.net/ with others on the page that include: http://www.object-craft.com.au/projects/mssql/ http://www.egenix.com/files/python/eGenix-mx-Extensions.html Don't be lazy, Brane. Your first point of reference should _always_ be google. The fact that "I'm Feeling Lucky" points you to pymssql shows that you didn't do any research before posting here. -Noah From jester at NOSPAM.mcsnospam.vuw.acNOSPAM.nz Tue Jan 18 21:05:06 2005 From: jester at NOSPAM.mcsnospam.vuw.acNOSPAM.nz (Mike McGavin) Date: Wed, 19 Jan 2005 15:05:06 +1300 Subject: Problem parsing namespaces with xml.dom.minidom In-Reply-To: References: <41eca38d@clear.net.nz> <41ece45f@clear.net.nz> Message-ID: <1106100306.989766@bats.mcs.vuw.ac.nz> Hi Fredrik. Fredrik Lundh wrote: >>It wouldn't need to conform to the official specifications of the DOM API, but I guess I'm after >>some comparable functionality. [--snip--] > sounds like this might be exactly what you need: > http://effbot.org/zone/element-index.htm > (it's also the fastest and most memory-efficient Python-only parser you > can get, but I suppose that's not a problem ;-) Thanks. The original problem I was having turned out to the be reversing a couple of parameters in a method call, as Paul pointed out, and I now feel pretty silly as a result. But I'll take a look at this, too. Much appreciated. Mike. From sp1d3rx at gmail.com Tue Jan 11 15:49:04 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 11 Jan 2005 12:49:04 -0800 Subject: Time script help sought! In-Reply-To: <1105474524.083536.129220@f14g2000cwb.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> Message-ID: <1105476544.039325.273010@f14g2000cwb.googlegroups.com> using my code above... start = x[3].split(":") #split the minutes from the seconds this splits something like 1:22:40 into three parts 1(hours), 22(mintes), 40(seconds) so, you must add a special case handler... if len(start) == 3: { start[1] = int(start[0]) * 60 + int(start[1]) start = start[1], start[2] } and there you go.... what this does is take the hours , multiply them by 60 and add it to the minutes. You will also have to change your output function to convert from "seconds" to "hours, minutes, seconds". From tim.peters at gmail.com Mon Jan 24 14:37:45 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 24 Jan 2005 14:37:45 -0500 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> References: <41F427EB.3000200@rogers.com> <1f7befae0501231720428ca3c@mail.gmail.com> <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> Message-ID: <1f7befae05012411376821bb92@mail.gmail.com> [Tim] >> I'll note that one fairly obvious pattern works very well for weakrefs >> and __del__ methods (mutatis mutandis): don't put the __del__ method >> in self, put it in a dead-simple object hanging *off* of self. Like >> the simple: >> >> class BTreeCloser: >> def __init__(self, btree): >> self.btree = btree >> >> def __del__(self): >> if self.btree: >> self.btree.close() >> self.btree = None >> >> Then give self an attribute refererring to a BTreeCloser instance, and >> keep self's class free of a __del__ method. The operational >> definition of "dead simple" is "may or may not be reachable only from >> cycles, but is never itself part of a cycle". [Richie Hindle] > This is very nice - I've been wondering about just this problem recently, > and this will be very useful. Many thanks! Thank me if it's *actually* useful <0.5 wink>: depending on everything, it may leave problems anyway, including that there's no 100% guarantee that a __del__ method will ever get called, and that __del__ methods (weakref callbacks too, for that matter) triggered while Python is tearing itself down at exit may suffer bizarre exceptions (due to trying to use facilities in partially-torn down modules, including the module the __del__ method appears in). For those reasons, it's best practice to release critical resources explicitly. __del__ is more a crutch than a limousine. > One question: why the `self.btree = None` in the last line? Isn't > `self.btree` guaranteed to go away at this point anyway? (If the answer > is "it's necessary for weird cases that would take an hour to explain" > then I'll be more than happy to simply use it. 8-) Here, it was mostly just copy+paste from Mike's original example. In general, __del__ is a user-visible method like any other, and user code may call it explicitly. For that reason, it's safest to write __del__ methods in library objects such that they can be invoked multiple times gracefully. I think the nicest way to do that is along the lines Mike later showed: write a close()-like method to release resource explicitly (although naming it __call__ seems dubious), ensure close() is idempotent, and then write a one-liner __del__: def close(self): yadda yadda yadda def __del__(self): self.close() If you're writing code for your own use, and know __del__ will never be called explicitly, and know your __del__ can't resurrect self, then "`self.btree` [is] guaranteed to go away at this point" is true, and you can ignore all this safely. From engsolnorm at peak.org Sat Jan 15 17:02:07 2005 From: engsolnorm at peak.org (engsol) Date: Sat, 15 Jan 2005 14:02:07 -0800 Subject: Com port interrupts again References: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> Message-ID: <3k4ju0t679d5fdv7gn4tkouqt8d9hi01bn@4ax.com> On Sat, 15 Jan 2005 19:38:19 +0000 (UTC), Chris Liechti wrote: >engsol wrote in >news:154gu09bghnq674s2nqot9si6d50igueq7 at 4ax.com: > >> I didn't fully think through my application before posting my >> question. Async com port routines to handle com port interrups >> only work well if one has access to the low level operating >> system. In that case the receive buffer interrupt would cause >> a jump to an interrupt service routine.. I don't believe that > >i would not go that route... the operating system provides sync and async >methods to access the serial port. it would make sense to use these before >hacking the operating system. (also see below) > >> Python provides that capabilty directly. The solution then would >> be to write a C extention? > >ctypes can do many things without a C compiler. it's a very nice an >valuable extension, but i won't like to encurage to use it for this >particular problem. > >> The suggestions offered by respondents to my original post >> were almost all of a "Use threads, and poll as needed" flavor. >> You're right...I need to learn threads as applied to com ports. > >if you realy want to do async programming, have a look at twisted >(http://twistedmatrix.com). it does not only provide async access to the >serial port (trough pyserial + some code in twisted) it also delivers some >nice utility functions, classes etc, like the reactor, defereds, thread >pools (if you can't resist ;-) and many protocol handlers. > >chris Chris, thanks for the pointer to twisted. I'm a bit snow bound, so it's a good time to actually read some docs...:) Norm B From peter at engcorp.com Thu Jan 6 20:51:37 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jan 2005 20:51:37 -0500 Subject: Python Operating System??? In-Reply-To: <1105056994.107116.216480@f14g2000cwb.googlegroups.com> References: <10trb0mgiflcj4f@corp.supernews.com> <1105056994.107116.216480@f14g2000cwb.googlegroups.com> Message-ID: Fuzzyman wrote: > There is/was a project (Peter Hansen ?) to produce a pure python file > system. that could be an interesting component. Good memory... uh, sort of. :-) It was probably me you're thinking of, but the point of the project was solely a "virtual" file system, to be used exclusively as a tool for supporting automated testing. It has no concept of persistence, no support for it in the design, and wouldn't be what would help anyone in this respect. Sorry. (Work on it has actually not progressed lately, because there is no additional requirement driving the work. The primitive initial state of the tool suffices so far.) -Peter From michael at stroeder.com Thu Jan 6 21:26:11 2005 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 07 Jan 2005 03:26:11 +0100 Subject: Working with flat files [LDIF]. In-Reply-To: <1104871974.248122.102230@f14g2000cwb.googlegroups.com> References: <33A3E2B3.7F5CF6F0@whoi.edu> <1104871974.248122.102230@f14g2000cwb.googlegroups.com> Message-ID: <3j81b2-5v3.ln1@nb2.stroeder.com> generate at gmail.com wrote: > Scott A. McIntyre wrote: > >>I looked around but didn't see any LDIF tools for perl or python... > > Did you ever get this issue resolved? I have a similar need to merge > two LDIF files. Use module LDIF which is part of http://python-ldap.sourceforge.net/. You can use it stand-alone without installing the rest. Yes, docs are *very* sparse for this module but you can find sample code in directory Demo/Lib/ldif/ of the source distribution. Ciao, Michael. From a at b.c Sat Jan 22 15:18:10 2005 From: a at b.c (Doug Holton) Date: Sat, 22 Jan 2005 14:18:10 -0600 Subject: What YAML engine do you use? In-Reply-To: <35fo4iF4maov2U1@individual.net> References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> Message-ID: rm wrote: > this implementation of their idea. But I'd love to see a generic, > pythonic data format. That's a good idea. But really Python is already close to that. A lot of times it is easier to just write out a python dictionary than using a DB or XML or whatever. Python is already close to YAML in some ways. Maybe even better than YAML, especially if Fredrik's claims of YAML's inherent unreliability are to be believed. Of course he develops a competing XML product, so who knows. From tjreedy at udel.edu Tue Jan 25 14:51:24 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 Jan 2005 14:51:24 -0500 Subject: Another scripting language implemented into Python itself? References: <10vb8cve125v0b0@corp.supernews.com> Message-ID: "Cameron Laird" wrote in message news:bt6ic2-7dg.ln1 at lairds.us... > The original poster wants to work in Python. That's > fine. Several of us have suggested he further > expose Python itself to his end-users as an extension > language. That certainly is feasible. He needn't > explain all of Python to those end-users--probably > only a bit about "assignments", control structures, > and maybe lists. > > That approach creates a sort of fragility, though. > Python includes, along with much else, os.unlink(). > Suppose our original poster doesn't want end-users > to be able to delete files (or directories ...). I don't remember if the OP specified *where* the scripted application is to be run. If on a server, then *any* language with loops is vulnerable to malicious users. If on a person's own desktop machine, where one can run 'diskformat' or the equivalent, or pick up and drop the machine, then worrying about Python security seems superfluous. Why worry, for instance, about os.unlink when the user can just do the same much easier in a text or gui shell? Terry J. Reedy From http Fri Jan 28 08:23:56 2005 From: http (Paul Rubin) Date: 28 Jan 2005 05:23:56 -0800 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> <1106917317.595640.149010@z14g2000cwz.googlegroups.com> Message-ID: <7xy8edwutv.fsf@ruckus.brouhaha.com> "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. From gurpreet.sachdeva at gmail.com Thu Jan 13 23:53:44 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Fri, 14 Jan 2005 10:23:44 +0530 Subject: pyPgSQL giving error! In-Reply-To: References: Message-ID: > did you really do ./configure, make and make install? No, I did python setup.py build and python setup.py install > where is libpq.* linpq is there in /usr/lib/python2.3/site-packages/pyPgSQL/ > was a postgres installation present while doing ./configure et all? No, But I installed postgresql-libs before installing pyPgSQL Regards, Garry From ncoghlan at iinet.net.au Wed Jan 26 08:12:20 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 23:12:20 +1000 Subject: execute python code from db In-Reply-To: References: Message-ID: <41F79734.3030301@iinet.net.au> robert wrote: > Hello, > > Anybody knows if it's possible to execute python code from an db. > > db=MySQLdb.connect(host="localhost",user="r",passwd="j",db="v") > > c=db.cursor() > c.execute("""SELECT * FROM table > WHERE id = %s""", (id,)) > > for python_code in c.fetchall(): > execute (python_code) > > Maybe feed python with stdin??. What's wrong with the exec statement? Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From engsolnorm at peak.org Wed Jan 12 17:24:48 2005 From: engsolnorm at peak.org (engsol) Date: Wed, 12 Jan 2005 14:24:48 -0800 Subject: pyserial and com port interrupts Message-ID: Has anyone done a script that will rspond to the serial com port(s) receive buffer interrupt, as opposed to polling and timeouts? Win2000 is the main interest right now. Thanks Norm B From Prikryl at skil.cz Thu Jan 20 04:15:35 2005 From: Prikryl at skil.cz (Petr Prikryl) Date: Thu, 20 Jan 2005 10:15:35 +0100 Subject: [OT] Good C++ book for a Python programmer Message-ID: Try also the Bruce Eckel's "Thinking in C++". It is also available on-line for free at http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html I like the book because it explains the things very clearly. After reading it, one will stop to think and say that C++ is "only C with strange OO things on the top". Petr "Paul Rubin" wrote in message news:<7x4qhdia8p.fsf at ruckus.brouhaha.com>... > "rick_muller at yahoo.com" writes: > > I was wondering whether anyone could recommend a good C++ book, with > > "good" being defined from the perspective of a Python programmer. I > > realize that there isn't a book titled "C++ for Python Programmers", > > but has anyone found one that they think goes particularly well with > > the Python way? > > I think it's not possible to really grok C++ without having worked on > large multi-person C projects and understood what problems C++ tried > to solve. The only good book I know about C++ is by Stroustrup, "The > C++ Programming Language" or something like that; it's not an easy > book though. From ncoghlan at iinet.net.au Fri Jan 28 19:07:34 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 29 Jan 2005 10:07:34 +1000 Subject: Coding style article with interesting section on white space Message-ID: <41FAD3C6.1030400@iinet.net.au> Thought some folks here might find this one interesting. No great revelations, just a fairly sensible piece on writing readable code :) The whole article: http://www.acmqueue.com/modules.php?name=Content&pa=showpage&pid=271&page=1 The section specifically on white space: http://www.acmqueue.com/modules.php?name=Content&pa=showpage&pid=271&page=3 Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From apardon at forel.vub.ac.be Wed Jan 19 09:55:23 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Jan 2005 14:55:23 GMT Subject: generator expressions: performance anomaly? References: <354esdF4fouh0U1@individual.net> <5PtHd.80946$Jk5.119@lakeread01> Message-ID: Op 2005-01-19, Steve Holden schreef : > Antoon Pardon wrote: > >> Op 2005-01-18, Steve Holden schreef : > [...] >> >> But you do have a point that I have a tendency to put salt on >> any snail. I'll try to restrain myself a bit more in the future. >> > Finally! :-) > > I find I like you much better after this reflective response. Thanks for > taking the time to read my snarking and respond to it. > > "A tendency to put salt on any snail" is a nice phrase I've never come > across before. Is it specifically Belgian? It is a literal translation of a dutch idiom: "Op alle slakken zout leggen". Most people in Belgium speak dutch although foreigner often seem to think we all speak native French. From __peter__ at web.de Tue Jan 11 08:02:31 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Jan 2005 14:02:31 +0100 Subject: SuSE 9.1: updating to python-2.4 References: Message-ID: Torsten Mohr wrote: > along with my distribution SuSE 9.1 came python 2.3.3. > > I'd like to update to 2.4 now, is this an easy thing to do > or will lots of installed modules refuse to work then? > > Is there an easy way to find out what i need to update? I shied away from a full upgrade and installed 2.4 from source just to play around with it. This is painless if you use make altinstall instead of make install If you want Tkinter support you have to install the tk-devel package before configuring 2.4. One easy way to find out what depends on python is to mark python for removal in yast, then click the [Abh?ngigkeiten pr?fen] (check dependencies) button -- and probably cancel the changes afterwards. Peter From mhartl at post.harvard.edu Wed Jan 12 17:09:44 2005 From: mhartl at post.harvard.edu (Michael Hartl) Date: 12 Jan 2005 14:09:44 -0800 Subject: counting items References: <1105559439.538736.87370@z14g2000cwz.googlegroups.com> Message-ID: <1105567784.297529.246800@c13g2000cwb.googlegroups.com> That's cool! Of course, walk returns a generator, so using a list comprehension to turn it into a list seems natural, but I didn't realize that list() does the same thing (and neither, apparently, did the original implementor) -- although, with a little reflection, it obviously must! Michael From jack at performancedrivers.com Wed Jan 19 21:58:55 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 19 Jan 2005 21:58:55 -0500 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <10uu3iphdr23mf4@corp.supernews.com> Message-ID: <20050120025855.GN26167@performancedrivers.com> On Wed, Jan 19, 2005 at 09:28:13PM -0500, Peter Hansen wrote: > Jeff Shannon wrote: > >Timothy Fitz wrote: > >>Which I agree with, and which makes sense. However your "gist" is a > >>different meaning. It's not that "Flat is better than nested" it's > >>that "Too flat is bad and too flat is nested so be as nested (or as > >>flat) as you have to be and no more." Perhaps Tim Peters is far too > >>concise for my feeble mind > > > >Well, the way that the Zen is phrased, it implies a bit more than that. > > A Zen koan always implies more than the listener infers. I've met Zell Cohen, and you sir ... /got nothing. -Jack From steve at holdenweb.com Sun Jan 23 14:45:33 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 23 Jan 2005 14:45:33 -0500 Subject: OT: problems mirroring python-list to c.l.py? In-Reply-To: References: <1d6cdae305012310535980e82d@mail.gmail.com> <20050123190637.GA4820@grulic.org.ar> Message-ID: Daniel Bickett wrote: > John Lenton wrote: > >>>On Sun, Jan 23, 2005 at 01:53:52PM -0500, Daniel Bickett wrote: >>> >>>>Is there a reason that Google Groups isn't mirroring python-list >>>>exactly like it used to, or is it simply a conspiracy I'm not in on? >>> >>>You should not ask this kind of question in a public forum, >> >>and *you* should know better than to go around flapping your mouth >>like that. > > > Now I'm further confused, because I don't know what you quoted, but it > isn't on the mailing list and it isn't on c.l.py :) Maybe I should > give up trying to figure these things out. > > You didn't include a name at the beginning of your citation... Who had > the audacity to take my joke seriously? ;-) > > Daniel Bickett It is well known tha the PSU ha From sw at wordtech-software.com Thu Jan 27 17:05:57 2005 From: sw at wordtech-software.com (Kevin Walzer) Date: Thu, 27 Jan 2005 17:05:57 -0500 Subject: Configuring Python for Tk on Mac (continued) In-Reply-To: References: Message-ID: <41F965C5.3030909@wordtech-software.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Martyn Quick wrote: | From: Alex Martelli (aleaxit at yahoo.com) | |>No idea about any 10.2, sorry, but on 10.3 that's not the problem: Tk |>support is there alright, it's Tcl/Tk which _isn't_. Get MacPython, its |>PackageManager will explain where to get Tcl/Tk Aqua from, as a prereq |>for Tkinter and IDLE! | | | Ok, I've installed MacPython. It doesn't seem to work right though... | for example, if I try to run the 00-HELLO-WORLD.py example then it | crashes and tells me the IDE has unexpectedly crashed. | | I can't really see how to run things either. (I'm used to just typing | "python" in a terminal on Unix but that seems to just run the version | that comes pre-installed.) | | Sorry for not knowing much about Macs and being a bit clueless. | | Martyn You need to install Tk Aqua at this site: http://tcltkaqua.sourceforge.net You then need to install the tkinter bindings using Package Manager, which comes as part of the Macpython distribution. IDLE then should run fine. Also, you can't run Python gui programs by typing "python" in the console on the Mac: either double-click the script, or use "pythonw" as the launching program in the terminal. - -- Cheers, Kevin Walzer, PhD WordTech Software--Open Source Applications and Packages for OS X http://www.wordtech-software.com http://www.smallbizmac.com http://www.kevin-walzer.com mailto:sw at wordtech-software.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (Darwin) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFB+WXEJmdQs+6YVcoRAg5rAJ4zJYRVvEe0wvT3ZIJLwa79Am90CACdFeiv NXU/lT4hYVCPCtU6bGEWc40= =+Q7e -----END PGP SIGNATURE----- From aleaxit at yahoo.com Mon Jan 31 12:06:38 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 31 Jan 2005 18:06:38 +0100 Subject: variable declaration References: Message-ID: <1gr9ltj.1tiisn018pnse6N%aleaxit@yahoo.com> 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 From mark.asbach at post.rwth-aachen.de Wed Jan 12 16:34:50 2005 From: mark.asbach at post.rwth-aachen.de (Mark Asbach) Date: Wed, 12 Jan 2005 22:34:50 +0100 Subject: readline, rlcompleter References: <1105429869.770262.14360@c13g2000cwb.googlegroups.com> Message-ID: <1gqaqap.1h5fh1voo5axiN%mark.asbach@post.rwth-aachen.de> Hi Michele, > readline.parse_and_bind("tab: complete") > > but I don't find a list of recognized key bindings. The python readline module just wraps the GNU Readline Library, so you need to check the manuals of the latter. It's not that much text and you'll find the information needed at: http://cnswww.cns.cwru.edu/php/chet/readline/rluserman.html#SEC10 Yours, Mark From stephen.thorne at gmail.com Wed Jan 19 02:06:29 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Wed, 19 Jan 2005 17:06:29 +1000 Subject: File objects? - under the hood question In-Reply-To: <20050118225310.1939807216.whereU@now.com> References: <20050119034955.75129.qmail@web50306.mail.yahoo.com> <20050118225310.1939807216.whereU@now.com> Message-ID: <3e8ca5c8050118230670ab3d9e@mail.gmail.com> On Tue, 18 Jan 2005 22:53:10 -0800, Eric Pederson wrote: > > I didn't come across any illuminating discussion via Google, thus my question here (though it may be a neophyte question.) I am interested in the workings under the hood of Python's access of "files". > > What is actually happening at the various stages when I create a file object and "read" it? > > (1) >>> f = file("C:/GuidosParrot.txt","r") You've just opened a file for reading. You haven't read any data, but at this point if the file wasn't there, the OS would have throw you an error. > (2) >>> hesjustsleeping = f.read() The entire file is read directly into a single python str. Regards, Stephen Thorne. From nobody at here.com Sat Jan 1 07:01:50 2005 From: nobody at here.com (fedor) Date: Sat, 01 Jan 2005 13:01:50 +0100 Subject: pickling a subclass of tuple Message-ID: <41d69113$0$14985$3a628fcd@reader2.nntp.hccnet.nl> Hi all, happy new year, I was trying to pickle a instance of a subclass of a tuple when I ran into a problem. Pickling doesn't work with HIGHEST_PROTOCOL. How should I rewrite my class so I can pickle it? Thanks , Fedor #!/usr/bin/env python import pickle class A(tuple): def __new__(klass, arg1,arg2): return super(A,klass).__new__(klass, (arg1,arg2)) a=A(1,2) print "no pickle",a print "normal pickle",pickle.loads(pickle.dumps(a)) print "highest protocol", pickle.loads(pickle.dumps(a,pickle.HIGHEST_PROTOCOL)) This is the output: ''' no pickle (1, 2) normal pickle (1, 2) highest protocol Traceback (most recent call last): File "./test.py", line 9, in ? print "highest protocol",pickle.loads(pickle.dumps(a,pickle.HIGHEST_PROTOCOL)) File "/usr/lib/python2.3/pickle.py", line 1394, in loads return Unpickler(file).load() File "/usr/lib/python2.3/pickle.py", line 872, in load dispatch[key](self) File "/usr/lib/python2.3/pickle.py", line 1097, in load_newobj obj = cls.__new__(cls, *args) TypeError: __new__() takes exactly 3 arguments (2 given) ''' From fredrik at pythonware.com Tue Jan 11 15:00:40 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 11 Jan 2005 21:00:40 +0100 Subject: Python Installation References: <1105220812.579690.292260@c13g2000cwb.googlegroups.com><1105232505.142279.85810@c13g2000cwb.googlegroups.com> <41E15306.7090108@holdenweb.com> Message-ID: Steve Holden wrote: > Hmm, effbot.org seems to be down just now. Sure it'll be back soon, though. http://news.bbc.co.uk/2/hi/europe/4158809.stm From rupole at hotmail.com Wed Jan 19 22:34:48 2005 From: rupole at hotmail.com (Roger Upole) Date: Wed, 19 Jan 2005 22:34:48 -0500 Subject: Automatic Windows printer creation? References: Message-ID: <41ef2765$1_2@127.0.0.1> You can probably do it through WMI. (class is Win32_Printer) WMI works well with win32com, and there's also a wrapper module http://tgolden.sc.sabren.com/python/wmi.html for simplified access. I imagine getting all the device parameters and port configuration right will be messy, though. Roger "GMane Python" wrote in message news:mailman.902.1106163375.22381.python-list at python.org... > Anyone know if there's a module which will allow me to 'create' windows > printer definitions? Not from a Windows domain network, but just to add a > printer that sends to a jet-direct-attached printer. > > Thanks! > Dave > > > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From jeff at ccvcorp.com Tue Jan 25 21:09:09 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 25 Jan 2005 18:09:09 -0800 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> Message-ID: <10vduiphjmli9d@corp.supernews.com> Davor wrote: > M.E.Farmer wrote: > >> Wrap your head around Python, don't wrap the Python around your head! >> This is NOT Java, or C++ or C , it IS Python. > > > that's interesting hypothesis that behavior will vary due to the use of > different language ... If using a different language doesn't require/encourage different programming habits, then what's the point of using a different language? "A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis Different languages offer different modes of expression, different ways of approaching the same problem. That's *why* we have so many different programming languages -- because no single approach is the best one for all problems, and knowing multiple approaches helps you to use your favored approach more effectively. Jeff Shannon Technician/Programmer Credit International From bokr at oz.net Fri Jan 7 21:01:48 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 08 Jan 2005 02:01:48 GMT Subject: Notification of PEP Updates References: <41df128d.260695390@news.oz.net> Message-ID: <41df3e19.271843109@news.oz.net> On Fri, 07 Jan 2005 16:05:31 -0700, Steven Bethard wrote: >Bengt Richter wrote: >> On Sat, 08 Jan 2005 03:28:34 +1000, Nick Coghlan wrote: >> >> >>>I can't recall which thread this came up in, so I'm starting a new one. . . >>> >>>Barry Warsaw has kindly added a "peps" topic to the python-checkins mailing >>>list. If you want to be notified only when PEP's get updated, then subscribe to >>>python-checkins and edit your settings to select just the 'peps' topic. >> >> How does one get to editing one's settings? > > >Go to the bottom of the page > >http://mail.python.org/mailman/listinfo/python-checkins > >under "Python-checkins Subscribers", fill in your email address and >click "Unsubscribe or edit options". Fill in the "password" field on >the next page and click "Log in". The topic option should be near the >bottom of the page. > Thanks. It was below the bottom of the screen, and I expected the option in the context of first subscribing, not coming back in after confirmation. D'oh ;-/ Regards, Bengt Richter From ialbert at mailblocks.com Tue Jan 18 10:42:31 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 18 Jan 2005 10:42:31 -0500 Subject: Integration with java (Jpype vs. JPE) In-Reply-To: References: <34s5krF4c85d5U1@individual.net> Message-ID: Steve Menard wrote: > To asnwer your question more fully, the jpype-specific cide is only for > looking up the Classes and startting/stopping the environment. For > everything else, Java objects and classes are used as regular Python > objects. Thanks for the response. Currently I don't need to use java but in the past when I explored such a possibility I looked at jpype and I was unable to understand from the documentation what it actually does. There is a lot of text there, but it is all concerning catching errors or other subtleties. For a new visitor the most important question is about how it works, what does it do, and how can it be applied for the given problem. > everything else, Java objects and classes are used as regular Python > objects. This is too generic. My question was a little more specific, how would I pass a python list as an argument of a java class/method or transform a java list into a python one? You don't have to answer it here, I'm just pointing out the kind of questions that I was unable to get an answer for on the jpype website. best, Istvan. From steve at holdenweb.com Sat Jan 8 13:56:30 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 08 Jan 2005 13:56:30 -0500 Subject: tuples vs lists In-Reply-To: <41dff650$0$29357$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dff650$0$29357$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: worzel wrote: > Cheers - thanks for the feedback guys - pretty much answers the question for > me. > > 'Two-Pull' it is then, thanks. > Well, it might be "Two-Pull" in American, but in English it's "tyoopl" -- NOT "choopl" (blearch!). I've also heard people say "tuppl". So, basically, say whatever you want. Language is about communication :-) you-say-tomato-ly y'rs - 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 alia_khouri at yahoo.com Wed Jan 26 13:57:31 2005 From: alia_khouri at yahoo.com (alia_khouri at yahoo.com) Date: 26 Jan 2005 10:57:31 -0800 Subject: .WAV processing library ? In-Reply-To: References: Message-ID: <1106765851.535421.150970@f14g2000cwb.googlegroups.com> Chris Stiles wrote: > Is there a library available for python that will enable me to process .wav > files ? > > Preferably extensible so I can write handlers for dealing with the non audio > sections. You will probably find everything you're looking for here: http://www.python.org/moin/PythonInMusic AK From sylvain.thenault at nospam.logilab.fr Tue Jan 11 04:37:20 2005 From: sylvain.thenault at nospam.logilab.fr (Sylvain Thenault) Date: Tue, 11 Jan 2005 10:37:20 +0100 Subject: PyChecker messages References: Message-ID: On Tue, 11 Jan 2005 06:54:54 +0000, Frans Englich wrote: > Hello, Hi > I take PyChecker partly as an recommender of good coding practice You may alos be interested by Pylint [1]. Pylint is less advanced in bug detection than pychecker, but imho its good coding practice detection is more advanced and configurable (as the pylint author, i'm a little biased... ;), including naming conventions, code duplication, bad code smells, presence of docstring, etc... Side note : I wish that at some point we stop duplicated effort between pylint and pychecker. In my opinion that would be nice if each one focus on its strenghs (as i said bugs detection for pychecker and convention violation / bad code smell for pylint). That would be even better if both tools could be merged in one, but (at least last time I took a look at pychecker) the internal architecture is so different that it's not an easy task today. Any thoughts ? [1] 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 firemoth at gmail.com Wed Jan 19 19:41:20 2005 From: firemoth at gmail.com (Timothy Fitz) Date: Wed, 19 Jan 2005 19:41:20 -0500 Subject: Zen of Python In-Reply-To: <1106177050.630141.33090@c13g2000cwb.googlegroups.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> Message-ID: <972ec5bd0501191641166972b0@mail.gmail.com> On 19 Jan 2005 15:24:10 -0800, Carl Banks wrote: > The gist of "Flat is better than nested" is "be as nested as you have > to be, no more," because being too nested is just a mess. Which I agree with, and which makes sense. However your "gist" is a different meaning. It's not that "Flat is better than nested" it's that "Too flat is bad and too flat is nested so be as nested (or as flat) as you have to be and no more." Perhaps Tim Peters is far too concise for my feeble mind From mike at hobbshouse.org Wed Jan 12 10:41:59 2005 From: mike at hobbshouse.org (Michael Hobbs) Date: Wed, 12 Jan 2005 15:41:59 -0000 Subject: Detecting shutdown of remote socket endpoint. References: <1105504107.d645f57ce935d6cb8e82567c0be1e97e@onlynews> Message-ID: <10uaha7b1o9i22f@corp.supernews.com> Tim Gosselin wrote: > I am writing a tcp tunnel but cannot find a way of detecting when a socket > shuts down its read end without writing to the socket. For testing the > write end of the remote endpoint I just do a: > > if not sock.recv(buffsize) > > I cannot write to the socket and check if send returns 0 though, because > that involves sending data out of the which may not have come in yet. > > When I try polling the socket with: > r, w, e=select([],[sock],[], 0) > w returns with the socket still writable, even if the other end was > closed. Even at the C level, I believe there were some differences between Unix and Windows sockets in regard to this, so this advice may be dependent on your platform. At any rate, on both Unix and Windows, a closed socket will continue to report itself as writable. To detect the closed socket, I believe that one system reports the socket as being in error whereas the other system reports the socket as being readable (where read() will then immediately return 0 because the socket is closed). So in summary, instead of: r, w, e=select([],[sock],[], 0) try this: r, w, e=select([sock],[],[sock], 0) If r or e is non-empty, then the socket has been closed (or there's some other error). HTH, - Mike From martin at v.loewis.de Fri Jan 28 03:21:04 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 28 Jan 2005 09:21:04 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xu0p2dvsa.fsf@ruckus.brouhaha.com> References: <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> Message-ID: <41f9f5e6$0$25927$9b622d9e@news.freenet.de> Paul Rubin wrote: >>I can say that assuming I know what so-and-so is. For the specific >>case of AES, I would say "I don't think the Python lib necessarily >>needs to have an AES module, but I would not object if it had one" > > > Well, ok, you're changing your tune a little bit now, and getting more > reasonable. Before, you were making blanket statements of any modules > written for the Python stdlib. Now you're limiting it to AES and basing > it on some AES-specific things. And I still stand by those blanket statements. Any new module (i.e. specific code) should see real users for some time before it can be incorporated into Python. The question whether I would like to see a certain *feature* in Python (whether as a separate module, a language feature, or otherwise) is an entirely different question. That I would not object to an AES code in general doesn't imply that I will agree to any AES module that somebody contributes. > I would say the first thing I'd request would be your sense of how > plausible it is that the current no-crypto policy might be relaxed. There is no such policy in force. Different people have different opinions, and those opinions change over time. I cannot speak for others. > Again OK. I had thought from earlier discussions that you were a > crypto developer and familiar with this stuff; no problem if you're > not. However, in that case, you probably wouldn't be using the module > if it got included. I think the best policy if you don't feel > comfortable supporting including some module (whether it's crypto or > something else) that you're not personally going to use, is don't > support inclusion, but also don't obstruct it. Thanks for the advise, but I'll have my own policies. I have included several modules in the past which I'm not personally using. >>In addition, for any new module, there is one primary requirement >>for acceptance that cannot be fulfilled in code quality: the >>contributor should promise to support the module in a foreseeable >>future (i.e. a couple of years). > > > That's not too unreasonable, though I don't think I've heard it > mentioned as a requirement before. See PEP 2. > I've never heard of any requirement before that there be two separate > implementations of every Python stdlib module, by the way. That would > be silly. And I did not suggest such a thing. You said you never heard about a process which requires an implementation before deciding that the proposed feature is good, and I said that, for an example, IETF even requires *two* implementations before deciding that the feature is good. >>>However, the result of my not writing an AES module is that Python >>>doesn't have an AES module. >> >>That's not true. PyCrypto does have AES support. > > That's not in any Python distro that I know of. Sure, but "Python" is more than the Python core. > I myself would probably never support including any > such module no matter how long it was distributed, but rather would > just defer the whole question to people experienced with such modules > and trust their sense of what the acceptance criteria should be for a > specific module. That is, I'd abstain from any decision. With that attitude, the patches tracker on SF would grow unbounded, because we *continuously* get patches that no core developer has any personal interest in. I'll try to look at *all* patches, whenever I can, and in the process, I have to learn about technologies which I've never used before (primarily operating systems, but also APIs and protocols). Rejecting all these patches would be unfair to the contributors. > Your answer is more like "make enough for 500 people and bring it to > the conference site and only then will we even THINK about whether to > serve it for breakfast. I cannot see these as the same thing. > I'm sure that's true of lots of modules. If you're the sole maintainer > of the Python distro, then you have to evaluate every module that anyone > submits. But since you're part of a reasonable sized group, I think > it's best to examine the modules you care about, but don't feel that > you have to have your hands in everything. Thanks again for the advise, but this is not how Python is being maintained. Regards, Martin From alanmk at hotmail.com Sun Jan 23 14:06:11 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 23 Jan 2005 19:06:11 +0000 Subject: Textual markup languages (was Re: What YAML engine do you use?) In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> Message-ID: [Alan Kennedy] >> From what I've seen, pretty much every textual markup targetted >> for web content, e.g. wiki markup, seems to have grown/evolved >> organically, meaning that it is either underpowered or overpowered, >> full of special cases, doesn't have a meaningful object model, etc. [Fredrik Lundh] > I spent the eighties designing one textual markup language after > another, for a wide variety of projects (mainly for technical > writing). I've since come to the conclusion that they all suck > (for exactly the reasons you mention above, plus the usual > "the implementation is the only complete spec we have" issue). Thanks Fredrik, I thought you might have a fair amount of experience in this area :-) [Fredrik Lundh] > the only markup language I've seen lately that isn't a complete mess > is John Gruber's markdown: > > http://daringfireball.net/projects/markdown/ > > which has an underlying object model (HTML/XHTML) and doesn't have > too many warts. not sure if anyone has done a Python implementation > yet, though (for html->markdown, see > http://www.aaronsw.com/2002/html2text/ ), and I don't think it > supports footnotes (HTML doesn't). Thanks for the pointer. I took a look at Markdown, and it does look nice. But I don't like the dual syntax, e.g. switching into HTML for tables, etc: I'm concerned that the syntax switch might be too much for non-techies. [Alan Kennedy] >> If I can't find such a markup language, then I might instead end up >> using a WYSIWYG editing component that gives the user a GUI and >> generates (x)html. >> >> htmlArea: http://www.htmlarea.com/ >> Editlet: http://www.editlet.com/ >> >> But I'd prefer a markup solution. [Fredrik Lundh] > some of these are amazingly usable. have you asked your users what > they prefer? (or maybe you are your user? ;-) Actually, I'm looking for a solution for both myself and for end-users (who will take what they're given ;-). For myself, I think I'll end up picking Markdown, ReST, or something comparable from the wiki-wiki-world. For the end-users, I'm starting to think that GUI is the only way to go. The last time I looked at this area, a few years ago, the components were fairly immature and pretty buggy. But the number of such components and their quality seems to have greatly increased in recent times. Particularly, many of them seem to address an important requirement that I neglected to mention in my original list: unicode support. I'll be processing all kinds of funny characters, e.g. math/scientific symbols, european, asian and middle-eastern names, etc. thanks-and-regards-ly-y'rs, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From sjmachin at lexicon.net Tue Jan 4 14:11:44 2005 From: sjmachin at lexicon.net (John Machin) Date: 4 Jan 2005 11:11:44 -0800 Subject: Reaching the real world In-Reply-To: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> References: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: <1104865904.543973.63380@z14g2000cwz.googlegroups.com> Fuzzyman wrote: > I have a friend who would like to move and program lights and other > electric/electro-mechanical devices by computer. I would like to help - > and needless to say Python would be an ideal language for the > 'programmers interface'. Try Googling for "Python X10" From sjmachin at lexicon.net Sat Jan 15 20:29:44 2005 From: sjmachin at lexicon.net (John Machin) Date: 15 Jan 2005 17:29:44 -0800 Subject: How to del item of a list in loop? In-Reply-To: References: Message-ID: <1105838984.045727.55730@f14g2000cwb.googlegroups.com> Michael Hoffman wrote: > skull wrote: > > but I still have an other thing to worry about coming with this way: does > > performance sucks when the list is big enough? > > It makes a copy operation! > > > > here is a faster and 'ugly' solution: > > > > lst = [1, 2, 3] > > i = 0 > > while i < len(lst): > > if lst[i] == 2: > > lst.remove(i) > > else: > > i += 1 > > Actually, that is the slowest of the three methods proposed so far for > large lists on my system. Assuming, as have other posters, that the requirement is to remove all elements whose value is 2: it doesn't work. The result is [2, 3] instead of the expected [1, 3]. > method_while: [3.8680000305175781, 3.8680000305175781, 3.872999906539917] Three significant figures is plenty. Showing just the minimum of the results might be better. > If you want to get really hairy, you can compare the bytecode instructions > for these three methods: Timing and bytecode-peeking a broken function are a little "premature". From roy at panix.com Fri Jan 7 11:36:36 2005 From: roy at panix.com (Roy Smith) Date: 7 Jan 2005 11:36:36 -0500 Subject: Getting rid of "self." References: <740c3aec05010705393048a374@mail.gmail.com> <1105114214.359029.152240@f14g2000cwb.googlegroups.com> Message-ID: Simon Brunning wrote: >On 7 Jan 2005 08:10:14 -0800, Luis M. Gonzalez wrote: >> The word "self" is not mandatory. You can type anything you want >> instead of self, as long as you supply a keyword in its place (it can >> be "self", "s" or whatever you want). > >You *can*, yes, but please don't, not if there's any chance that >anyone other than you are going to have to look at your code. >'self.whatever' is clearly an instance attribute. 's.whatever' isn't >clearly anything - the reader will have to go off and work out what >the 's' object is. +1. If there is one coding convention which is constant through the Python world, it's that the first argument to a class method is named "self". Using anything else, while legal, is just being different for the sake of being different. From fumanchu at amor.org Wed Jan 19 16:35:20 2005 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 19 Jan 2005 13:35:20 -0800 Subject: Accessing MDB files on Windows Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398207@exchange.hqamor.amorhq.net> Jorge Luiz Godoy Filho wrote: > What is the best way to deal with MDB files? I was thinking on using > ODBC... I'll need to read and write some information to it. The load > won't be so high, but there might be a lot of data. > > Any advices? Will my approach work? I'm not a Windows guy... :-) Use ADO unless you need to support older versions of Windows. It'll be a lot faster and cleaner than ODBC. Robert Brewer MIS Amor Ministries fumanchu at amor.org From craig at postnewspapers.com.au Fri Jan 21 10:42:21 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 21 Jan 2005 23:42:21 +0800 Subject: need help on need help on generator... In-Reply-To: <200501211605.40696.francis.girard@free.fr> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <200501211605.40696.francis.girard@free.fr> Message-ID: <1106322141.19065.42.camel@bucket.localnet> On Fri, 2005-01-21 at 16:05 +0100, Francis Girard wrote: > I recently read David Mertz (IBM DeveloperWorks) about generators and > got excited about using lazy constructs in my Python programming. Speaking of totally great articles, and indirectly to lazyness (though not lazyily evaluated constructs), I was really impressed by this fantastic article on metaclasses: http://gnosis.cx/publish/programming/metaclass_1.html http://gnosis.cx/publish/programming/metaclass_2.html which shows that they're really just not that hard. That saved me an IMMENSE amount of utterly tedious coding just recently. > But besides the fact that generators are either produced with the new > "yield" reserved word or by defining the __new__ method in a class > definition, I don't know much about them. They can also be created with a generator expression under Python 2.4. A generator expression works much like a list comprehension, but returns a generator instead of a list, and is evaluated lazily. (It also doesn't pollute the outside namespace with its working variables). >>> print [ x for x in range(1,10)] [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print ( x for x in xrange(1,10) ) >>> print list(( x for x in xrange(1,10) )) [1, 2, 3, 4, 5, 6, 7, 8, 9] Not the use of xrange above for efficiency in the generator expressions. These examples are trivial and pointless, but hopefully get the point across. > In particular, I don't know what Python constructs does generate a > generator. As far as I know, functions that use yield, and generator expressions. I was unaware of the ability to create them using a class with a __new__ method, and need to check that out - I can imagine situations in which it might be rather handy. I'm not sure how many Python built-in functions and library modules return generators for things. > I know this is now the case for reading lines in a file or with the > new "iterator" package. But what else ? Does Craig Ringer answer mean > that list comprehensions are lazy ? Nope, but generator expressions are, and they're pretty similar. > Where can I find a comprehensive list of all the lazy constructions > built in Python ? (I think that to easily distinguish lazy from strict > constructs is an absolute programmer need -- otherwise you always end > up wondering when is it that code is actually executed like in > Haskell). I'm afraid I can't help you with that. I tend to take the view that side effects in lazily executed code are a bad plan, and use lazy execution for things where there is no reason to care when the code is executed. -- Craig Ringer From premshree.pillai at gmail.com Sat Jan 1 08:27:25 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Sat, 1 Jan 2005 18:57:25 +0530 Subject: Which blog tool In-Reply-To: <41d6a22f$0$42579$ed2619ec@ptn-nntp-reader03.plus.net> References: <41d6a22f$0$42579$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: On Sat, 01 Jan 2005 13:14:23 +0000, Mark Carter wrote: > I currently use python to automatically summarise a certain newsgroup > daily, and post the findings that it makes. Someone has suggested that > they would like a to see a blog of the posts. I wondered if there was a > python tool/library that could automate the blog postings. Any ideas? > > Some details: > * the summaries are basically just text files > * I already have a blog at www.blogger.com > (http://markcarterturriff.blogspot.com/), so I would like to use that if > possible; although any alternative free one that I can use to achieve my > objective would be OK, too. You can use the Blogger API to post to your Blogger account. There's a Python interface to the API -- PyBlogger -- available here: http://beetle.cbtlsl.com/archives/category/pyblogger You could also use a free service like LiveJournal (http://www.livejournal.com/). There are several clients available to post to LJ. I don't know if a Python wrapper to post is available or not. IAC, it'd be a few lines of code to make the XML-RPC calls. The protocol docs are available here: http://www.livejournal.com/doc/server/ljp.csp.protocol.html HTH > * I do have my own hosted website, which can use perl but not python; > but I'd rather use a freebie blog site > * the whole thing must be scriptable, because it will run daily. A GUI > would therefore likely get in the way. > * generating an RSS feed would be nice > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From Benjamin_Schmeling at gmx.de Mon Jan 31 08:01:56 2005 From: Benjamin_Schmeling at gmx.de (Benjamin Schmeling) Date: Mon, 31 Jan 2005 14:01:56 +0100 Subject: implicit conversion Message-ID: <41FE2C44.20205@gmx.de> Hi, I am working on exposing a bigint class to python. Now I've got the problem that methods which take an bigint as an parameter do not accept Python longs. For example: import _PythonLiDIA x=123L; c=_PythonLiDIA.bigint(); _PythonLiDIA.gcd(c,x); Traceback (most recent call last): File "test.py", line 132, in ? _PythonLiDIA.gcd(a,x); Boost.Python.ArgumentError: Python argument types in _PythonLiDIA.gcd(bigint, long) did not match C++ signature: gcd(LiDIA::bigint, LiDIA::bigint) I don't know how to achieve implicit conversion at this point, turning an long automatically into an bigint. The other way round, turning an bigint into long can be realized by defining __long__. Can someone help me please? Benjamin From jurgenex at hotmail.com Tue Jan 18 22:16:18 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Wed, 19 Jan 2005 03:16:18 GMT Subject: [perl-python] 20050118 keyed list References: <1106027360.920787.321590@z14g2000cwz.googlegroups.com> Message-ID: <6ikHd.10352$5t2.9480@trnddc01> Tassilo v. Parseval wrote: > Also sprach J?rgen Exner: > >> Xah Lee wrote: > >>> ? %a = ('john',3, 'mary', 4, 'jane', 5, 'vicky',7); >>> ? use Data::Dumper qw(Dumper); >>> ? print Dumper \%a; >> >> Wow, my compliments. The very first time that using Data::Dumper >> actually may do something useful (formats the data more nicely). >> Still, why you are passing a reference is beyond me. > > How else would you use 'Dumper' on a hash? Well, fair enough. If you do a plain print Dumper(%a); you do loose a lot of the nifty pretty printing that is provided by Dumper otherwise. jue From rNOSPAMon at flownet.com Sun Jan 2 12:26:14 2005 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 02 Jan 2005 09:26:14 -0800 Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: In article <1104657461.868175.252380 at c13g2000cwb.googlegroups.com>, "Erik Bethke" wrote: > > I have NEVER experienced this kind of programming joy. Just wait until you discover Lisp! ;-) rg From emami at knmi.nl Wed Jan 5 09:08:37 2005 From: emami at knmi.nl (Nader Emami) Date: Wed, 05 Jan 2005 15:08:37 +0100 Subject: date/time Message-ID: L.S., Could somebody help me how I can get the next format of date from the time module? example: I have to have this time 20050105. It is the next attributes of format %Y%m%d. with regards, Nader From ncoghlan at iinet.net.au Sat Jan 8 23:49:11 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 14:49:11 +1000 Subject: python3: 'where' keyword In-Reply-To: <7x3bxbe97m.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> Message-ID: <41E0B7C7.5010607@iinet.net.au> Paul Rubin wrote: >>What would be the advantage of that over this? >> >>. x = sqrt(a) + sqrt(b) where: >>. a = 2.0 >>. b = 3.0 > > > The idea of "where" is to allow re-using variable names instead of > having to keep track of which ones are in use. I just tried to give a > very simple example of how you might do that more than once in a > statement. I think having to keep the names unique within the statement you are currently writing is a reasonable request :) Cheers, Nick -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ptmcg at austin.rr._bogus_.com Thu Jan 13 12:33:37 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 13 Jan 2005 17:33:37 GMT Subject: Refactoring; arbitrary expression in lists References: <41e5cb07.701137402@news.oz.net><41e5fdce.714136143@news.oz.net> Message-ID: Despite the regexp alternatives, I refuse to post a pyparsing solution to this! :) -- Paul From motokoit at tiscali.it Thu Jan 27 19:47:43 2005 From: motokoit at tiscali.it (motokoit) Date: Fri, 28 Jan 2005 01:47:43 +0100 Subject: python under java Message-ID: <41f98cba$0$129$5fc30a8@news.tiscali.it> For some reason i need to start a python script from inside a java code. The technique is standard Process proc = Runtime.getRuntime().exec("python myscript.py") and so worked for months.... since yestarday the same instruction does not work but the line is correct because from the terminal prompt it works! By the way the instruction work for every other command, for example Process proc = Runtime.getRuntime().exec("emacs") works. Some suggestion? My machine is a Linux Mandrake64 10.1 From ncookson at networkusa.net Thu Jan 13 05:54:07 2005 From: ncookson at networkusa.net (ncookson at networkusa.net) Date: 13 Jan 2005 02:54:07 -0800 Subject: wxPython and CheckListBox Message-ID: <1105613647.610479.13280@z14g2000cwz.googlegroups.com> I am trying to add a caption or title to the box drawn around a checklistbox and having no luck. Is there a way to do this? I am using python 2.3.4 and wxPython 2.5 on a windows platform. Noel From jacek at -no-spam-.devguide.net Fri Jan 14 13:52:14 2005 From: jacek at -no-spam-.devguide.net (Jacek) Date: Fri, 14 Jan 2005 19:52:14 +0100 Subject: python connect to db2 In-Reply-To: References: <1105689253.3167.0.camel@linux.tister.com> Message-ID: yuzx wrote: > anyone can help me ? this might help: http://www6.software.ibm.com/reg/devworks/dw-db2pylnx-i?S_TACT=104AHW03&S_CMP=EDU jacek From cdavisNOSP at NOSPstaffmail.ed.ac.uk Wed Jan 12 07:44:08 2005 From: cdavisNOSP at NOSPstaffmail.ed.ac.uk (Cory Davis) Date: Wed, 12 Jan 2005 12:44:08 +0000 Subject: distutils linux script installation broken? In-Reply-To: References: Message-ID: Thanks Albert. I already do use #!/usr/bin/env python in my package directory, but the build_scripts part of "setup.py install" changes this line to #!None before copying to my bin directory. Cheers, Cory. Albert Hofkamp wrote: > On Wed, 12 Jan 2005 10:09:03 +0000, Cory Davis wrote: > >>command has been behaving badly. In the part where it is supposed to >>adjust the first line of the script it now produces >> >>#!None >> >>instead of >> >>#!/whereverpythonis/python >> >>Has anyone else encountered this? > > > I haven't (as I am not using 2.4 :-) ) > > However, there is an easy way around this, just use > > #!/usr/bin env python > > instead. > > > Albert From steve at holdenweb.com Mon Jan 17 10:19:46 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 10:19:46 -0500 Subject: Native widgets for Python In-Reply-To: <87oefom7at.fsf@mrbun.watterson> References: <41EBC7F3.5050807@web.de> <87oefom7at.fsf@mrbun.watterson> Message-ID: Tim Heaney wrote: > Stephen Thorne writes: > >>there's someone writing 'dabo', which is apparently "wxpython but >>more python". > > > It looks like dabo uses, not replaces, wxPython > > http://dabodev.com/about Actually I think it *layers* wxPython, with the intention of being able to replace wxPython with other GUI kits at a later date. So, there should be a simpler graphical API, but since I haven't yet done more than dabble (dabole?) with dabo I can't be sure. 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 stephen.thorne at gmail.com Sat Jan 8 18:46:35 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Sun, 9 Jan 2005 09:46:35 +1000 Subject: Pre/Postconditions with decorators In-Reply-To: <34814fF43bm4cU1@individual.net> References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> <34814fF43bm4cU1@individual.net> Message-ID: <3e8ca5c805010815462170f496@mail.gmail.com> On Fri, 7 Jan 2005 20:01:50 +0200, George Sakkis wrote: > > Hi George, > > it would be nice to see how you have tackled > > the task. > > Maybe we will have a checker > > module in Python one day... ;-) > > I posted my module on http://rafb.net/paste/results/voZYTG78.html and its unit test on > http://rafb.net/paste/results/MYxMQW95.html. Any feedback will be appreciated. Okay, nice. Unresolved Problems: 1) How do you handle duck types, i.e. a method that accepts StringIO, cStringIO or any other object that has a .readlines(), .seek() and .read() method? 2) How do you turn off the type checking for production code? Otherwise I quite like it. Please publish it somewhere. Stephen. From premshree.pillai at gmail.com Wed Jan 5 07:17:05 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Wed, 5 Jan 2005 17:47:05 +0530 Subject: is python more popular than coldfusion? In-Reply-To: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: On Wed, 5 Jan 2005 19:59:21 +0800, worzel wrote: > > > > is python more popular than coldfusion? I don't know if Coldfusion _was_ ever more "popular" than Python, but Python is definitely more "popular" _now_. This might be of some help: http://www.tiobe.com/tpci.htm > > I realsie that is a very general question as one thing does not directly > relate to the other. My issue is that I am ditching coldfusion due to there > being next to no work for it, and I am thinking of taking on python as a > second language to java in the hope of improving my resume. > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Premshree Pillai http://www.livejournal.com/~premshree From lee at example.com Wed Jan 5 17:35:21 2005 From: lee at example.com (Lee Harr) Date: Wed, 05 Jan 2005 22:35:21 GMT Subject: date/time References: Message-ID: On 2005-01-05, Nader Emami wrote: > L.S., > > Could somebody help me how I can get the next format of date > from the time module? > > example: I have to have this time 20050105. It is the next > attributes of format %Y%m%d. > I would use the datetime module: >>> import datetime >>> today = datetime.date.today() >>> today datetime.date(2005, 1, 5) >>> today.strftime('%Y%m%d') '20050105' >>> one_day = datetime.timedelta(1) >>> tomorrow = today + one_day >>> tomorrow.strftime('%Y%m%d') '20050106' From mcturra2000 at yahoo.co.uk Sun Jan 2 06:45:58 2005 From: mcturra2000 at yahoo.co.uk (Mark Carter) Date: Sun, 02 Jan 2005 11:45:58 +0000 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> > It might be nice if it was widely understood (in IT) that Python was a language any competent > programmer could pick up in an afternoon I am a programmer who works for a firm of engineers, where they program in VBA, badly. I've often mentioned Python, whereupon I'm usually dismissed as a crank. One of them expressed concern that if they used Python and I left, then nobody would understand what to do. I could have countered that Python is actually quite an easy language to pick up, but what's the point. We might be doing a project which involves web-type stuff. I pointed out that if they did, they wouldn't be able to use VB/VBA, and may need to use something like Python. I didn't get a reaction from that at the time, but no doubt they'll be telling me that I'll have to make Excel work through the internet, or something. From skip at pobox.com Sat Jan 29 09:53:45 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 29 Jan 2005 08:53:45 -0600 Subject: limited python virtual machine In-Reply-To: <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> Message-ID: <16891.41849.882856.527798@montanaro.dyndns.org> >> One thing my company has done is written a ``safe_eval()`` that uses >> a regex to disable double-underscore access. Alex> will the regex catch getattr(object, Alex> 'subclasses'.join(['_'*2]*2)...?-) Now he has two problems. ;-) Skip From abigail at abigail.nl Thu Jan 13 18:35:41 2005 From: abigail at abigail.nl (Abigail) Date: 13 Jan 2005 23:35:41 GMT Subject: [perl-python] 20050112 while statement References: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee (xah at xahlee.org) wrote on MMMMCLIII September MCMXCIII in : .. # here's a while statement in python. .. .. a,b = 0,1 .. while b < 20: .. print b IndentationError: expected an indented block .. a,b = b,a+b You have already proven you don't know Perl, but now it turns out, you don't know Python either. Go away. Abigail -- package Z;use overload'""'=>sub{$b++?Hacker:Another}; sub TIESCALAR{bless\my$y=>Z}sub FETCH{$a++?Perl:Just} $,=$";my$x=tie+my$y=>Z;print$y,$x,$y,$x,"\n";#Abigail From steven.bethard at gmail.com Thu Jan 20 18:34:55 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 20 Jan 2005 16:34:55 -0700 Subject: [Python-Dev] Updated Monkey Typing pre-PEP In-Reply-To: <001d01c4ff46$bec52040$793ec797@oemcomputer> References: <001d01c4ff46$bec52040$793ec797@oemcomputer> Message-ID: On Thu, 20 Jan 2005 18:21:17 -0500, Raymond Hettinger wrote: > > Instead of a __getattr__ solution, I recommend subclassing from a mixin: > > class RichMap(SomePartialMapping, UserDict.DictMixin): pass > > class RichFile(SomePartialFileClass, Mixins.FileMixin): pass I've been wondering for a while if there shouldn't be a mixins module for these kind of things. DictMixin, of course, and a maybe ListMixin to add extended slicing, append, extend, index, etc. I can see that a FileMixin might also be useful... If a mixins module was created, it would also give us the opportunity to break backwards compatibility with DictMixin and base it off of __getitem__(), __setitem__(), __delitem__(), and __iter__() instead of __getitem__(), __setitem__(), __delitem__(), and keys(). (According to the language reference, the __iter__ method is much more integral to mapping types than the keys method: http://docs.python.org/ref/sequence-types.html) Steve -- You can wordify anything if you just verb it. --- Bucky Katt, Get Fuzzy From michele.simionato at gmail.com Sun Jan 9 00:42:36 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 8 Jan 2005 21:42:36 -0800 Subject: Returning same type as self for arithmetic in subclasses In-Reply-To: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> References: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> Message-ID: <1105249356.919694.299020@c13g2000cwb.googlegroups.com> Max. M.: > So I wondered if there was a simlpler way to coerce the result into my > desired types rather than overwriting the __add__, __sub__ etc. methods? Tim Peters: >> Generally speaking, no. But I'm sure someone will torture you with a >> framework that purports to make it easy . I will not dispute the Timbot assessment ;) He is also right that people have already undergone under this level of torture: see http://tinyurl.com/6m373 for instance. Michele Simionato From cookedm+news at physics.mcmaster.ca Fri Jan 28 16:23:15 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 28 Jan 2005 16:23:15 -0500 Subject: LinearAlgebra incredibly slow for eigenvalue problems References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> Message-ID: "drife" writes: > Hello, > > I need to calculate the eigenvectors and eigenvalues for a 3600 X 3600 > covariance matrix. > > The LinearAlgebra package in Python is incredibly slow to perform the > above calculations (about 1.5 hours). This in spite of the fact that > I have installed Numeric with the full ATLAS and LAPACK libraries. > > Also note that my computer has dual Pentium IV (3.1 GHz) processors > with 2Gb ram. > > Every Web discussion I have seen about such issues indicates that > one can expect huge speed ups if one compiles and installs Numeric > linked against the ATLAS and LAPACK libraries. Are you *sure* that Numeric is linked against these? > Even more perplexing is that the same calculation takes a mere 7 min > in Matlab V6.5. Matlab uses both ATLAS and LAPACK. > > Moreover, the above calculation takes the same amount of time for > Numeric to complete with --and-- without ATLAS and PACK. I am certain > that I have done the install correctly. This is good evidence that Numeric *isn't* linked to them. If you're on a Linux system, you can check with ldd: cookedm at arbutus$ ldd /usr/lib/python2.3/site-packages/Numeric/lapack_lite.so liblapack.so.3 => /usr/lib/atlas/liblapack.so.3 (0x0000002a95677000) libblas.so.3 => /usr/lib/atlas/libblas.so.3 (0x0000002a95e55000) libg2c.so.0 => /usr/lib/libg2c.so.0 (0x0000002a96721000) libpthread.so.0 => /lib/libpthread.so.0 (0x0000002a96842000) libc.so.6 => /lib/libc.so.6 (0x0000002a96957000) libm.so.6 => /lib/libm.so.6 (0x0000002a96b96000) /lib64/ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x000000552aaaa000) You can see that lapack and blas (the Atlas versions) are linked to the lapack_lite.so. To install Numeric using Lapack: - remove the build/ directory in your Numeric sources, so you don't any old binaries - edit setup.py and follow the comments on using Lapack (you need to comment out a few lines, and set some directories) Also set use_dotblas to 1. - do the 'python setup.py build', 'python setup.py install' dance. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From macrocosm at fastmail.fm Sun Jan 9 09:50:19 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Sun, 09 Jan 2005 09:50:19 -0500 Subject: Python Operating System??? In-Reply-To: <10u19fmj9086b8b@news.supernews.com> References: <10trb0mgiflcj4f@corp.supernews.com> <1105219440.064891.199690@c13g2000cwb.googlegroups.com> <10u19fmj9086b8b@news.supernews.com> Message-ID: <41E144AB.8050002@fastmail.fm> John Roth wrote: > > "jtauber" wrote in message > news:1105219440.064891.199690 at c13g2000cwb.googlegroups.com... > >> My experiment, Cleese, was making progress before I got distracted by >> other things. >> .... >> >> I should probably get back to it at some stage. > > > As my ex-wife was fond of saying, "I wish you'd have > told me it was impossible before I did it." > > John Roth Is that why she divorced you? You will notice that tauber says he stopped working on Cleese due to "distraction" not a lack of progress or a notion of impending doom/"impossibility". > >> >> see http://cleese.sourceforge.net/ >> James Tauber >> http://jtauber.com/blog/ >> > From benn at cenix-bioscience.com Thu Jan 20 04:48:17 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Thu, 20 Jan 2005 10:48:17 +0100 Subject: Oddity is shutil.copyfileobj Message-ID: <41EF7E61.1090602@cenix-bioscience.com> Hello, I'm running a program which is using shutil.copyfileobj on a Win2K Pro, python 2.3 box. The source and dest file are both opened in textual mode as 'w', the source file on the local hard drive and the dest file is on a file server (transmitted through a samba server), the block size for copying is not entered - so the default setting is used (whatever that is). The files are copied across perfectly (diffing them shows they are identical), however I have one small problem, the destination filename has .read appended to the end. I've checked my code again and again and I'm definatly not apeending this. I'm also copying files across, in the same program but the source and dest are binary - this doesn't have the same problem, the filenames are not changed. My question is - has anyone else seen this behaviour? Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 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 peter at somewhere.com Tue Jan 11 15:37:20 2005 From: peter at somewhere.com (Peter Maas) Date: Tue, 11 Jan 2005 21:37:20 +0100 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: References: <7x6524d6pv.fsf@ruckus.brouhaha.com> Message-ID: <34irrfF4bvjsvU1@individual.net> Alexander Schremmer schrieb: > Having a DBMS backend is good in your opinion? It has some severe > disadvantages like not easy to scale (you would need to setup DBMS > replication), two potential points of failure, more complex setup, bigger > memory requirements, etc. So nobody should use DBMS backends, right? Except those poor guys who need transactions, consistency rules, indexes, a standard query language, ... ;) What do you mean with scaling? If you multiply CPU and RAM by 8, good DBMS deliver nearly eightfold performance. If you distribute a DBMS on an 8 computer cluster, the DBMS will scale. If you distribute a DBMS on 8 arbitrary unrelated computers, you have 8 DBMSs which need to synchronize their data by replication. Do applications with file based persistence scale better? Since files need no setup beyond creation, every setup is complex compared to files ;) See e.g. the setup of an PostgreSQL DBMS: ./configure gmake su gmake install adduser postgres mkdir /usr/local/pgsql/data chown postgres /usr/local/pgsql/data su - postgres /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data /usr/local/pgsql/bin/postmaster -D /usr/local/pgsql/data >logfile 2>&1 & /usr/local/pgsql/bin/createdb test /usr/local/pgsql/bin/psql test The first four lines are the same for every source based distribution, only 8 lines are PostgreSQL specific. I don't think this is too complex. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From peter at engcorp.com Sun Jan 23 21:07:46 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jan 2005 21:07:46 -0500 Subject: Help on project, anyone? In-Reply-To: <35ienhF4lu88lU1@individual.net> References: <35ienhF4lu88lU1@individual.net> Message-ID: Georg Brandl wrote: > Hello, > > to train my Python skills I am looking for some project I can contribute > to. I learned Python about one year ago, and had already some > programming background behind (I contributed to SharpDevelop for > instance), so I'm not the complete newbie. > > About myself: I'm a 20 year old German with strong interests in > programming and, of course, especially in Python (I love it...). > > Does anyone run, or participate in, a project looking for fellow > programmers? I don't have a special area of interest, well, perhaps web > programming... Maybe here? http://www.uselesspython.com/pythonchallenge.html From xun.ling at gmx.de Mon Jan 10 10:04:45 2005 From: xun.ling at gmx.de (xunling) Date: 10 Jan 2005 07:04:45 -0800 Subject: "Re: Re: Probleme mit der Installation der openSource Bittorrent.... python vs JAVA" Message-ID: i still need an answer ... anyone out there who could help me plz? :/ thx - xun From spam at nospam.org Tue Jan 25 20:48:53 2005 From: spam at nospam.org (Erik Johnson) Date: Tue, 25 Jan 2005 18:48:53 -0700 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> Message-ID: <41f6f4ee$1@nntp.zianet.com> "Davor" wrote > I do not hate OO - I just do not need it for the project size I'm > dealing with - and the project will eventually become open-source and > have additional developers... If you think your project is valuable enough to eventually be "Open Source", you can bet that one of the first criticisms it will face is that it is not OO if it is perceived that there would be any advantage to being so. If your question is "Can I write useful Python code without writing my own classes, without creating a class inheritance heirarchy, etc.?" then the answer is definitely "Yes!" Python has lots of very useful and practical libraries to allow you to do all sorts of cool things. Many of those interfaces though are presented in an OO manner (to varying degrees). >so I would prefer that we all stick to > "simple procedural" stuff rather than having to deal with a developer > that will be convincing me that his 50 layers inheritance hierarchy is > good since it exists in some weird pattern that he saw somewhere on > some Java design patterns discussion board :-) and other "proper" OO > design issues... If your question is "Can I somehow hobble Python so that there are no objects anywhere and it is not possible for other developers to even think about creating something I can't understand?" then I would ask how is it you are leading a team of other programmers that is apparently not afraid of OO concepts? You can write lot's of code that is just functions, and have functions call other functions, but what does a 'def' statement (python's syntax for function definition) do? It instantiates a function object. That function can be copied (well, the reference to it, anyway), passed to other functions, returned from functions, stored in variables, etc. You may or may not see any practical use for that, but Python was (very wisely) designed to be OO right from the very start - it definitely wasn't something that was added on later. You might want to spend a little time pondering why that is. If you don't understand the difference between pop(mylist) and mylist.pop(), it would be a wise career move to invest a little time to understand what the difference is and why the state of software development has come to prefer one over the other. At the bottom, practically everything in Python is an object... >>> dir(42) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__hash__', '__hex__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] there's just no getting around it. If you want to set down the groundrules for your project that you will stick to basically just procedural code, fine - that's a project management issue. If you are insistent there can be no objects anywhere in your implementation, Python is definitely the WRONG choice. Well... there is no choice. It would be impossible with Python. Note also that Perl is definitely out, as is JavaScript and even PHP. ANSI C might work and (as pointed out earlier), some other likely candidates are sh, bash, csh, ksh... I don't know a lot about Tcl/Tk - I think it implements some rather OO'ish stuff, but worth consideration. Good luck. -ej From elbertlev at hotmail.com Wed Jan 12 17:45:21 2005 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 12 Jan 2005 14:45:21 -0800 Subject: pyXLwriter and jython Message-ID: <1105569920.986226.253150@z14g2000cwz.googlegroups.com> Hi! I was using pyXLwriter in C-python, but recently had to code in jython. Tried to port pyXLwriter to jython and it does not work. Did somebody uset this module with jython? From klaus_neuner82 at yahoo.de Wed Jan 26 09:41:19 2005 From: klaus_neuner82 at yahoo.de (Klaus Neuner) Date: 26 Jan 2005 06:41:19 -0800 Subject: fast list lookup Message-ID: <3e96ebd7.0501260641.159e007f@posting.google.com> Hello, what is the fastest way to determine whether list l (with len(l)>30000) contains a certain element? Klaus From bulba at bulba.com Sun Jan 9 13:53:04 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 09 Jan 2005 19:53:04 +0100 Subject: Speed revisited References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> <1105237556.402188.126980@c13g2000cwb.googlegroups.com> Message-ID: On 8 Jan 2005 18:25:56 -0800, "John Machin" wrote: >> Both versions use local variables, etc. Both have their >> lists initially sorted. Both essentially use a loop with >> conditional for comparison, >> then process the record in the >> same way. > >"process the record in the same way"??? That's an interesting use of >"same". Meaning when the records with the same 'english' key is found, just write the comparison result to the result file. >> The overhead of second version is that it also >> uses cmp() function and two additional integer >> variables - that should not slow the program _so much_. >> I have measured the run of snippet 2 with time checkpoints >> written to a log (write time delta to log every 200 records), >> even made a graph of time deltas in spreadsheet and in fact >> snippet 2 seems after initial slowdown looks exactly linear, >> like that: >> >> ^ (time) >> | >> | /----------- >> | / >> |/ >> ---------------> (# of records written) >> >> So yes, it would scale to big files. > >On your empirical evidence, as presented. However, do read on ... >>However, why is it so >> frigging slow?! >Mainly, because you are (unnecessarily) deleting the first item of a >list. This requires copying the remaining items. It is O(N), not O(1). >You are doing this O(N) times, so the overall result is O(N**2). Your >graph has no obvious explanation; after how many cycles does the speed >become constant? After some 2000 records. I was "tracking" it with printouts of variables and initially the main loop was taking advantage of records being sorted, with the first condition (with keys being equal) quickly writing the records into a file, and the further into the dataset, the greater the distance was between the beginning of the list where the record was sought to the appropriate record, i.e. either o or n were becoming steadily higher. This could explain linearity further down the path: the list is becoming gradually shorter, so the deletion times were decreasing linearly, but in the meantime the search time was linearly increasing. >Secondly, you are calling cmp() up to THREE times when once is enough. >Didn't it occur to you that your last elif needed an else to finish it >off, and the only possible action for the else suite was "assert >False"? Sure, but I was trying to make it shorter and absolutely clear what I mean in this place (when people see the comparison in every place, they see immediately what it was, they don't have to recall the variable). Obviously I'd optimise it in practice. It was supposed to be "proof of concept" rather than any working code. BTW, this particular example didn't work out, but I still found Python to be the most convenient language for prototyping, I wrote smth like five versions of this thing, just to learn dictionaries, lists, sets, etc. In no other language I'd do it so quickly. >It would appear after reading your "snippet 2" a couple of times that >you are trying to implement the old 3-tape update method. Well, ahem, I admit you got me curious just how it would work with tapes (never used them), so I was sort of trying to simulate that - it's just a bit weird undertaking, I did it rather to explore the issue and try to learn smth rather than to get working code. Deleting the first item from a list was to be a convenient equivalent of forwarding the reading head on the tape one record ahead, because I assumed that any deletion from the list was to take more or less the same time, just like reading heads on tapes were probably reading the records with similar speeds regardless of what length of tape was already read. >It would also appear that you are assuming/hoping that there are never >more than one instance of a phrase in either list. Sure. Because using advice of Skip Montanaro I initially used sets to eliminate duplicates. It's just not shown for brevity. If the keys are guaranteed to be unique, it makes it easier to think about the algorithm. >You need something a little more like the following. >Note that in your snippet2 it was not very obvious what you want to do >in the case where a phrase is in "new" but not in "old", and vice versa >-- under one circumstance (you haven't met "end of file") you do >nothing but in the the other circumstance you do something but seem to >have not only a polarity problem but also a copy-paste-edit problem. What exactly is a "polarity problem"? I concede that the code is rather contrived, but I didn't bother to do smth like writing classes or functions that would simulate a tape reader, so the result is rather ugly. I only posted it because I could not explain why it were so slow. > In >the following code I have abstracted the real requirements as >handle_XXX_unmatched() Thanks, I'll have to try that out. -- It's a man's life in a Python Programming Association. From frans.englich at telia.com Wed Jan 12 14:18:36 2005 From: frans.englich at telia.com (Frans Englich) Date: Wed, 12 Jan 2005 19:18:36 +0000 Subject: Refactoring; arbitrary expression in lists In-Reply-To: <1105556212.036972.160470@z14g2000cwz.googlegroups.com> References: <1105556212.036972.160470@z14g2000cwz.googlegroups.com> Message-ID: <200501121918.36423.frans.englich@telia.com> On Wednesday 12 January 2005 18:56, wittempj at hotmail.com wrote: > I can not break the original code in 2.4, if I try this: [...] > > So although the dictionary solution is much nicer nothing seems wrong > with your code as it is - or am I missing something? Nope, the current code works. I'm just looking at Python's cool ways of solving problems. (the matter about 11 returns was a coding-style report from PyChecker). Cheers, Frans From john at grulic.org.ar Sun Jan 23 14:06:37 2005 From: john at grulic.org.ar (John Lenton) Date: Sun, 23 Jan 2005 16:06:37 -0300 Subject: OT: problems mirroring python-list to c.l.py? In-Reply-To: <1d6cdae305012310535980e82d@mail.gmail.com> References: <1d6cdae305012310535980e82d@mail.gmail.com> Message-ID: <20050123190637.GA4820@grulic.org.ar> > On Sun, Jan 23, 2005 at 01:53:52PM -0500, Daniel Bickett wrote: > > > > Is there a reason that Google Groups isn't mirroring python-list > > exactly like it used to, or is it simply a conspiracy I'm not in on? > > You should not ask this kind of question in a public forum, and *you* should know better than to go around flapping your mouth like that. -- John Lenton (john at grulic.org.ar) -- Random fortune: Comer se ha de hacer en silencio, como los frailes en sus conventos. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From Serge.Orlov at gmail.com Thu Jan 13 17:33:20 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 13 Jan 2005 14:33:20 -0800 Subject: Unicode conversion in 'print' In-Reply-To: References: Message-ID: <1105655600.059496.70350@z14g2000cwz.googlegroups.com> Ricardo Bugalho wrote: > Hello, > I'm using Python 2.3.4 and I noticed that, when stdout is a terminal, > the 'print' statement converts Unicode strings into the encoding > defined by the locales instead of the one returned by > sys.getdefaultencoding(). Sure. It uses the encoding of you console. Here is explanation why it uses locale to get the encoding of console: http://www.python.org/moin/PrintFails > However, I can't find any references to it. Anyone knows where it's > descrbed? I've just wrote about it here: http://www.python.org/moin/DefaultEncoding > > Example: > > !/usr/bin/env python > # -*- coding: utf-8 -*- > > import sys, locale > > print 'Python encoding:', sys.getdefaultencoding() > print 'System encoding:', locale.getpreferredencoding() > print 'Test string: ', u'Ol? mundo' > > > If stdout is a terminal, works fine > $ python x.py > Python encoding: ascii > System encoding: UTF-8 > Test string: Ol? mundo > > If I redirect the output to a file, raises an UnicodeEncodeError exception > $ python x.py > x.txt > Traceback (most recent call last): > File "x.py", line 8, in ? > print 'Test string: ', u'Ol? mundo' > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 2: ordinal not in range(128) > http://www.python.org/moin/ShellRedirectionFails Feel free to reply here if something is not clear, corrections in wiki are also welcome. Serge. From steve at holdenweb.com Sat Jan 8 14:02:23 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 08 Jan 2005 14:02:23 -0500 Subject: Returning same type as self for arithmetic in subclasses In-Reply-To: References: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> Message-ID: <_aWDd.69984$Jk5.34806@lakeread01> Tim Peters wrote: > [Max M] > >>""" >>I subclass datetime and timedelta >> [...] > > Generally speaking, no. But I'm sure someone will torture you with a > framework that purports to make it easy . Clearly the easy way is to have the type declaration introspect on the definitions of datetime and timedelta and then auto-create methods wrapping the base types' methods in a "myxxx" conversion. left-as-an-exercise-for-the-reader-ly y'rs - 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 daranrife at yahoo.com Fri Jan 28 23:08:27 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 20:08:27 -0800 Subject: Installing Numeric with ATLAS and LAPACK In-Reply-To: References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> <1106940704.164253.134630@c13g2000cwb.googlegroups.com> Message-ID: <1106971706.986114.26420@c13g2000cwb.googlegroups.com> Could you clarify this please? Let's say that I want to make a call to the LAPACK routine sspevd, and pass it a matrix, and get the result. How do I accomplish this? Thanks, Daran From craig at postnewspapers.com.au Wed Jan 19 22:35:42 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Thu, 20 Jan 2005 11:35:42 +0800 Subject: [OT] Good C++ book for a Python programmer In-Reply-To: <1106151297.339844.95380@c13g2000cwb.googlegroups.com> References: <1106136496.719185.87850@c13g2000cwb.googlegroups.com> <1106151297.339844.95380@c13g2000cwb.googlegroups.com> Message-ID: <1106192142.20679.1.camel@bucket.localnet> On Wed, 2005-01-19 at 09:04 -0800, beliavsky at aol.com wrote: > Rick Muller wrote: > >I was wondering whether anyone could recommend a good C++ book, with > >"good" being defined from the perspective of a Python programmer. > > The STL and the template feature of C++ gives the programmer some of > the functionality of Python (using templates instead of duck typing, > vectors instead of lists etc.), I'm particularly fond of internally refcounted objects (as used extensively in Qt) and of guarded pointers, myself. The use of these two things means one can avoid the "sometimes works, sometimes doesn't" fun of referencing deleted memory by accident. -- Craig Ringer From max at alcyone.com Mon Jan 31 13:32:34 2005 From: max at alcyone.com (Erik Max Francis) Date: Mon, 31 Jan 2005 10:32:34 -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: <3YCdnbjoYNJe5GPcRVn-gQ@speakeasy.net> Steve Holden wrote: > Would there, I wonder, be any enthusiasm for a "Best Xah Lee impression" > prize at PyCon? I imagine standing in a corner, facing the wall, and screaming incoherently at the top of your lungs would be guaranteed at least second place. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis You've got me wondering / If you know that I am wondering about you -- India Arie From jurgenex at hotmail.com Fri Jan 14 11:24:45 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Fri, 14 Jan 2005 16:24:45 GMT Subject: [perl-python] 20050113 looking up syntax References: <1105699357.565028.107750@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > --------------------- > > for perl syntax lookup, use perldoc in the command line. For example: > perldoc perl Wrong. That command will give you a high-level overview of Perl but tell you nothing about the syntax. To lookup the Perl syntax you would have to use perldoc perlsyn > use 'perldoc -f functionName' for specific function. example: > perldoc -f qq BS. That will tell you what a function does, it doesn't tell you anything at all about the syntax of Perl. BTW: Why on earth are you using qq() as an example? That doc page just points you to 'perldoc perlop'. > note that keywords cannot be looked up with -f. For basic keywords > like > > if, while..., use > perldoc perlop BS. What gave you the idea that keywords were operators? Of course keywords can be found where they belong, in the syntax definition of the language, but not in the operator section of the documentation. Why don't you just stop posting this nonsense? jue From john at grulic.org.ar Mon Jan 10 19:40:30 2005 From: john at grulic.org.ar (John Lenton) Date: Mon, 10 Jan 2005 21:40:30 -0300 Subject: Writing huge Sets() to disk In-Reply-To: <8765246hix.fsf@sme.intra.citec.fi> References: <1105390704.241316.267690@f14g2000cwb.googlegroups.com> <8765246hix.fsf@sme.intra.citec.fi> Message-ID: <20050111004030.GA24860@grulic.org.ar> On Tue, Jan 11, 2005 at 12:33:42AM +0200, Simo Melenius wrote: > "John Lenton" writes: > > > you probably want to look into building set-like objects ontop of > > tries, given the homogeneity of your language. You should see > > imrpovements both in size and speed. > > Ternary search trees give _much_ better space-efficiency compared to > tries, at the expense of only slightly slower build and search time. > This is especially essential as the OP mentioned he could have huge > sets of data. hmm! sounds like *some*body needs to go read up on ternary trees, then. Ok, ok, I'm going... -- John Lenton (john at grulic.org.ar) -- Random fortune: Fortune finishes the great quotations, #6 "But, soft! What light through yonder window breaks?" It's nothing, honey. Go back to sleep. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From skip at pobox.com Wed Jan 12 23:12:37 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 12 Jan 2005 22:12:37 -0600 Subject: why not datetime.strptime() ? In-Reply-To: <20050111173335.GB26246@yucs.org> References: <20050111021152.GA20127@yucs.org> <16867.59681.423983.244528@montanaro.dyndns.org> <20050111173335.GB26246@yucs.org> Message-ID: <16869.62773.572880.581805@montanaro.dyndns.org> Josh> The datetime is full of these calls. Would it make sense to make Josh> this a separate patch? (Or maybe the PyImport_ImportModule could Josh> implement such a cache :) ?) Hmmm... I wonder why that wasn't done before. Perhaps it just doesn't matter performance-wise. I just checked in your changes. Thanks for the effort. Skip From steven.bethard at gmail.com Thu Jan 27 13:45:42 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 11:45:42 -0700 Subject: String Fomat Conversion In-Reply-To: <1gr2aln.1a15eud1xil75nN%aleaxit@yahoo.com> References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> <1gr2aln.1a15eud1xil75nN%aleaxit@yahoo.com> Message-ID: <-qWdnbQcLoZJq2TcRVn-vA@comcast.com> Alex Martelli wrote: > Steven Bethard wrote: > ... > >>Beware of mixing iterator methods and readline: > [snip] > > I hope this concisely indicates that the problem (in today's current > implementations) is only with switching FROM iteration TO other > approaches to reading, and (if the file is seekable) there's nothing so > problematic here that a good old 'seek' won't cure... Thanks for the clarification! Steve From newsgroups at jhrothjr.com Wed Jan 5 12:26:34 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 5 Jan 2005 11:26:34 -0600 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> Message-ID: <10to8qulnc3vke1@news.supernews.com> "Paul Rubin" wrote in message news:7xhdlwh5qs.fsf at ruckus.brouhaha.com... > "alex23" writes: >> It's called "having an opinion". "Good" documentation does its job, if >> noone else thought it was poorly documented then to them it wasn't. ... > >> In short: grow up and just write the damn documentation. I've been reading this thread and quietly congratulating myself on staying out of it, but this statement takes the cake. I would like to contribute some documentation to Python. I've got the time, I write quite a bit, etc. I've got fairly strong opinions about some things that need to be documented, (such as all the new style class descriptor stuff from 2.2) and I have relatively little difficulty matching the existing style. However, I don't know TEX, Latex, CVS or Sourceforge. (The latter two are on my "learn sometime soon so I can put PyFIT where it belongs" list.) I have no desire to install Perl to run the documentation toolchain. I also have no particular desire to write up a bunch of final format stuff and drop it on someone else to put into the latex format so it can be included. That means I'm not going to spend literally months learning all of this stuff so I can then spend the two or three days (each) it would take to write decent documentation for the places I think are lacking, and where I have the competence to write it up. I'm also not going to spend those same months writing a current source to XML translator, and then writing XSLT or more scripts to do the translations to final format, a strategy which would arguably be much more beneficial for the Python community as a whole. The bottom line is that I'm not going to be writing any extensive pieces of Python documentation. My time is better spent elsewhere. John Roth From grig.gheorghiu at gmail.com Tue Jan 18 11:22:25 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 18 Jan 2005 08:22:25 -0800 Subject: script to automate GUI application (newbie) References: Message-ID: <1106065345.967083.163970@f14g2000cwb.googlegroups.com> Bogdan, If your app is written in Java, take a look at Marathon (http://marathonman.sourceforge.net/). It uses Jython as its scripting language and it's pretty smart about how it does automation (i.e. it doesn't look at screen coordinates, but at control names). It also offers a capture/replay functionality, and it automatically builds the Jython script that drives your flow of actions. You can then edit and enhance the script manually. Grig bogdan romocea wrote: > Dear Python experts, > > I have a GUI application (Windows; apparently written in Java) which I > want to use through a script (without a mouse or keyboard). First, one > of several buttons needs to be clicked (no keyboard shortcuts > available, but I can measure the coordinates in pixels from the top > left corner of the window to the center of the button to be clicked). > Then, a window with a few drop-down lists pops up - I have to make some > choices and click OK (it's possible to navigate from one drop-down to > the next with Tab, and hit Enter for OK). > > I want to run the script above from code (if this then click "... and > OK") and perhaps by means of several desktop shortcuts (one shortcut > for each set of GUI inputs). > > Is such a script possible? If yes, how do I get there? I searched > comp.lang.python but didn't find something directly applicable (or so > it seemed to me - I'm a beginner). Directions (and sample code, if > possible) will be warmly appreciated. > > Thank you, > b. > > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - Easier than ever with enhanced search. Learn more. > http://info.mail.yahoo.com/mail_250 From deetsNOSPAM at web.de Thu Jan 20 07:50:37 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 20 Jan 2005 13:50:37 +0100 Subject: Class introspection and dynamically determining function arguments References: <359lfnF4hd6e3U1@individual.net> Message-ID: <359nmoF4koiepU1@individual.net> Nick Coghlan wrote: > > If this only has to work for classes created for the purpose (rather than > for an arbitrary class): > Certainly a step into the direction I meant - but still missing type declarations. And that's what at least I'd like to see - as otherwise you don't know what kind of editing widget to use for a property. -- Regards, Diez B. Roggisch From tzot at sil-tec.gr Wed Jan 26 06:03:18 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 26 Jan 2005 13:03:18 +0200 Subject: string.atoi and string.atol broken? References: Message-ID: <0ttev01qgb9k6a9f34g185lhohkn2p3evq@4ax.com> On Wed, 26 Jan 2005 02:10:44 +0100, rumours say that "Fredrik Lundh" might have written: >Mike Moum wrote: >> s.atoi('4',3) should result in 11 >> >> s.atoi('13',4) should result in 31 >> >> s.atoi('12',4) should result in 30 >> >> s.atoi('8',4) is legitimate, but it generates an error. >> >> Is this a bug, or am I missing something obvious? >the function's named "atoi", not "atoitoa". s.itoa(4,3) should result in '11' s.itoa(13,4) should result in '31' s.itoa(12,4) should result in '30' s.itoa(8,4) should result in '20' s.atoi('4', 3) should fail s.atoi('13', 4) should result in 7 s.atoi('12', 4) should result in 6 s.atoi('8', 4) should fail :) -- 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 max at alcyone.com Sat Jan 15 19:27:05 2005 From: max at alcyone.com (Erik Max Francis) Date: Sat, 15 Jan 2005 16:27:05 -0800 Subject: ANN: BOTEC 0.3 -- An astrophysical and orbital mechanics calculator Message-ID: Summary BOTEC is a simple astrophysical and orbital mechanics calculator, including a database of all named Solar System objects. Overview BOTEC is intended as a simple but useful calculator to assist with making astrophysical, orbital mechanics, and space navigation calculations. As the origin of the acronym applies, BOTEC is more of a "back-of-the-envelope calculator" rather than an industrial-strength calculator, although this may change in the future. BOTEC is primarily intended for people familiar with physics and Python, and as such is unlikely to be useful to the average enduser. BOTEC really consists of two parts: The BOTEC software, which knows what to do with the data, and the Solar System data itself, which is represented in a large data file (a Python pickle, actually). This is deliberately modularized so that the Solar System data BOTEC uses can be updated independently of thet software, and also that alternative data files (*e.g.*, hypothetical stellar systems for fictional purposes) can be supported. All values are strictly in SI units. Getting the software The current version of botec is 0.3. The latest version of the software is available in a tarball here: http://www.alcyone.com/software/botec/botec-latest.tar.gz. The official URL for this Web site is http://www.alcyone.com/software/botec/. Requirements BOTEC requires Python 2.3 or greater. In its present state, BOTEC will also not be of much use to endusers not familiar with Python, or people without some basic working knowledge of physics, astrophysics, orbital mechanics, and space navigation. License This code is released under the GPL. ... Release history [since 0.2] - 0.3, 2005 Jan 15. Separate transfers from maneuvers; support Oberth maneuvers. - 0.2.1, 2005 Jan 8. Various collected modifications. -- 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 quickest way of ending a war is to lose it. -- George Orwell From peter at engcorp.com Mon Jan 3 17:19:22 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Jan 2005 17:19:22 -0500 Subject: How do I make Windows Application with Python ? In-Reply-To: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> Message-ID: BOOGIEMAN wrote: > Well that's it, how do I make Windows Application with Python ??? > Is there simple way that works 100% ? How can I rework visual design > done in VS 2003 to use it for my python program ? What do you mean by "Windows Applications"? I'm running Python on Windows XP, so every program I write with Python is a "Windows application" by my definition. Obviously you are using a different one. (And if you just mean "it has a GUI", then my answer is "I use wxPython with Python". There is also Tkinter, and other options. Please ask a more specific, detailed question to get useful answers.) -Peter From Mark.English at liffe.com Wed Jan 26 06:57:18 2005 From: Mark.English at liffe.com (Mark English) Date: Wed, 26 Jan 2005 11:57:18 -0000 Subject: threading.py Condition wait overflow error Message-ID: <40E605146701DE428FAF21286A97D309174516@wphexa02.corp.lh.int> > Date: Wed, 26 Jan 2005 00:10:31 -0500 > From: Tim Peters > The most common cause for "impossible exceptions" > is flawed C code in an extension that fails to > check a Python C API call for an error return. Yes, I use a lot of C modules which I wrote. It could certainly be one of them (although which one could be an interesting challenge to find out). It may even have something to do with moving to the VC7.1 compiler. Thank you very much for your suggestion. Without it I would never have thought to look at that code. Mark ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From and-google at doxdesk.com Wed Jan 12 22:31:38 2005 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 12 Jan 2005 19:31:38 -0800 Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> Message-ID: <1105587098.932273.315230@c13g2000cwb.googlegroups.com> John Machin wrote: > I regard continued usage of octal as a pox and a pestilence. Quite agree. I was disappointed that it ever made it into Python. Octal's only use is: a) umasks b) confusing the hell out of normal non-programmers for whom a leading zero is in no way magic (a) does not outweigh (b). In Mythical Future Python I would like to be able to use any base in integer literals, which would be better. Example random syntax: flags= 2x00011010101001 umask= 8x664 answer= 10x42 addr= 16x0E800004 # 16x == 0x gunk= 36x8H6Z9A0X But either way, I want rid of 0->octal. > Is it not regretted? Maybe the problem just doesn't occur to people who have used C too long. OT: Also, if Google doesn't stop lstrip()ing my posts I may have to get a proper news feed. What use is that on a Python newsgroup? Grr. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From tim.golden at viacom-outdoor.co.uk Wed Jan 19 03:41:18 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 19 Jan 2005 08:41:18 -0000 Subject: Print to Windows default Printer Message-ID: <9A28C052FF32734DACB0A288A35339910359CC@vogbs009.gb.vo.local> [Samantha] | I am new to Python and I am having considerable trouble | trying to print | (using a simple script) to the default printer rather than the screen. | Thanks for any help. | S It may be that something here will help you: http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html Specifically, I think that the section print raw text is closest to what you're asking (although not necessarily to what you'll eventually want): http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html#win32print 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 engsolnorm at peak.org Fri Jan 14 13:43:47 2005 From: engsolnorm at peak.org (engsol) Date: Fri, 14 Jan 2005 10:43:47 -0800 Subject: Com port interrupts again Message-ID: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> I didn't fully think through my application before posting my question. Async com port routines to handle com port interrups only work well if one has access to the low level operating system. In that case the receive buffer interrupt would cause a jump to an interrupt service routine.. I don't believe that Python provides that capabilty directly. The solution then would be to write a C extention? The suggestions offered by respondents to my original post were almost all of a "Use threads, and poll as needed" flavor. You're right...I need to learn threads as applied to com ports. Norm B From R.Brodie at rl.ac.uk Wed Jan 12 11:09:36 2005 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 12 Jan 2005 16:09:36 -0000 Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> Message-ID: "Henrik Holm" wrote in message news:1gq9qs9.3snutr1s4mcn2N%news+0409 at henrikholm.com... > I suppose I could also use a lambda here -- but is there a different, > efficient, and obvious solution that I'm overlooking? Check the itertools recipes in the library documentation. From mwm at mired.org Mon Jan 3 17:28:18 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 03 Jan 2005 16:28:18 -0600 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <86652eqha5.fsf@guru.mired.org> "It's me" writes: > Well, now that they are API based, they can easily add any script language > they so wish through SWIG (www.swig.org). > > Maybe not LISP. SNOBOL would be the right thing to do. (*NOT*) SWIG generates wrappers for GUILE, which is Scheme, which looks enough like LISP to fool most people. It's the GNU extensible embeddable language. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steven.bethard at gmail.com Thu Jan 13 13:23:09 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 13 Jan 2005 11:23:09 -0700 Subject: [perl-python] 20050112 while statement In-Reply-To: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> References: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > # here's a while statement in python. > > a,b = 0,1 > while b < 20: > print b > a,b = b,a+b > > --------------- > # here's the same code in perl > > ($a,$b)=(0,1); > while ($b<20) { > print $b, "\n"; > ($a,$b)= ($b, $a+$b); > } Because you're posting this to newsgroups, it would be advisable to use only spaces for indentation -- tabs are removed by a lot of newsreaders, which means your Python readers are going to complain about IndentationErrors. Personally, I think you should not do this over comp.lang.python (and perhaps others feel the same way about comp.lang.perl.misc?) Can't you start a Yahoo group or something for this? What you're doing is probably not of interest to most of the comp.lang.python community, and might me more appropriate in a different venue. Steve From peter at somewhere.com Tue Jan 11 15:08:40 2005 From: peter at somewhere.com (Peter Maas) Date: Tue, 11 Jan 2005 21:08:40 +0100 Subject: reference or pointer to some object? In-Reply-To: References: Message-ID: <34iq5oF4c83i9U1@individual.net> Torsten Mohr schrieb: > i'd like to pass a reference or a pointer to an object > to a function. The function should then change the > object and the changes should be visible in the calling > function. [..] > is something like this possible in python? Yes, wrap it in a container, e.g. a list or an object. Change the containers content in the called function. > The keyword "global" does NOT fit this purpose to > my understanding as it only makes the variables of > the UPPERMOST level visible, not the ones of ONE > calling level above. There are three namespaces in python, sorted according to priority: - local variables of the current scope (function or method), highest priority, show with locals() - global variables of the containing module, show with globals() - builtin builtin variables, show with __builtins__.__dict__ Since Python 2.1 the local namespace can be nested e.g. if a function is defined inside a function. Example: >>> def fo(u): ... def fi(v): ... v2 = 2*v ... print locals() ... return v2 ... u2 = fi(u) ... print locals() ... return u2 ... >>> fo(4) {'v2': 8, 'v': 4} <-- inner local namespace {'fi': , 'u': 4, 'u2': 8} <-- outer local namespace 8 -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 15:33:32 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Mon, 10 Jan 2005 21:33:32 +0100 Subject: Writing huge Sets() to disk In-Reply-To: References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> Message-ID: <41E2E69C.7080104@ribosome.natur.cuni.cz> Istvan Albert wrote: > Martin MOKREJ? wrote: > > >> But nevertheless, imagine 1E6 words of size 15. That's maybe 1.5GB of raw >> data. Will sets be appropriate you think? > > > You started out with 20E20 then cut back to 1E15 keys > now it is down to one million but you claim that these > will take 1.5 GB. I gave up the theoretical approach. Practically, I might need up to store maybe those 1E15 keys. So you say 1 million words is better to store in dictionary than in a set and use your own function to get out those unique or common words? > > On my system storing 1 million words of length 15 > as keys of a python dictionary is around 75MB. Fine, that's what I wanted to hear. How do you improve the algorithm? Do you delay indexing to the very latest moment or do you let your computer index 999 999 times just for fun? > > I. From bokr at oz.net Wed Jan 12 05:10:26 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 12 Jan 2005 10:10:26 GMT Subject: Another look at language comparisons References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> <1105188426.955508.263030@c13g2000cwb.googlegroups.com> <41e00ac1$0$265$edfadb0f@dread12.news.tele.dk> <34kaf5F4ag9k6U1@individual.net> Message-ID: <41e4f770.646970063@news.oz.net> On Wed, 12 Jan 2005 17:54:49 +0800, Jon Perez wrote: >Max M wrote: >> Jan Dries wrote: >> >>> beliavsky at aol.com wrote: >>> And there is hope for Python, as Guido has recently been seen with a >>> beard :-) >>> http://www.tbray.org/ongoing/When/200x/2004/12/08/-big/IMG_3061.jpg >> >> >> LOL, he is working on linux, isn't he? >> >> So it was about bloody time. > >Guido Van Rossum is now working on linux?? Are they both left-handed? Hm, sinister ... Regards, Bengt Richter From bvande at po-box.mcgill.ca Sat Jan 22 20:46:11 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 22 Jan 2005 20:46:11 -0500 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xbrbhosh7.fsf@ruckus.brouhaha.com> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> Message-ID: <41F301E3.9000904@po-box.mcgill.ca> Paul Rubin said unto the world upon 2005-01-22 20:16: > "Fredrik Lundh" writes: > >>>You're not making any bloody sense. >> >>oh, I make perfect sense, and I think most people here understand >>why I found your little "lecture" so funny. if you still don't get >>it, maybe some- one can explain it to you. > > > I would appreciate it if someone did. Hi, no Python expert, just a hobbyist. But, I think I can take this one on: Fredrik's contributed a lot to Python. The Standard Library book, several well know tools, and, I'd wager a finger, a fair bit of code in the standard lib. I don't think the community gives you a name like F-bot, but that you know a wee bit about how Python is actually used, etc. Best, Brian vdB From steve at holdenweb.com Mon Jan 10 20:15:53 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Jan 2005 20:15:53 -0500 Subject: exceptions and items in a list In-Reply-To: References: Message-ID: vincent wehren wrote: > rbt wrote: > >> If I have a Python list that I'm iterating over and one of the objects >> in the list raises an exception and I have code like this: >> >> try: >> do something to object in list >> except Exception: >> pass >> >> Does the code just skip the bad object and continue with the other >> objects in the list, or does it stop? >> >> Thanks > > > Fire up a shell and try: > > >>> seq = ["1", "2", "a", "4", "5", 6.0] > >>> for elem in seq: > .... try: > .... print int(elem) > .... except ValueError: > .... pass > > > and see what happens... > > -- > Vincent Wehren I suspect the more recent versions of Python allow a much more elegant solution. I can't remember precisely when we were allowed to use continue in an except suite, but I know we couldn't in Python 2.1. Nowadays you can write: 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. >>> for i in [1, 2, 3]: ... try: ... print i ... if i == 2: raise AttributeError, "Bugger!" ... except AttributeError: ... print "Caught exception" ... continue ... 1 2 Caught exception 3 >>> To terminate the loop on the exception you would use "break" instead of "continue". 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 harold.fellermann at upf.edu Thu Jan 13 12:06:43 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 13 Jan 2005 18:06:43 +0100 Subject: Tix.FileSelectDialog wait for user? Message-ID: <7FE013CC-6585-11D9-B3E0-003065FB7B26@upf.edu> Hi, I have a question concerning the Tix file select mechanisms. Unfortunately, I have very little experience with neither tk, Tkinter nor Tix. Somewhere in my GUI I have a save button. What I want is that pressing the button opens a file requester. The user can either select a filename or cancel the action. I have found Tix.FileSelectDialog which seems to be nice for the task. But how can I use this dialog after all? how can I e.g. attach a command to the "Ok"-Button. Or isn't there a simple function that 1.) opens the requester 2.) waits until the requester is closed 3.) returns either a string (filename) or None (canceled) so that I can just write something like: fname = FileSelect() if fname != None : do_something_with(fname) Damn, I hate Tk's and Tix' so called "manuals": The Tk manual takes a user and makes it into a grammar parser. Further information, like common usage or examples, that might normally be expected in a manual cannot be found with no additional arguments. The Tk manual returns the completely clueless programmer. Start to like pydoc(Tkinter) and pydoc(Tix), though :-) - harold - -- "Mr Ghandi, what do you think of western civilization?" "Oh, this would be a great idea." From rmemmons at member.fsf.org Wed Jan 5 21:37:52 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Wed, 05 Jan 2005 20:37:52 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: > I'd go further. It's not possible to force anyone to share, but the > GPL aims to remove software from a system that instead aims to force > people NOT to share. Well said. I do think the point is -- no one liscence fits all. The GPL is a great tool for those that write software for the purpose of sharing with those that want to mutually share. Personally it has the feel of justice to me -- but that's just me. But of course it does not fit all needs and the politics and personalities of all developers and teams of developers. For example, RMS developed the LGPL for other cases where it makes sense, and I think I read somewhere that RMS encouraged the release of BSD (is that right?) -- because that too is a help to free software in the end. As for Python -- I think the best liscence depends on the goals of the developers. If you want python to be infrastructure, especially, for applciation scripting -- it's kind of nice that it's BSD like or perhaps LGPL, on the other hand if you want it to be free software focused -- then GPL would be better. So there are many alternatives depending on goals. You see this played out throughout the Open Source community. In any case -- regardless of liscence -- I think Python is the greatest and I have great respect for all those that have made it possible. Rob From steven.bethard at gmail.com Wed Jan 19 01:09:57 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 18 Jan 2005 23:09:57 -0700 Subject: generator expressions: performance anomaly? In-Reply-To: <41edcc68.1225778626@news.oz.net> References: <377Hd.77904$Jk5.30235@lakeread01> <41ED1C0F.4030800@holdenweb.com> <41eda453.1215517842@news.oz.net> <41edcc68.1225778626@news.oz.net> Message-ID: <_NCdnVV_I9UrZHDcRVn-og@comcast.com> Bengt Richter wrote: > On Tue, 18 Jan 2005 17:38:20 -0700, Steven Bethard wrote: > > >>Bengt Richter wrote: >> >>>Which make me wonder what plans there are for providing a better >>>mechanism than default arguments as a way of initializing local function >>>variables. Nested def's to create a closure with initialized values is >>>pretty crufty for that, IMO. >> >>What about using a class? Associating functions with data is pretty >>much what they're for... >> >> >>>Maybe extending the default argument space >>>with whatever comes after e.g. a triple star delimiter in the argument list, >>>but which wouldn't be counted as part of the normal arguments? E.g., >>> >>> def foo(x, y=123, *args, **kw, *** i=1, deftime=time.ctime()): >>> return x*y, kw.get('which_time')=='now' and time.ctime() or deftime >> >>If what you want is to have i=1 and deftime=time.ctime() available >>within foo, you could do something like (untested): >> >>class foo(object): >> def __init__(self): >> self.i = 1 >> self.deftime = time.ctime() >> def __call__(self, x, y=123, *args, **kwds): >> return x*y, (kw.get('which_time') == 'now' >> and time.ctime() or self.deftime) >>foo = foo() > > Total: 8 lines, much irrelevant cruft. > > >>Or if you don't like 'foo = foo()', you could probably abuse the __new__ >>method (also untested): >> >>class foo(object): >> i = 1 >> deftime = time.ctime() >> def __new__(cls, x, y=123, *args, **kwds): >> return x*y, (kw.get('which_time') == 'now' >> and time.ctime() or self.deftime) > > Total: 6 lines, newbie-unfriendly abuse of __new__ ;-) > > >>I guess my point is that if you want attribute associated with the >>function, it's often easy enough to write a class instead... > > vs. 2 easy lines with minimal irrelevant cruft ;-) If you're really counting lines, you might compare with the more compact: class foo(object): def __init__(self): self.i, self.deftime = 1, time.ctime() def __call__(self): return x*y, kw.get('which_time') == 'now' and time.ctime() or self.deftime foo = foo() and class foo(object): i, deftime = 1, time.ctime() def __new__(cls, x, y=123, *args, **kwds): return x*y, kw.get('which_time') == 'now' and time.ctime() or self.deftime And probably what you want to compare is N lines (function only) versus N + 2 lines (using __new__) and N + 4 lines (using __call__). If N is more than 2 lines (which is probably true in most cases), the difference isn't so dramatic. Using a class also has the advantage that, assuming one already knows how classes work (which any Python programmer who wants the kind of scoping you're talking about should) you don't have to learn how something new to be able to use it -- that is, *** -> bound locals that don't contribute to arguments but are listed in the same place as arguments. If you really want locals that don't contribute to arguments, I'd be much happier with something like a decorator, e.g.[1]: @with_consts(i=1, deftime=time.ctime()) def foo(x, y=123, *args, **kw): return x*y, kw.get('which_time')=='now' and time.ctime() or deftime Then you don't have to mix parameter declarations with locals definitions. Steve [1] I have no idea how implementable such a decorator would be. I'd just like to see function constants declared separate from arguments since they mean such different things. From irmen at -nospam-remove-this-xs4all.nl Tue Jan 18 13:54:25 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 18 Jan 2005 19:54:25 +0100 Subject: hex notation funtion In-Reply-To: References: Message-ID: <41ed5b61$0$6211$e4fe514c@news.xs4all.nl> tertius wrote: > Hi, > > Is there a builtin function that will enable me to display the hex > notation of a given binary string? (example below) Does this help: >>> "hello".encode("hex") '68656c6c6f' >>> "deadbeef".decode("hex") '\xde\xad\xbe\xef' ? --Irmen From bj_666 at gmx.net Sat Jan 8 15:48:26 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 08 Jan 2005 21:48:26 +0100 Subject: EOF for binary? References: <1105147072.909665.242360@z14g2000cwz.googlegroups.com> Message-ID: In <1105147072.909665.242360 at z14g2000cwz.googlegroups.com>, flamesrock wrote: > os.path.getsize(infile) <= infile.tell() > > Because that returns the error: > # File "/usr/lib/python2.3/posixpath.py", line 142, in getsize > # return os.stat(filename).st_size > #TypeError: coercing to Unicode: need string or buffer, file found > for me. This error message gives a good hint what's wrong with your code snippet. >>> f = open('tmp.txt') >>> os.path.getsize(f) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/posixpath.py", line 142, in getsize return os.stat(filename).st_size TypeError: coercing to Unicode: need string or buffer, file found Something expected a string instead of a file object. >>> os.path.getsize("tmp.txt") 28190L Ciao, Marc 'BlackJack' Rintsch From aorfanakos at gmail.com Fri Jan 28 09:17:38 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 28 Jan 2005 06:17:38 -0800 Subject: python: can't open file 'timeit.py' Message-ID: <1106921858.598528.77300@f14g2000cwb.googlegroups.com> Hello. Under Gentoo Linux, I issue: $ python timeit.py python: can't open file 'timeit.py' $ ls -al /usr/lib/python2.3/timeit.py -rw-r--r-- 1 root root 9833 Oct 19 02:17 /usr/lib/python2.3/timeit.py But if I specify the full path, it works: $ python /usr/lib/python2.3/timeit.py -n 1 "pass" 1 loops, best of 3: 3.1 usec per loop Any ideas how can I fix this? I think it may have to do with where Python looks for modules, but I am not sure. Thanks in advance. From skip at pobox.com Fri Jan 21 11:23:50 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 21 Jan 2005 10:23:50 -0600 Subject: ElementTree.findtext() In-Reply-To: References: Message-ID: <16881.11414.228817.410692@montanaro.dyndns.org> Richie> I realised what the problem was the second after I hit Send (why Richie> is it never the second *before*?) So you could enlighten those of us who didn't realize what the problem was, even ten seconds later than that... Richie> The tree represents the top-level element, so of course Richie> searching within it for 'html' fails. Thanks... Skip From jeff at ccvcorp.com Thu Jan 13 13:36:21 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 13 Jan 2005 10:36:21 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <1105632841.461042.68310@c13g2000cwb.googlegroups.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> <1105632841.461042.68310@c13g2000cwb.googlegroups.com> Message-ID: <10udfj4c4rgkvcc@corp.supernews.com> Chris Lasher wrote: >>Given that the information content is 2 bits per character >>that is taking up 8 bits of storage, there must be a good reason >>for storing and/or transmitting them this way? I.e., it it easy >>to think up a count-prefixed compressed format packing 4:1 in >>subsequent data bytes (except for the last byte which have >>less than 4 2-bit codes). > > My guess for the inefficiency in storage size is because it is > human-readable, and because most in-silico molecular biology is just a > bunch of fancy string algorithms. This is my limited view of these > things at least. Yeah, that pretty much matches my guess (not that I'm involved in anything related to computational molecular biology or genetics). Given the current technology, the cost of the extra storage size is presumably lower than the cost of translating into/out of a packed format. Heck, hard drives cost less than $1/GB now. And besides, for long-term archiving purposes, I'd expect that zip et al on a character-stream would provide significantly better compression than a 4:1 packed format, and that zipping the packed format wouldn't be all that much more efficient than zipping the character stream. Jeff Shannon Technician/Programmer Credit International From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 16:28:44 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Mon, 10 Jan 2005 22:28:44 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <1f7befae0501101245679b26f2@mail.gmail.com> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> <41E2E69C.7080104@ribosome.natur.cuni.cz> <1f7befae0501101245679b26f2@mail.gmail.com> Message-ID: <41E2F38C.30200@ribosome.natur.cuni.cz> Tim Peters wrote: > [Martin MOKREJ?] > >>... >> >>I gave up the theoretical approach. Practically, I might need up >>to store maybe those 1E15 keys. > > > We should work on our multiplication skills here . You don't > have enough disk space to store 1E15 keys. If your keys were just one > byte each, you would need to have 4 thousand disks of 250GB each to > store 1E15 keys. How much disk space do you actually have? I'm > betting you have no more than one 250GB disk. Can get about 700GB on raid5, but this doesn't help here of course. :( I definitely appreciate your comments, I somehow forgot to make sure I can store it. I was mainly distracted by the fact I might anyway hit almost the same size, if there's too few words used in reality. Therefore when looking for those words not found in such a dictionary, I'd be close to the teoretical, maximal size of say in order of E15 or E14. > ... > > [Istvan Albert] > >>>On my system storing 1 million words of length 15 >>>as keys of a python dictionary is around 75MB. > > >>Fine, that's what I wanted to hear. How do you improve the algorithm? >>Do you delay indexing to the very latest moment or do you let your >>computer index 999 999 times just for fun? > > > It remains wholly unclear to me what "the algorithm" you want might My intent is do some analysis in protein science. But it can be really thought of as analysing those 4 different languages. > be. As I mentioned before, if you store keys in sorted text files, > you can do intersection and difference very efficiently just by using > the Unix `comm` utiltity. Now I got your point. I understand the comm(1) is written in C, but it still has to scan file1 once and file2 n-times, where n is a number of lines in file1, right? Without any index ... I'll consider it, actually will test, thanks! I was really hoping I'll get an answer how to alter the indexes for dictionaries in python. You convinced me not to even try to construct to theoretical dictionary, as it will take ages just to create. Even if I'd manage, I couldn't save it (the theoretical and possibly not even the dict(theoret) - dict(real) result). Still, before I give the whole project, once more: I'll parse some text files, isolates separate words and add them to either Set(), list, dict, flatfile line by line. Depending on the above, I'll compare them and look for those unique to some "language". I need to keep track of frequencies used in every such language, so the dict approach would be the best. The number stored as a value vould be a float ^H^H^H^H^H^H Decimal() type - very small number. Once more, I expect to have between E4 or E5 to E8??? words stored in 20 dictionaries (remember words of sizes in range 1-20? Every of those 20 dictionaries should be, I believe, indexed just once. The indexing method should know all entries in a given file are of same size, i.e. 5 chars, 15 chars, 20 chars etc. I already did implement the logic to walk through those 20 different dictionaries from language a and from language b and find uout those unique to a or common to both of them. Why I went to ask on this list was to make sure I took right approach. Sets seemed to be better solution for the simple comparison (common, unique). To keep track of those very small frequencies, I anyway have to have dictionaries. I say that again, how can I improve speed of dictionary indexing? It doesn't matter here if I have 10E4 keys in dictionary or 10E8 keys in a dictionary. Or I wanted to hear: go for Sets(), having set with 1E8 keys might take 1/10 of the size you need for a dictionary ... but you cannot dump them efficiently on a disk. Using shelve will cost you maybe 2x the size of dictionary approach and will be also slover that writing dictionary directly. Something along these words. I really appreciate your input! Martin From cwilbur at mithril.chromatico.net Sun Jan 9 14:39:29 2005 From: cwilbur at mithril.chromatico.net (Charlton Wilbur) Date: Sun, 09 Jan 2005 19:39:29 GMT Subject: unicode support References: <1105259315.471816.291600@c13g2000cwb.googlegroups.com> Message-ID: <87r7ku5riu.fsf@mithril.chromatico.net> >>>>> "xah" == xah writes: xah> python supports unicode in source xah> code by putting a coding declaration as the first line. [...] xah> In perl, support of unicode is very flaky. The language does xah> not support it, [...] All: Xah Lee is trolling. (Whether he's *only* a troll, or a reasonable person who occasionally trolls to amuse himself, is a matter of perspective.) Please note the inaccuracy of his comment on Perl and the two newsgroups to which this message was posted before replying; this is a clear case of "lets you and him fight." Charlton -- cwilbur at chromatico dot net cwilbur at mac dot com From tundra at tundraware.com Wed Jan 12 04:28:28 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 12 Jan 2005 04:28:28 EST Subject: [ANN]: twander 3.160 Released And Available Message-ID: <41E4ED28.60906@tundraware.com> 'twander' Version 3.160 is now released and available for download at: http://www.tundraware.com/Software/twander The last public release was 3.146. Existing users are encouraged to upgrade to this release as it has a number of bug fixes and several nice new features including: - Mouse popups for all the menus (except Help). - Ability to force Unix-style paths under Windows when doing substitutions in command macros. (Very helpful for cygwin users.) - A smarter "adaptive" directory refresh mechanism. - A new "Shortcut" menu for fast navigation around the filesystem. Complete details of all fixes, changes, and new features can be found in the WHATSNEW.txt file included in the distribution. Users are strongly encouraged to join the twander-users mailing list as described in the documentation. What Is 'twander'? ------------------ 'twander' is a macro-programmable Filesystem Browser that runs on both Unix-like systems as well as Win32 systems. It embraces the best ideas of both similar GUI-driven programs (Konqueror, Windows Explorer) as well as text-based interfaces (Midnight Commander, List, Sweep). Or, If You Prefer The "Elevator Pitch" -------------------------------------- 'twander' is: - A better file browser for Unix and Win32. (Tested on FreeBSD, Linux, Win32.) - A way to make browsing the same on all the OSs you use. - A macro-programmable tool that lets *you* define the features. - A GUI navigation front-end for your shell. - A way to "can" workflows for your technically-challenged colleagues. - A way to free yourself from the shackles of the mouse. - A way to significantly speed up your day-to-day workflow. - A Python/Tkinter application - about 3100/1300 lines of code/comments - A RCT (Really Cool Tool) that will have you addicted in a day or two See the web page for more information, a screen shot, and the complete documentation. ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From rbt at athop1.ath.vt.edu Sun Jan 2 14:18:18 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sun, 02 Jan 2005 14:18:18 -0500 Subject: arbitrary number of arguments in a function declaration Message-ID: How do I set up a function so that it can take an arbitrary number of arguments? For example, I have a bunch of expenses which may grow or shrink depending on the client's circumstance and a function that sums them up... hard coding them is tedious. How might I make this dynamic so that it can handle any amount of expenses? def tot_expenses(self, e0, e1, e2, e3): pass From frans.englich at telia.com Mon Jan 17 16:43:23 2005 From: frans.englich at telia.com (Frans Englich) Date: Mon, 17 Jan 2005 21:43:23 +0000 Subject: Assigning to self In-Reply-To: References: Message-ID: <200501172143.23022.frans.englich@telia.com> On Monday 17 January 2005 21:24, Peter Otten wrote: > Frans Englich wrote: > > On Monday 17 January 2005 20:03, John Roth wrote: > >> "Frans Englich" wrote in message > > > > > > > >> In other words, you're trying to create a singleton. In general, > >> singletons are frowned on these days for a number of reasons, > >> not least because of the difficulty of testing them. > > > > Then I have some vague, general questions which perhaps someone can > > reason from: what is then the preferred methods for solving problems > > which requires Singletons? Is it only frowned upon in Python code? > > Sorry, no answer here, but do you really want a singleton? > > Singleton: "Ensure a class only has one instance, and provide a global > point of access to it" > > whereas > > Flyweight: "Use sharing to support large numbers of fine-grained objects > efficiently" > > as per "Design Patterns" by Gamma et al. Hehe :) Singleton sounds like what I want, but OTOH I do not know what Flyweight is, except for sounding interesting. Darn, I really must save for that Design Patterns by GOF. Cheers, Frans From michele.simionato at gmail.com Thu Jan 6 04:05:57 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 6 Jan 2005 01:05:57 -0800 Subject: python-dev Summary for 2004-11-16 through 2004-11-30 In-Reply-To: References: Message-ID: <1105002357.261642.292880@f14g2000cwb.googlegroups.com> > Would you like the source with your function? Yes, since I asked for this feature something like two years ago ;-) Michele Simionato From __peter__ at web.de Wed Jan 26 03:17:15 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Jan 2005 09:17:15 +0100 Subject: string.atoi and string.atol broken? References: Message-ID: Nick Coghlan wrote: > Huh - you remind me that I forgot to put the "show_base" Bengt and I came > up with into the ASPN cookbook. . . > > Py> def show_base(val, base, min_digits=1, complement=False, > ...???????????????digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"): > ...???if?base?>?len(digits):?raise?ValueError("Not?enough?digits?for > base") ...???negative?=?val? ...???val?=?abs(val) > ...???if?complement: > ...?????sign?=?"" > ...?????max?=?base**min_digits > ...?????if?(val?>=?max)?or?(not?negative?and?val?==?max): > ...???????raise?ValueError("Value?out?of?range?for?complemented?format") > ...?????if?negative: > ...???????val?=?(max?-?val) > ...???else: > ...?????sign?=?"-"?*?negative > ...???val_digits?=?[] > ...???while?val: > ...?????val,?digit?=?divmod(val,?base) > ...?????val_digits.append(digits[digit]) > ...???result?=?"".join(reversed(val_digits)) > ...???return?sign?+?("0"?*?(min_digits?-?len(result)))?+?result > ... > Yes, that is a bit more general. For the cookbook you might consider factoring out the "".join() operation, thus entirely removing the upper limit for the base (the output of the first step would be a tuple of integers). Peter From stuart at zapata.org Fri Jan 21 07:25:27 2005 From: stuart at zapata.org (Stu) Date: 21 Jan 2005 04:25:27 -0800 Subject: map in Python Message-ID: <1106310327.213874.305660@f14g2000cwb.googlegroups.com> I have recently switched over to Python from Perl. I want to do something like this in Python: @test = ("a1", "a2", "a3"); map {s/[a-z]//g} @test; print @test; However, I take it there is no equivalent to $_ in Python. But in that case how does map pass the elements of a sequence to a function? I tried the following, but it doesn't work because the interpreter complains about a missing third argument to re.sub. import re test = ["a1", "a2", "a3"] map(re.sub("[a-z]", ""), test) print test Thanks in advance. Regards, Stuart From harold.fellermann at upf.edu Fri Jan 21 23:11:46 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Sat, 22 Jan 2005 05:11:46 +0100 Subject: Class introspection and dynamically determining functionarguments In-Reply-To: <40E605146701DE428FAF21286A97D30917450D@wphexa02.corp.lh.int> References: <40E605146701DE428FAF21286A97D30917450D@wphexa02.corp.lh.int> Message-ID: On 20.01.2005, at 12:24, Mark English wrote: > I'd like to write a Tkinter app which, given a class, pops up a > window(s) with fields for each "attribute" of that class. The user > could > enter values for the attributes and on closing the window would be > returned an instance of the class. The actual application I'm > interested > in writing would either have simple type attributes (int, string, > etc.), > or attributes using types already defined in a c-extension, although > I'd > prefer not to restrict the functionality to these requirements. I am working on nearly the same thing! Small sort of generic attribute editor in Tkinter (and Tix). Altough my implementation is still very unpythonic (== ugly) in many places, it can edit the attributes of instances and classes, as well as generate new instances / classes. I would like to create new attributes or delete them as well, but haven't done it so far. A still faraway dream would be, to allow the user to enter source code, that will be compiled into byte code and assign it to the instance, so the user can modify code at run time (if it is possible to disallow access to insecure modules while code is compiled). > Secondly, the code won't know exactly how to initialise the class > instance used to determinte the attributes. Do I need to make it a > prerequesite that all instances can be created with no arguments ? I did it this way, too. Maybe you can provide a parameterless __new__ in addition to the __init__. I imagine this is the way that e.g. pickle does the job. Well, I don't know. Let this sentence just be an invitation for an expert to write something here. > Should I force/allow the user to pass an instance instead of a class ? However you like. I prefer passing classes, otherwise you end up in a situation where you need to create dummy instances that are only used as "copying templates". If you get an instance: foo = type(bar)() would give you an instance of the same class as bar. But this just looks like a hack to me when compared to foo = Bar(). Passing an instance allows you to look at its __dict__ of course. But you have no assurance that the variables you find there are present in all instances of that class. Phython is just to dynamic for that. > Should I be using inspect.getargspec on the class __init__ method and > then a loop with a try and a lot of except clauses, or is there a nicer > way to do this ? Presumably the pickling code knows how do > serialise/deserialise class instances but I'm not sure how I'd use this > without already having a class instance to hand. Personally, I ended up writing a class Attribute that provides access to the attributes and allows more finetuning than a generic approach would do (think of e.g. validation). My overall setting works like this: For each attribute that you want to appear in the GUI you define an Attribute class Attribute(object) : def __init__(self, name, # name of the attribute type, # specifies the widget type values=None, # then OptionMenu is used instead validate=None, # if given, a callable that returns # either True or False get=None, # callable to get the actual value # None: generic getattr() widget_options={} # passed to the Tix widget used ) : pass # [...] The "controller" of an editable object gets the object and a list of those Attribute()'s. There is a generic one that handles validation and generic setattr(), but can be overwritten to allow more sophisticated stuff. When creating a new instance, I ask for initial arguments which I know (like __name__ and __doc__ if its a class that I create) in nearly the same way. If you already have your instance, it is possible to generate the Attribute()-list from the dict of this instance: attributes = [ Attribute(name,type(getattr(instance,name))) for name in dir(instance) ] > Lastly, does such an app already exist ? As you see, my solution is not as general as what you might have in mind. I needed to finetune so much of the underlying generic plan, that it looks more like declaration-based now. Anyway, if you are interested: This is the edit part of my app (It's only the mapping from attributes to widgets, so no instance creation in this part). As this was only a short snippet in the project I am doing, I could, never give it the time it deserved. So I am sure that my code is not the best sollution, but maybe it serves as a starting point for further discussion. All the best, - harold - import Tkinter import Tix class Attribute(object) : def __init__(self, name, type, values=None, validate=None, get=None, widget_options={} ) : if not get : get = lambda obj : getattr(obj,name) self.name = name self.type = type self.values = values self.get = get self.validate = validate self.widget_options = widget_options self.label = None self.widget = None class Edit(Tkinter.Frame) : import types def __init__(self,obj,items) : self.obj = obj self.items = items def create_widgets(self,master,**options) : Tkinter.Frame.__init__(self,master,**options) for item in self.items : if item.values : widget = Tix.OptionMenu(master,label=item.name) for v in item.values : widget.add_command(str(v),label=str(v)) item.label = None item.widget = widget else : widget = self.widget_types[item.type](master) widget.config(label=item.name,**item.widget_options) item.label = widget.label item.widget = widget.entry widget.pack(side=Tkinter.TOP,fill=Tkinter.X) self.pack() def update_widget(self,item) : if isinstance(item.widget,Tix.OptionMenu) : item.widget.set_silent(item.get(self.obj)) else : item.widget.delete(0,Tkinter.END) item.widget.insert(0,item.get(self.obj)) def update_widgets(self) : for item in self.items : self.update_widget(item) def validate(self,item) : if isinstance(item.widget,Tix.OptionMenu) : return True value = item.widget.get() if item.validate : valid = item.validate(value) elif item.values : valid = value in item.values else : try : valid = item.type(value) except ValueError : valid = False if valid : item.label.config(fg="black") else : item.label.config(fg="red") item.widget.focus_set() return valid def isvalid(self) : for item in self.items : if not self.validate(item) : return False return True def apply(self) : if self.isvalid() : for item in self.items : try : value = item.type(item.widget.get()) except AttributeError : value = item.type(item.widget.cget("value")) if value != item.get(self.obj) : setattr(self.obj,item.name,value) widget_types = { types.StringType : Tix.LabelEntry, types.IntType : Tix.Control, types.FloatType : Tix.LabelEntry, } if __name__ == "__main__" : class myClass : string = "hello world" float = 1. int = 0 proxy = Edit( myClass, [ Attribute("string",type(str())), Attribute("float",type(float())), Attribute("int",type(int()),validate=lambda x : int(x) in [-1,0,1] ) ] ) win = Tix.Tk(None) proxy.create_widgets(win) proxy.update_widgets() button1 = Tkinter.Button( win, text="apply", command=proxy.apply ) button1.pack() button2 = Tkinter.Button( win, text="update", command=proxy.update_widgets ) button2.pack() win.mainloop() -- Man will occasionally stumble over the truth, but most of the time he will pick himself up and continue on. -- Winston Churchill From news+0409 at henrikholm.com Wed Jan 12 10:54:12 2005 From: news+0409 at henrikholm.com (Henrik Holm) Date: Wed, 12 Jan 2005 09:54:12 -0600 Subject: Iteration over two sequences Message-ID: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> I am just starting to learn Python, mostly by going through the examples in Dive Into Python and by playing around. Quite frequently, I find the need to iterate over two sequences at the same time, and I have a bit of a hard time finding a way to do this in a "pythonic" fashion. One example is a dot product. The straight-ahead C-like way of doing it would be: def dotproduct(a, b): psum = 0 for i in range(len(a)): psum += a[i]*b[i] return psum However, the range(len(a)) term is awfully un-pythonic :) The built-in function map() gives me a way of "transposing" the a list and the b list, and now I can handle it with a list comprehension: def dotproduct(a, b): return sum([x*y for x, y in map(None, a, b)]) My concern is one of efficiency: it seems to me that I have two loops there: first one implied with map(...) and then the for loop -- which seems like a waste since I feel I should be able to do the multiplication via an argument to map. So far I have come up with an alternative via defining a separate function: def dotproduct(a, b): def prod(x,y): return x*y return sum(map(prod, a, b)) I suppose I could also use a lambda here -- but is there a different, efficient, and obvious solution that I'm overlooking? Thanks, Henrik -- "On some great and glorious day the plain folks of the land will reach in their heart's desire at last and the White House will be adorned by a downright moron." -H.L. Mencken (1880-1956) American Writer From tjreedy at udel.edu Sun Jan 9 21:17:43 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 9 Jan 2005 21:17:43 -0500 Subject: Python3: on removing map, reduce, filter References: <34csn1F4a46hqU1@individual.net> Message-ID: "Andrey Tatarinov" wrote in message news:34csn1F4a46hqU1 at individual.net... > How does GvR suggestions on removing map(), reduce(), filter() While GvR *might* prefer removing them completely on any given day, I think moving them to a functional module, as others have suggested and requested, is currently more likely. I believe that GvR has indicated at times that this would be an acceptible compromise. I am one of those who think the list of builtins is currently too long to be easily grasped and should be shrunk. Terry J. Reedy From tjreedy at udel.edu Tue Jan 18 02:32:08 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Jan 2005 02:32:08 -0500 Subject: wxPython and PyGame - do they play well together? References: <1106026599.092269.292170@c13g2000cwb.googlegroups.com> Message-ID: "Erik Bethke" wrote in message news:1106026599.092269.292170 at c13g2000cwb.googlegroups.com... > I am having a great time with python and pygame, and last night I took > a long look at the wxPython demo. I think that rocks as well. > > So now, my question is do wxPython and PyGame work together? I have no personal experience, but based on posts to the Pygame mailing list, also accessible via Google or as newsgroup thru Gmane (where I read it), the answer is yes. The subject of Pygame with guis has been discussed in the past couple of months. I recommend that you read the archives for the recent past and then join the list or subscribe via gmane or google. It is a low volume, low noise, list. Terry J. Reedy From belred1 at yahoo.com Sat Jan 1 18:15:32 2005 From: belred1 at yahoo.com (Bryan) Date: Sat, 01 Jan 2005 23:15:32 GMT Subject: what would you like to see in a 2nd edition Nutshell? In-Reply-To: References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> <1104424176.958689.285570@z14g2000cwz.googlegroups.com> Message-ID: Nick Coghlan wrote: > JoeG wrote: > >> wxPython takes on more of the native platform's interface. I say seems >> to because I haven't actually written any code with it. > > > While Tkinter is the GUI toolkit shipped *with* Python, then that's the > correct toolkit for Alex to cover in PiaN. Mentioning other toolkits > (and providing references for additional information, including books if > they're available) seems like the most reasonable alternative. > > Now, if we could just switch to wxPython and Boa Constructor for Py3K. . . > > Cheers, > Nick. > Sorry Kurt! > i would prefer PiaN not to cover any gui toolkits, and instead use that space for more core funcionality. thanks, bryan From itsme at yahoo.com Thu Jan 6 11:44:22 2005 From: itsme at yahoo.com (It's me) Date: Thu, 06 Jan 2005 16:44:22 GMT Subject: Another PythonWin Excel question References: <344586F48830bU1@individual.net> Message-ID: "Marten Bauer" wrote in message news:344586F48830bU1 at individual.net... > > I did it yesterday like this way and it works well (part of my code): > > wb.Worksheets.Add(Count=nrMonths,After=wb.Worksheets(1)) > > As I read in MSDN you could not write After="sheet1" instead you must > use the Object of sheet1 like in my example and it works well in my > case. The Count=... statement will create n Sheets after the first worksheet > Yes, I learn that as well. The parameter to After is a Worksheet object. It appears if you don't specify any parameters, it would add it Before the current sheet. Thanks, > > By > Marten From mike.kreiner at gmail.com Fri Jan 14 00:58:36 2005 From: mike.kreiner at gmail.com (mike kreiner) Date: 13 Jan 2005 21:58:36 -0800 Subject: import problems *newbie* Message-ID: <1105682316.601321.118820@f14g2000cwb.googlegroups.com> I am having trouble importing a module I created. I'm running PythonWin on Windows XP if that helps. I saved my module in a folder called my_scripts in the site-packages directory. I edited the python path to include the my_scripts folder (it now reads C:\Python23\Lib;C:\Python23\DLLs;C:\Python23\Lib\lib-tk;C:\Python23\Lib\site-packages\my_scripts). When I try to import the module, I get this error: >>> from PolyDraw import * Traceback (most recent call last): File "", line 1, in ? ImportError: No module named PolyDraw When I select Browse PythonPath from the tools menu, I'm able to locate my module, PolyDraw.py. The problem goes away if I open PolyDraw.py from PythonWin, which I'm assuming is because opening the module makes my_scripts the current working directory. This is just a quick workaround, but I'd like to know how to fix the problem. Thanks. -Mike From vmlinuz at abisen.com Fri Jan 7 12:15:48 2005 From: vmlinuz at abisen.com (Anand S Bisen) Date: Fri, 07 Jan 2005 12:15:48 -0500 Subject: how to extract columns like awk $1 $5 Message-ID: <41DEC3C4.2030103@abisen.com> Hi Is there a simple way to extract words speerated by a space in python the way i do it in awk '{print $4 $5}' . I am sure there should be some but i dont know it. Thanks n00b From peter at engcorp.com Mon Jan 3 17:10:31 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Jan 2005 17:10:31 -0500 Subject: Advice request for project In-Reply-To: <41D957B1.3040500@holdenweb.com> References: <41D957B1.3040500@holdenweb.com> Message-ID: Steve Holden wrote: > Look at the Pyrex package to get you started thinking about remote > execution and client/server communications. This lets a program on one > machine call methods on objects on another machine. Steve meant to say "Pyro", not "Pyrex". The former is what he actually described. The latter is actually a Python-like language that lets one write code that can be compiled as an extension module, to write performance-critical code or interface to existing libraries more easily. -Peter From ncoghlan at iinet.net.au Sat Jan 8 23:43:50 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 14:43:50 +1000 Subject: python3: 'where' keyword In-Reply-To: <41dfc018.305122743@news.oz.net> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> Message-ID: <41E0B686.4090305@iinet.net.au> Bengt Richter wrote: > On Sat, 08 Jan 2005 16:42:16 +1000, Nick Coghlan wrote: > And, is the whole thing after the '=' an expression? E.g., > > x = ( foo(x) where: > x = math.pi/4.0 > ) where: > def foo(x): print 'just for illustration', x > > or is this legal? > > for y in ([foo(x) for x in bar] where: > bar = xrange(5) > ): baz(y) where: > def baz(arg): return arg*2 > > Not trying to sabotage the idea, really, just looking for clarification ;-) Actually, I was conceiving this as an addition to the grammar for the relevant 'simple statements', rather than to the grammar for expressions. Using the assignment statement as the ongoing example: Current: assignment_stmt ::= (target_list "=")+ expression_list augmented_assignment_stmt ::= target augop expression_list New: assignment_stmt ::= (target_list "=")+ expression_list [where_clause] augmented_assignment_stmt ::= target augop expression_list [where_clause] where_clause ::= "where" ":" suite So the expressions in existing compound statements (for, while, if, elif) would be out of luck. You could conceivably add the 'where' clause to the end of those as well, to give statement local variables that apply to the whole compound statement: for y in [foo(x) for x in bar]: baz(y) where: meaningful_name = xrange(5) def baz(arg): return arg * 2 This would only be appropriate for short loops - for long loops, the 'where' clause gets *too* hidden. Keeping the grammar simple might favour making the addition higher in the parse tree: Current: statement ::= stmt_list NEWLINE | compound_stmt New: statement ::= (stmt_list NEWLINE | compound_stmt) [where_clause] where_clause ::= "where" ":" suite However, doing it that way allows nonsense like this: pass where: print "This is just plain silly!" That would be something to be thrashed out in a PEP, though. The name 'statement local variables' also gave me an idea for a rough implementatation strategy. where: would be equivalent to: def stmt_with_locals(): stmt_with_locals() For the assignment versions, the behaviour would be: def assignment_with_locals(): return = assignment_with_locals() Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From fredrik at pythonware.com Sat Jan 22 06:17:03 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 12:17:03 +0100 Subject: Insanity References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> Message-ID: Tim Daneliuk wrote: > Given an arbitrary string, I want to find each individual instance of > text in the form: "[PROMPT:optional text]" > > I tried this: > > y=re.compile(r'\[PROMPT:.*\]') > > Which works fine when the text is exactly "[PROMPT:whatever]" didn't you leave something out here? "compile" only compiles that pattern; it doesn't match it against your string... > but does not match on: > > "something [PROMPT:foo] something [PROMPT:bar] something ..." > > The overall goal is to identify the beginning and end of each [PROMPT...] > string in the line. if the pattern can occur anywhere in the string, you need to use "search", not "match". if you want multiple matches, you can use "findall" or, better in this case, "finditer": import re s = "something [PROMPT:foo] something [PROMPT:bar] something" for m in re.finditer(r'\[PROMPT:[^]]*\]', s): print m.span(0) prints (10, 22) (33, 45) which looks reasonably correct. (note the "[^x]*x" form, which is an efficient way to spell "non-greedy match" for cases like this) From firemoth at gmail.com Wed Jan 19 14:13:47 2005 From: firemoth at gmail.com (Timothy Fitz) Date: Wed, 19 Jan 2005 14:13:47 -0500 Subject: Zen of Python Message-ID: <972ec5bd050119111359e358f5@mail.gmail.com> While I agree that the Zen of Python is an amazingly concise list of truisms, I do not see any meaning in: Flat is better than nested. I strive for balance between flat and nested. Does anyone have a good example of where this is applied? (specifically to python, or in general) From esj at harvee.org Tue Jan 18 11:26:46 2005 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 18 Jan 2005 11:26:46 -0500 Subject: simultaneous multiple requests to very simple database Message-ID: I have an application where I need a very simple database, effectively a very large dictionary. The very large dictionary must be accessed from multiple processes simultaneously. I need to be able to lock records within the very large dictionary when records are written to. Estimated number of records will be in the ballpark of 50,000 to 100,000 in his early phase and 10 times that in the future. Each record will run about 100 to 150 bytes. speed is not a huge concern although I must complete processing in less than 90 seconds. The longer the delay however the greater number of processes must be running parallel in order to keep the throughput up. It's the usual trade-off we have all come to know and love. it is not necessary for the dictionary to persist beyond the life of the parent process although I have another project coming up in which this would be a good idea. at this point, I know they will be some kind souls suggesting various SQL solutions. While I appreciate the idea, unfortunately I do not have time to puzzle out yet another component. Someday I will figure it out because I really liked what I see with SQL lite but unfortunately, today is not that day (unless they will give me their work, home and cell phone numbers so I can call when I am stuck. ;-) So the solutions that come to mind are some form of dictionary in shared memory with locking semaphore scoreboard or a multithreaded process containing a single database (Python native dictionary, metakit, gdbm??) and have all of my processes speak to it using xmlrpc which leaves me with the question of how to make a multithreaded server using stock xmlrpc. so feedback and pointers to information would be most welcome. I'm still exploring the idea so I am open to any and all suggestions (except maybe SQL :-) ---eric From aurora00 at gmail.com Sat Jan 8 14:52:03 2005 From: aurora00 at gmail.com (aurora) Date: Sat, 08 Jan 2005 11:52:03 -0800 Subject: "A Fundamental Turn Toward Concurrency in Software" References: <7x4qhs52rq.fsf@ruckus.brouhaha.com> Message-ID: Of course there are many performance bottleneck, CPU, memory, I/O, network all the way up to the software design and implementation. As a software guy myself I would say by far better software design would lead to the greatest performance gain. But that doesn't mean hardware engineer can sit back and declare this as "software's problem". Even if we are not writing CPU intensive application we will certain welcome "free performace gain" coming from a faster CPU or a more optimized compiler. I think this is significant because it might signify a paradigm shift. This might well be a hype, but let's just assume this is future direction of CPU design. Then we might as well start experimenting now. I would just throw some random ideas: parallel execution at statement level, look up symbol and attributes predicitively, parallelize hash function, dictionary lookup, sorting, list comprehension, etc, background just-in-time compilation, etc, etc. One of the author's idea is many of today's main stream technology (like OO) did not come about suddenly but has cumulated years of research before becoming widely used. A lot of these ideas may not work or does not seems to matter much today. But in 10 years we might be really glad that we have tried. > aurora writes: >> Just gone though an article via Slashdot titled "The Free Lunch Is >> Over: A Fundamental Turn Toward Concurrency in Software" >> [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that >> the continous CPU performance gain we've seen is finally over. And >> that future gain would primary be in the area of software concurrency >> taking advantage hyperthreading and multicore architectures. > > Well, another gain could be had in making the software less wasteful > of cpu cycles. > > I'm a pretty experienced programmer by most people's standards but I > see a lot of systems where I can't for the life of me figure out how > they manage to be so slow. It might be caused by environmental > pollutants emanating from Redmond. From daranrife at yahoo.com Fri Jan 28 11:11:56 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 08:11:56 -0800 Subject: Installing Numeric with ATLAS and LAPACK Message-ID: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> Hello, Could someone please provide instructions for install Numeric with ATLAS and LAPACK? I've actually done this correctly, I think. But I don't see any difference in the speed. I'm calculating eigenvalues for a 3600 X 3600 covariance matrix. Calculating the eigenvalues for this matrix requires a mere 7 min in Matlab 6.5...which uses ATLAS and LAPACK. Thanks, Daran From fredrik at pythonware.com Fri Jan 21 13:08:06 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 21 Jan 2005 19:08:06 +0100 Subject: xml parsing escape characters References: <357s61F4iossjU1@individual.net><41eeda3a$0$27828$9b622d9e@news.freenet.de><359o5cF4il48kU1@individual.net><41efedf2$0$11622$9b622d9e@news.freenet.de><35adg4F4jgvpnU1@individual.net> <41F01A86.2040805@v.loewis.de> <35ctgpF4ktmgoU2@individual.net> Message-ID: Luis P. Mendes wrote: > xml producer writes the code in Windows platform and 'thinks' that every > client will read/parse the code with a specific Windows parser. Could > that (wrong) XML code parse correctly in that kind of specific Windows > client? not if it's an XML parser. > Do you know any windows parser that could turn that erroneous encoding > to a xml tree, with four or five inner levels of tags? any parser *can* do that, but I doubt many parsers will do it unless you ask it to (by extracting the string and parsing it again). here's the elementtree version: from elementtree.ElementTree import parse, XML wrapper = parse(urllib.urlopen(url)) dataset = XML(wrapper.findtext("{http://www......}string")) From steve at holdenweb.com Mon Jan 24 07:29:19 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Jan 2005 07:29:19 -0500 Subject: short programming projects for kids In-Reply-To: <41f4e4b5@duster.adelaide.on.net> References: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> <41f4e4b5@duster.adelaide.on.net> Message-ID: Adrian Casey wrote: > Andr? Roberge wrote: > > >>bobdc wrote: >> >>>I will be teaching an "Introduction to Programming" class to some >>>middle school aged children and will be using Python, obviously. Does >>>anyone have suggestions for simple little programs to create and >>>analyze with them after I get past turtle graphics? >>> >>>Turtle graphics will be plenty for the first session, and I will leave >>>time to ask them what they'd like to do in later sessions, but I was >>>curious if anyone on the list has experience picking pedagogical >>>programming examples appropriate for twelve-year-olds' attention spans. >>>thanks, >>> >>>Bob >>> >> >>While it is not python per se, I suggest you have a look at GvR >>(Guido van Robot) (The app is written in Python but is too complicated >>for beginners). It is hosted on sourceforge (gvr.sourceforge.net). >>It is a very interesting way (imho) to learn about programming, in >>a pythonic way. >> >>(somewhat shameless plug follows:) >>A 'more advanced version' of GvR which uses the full Python syntax >>is RUR-PLE (rur-ple.sourceforge.net). The version currently hosted >>there does NOT work under Linux (untested on Mac). >>It uses wxPython 2.4 and will not work with 2.5. >>An updated release that will work under both Linux and Windows, >>and under both wxPython 2.4 and 2.5 will come out very soon, I hope. >> >>I'm working on it :-) I have two kids (ages 11 and 13) and plan to use >>rur-ple to teach them about programming. Note that, even though >>I plan it to be suitable for motivated children (with some guidance), >>the end product (to be finished in a year?) is planned to be suitable >>for a complete first-year university computer science. >> >>Andre Roberge > > > I started teaching my 11 year old first of all by doing silly stuff like -: > for i in range(10): > print "Silly me!" > > Moving on to more useful stuff like times tables (which they have to learn > anyway). > > After times tables, I plan to work on a simple number guessing game where > the computer picks a random number between 1 and 100 and asks the user to > take a guess. This will help demonstrate many basic programming concepts. > > Not sure how to introduce graphics though as so much is relatively abstract. > Have them type in guesses to make something hit a target that appears in a different position each time to introduce the notion of 2-D position, then you can talk about drawing lines between two positions, then the next thing you know they're writing algorithms to compute convex hulls (well, maybe not, but you probably get the idea). 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 Fri Jan 21 21:21:57 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 19:21:57 -0700 Subject: finding name of instances created In-Reply-To: <1106359068.802501.35190@z14g2000cwz.googlegroups.com> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106359068.802501.35190@z14g2000cwz.googlegroups.com> Message-ID: Andr? wrote: > Using the method suggested by Steven Bethard, I *almost* got it working > the way I would like. > Here's my program: > === > .class PrivateClass(object): > . dict = {} > . def not_so_simple_method(self): > . for name in PrivateClass.dict.keys(): > . if PrivateClass.dict[name] == self: > . print "instance " + name + " called not so simple" > . apparently_simple_method = not_so_simple_method > > . def __init__(self): > . print "instance created" > . for name, value in globals().iteritems(): > . if isinstance(value, PrivateClass): > . PrivateClass.dict[name] = value > > .def public_class(): > . return PrivateClass() > > .print "=== start===" > .alpha = public_class() > .print "created alpha" > .print PrivateClass.dict > .print "### alpha is not there\n" > > .beta = public_class() > .print "created beta" > .print PrivateClass.dict > .print "### we are always one behind in the dict content\n" > > .alpha.apparently_simple_method() > .beta.apparently_simple_method() It looks like you want PrivateClass.dict updated every time that globals() is updated. You can just use globals directly instead: py> class PrivateClass(object): ... def __init__(self, globals): ... self.globals = globals ... def apparently_simple_method(self): ... for name, value in self.globals.iteritems(): ... if value is self: ... print "instance %s called not so simple" % name ... py> def public_class(): ... return PrivateClass(globals()) ... py> alpha = public_class() py> alpha.apparently_simple_method() instance alpha called not so simple py> beta = public_class() py> beta.apparently_simple_method() instance beta called not so simple On the other hand, the iteration in PrivateClass.apparently_simple_method has a very bad code smell... Steve From tech at gpao.cc Mon Jan 31 10:40:48 2005 From: tech at gpao.cc (Olivier Noblanc ATOUSOFT) Date: Mon, 31 Jan 2005 16:40:48 +0100 Subject: import directory error References: <41fe49b5$0$2168$8fcfb975@news.wanadoo.fr> Message-ID: <41fe5181$0$10455$8fcfb975@news.wanadoo.fr> Problem solved thanks a lot "Steve Holden" a ?crit dans le message de news: f9sLd.101051$Jk5.32898 at lakeread01... > Olivier Noblanc ATOUSOFT wrote: > >> Hello, >> >> >> When i want to import a .py fire from another subdirectory i make >> >> import inc/setupxml >> >> >> but that make me an error message. >> >> A man tell me to put a dot but that doesn't work. >> >> Can you help me ? >> >> Thanks. >> >> >> > If you want to import a single .py (a Python module) then the ONLY way to > achieve that is to make sure it appears in a directory that is a member of > the sys.path list. (This is a slight simplification, but it will do as > long as you are only importing from the file store). > > There are various ways to affect the contents of sys.path, the best known > of which include > > 1. Setting the PYTHONPATH environment variable > 2. Creating *.pth files > 3. Altering sys.path inside site-customize.py in > your standard library > > Python does allow you to implement PACKAGES, which are directories > containing > > a) a file called __init__.py and (optionally) > b) other modules (.py files) and packages (directories > containing __init__.py files). > > The Python interpreter looks for packages in all the same places it looks > for modules, but it imports packages by running the __init__.py file (as > usual, this happens on the *first* time the package is imported). > > So, for example, under Cygwin or Linux/Unix, I can define a package (with > no Python in it, but still obeying the rules) as follows: > > sholden at dellboy ~ > $ mkdir mp1 > > sholden at dellboy ~ > $ touch mp1/__init__.py > > sholden at dellboy ~ > $ touch mp1/rhubarb.py > > sholden at dellboy ~ > $ mkdir mp1/p2 > > sholden at dellboy ~ > $ touch mp1/p2/__init__.py > > sholden at dellboy ~ > $ 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. > >>> import sys > >>> "" in sys.path > True > >>> import mp1 > >>> import mp1.rhubarb > >>> import mp1.p2 > >>> > > sholden at dellboy ~ > $ find mp1 > mp1 > mp1/p2 > mp1/p2/__init__.py > mp1/p2/__init__.pyc > mp1/rhubarb.py > mp1/rhubarb.pyc > mp1/__init__.py > mp1/__init__.pyc > > In this case mp1.rhubarb is a module from the mp1 package, mp1.p2 is a > sub-package of mp1. You can see what's been compiled by the interpreter on > import and when by looking at the .pyc files. > > Does this help any? > > 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 jdhunter at ace.bsd.uchicago.edu Wed Jan 26 22:21:17 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 26 Jan 2005 21:21:17 -0600 Subject: python without OO In-Reply-To: (Davor's message of "Wed, 26 Jan 2005 21:55:49 -0500") References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> Message-ID: >>>>> "Davor" == Davor writes: Davor> not really - it was not my intention at all - but it seems Davor> people get upset whenever this OO stuff is mentioned - and Davor> what I did not expect at all at this forum as I believed Davor> Python people should not be so OO hardcore (seems not all Davor> as quite a few have indicated in their Davor> replies)... Nevertheless, I think the discussion has Davor> several quite good points! -- Davor> http://mail.python.org/mailman/listinfo/python-list Consider the case of a list, say x = [1,2,3,4] suppose you wanted to reverse the list, so that x becomes [4,3,2,1]. In a procedural language, one might do x = reverse(x) In an OO language such as python, one might do x.reverse() Is the OO way more obscure and complicated, etc? Not really -- it's only a minor syntactical difference. One of the core ideas behind OO programming is that data (the contents of the list 1,2,3,4) and methods (sorting, reversing) are bound together into a single entity, the object. On the face of it, this is rather sensible. You may rightly recoil against unnecessary abstraction and complexity, abuse of multiple inheritance and so on. That's perfectly sensible. But object orientation is probably not the bogey man here. python values readable code that is as simple as possible (but no simpler!) as you seem to. Focus on the actual problem, which is probably not OO programming, but colleagues who are making a design more complex than need be. Indeed, the third chant in the mantra of python is "Simple is better than complex." John-Hunters-Computer:~> python 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 this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! From ola.natvig at infosense.no Wed Jan 26 09:04:54 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Wed, 26 Jan 2005 15:04:54 +0100 Subject: 4suite XSLT thread safe ? Message-ID: <6lkkc2-fbd.ln1@pluto.i.infosense.no> Anybody out there who knows if the 4suite implementation of XSLT are a threadsafe one? -- -------------------------------------- Ola Natvig infoSense AS / development From kartik_vad at yahoo.com Mon Jan 31 23:06:26 2005 From: kartik_vad at yahoo.com (kartik) Date: 31 Jan 2005 20:06:26 -0800 Subject: need for binary floats (except performance)? Message-ID: <81300027.0501312006.72454fd6@posting.google.com> Since the Decimal type can represent any given fractional number exactly, including all IEEE binary floating-point numbers, wouldn't it be advisable to use Decimals for all floating point numbers (except possibly for performance)? Thanks, Kartik. From steve at holdenweb.com Sat Jan 15 15:24:56 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 15 Jan 2005 15:24:56 -0500 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <1105734450.961150.32980@z14g2000cwz.googlegroups.com> <7xfz13zrb2.fsf@ruckus.brouhaha.com> Message-ID: <41E97C18.305@holdenweb.com> Bulba! wrote: > On 14 Jan 2005 12:30:57 -0800, Paul Rubin > wrote: > > >>Mmap lets you treat a disk file as an array, so you can randomly >>access the bytes in the file without having to do seek operations > > > Cool! > > >>Just say a[234]='x' and you've changed byte 234 of the file to the >>letter x. > > > However.. however.. suppose this element located more or less > in the middle of an array occupies more space after changing it, > say 2 bytes instead of 1. Will flush() need to rewrite the half of > mmaped file just to add that one byte? > Nope. If you try a[234] = 'banana' you'll get an error message. The mmap protocol doesn't support insertion and deletion, only overwriting. Of course, it's far too complicated to actually *try* this stuff before pontificating [not]: >>> import mmap >>> f = file("/tmp/Xout.txt", "r+") >>> mm = mmap.mmap(f.fileno(), 200) >>> mm[1:10] 'elcome to' >>> mm[1] = "banana" Traceback (most recent call last): File "", line 1, in ? IndexError: mmap assignment must be single-character string >>> mm[1:10] = 'ishing ::' >>> mm[1:10] 'ishing ::' >>> mm[1:10] = 'a' Traceback (most recent call last): File "", line 1, in ? IndexError: mmap slice assignment is wrong size >>> > flush() definitely makes updating less of an issue, I'm just > curious about the cost of writing small changes scattered all > over the place back to the large file. > Some of this depends on whether the mmap is shared or private, of course, but generally speaking you can ignore the overhead, and the flush() calls will be automatic as long as you don't mix file and string operations. The programming convenience is amazing. > -- > I have come to kick ass, chew bubble gum and do the following: > > from __future__ import py3k > > And it doesn't work. So make it work :-) 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 dieter at handshake.de Mon Jan 17 14:11:48 2005 From: dieter at handshake.de (Dieter Maurer) Date: 17 Jan 2005 20:11:48 +0100 Subject: Embedding a restricted python interpreter References: <7x4qhr4jis.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes on 08 Jan 2005 14:56:43 -0800: > Dieter Maurer writes: > > It uses a specialized compiler that prevents dangerous bytecode operations > > to be generated and enforces a restricted builtin environment. > > Does it stop the user from generating his own bytecode strings and > demarshalling them? Almost surely, I do not understand you: In the standard setup, the code has no access to most of Python's runtime library. Only a few selected modules are deemed to be safe and can be imported (and used) in "RestrictedPython". "marshal" or "unmarshal" are not considered safe. Security Declaration can be used to make more modules importable -- but then, this is an explicite decision by the application developper. *If* the framework decided to exchange byte code between user and iterpreter, then there would be no security at all, because the interpreter is the standard interpreter and security is built into the compilation process. Of course, you should not step in *after* the secured step ;-) Thus, "RestrictedPython" expects that the user sends Python source code (and not byte code!), it compiles this source code into byte code that enforces a strict access and facility policy. Dieter From steven.bethard at gmail.com Sat Jan 1 15:30:39 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 01 Jan 2005 20:30:39 GMT Subject: Looping using iterators with fractional values In-Reply-To: References: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> Message-ID: Mark McEahern wrote: > drife wrote: > >> Hello, >> >> Making the transition from Perl to Python, and have a >> question about constructing a loop that uses an iterator >> of type float. How does one do this in Python? >> >> > Use a generator: > > >>> def iterfloat(start, stop, inc): > ... f = start > ... while f <= stop: > ... yield f > ... f += inc > ... > >>> for x in iterfloat(0.25, 2.25, 0.25): > ... print '%9.2f' % x > ... > 0.25 > 0.50 > 0.75 > 1.00 > 1.25 > 1.50 > 1.75 > 2.00 > 2.25 > >>> > Or use the numarray module: py> import numarray as na py> for f in na.arange(0.25, 2.25, 0.25): ... print '%9.2f' % f ... 0.25 0.50 0.75 1.00 1.25 1.50 1.75 2.00 Steve From steve at holdenweb.com Tue Jan 18 09:24:15 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Jan 2005 09:24:15 -0500 Subject: generator expressions: performance anomaly? In-Reply-To: References: <377Hd.77904$Jk5.30235@lakeread01> Message-ID: <41ED1C0F.4030800@holdenweb.com> Stephen Thorne wrote: > On Tue, 18 Jan 2005 07:12:18 -0500, Steve Holden wrote: > >>Since it doesn't yet optimize 2+5 to a constant-folded 7 you should >>realize that you are suggesting a large increase in the compiler's >>analytical powers. > > > As in interesting aside to this, you might be interested to know that > PHP has constant folding, allowing you to do things like > $foo = 7+9; and have it generate bytecode that is "let 'foo' equal 16" > or somesuch. > > PHP achieves this by having a subset of expression parsing available > only for situations where a folded constant is allowed. > > i.e. > class Foo { > var $bar = 1+4; /* this constant is folded */ > } > > static_scalar: /* compile-time evaluated scalars */ > common_scalar | T_STRING | '+' static_scalar | > '-' static_scalar | T_ARRAY '(' static_array_pair_list ')' > ; > common_scalar: > /* all numbers, strings-not-containing-variable-interpolation and a > few hacks like __FILE__ and __LINE__ */ > ; > > As you can see from the grammar, there are any number of ways this can break. > > i.e. > Parse Error, * isn't allowed: > class Foo { var $bar = 60*60*24; } > > Parse Error, neither is anything except + and -: > class Foo { var $bar = 256 & 18; } > > Parse Error, and definately not variables: > $baz = 12; > class Foo { var $bar = $baz*2; } > > I compute 60*60*24 every time around the loop: > foreach ($myarray as $value) { $x = 60*60*24*$value; } > > Thankful, Former PHP Programmer, > Stephen Thorne. Yes, well, this just goes to confirm my belief that PHP isn't a programming language. I am always amazed at what's been achieved with it (though I sometimes wonder at what cost). You probably already know that sensible compiled language systems have used constant folding since time immemorial, but Python has always eschewed it. That's what comes of being a pragmatist's language: if such optimizations really are required the programmer is expected to perform them. and-ninety-nine-point-nine-nine-percent-of-the-time-they-aren't-ly y'rs - 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 alan.gauld at btinternet.com Sun Jan 2 13:25:10 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Jan 2005 18:25:10 +0000 (UTC) Subject: screen clear question References: <10teqpdvramua3@corp.supernews.com> <8ucft0tf456g07iuuavgu31m6dhrgjbmh3@4ax.com> Message-ID: On Mon, 03 Jan 2005 02:15:23 +1000, Nick Coghlan > Alan Gauld wrote: > > But the bottom line is that there is no builtin command > > because the mechanism is different on each platform. > > I'd have said it was because the inpreter is line-oriented rather than > screen-oriented, but YMMV. Yeah, that might be a reason as well :-) But then the early PC GW-Basic or BASICA interpreters were line based too but both provided a CLS command because the *programs* that were written were usually screen based... But they ran on a single OS so a CLS was easily possible. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From rNOSPAMon at flownet.com Sun Jan 2 17:02:34 2005 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 02 Jan 2005 14:02:34 -0800 Subject: Rebinding stdout References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <41D85CAF.2090505@mceahern.com> Message-ID: In article , Mark McEahern wrote: > Ron Garret wrote: > > > But this topic does bring up a legitimate question: I have a bunch of > > code that generates HTML using PRINT statements. I need to convert > > all this code to return strings rather than actually printing them (so > > I can use the results to populate templates). In Lisp I could do this: > > > > (with-output-to-string (s) > > (let ( (*standard-output* s) ) > > (call-html-generating-code) > > s)) > > > > Is there an equivalent Python trick to capture a function call's > > output as a string? > > > > > Just to make sure I understand, I'm going to restate your question: > > Is there a way to capture stdout? > > The answer: Sure, replace it with something file-like: > > >>> import sys, StringIO > >>> default = sys.stdout > >>> writer = StringIO.StringIO() > >>> sys.stdout = writer > >>> print 'Whatever' > >>> sys.stdout = default > >>> print writer.getvalue() > Whatever > > >>> > > // m That's exactly what I was looking for. Thanks! rg From zathras at thwackety.com Sun Jan 30 16:13:44 2005 From: zathras at thwackety.com (Michael Sparks) Date: Sun, 30 Jan 2005 21:13:44 +0000 (GMT) Subject: Coding style article with interesting section on white space In-Reply-To: <1107100318.251828.86360@c13g2000cwb.googlegroups.com> Message-ID: On 30 Jan 2005 beliavsky at aol.com wrote: > Sparring > with Alex Martelli is like boxing Mike Tyson, except that one > experiences brain enhancement rather than brain damage :). +1 QOTW :-) Michael. From tim.peters at gmail.com Thu Jan 27 12:40:27 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 27 Jan 2005 12:40:27 -0500 Subject: On benchmarks, heaps, priority queues In-Reply-To: <1106843673.755688.244160@f14g2000cwb.googlegroups.com> References: <1106835562.598569.211370@c13g2000cwb.googlegroups.com> <1106842754.010427.74630@c13g2000cwb.googlegroups.com> <1106843673.755688.244160@f14g2000cwb.googlegroups.com> Message-ID: <1f7befae05012709402140a21b@mail.gmail.com> [aaronwmail-usenet at yahoo.com, on ] > Yes I know in theory the insertion sort approach should be bad for > large enough values, but the weird thing is that if you mix inserts and > deletes (with enough deletes) even 1M elements is not a large enough > value. Anyway, for 10K or less the insertion sort priority queue > implementation seems to always be better. > > Weird. -- Aaron Watters It's the distribution of queue sizes that matters here, not the total number of elements thrown at the queue. Your code mixes "self" and "this" seemingly at random, and the __len__ methods in particular often don't agree about which is in use. If you repair that, and instrument mixBench() to keep track of queue size statistics, you'll find that even at 1000000, the queue at the top of the loop never exceeds 30 entries, and has a mean size less than 3. If you expect your queues to have only a couple elements on average, then sure, the simplest thing that could possibly work may be the fastest too. And if your queues never exceed 30 entries, then the poor O() behavior of "interior" list insertion doesn't matter either. The "n%5<3" part should be true about 60% of the time if n were truly random, which is a strong bias in mixBench pushing toward keeping the queue very small. Can't guess how close n is to being random, but the random-number generator is suspect (the multiplier is extremely small). Suspect it's more the strong bias than the dubious generator accounting for the almost-always near-trivial queue sizes in mixBench(), though. Note that in 2.4, bisect.insort() is also coded in C, so moving to 2.4 gives a boost to all the builtin gimmicks used here. On my box (with self-vs-this straightened out, and mixBench() instrumented to track queue size stats), using Python 2.4, PQPython23 "wins" maxBench 1000000 anyway: BENCHMARKS FOR 1000000 mixBench queue min 0 mean 2.517008 max 30 __main__.PQPython23 on 1000000 elapsed 4.54699993134 got 500001 queue min 0 mean 2.517008 max 30 __main__.PQ0 on 1000000 elapsed 4.79699993134 got 500001 queue min 0 mean 2.517008 max 30 __main__.PQueue on 1000000 elapsed 6.54699993134 got 500001 From skip at pobox.com Tue Jan 4 10:43:05 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Jan 2005 09:43:05 -0600 Subject: Python evolution: Unease In-Reply-To: <7xacrpdxy3.fsf@ruckus.brouhaha.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> Message-ID: <16858.47497.338059.125520@montanaro.dyndns.org> Paul> Care to figure out from the docs how tkinter works? That's not Paul> explained anywhere at all, except in some off-site resources and Paul> in some printed books. Even some language features like class Paul> methods and slots are explained only in PEP's and release notes, Paul> instead of in the language manual where you'd expect to find them Paul> since they're part of the language. Start writing (or reorganizing). Folks, this is open source. I'm sure by the traffic on the list most people here know how to write. In the case of Tkinter, you should probably get the okay of the authors of various external docs before incorporating them into the Python docs, but note that several Tkinter-related documents are referenced directly from the Tkinter module docs: Python Tkinter Resources The Python Tkinter Topic Guide provides a great deal of information on using Tk from Python and links to other sources of information on Tk. An Introduction to Tkinter Fredrik Lundh's on-line reference material. Tkinter reference: a GUI for Python On-line reference material. Tkinter for JPython The Jython interface to Tkinter. Python and Tkinter Programming The book by John Grayson (ISBN 1-884777-81-3). This being the Internet and all, it's not clear that referencing external documentation is somehow worse than incorporating it directly into the distribution. As for stuff that exists in PEPs and release notes, they should already all have the necessary copyright (either they were placed in the public domain or they are already part of the Python distribution) to allow you do just check out a CVS tree, make the necessary edits and either check the files back in or submit a patch to SourceForge. In the documentation arena, I think more thought should probably be given to producing online docs that can be directly annotated, thus further reducing the barrier to more complete documentation (and more updates). Take a look at latex2html, propose or implement changes, or just rewrite the damn thing in Python. I think latex2html is probably a recurring nightmare for Fred Drake. Skip From tim.peters at gmail.com Thu Jan 13 10:23:07 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 13 Jan 2005 10:23:07 -0500 Subject: python 2.3.4 for windows: float("NaN") throws exception In-Reply-To: <1105629033.442397.124820@c13g2000cwb.googlegroups.com> References: <1105629033.442397.124820@c13g2000cwb.googlegroups.com> Message-ID: <1f7befae050113072372bad736@mail.gmail.com> [asmirnov1234567890 at yahoo.com] > my python 2.3.4 for windows refuse to execute line float("NaN"). It > says: > > >>> float("NaN") > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for float(): NaN > > The same line works as expected on Linux and Solaris with python 2.3.4. > Could anybody explain what is possibly wrong here? is it bug or > feature? Neither -- all Python behavior in the presence of float NaNs, infinities, or signed zeroes is a platform-dependent accident. In this specific case, the accident is that the platform C runtime string->double functions on your Linux and Solaris boxes recognize "NaN", but Microsoft's string->double functions do not. Microsoft's libraries can't even read back the strings they *produce* for NaNs.(usually "-1.#IND"). From "iwk\" at (none) Sun Jan 2 08:24:00 2005 From: "iwk\" at (none) (@(none)) Date: Sun, 02 Jan 2005 14:24:00 +0100 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> Message-ID: <41d7f5eb$0$10383$e4fe514c@dreader18.news.xs4all.nl> Mike Thompson wrote: > 'Seaside' is a Smalltalk framework for what might be called "Modal Web > Development" or "Synchronous Web Programming", or even "Continuation > Based Web Apps". Continuation Based Frameworks seem to be getting quite some attention lately. For example in the Lisp world. Check out Bill Clementson's blog for some excellent posts. http://home.comcast.net/~bc19191/blog/041229.html And Seaside looks indeed very nice. Would be good to see it generate some new interests in Smalltalk/Squeak. > I googled for the python spin-off but didn't find one. Does Python really need yet another framework? Apart from the intellectual excersise, wouldn't it be nice if Python would get a framework "for the rest of us" (meaning: mere mortals) which would focus upon getting work done in a simple manner instead of creating yet another, new, hip, exciting, way of creating dynamic websites? If Python cannot deliver a PHP clone, at least you would expect a Rails lookalike. And though part of the Rails stack may be surpassed easily by Python equivalents, no Python alternative offers (imho of course) the same level of simplicity, elegance and pragmatism (!!) as Rails does. Regards, Iwan From fumanchu at amor.org Sun Jan 2 16:34:47 2005 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 2 Jan 2005 13:34:47 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3024F6C@exchange.hqamor.amorhq.net> mirnazim at gmail.com wrote: > Let me make an attemp at defining "Non-Content > Oriented Web Applications". > > A "Non-Content Oriented Web Application": > (1) will be accessed from web browser(obviously). Clear enough. > (2) will be developed using 'W3C' and other open > standards(STRICTLY, to ensure compatibility and > portablity). This is getting better IMO. But we're still at the point where exclusively following open standards ensures in-compatibility and non-portability. Meh. > (3) will expose some kind of functionality to the user, > not just some document to read. If I were to rephrase that, I would say "serves dynamic pages" as opposed to "static". > (4) functionality can be very simple to very complex. Which usually means a multitude of tools, depending on "how complex". The big issue with leaving this question so generic is that the answers are legion. So I'll just keep it short and make my own shameless plug: try Cation for the Web interface and Dejavu for the data layer, both developed by yours truly. ;) http://www.aminus.org/rbre/python or... svn://casadeamor.com/cation/trunk svn://casadeamor.com/dejavu/trunk Robert Brewer MIS Amor Ministries fumanchu at amor.org From aldo at nullcube.com Wed Jan 26 21:58:59 2005 From: aldo at nullcube.com (Aldo Cortesi) Date: Thu, 27 Jan 2005 13:58:59 +1100 Subject: Which is faster? In-Reply-To: <1106793602.782397.61260@z14g2000cwz.googlegroups.com> References: <1106793602.782397.61260@z14g2000cwz.googlegroups.com> Message-ID: <20050127025859.GA21360@nullcube.com> Thus spake Aggelos I. Orfanakos (aorfanakos at gmail.com): > Any idea which of the following is faster? > > 'a/b/c/'[:-1] > > or > > 'a/b/c/'.rstrip('/') > > Thanks in advance. > > P.S. I could time it but I thought of trying my luck here > first, in case someone knows already, and of course the > reason. Expecting other people to do something simply because you couldn't be bothered to do it yourself is not polite... That said, here are the timings on my system: > python ./timeit.py "'a/b/c/'[:-1]" 1000000 loops, best of 3: 0.511 usec per loop > python ./timeit.py "'a/b/c/'.rstrip('/')" 1000000 loops, best of 3: 1.3 usec per loop As you can see, this suggests that the list access method is quicker. This is to be expected, since the two methods don't do the same thing - rstrip will return a copy of your string with any number of trailing '/'es removed. If there aren't any, it will return the string as-is. The string access method will always chop exactly one character off the end. Even though the results for your specific input are the same, rstrip is a more complex, and therefore slower, beast. Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Off: (02) 9283 1131 Mob: 0419 492 863 From kp8 at mac.com Tue Jan 11 16:49:11 2005 From: kp8 at mac.com (kpp9c) Date: 11 Jan 2005 13:49:11 -0800 Subject: Time script help sought! In-Reply-To: <1105479292.689762.155510@f14g2000cwb.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> <1105477084.525279.312970@f14g2000cwb.googlegroups.com> <1105479292.689762.155510@f14g2000cwb.googlegroups.com> Message-ID: <1105480151.431987.327080@c13g2000cwb.googlegroups.com> still working on it and also fixing the input data. I think for simplicity and consistency's sake i will have *all* time values input and output as hh:mm:ss maybe that would be easier.... but i have a few thousand find and replaceeseseses to do now (yes i am doing them by hand) grr... this is hard! From aut_gbarros at uolinc.com Thu Jan 27 12:17:51 2005 From: aut_gbarros at uolinc.com (Gabriel Cosentino de Barros) Date: Thu, 27 Jan 2005 15:17:51 -0200 Subject: Tkinter vs wxPython Message-ID: <2814F26DA6908F41927A81C410C4991A02079C77@siamun.server.bl.corp.intranet> *warning* My very own opinions ahead. no flame intended. > Try them both out for an hour or two, and go with whichever > one "feels right". You very likely won't be making a mistake. i did that for java+swing, python+tk, python+gtk, python+wxWindow and python+glade I limited myself in one hour, and at a maximum 2 hours if the docs aren't perfect (i had zero experience at the time with all of them) The program code was already written, it only needed the gui. Java took me 3 hours to hook all the ungly hacks for dealing with threads in the AWT... but i will not elaborate on it because it would be kicking a dead horse. now for something completely diferent: python :) tk: the docs where superberb! done everything in 25min! then spent an hour polishing and adding status bars for everything :) gtk: had to use the C api docs. wasted some time figuring it out, gave up after one hour and a half and ended up with a window layout that didn't maximezed well. wx: Almost two hours. Once you get used to the docs and get the knowledge to read some examples all is fine. i liked the result. and liked the api but disliked the sea of constants necessary (i hated it in gtk also) glade: i gave up after 2hours of reading licenses and dealing with broken libs. Also, i can't run in beOS or tweak widgets. bah! rather go back to visual basic ;) Now going back on topic: A think that neighter Tk nor wxWindow is a good choice for python. They both suck much of it when it came to abstraction. They're still better than glade or gtk. But could improve a lot. wxWindow has simple an ugly API, and Tk has a huge sin in the syntax to pass actions to the buttons. But after all, i'm using exclusively TK for now. But things might change as i'm in a project with a huge need of non-ortodox input, so i may be going back to read about wxWindow event handlers or even pygame. peace, Gabriel -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Sat Jan 15 12:12:15 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 15 Jan 2005 18:12:15 +0100 Subject: Pointer or unique id In-Reply-To: <1q9pydh06wjuk.fexsf964ckya$.dlg@40tude.net> References: <1q9pydh06wjuk.fexsf964ckya$.dlg@40tude.net> Message-ID: <41e94d40$0$29202$636a15ce@news.free.fr> Nomak a ?crit : > Hello, > > does python have an equivalent to Java: int Object.hashCode() ? > id(object) -> integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.) hash(obj) -> integer Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely. HTH Bruno From cam.ac.uk at mh391.invalid Sun Jan 16 20:01:40 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 17 Jan 2005 01:01:40 +0000 Subject: List problems in C code ported to Python In-Reply-To: <3SDGd.22010$Z%.6947@fe1.texas.rr.com> References: <3SDGd.22010$Z%.6947@fe1.texas.rr.com> Message-ID: Paul McGuire wrote: > So "A" == 'a' is true in Python, not true in C. >>> "A" == 'a' False I think you meant: >>> "A" == "A" True -- Michael Hoffman From google_groups_web at yahoo.com Tue Jan 25 20:07:41 2005 From: google_groups_web at yahoo.com (google_groups_web at yahoo.com) Date: 25 Jan 2005 17:07:41 -0800 Subject: HAVE YOU HEARD THE GOOD NEWS! Message-ID: <1106701661.128249.250310@c13g2000cwb.googlegroups.com> Good News! Do you know how simple it is to go to Heaven after this life has ended? Some people believe that belonging to a local church, temple, mosque or synagogue will get them to Heaven. Others believe that water baptism, obeying the ten commandments or just being a good person will get them to Heaven. There are many other beliefs as well, but the good news about God's way to Heaven is found in the Holy Bible. The good news is that God came from Heaven to earth in the person of Jesus Christ over 2000 years ago and died for our sins(misdeeds). He was born in the land of Israel supernaturally to a virgin Jewish woman named Mary. He lived a sinless life for thirty-three years and then sacrificed His sinless blood and died on a cross to pay the death penalty for our sins. After Jesus was placed in a tomb He rose from the dead three days later as He said He would. The Holy Bible also tells us that Jesus Christ ascended into Heaven and that all who accept Him as their Lord and Saviour will live forever with Him in Heaven where there is no more death, sorrow, sickness and pain. The Bible says, "For the wages of sin is death, but the gift of God is eternal life through Christ Jesus our Lord." (Romans 6:23) This verse in the Bible says, "For ALL HAVE SINNED, and come short of the glory of God." (Romans 3:23) This verse says, "But God demonstrates his own love for us in this: While we were still sinners, Christ died for us." (Romans 5:8) In this passage the Bible clearly explains how simple it is to be saved and on your way to Heaven, "For if you confess with your mouth, "Jesus is Lord," and believe in your heart that God raised him from the dead, you WILL BE SAVED." (Romans 10:9) You can be saved right now and on your way to Heaven if you will open your heart to Jesus and pray the following prayer: Dear Jesus Christ, I want to be saved so that I can have a home in Heaven when I die. I agree with You that I am a sinner. I believe You love me and want to save me. I believe that You bled and died on the cross to pay the penalty for my sins. I believe that You rose from the dead. Please forgive my sins and come into my heart and be my Lord and Saviour. Thank You Lord Jesus Christ for forgiving me and saving me through Your merciful grace. Amen. You are now a Christian if you said the prayer and allowed God to save you. Welcome to the family of God. Salvation is not a reward but a gift. The Bible says it this way, "For it is by GRACE you have been SAVED, through FAITH and this not from yourselves, it is the GIFT of God." (Ephesians 2:8) Nothing in the world is more important than your eternal destiny. The Bible says, "In Him(Jesus) we have redemption through His blood, the forgiveness of sins..." (Ephesians 1:7) If you have not yet made a decision to be saved, please do so now before it is too late. The reason why it is so important to be saved now is because you do not know exactly when you will die. You may die prematurely in a traffic accident, terrorist attack or some other way before you get another chance to be saved. The Bible tells us that we will spend eternity in Heaven or a place of eternal torment called Hell. It would be terrible to die and go to Hell when all you have to do is accept Jesus Christ as your personal Lord and Saviour. Some people that have already made Jesus Christ their Lord and Saviour worry about losing their salvation. The Bible teaches Christians that we can never lose our salvation no matter what happens. The Bible says it this way, "My dear children, I write this to you so that you will not sin. But if anybody does sin, we have one who speaks to the Father in our defense Jesus Christ, the Righteous One." Yes my friend, Jesus Christ is able to save you and keep you saved. Please tell your family and friends, thanks! Have a great day! Internet Evangelist R.L. Grossi 1. http://www.biblegateway.com << Free Online Bible 2. http://www.free-hoster.com/goodnews << Passion of the Christ 3. http://www.carm.org/cults/cultlist.htm << Beware Of Cults 4. http://www.equip.org/free/DH198.htm << About Hell 5. http://www.powertochange.com/questions/qna2.html << Is Jesus God? From steven.bethard at gmail.com Tue Jan 4 09:55:05 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 04 Jan 2005 14:55:05 GMT Subject: Lambda as declarative idiom (was RE: what is lambda used for in real code?) In-Reply-To: <41da41d1.1835252503@news.oz.net> References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> <41da41d1.1835252503@news.oz.net> Message-ID: Bengt Richter wrote: > On Mon, 03 Jan 2005 18:54:06 GMT, Steven Bethard wrote: > > >>Roman Suzi wrote: >> >>>I wish lambdas will not be deprecated in Python but the key to that is >>>dropping the keyword (lambda). If anybody could think of a better syntax for >>>lambdas _with_ arguments, we could develop PEP 312 further. >> >>Some suggestions from recent lambda threads (I only considered the ones >>that keep lambda as an expression): >> > > Just for reference, am I correct in assuming these are the equivalent > uses of lambda?: > > lambda a, b, c:f(a) + o(b) - o(c) > lambda x: x * x > lambda : x > lambda *a, **k: x.bar(*a, **k) > (lambda : x(*a, **k)) for x, a, k in funcs_and_args_list) Yeah, I believe that was the intention, though I stole the examples from [1]. > That last seems like it might need the default-arg-value hack: i.e., > (lambda x=x, a=a, k=k: x(*a, **k)) for x, a, k in funcs_and_args_list) Good point. Steve From snacktime at gmail.com Sun Jan 23 17:03:48 2005 From: snacktime at gmail.com (snacktime) Date: Sun, 23 Jan 2005 14:03:48 -0800 Subject: Set parity of a string Message-ID: <1f060c4c050123140310e6f887@mail.gmail.com> Is there a module that sets the parity of a string? I have an application that needs to communicate with a host using even parity So what I need is before sending the message, convert it from space to even parity. And when I get the response I need to convert that from even to space parity. The perl module String::Parity is what I have used to do this under perl. Chris From wuwei23 at gmail.com Sun Jan 23 03:38:32 2005 From: wuwei23 at gmail.com (alex23) Date: 23 Jan 2005 00:38:32 -0800 Subject: Comments in configuration files In-Reply-To: <41f20f4a$0$6599$8fcfb975@news.wanadoo.fr> References: <41f20f4a$0$6599$8fcfb975@news.wanadoo.fr> Message-ID: <1106469512.131381.256450@z14g2000cwz.googlegroups.com> > I would like it to be editable, through a web browser or a GUI > application. With ConfigParser I can read the configuration file and > edit the options, but when I write the result all the comments are lost Hey Pierre, I came across a good review of a number of possible solutions for this at http://www.python.org/moin/ConfigParserShootout Hope it helps. - alex23 From http Tue Jan 11 12:26:14 2005 From: http (Paul Rubin) Date: 11 Jan 2005 09:26:14 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> Message-ID: <7x8y6z7u89.fsf@ruckus.brouhaha.com> Richie Hindle writes: > > [MoinMoin] doesn't have [...] automatic update notification for > > specific pages of your choice > > Yes it does. See http://entrian.com/sbwiki for example - register there > and you'll see in your preferences "Subscribed wiki pages (one regex per Oh interesting, thanks. > MoinMoin has an option to display WikiWords with spaces between them > (albeit still capitalised), again in the user preferences. Oh good, that's cool too, though this goes to show that the MoinMoin documentation could stand a lot of improvement (this holds in other areas as well). I don't understand why using spaces is the default. Who except for demented Java programmers really likes this MixedCase nonsense? Is there a way to turn it off altogether, so you can use mixed case words on wiki pages without automatically generating a link? > I'm not saying that MoinMoin is better than MediaWiki, just that it really > does have some of the features you say it doesn't (perhaps you've been > looking at an old version). I'm not saying MoinMoin is "worse" than MediaWiki, just as I wouldn't say a rowboat is worse than an aircraft carrier. MediaWiki is the only choice that makes any sense for large wikis (say > 20k pages). For small ones, MoinMoin is easier to operate in many ways, which is a big plus. It would be nice if MoinMoin changed its markup language to be closer to MediaWiki's. I edit MediaWiki pages all the time and I hate having to switch back and forth between languages (actually that's another reason I've reacted not-so-well to MoinMoin's language). I think I saw something in the MoinMoin docs saying that some standard was being developed that would look like MediaWiki, and that MoinMoin would support the standard, so I guess this will work out in the long run. From andreasp at qbcon.com Thu Jan 27 09:45:40 2005 From: andreasp at qbcon.com (Andreas Pauley) Date: Thu, 27 Jan 2005 16:45:40 +0200 (SAST) Subject: Point of Sale In-Reply-To: References: Message-ID: On Thu, 27 Jan 2005, Cameron Laird wrote: > In article , > Andreas Pauley wrote: >> Hi, >> >> My company has given me a rather cool project: >> I have to provide them with an open-source python-based point-of-sale / >> cash register system that can integrate with their existing ERP backend. >> >> The project will include development to ensure that the features they >> require are included in the open-source POS system. >> >> Can you recommend anything that I can use? > . > . > . > Research. I think you're expecting an answer of the "I used > open-source openPOS project, and it worked great for me", but > I suspect all that is premature. What does POS mean to you? > What are your platform constraints? Does your company have > expectations about how POS will work? What access (CORBA? > RMI? SOAP? ...) is there to the ERP? Very well, I guess a little more detail would help. Platform: Cross-platform, although deployment would typically be done on Linux. My company typically expects that each POS station will have it's own database with all sales items and other info on it. The maintenance of sales items, prices etc. should however be done at a central location, and then be replicated to each POS station. The reason for this is that we will typically deploy such a system in deep-dark-africa where stable network connectivity cannot be taken for granted. If the network is down each POS station should still be able to function without interruption. These requirements is probably not available in a typical POS system, but I'm hoping for a general POS front-end for which I can develop a custom backend to plug in. At the moment the current POS system uses an inhouse developed message queing system to communicate with the ERP/Retail backend. A POS station submits each transaction (and other relevant messages) to a local queue, from where it is sent to the back-end system. If the network is down the messages just stay queued until the network is back up again. The central backend system uses the same queing technique to submit price updates etc. to each POS station. I'm not sure what protocol will be used to communicate with the backend. I might have SOAP available. The backend is written using Appservers from Progress Software Corporation (a proprietary database company). The Progress developers would probably be willing to help, so I'm relatively positive that we'll be able to figure out a solution there. The user interface for the current system is character-based. For the new POS we should ideally be able to use different user-interfaces that all access the same business logic, although I would primarily focus on a non-mouse driven GUI interface. I hope the above answers your question, if not feel free to ask again. Regards, Andreas Pauley From ialbert at mailblocks.com Wed Jan 26 09:46:12 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 26 Jan 2005 09:46:12 -0500 Subject: 4suite XSLT thread safe ? In-Reply-To: <35pntaF4os76kU1@individual.net> References: <6lkkc2-fbd.ln1@pluto.i.infosense.no> <35pntaF4os76kU1@individual.net> Message-ID: Diez B. Roggisch wrote: > What do you mean by that? You can of course transform xml using xslt in as > many threads as you like It is not unthinkable that some parts of the library would not be threadsafe. They could have some internal shared global variable that keeps track of an intermediate state. Some C string processing functions are not thread safe either. Istvan. From philippecmartin at sbcglobal.net Mon Jan 10 14:29:40 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 10 Jan 2005 20:29:40 +0100 Subject: fetching method names from a class, and the parameter list from a method Message-ID: <1105385380.10721.6.camel@localhost> Is this possible ? I am trying to have auto-completion working in a shell I wrote but I currently have the method lists done by hand (ie; if I add/subtract a method from that class, then my auto-completion is out of date). Same issue with method parameters. I have parsed through many of the attributes (ex: I use method.__doc__) but have not yet found a way to achieve the above goal. Is there a way? something like the following would be great: 1) list = Class.__methods__ 2) dict (because of default values: "param = None") = Class.__method__[0].__params__ Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From mwm at mired.org Wed Jan 5 14:54:53 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 05 Jan 2005 13:54:53 -0600 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <1104933800.156835.91350@f14g2000cwb.googlegroups.com> Message-ID: <86d5wjps6q.fsf@guru.mired.org> beliavsky at aol.com writes: >>is python more popular than coldfusion? > For your specific purpose of learning a language to get a job, I > suggest visiting the site http://mshiltonj.com/sm/categories/languages/ > , where it appears that Python is mentioned about as often as Fortran > or Ada in job listings at dice.com . Apart from Java, two languages in > demand are C++ and Visual Basic. C++ may be easier to learn along with > Java since the syntax is similar, but VB is a very easy language to > learn and use. SQL is also in pretty high demand in the places I watch. Problem is, they usually want *specific* SQL variants, so it's a fragmented market. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From m at e.net Mon Jan 24 18:31:05 2005 From: m at e.net (me) Date: Mon, 24 Jan 2005 15:31:05 -0800 Subject: error Message-ID: whenever i try and run my Python GUI, my computer thinks for a sec, then drops the process, without ever displaying the window. the command prompt window seems to work fine, but the IDLE GUI won't start. i'm running Windows 2K professional and python 2.4, so any advice help would be appreciated. i've already tried reinstalling and use a thread response, as the e-mail on this account is bogus. From martin at v.loewis.de Thu Jan 20 15:54:30 2005 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 20 Jan 2005 21:54:30 +0100 Subject: xml parsing escape characters In-Reply-To: <35adg4F4jgvpnU1@individual.net> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efedf2$0$11622$9b622d9e@news.freenet.de> <35adg4F4jgvpnU1@individual.net> Message-ID: <41F01A86.2040805@v.loewis.de> Luis P. Mendes wrote: > When I access the url via the Firefox browser and look into the source > code, I also get: > > > <DataSet> > ~ <Order> > ~ <Customer>439</Customer> > ~ </Order> > </DataSet> Please do try to understand what you are seeing. This is crucial for understanding what happens. You may have the understanding that XML can be represented as a tree. This would be good - if not, please read a book that explains why XML can be considered as a tree. In the tree, you have inner nodes, and leaf nodes. For example, the document Hello World has 5 nodes (ignoring whitespace content): Element:a ---- Element:b ---- Text:"Hello" | \-- Element:c ---- Text:"World" So the leaf nodes are typically Text nodes (unless you have an empty element). Your document has this structure: Element:string ---- Text:""" 439 """ So the ***TEXT*** contains the letter "<", just like it contains the letters "O" and "r". There IS no element Order in your document, no matter how hard you look. If you want a DataSet *element* in your document, it should read 439 As this is the document you apparently want to process, complain to whoever gave you that other document. > should I take the contents of the string tag that is text and replace > all '<' with '<' and '>' with '>' and then read it with xml.minidom? No. We still don't know what you want to achieve, so it is difficult to advise you what to do. My best advise is that whoever generates the XML document should fix it. > or should I use another parser that accomplishes the task with no need > to replace the escaped characters? No. The parser is working correctly. The document you got can also be interpreted as containing another XML document as a text. This is evil, but apparently people are doing it, anyway. If you really want that embedded document, you need first to extract it. To see what I mean, do print DataSetNode.data The .data attribute gives you the string contents of a text node. You could use this as an XML document, and parse it again to an XML parser. This would be ugly, but might be your only choice if the producer of the document is unwilling to adjust. Regards, Martin From kartic.krishnamurthy at gmail.com Wed Jan 5 11:08:54 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 08:08:54 -0800 Subject: get the IP address of a host In-Reply-To: References: Message-ID: <1104941334.814311.198610@z14g2000cwz.googlegroups.com> socket.gethostbyaddr(socket.gethostname()) will return a tuple containing fully qualified hostname, alternative hostnames, ip addresses (>1 if multihomed). Thanks, --Kartic From craig at postnewspapers.com.au Sun Jan 2 01:23:07 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sun, 02 Jan 2005 14:23:07 +0800 Subject: screen clear question In-Reply-To: <10teqpdvramua3@corp.supernews.com> References: <10teqpdvramua3@corp.supernews.com> Message-ID: <1104646987.25948.2.camel@rasputin.localnet> On Sun, 2005-01-02 at 11:31, jcollins wrote: > Is there a command in Python to clear the screen? That is without writing > multiple blank lines. Without knowing what 'screen' you're talking about, it's hard to say. If you mean clearing a terminal, you can call 'tput clear' or '/usr/bin/clear' on many UNIX systems; no idea about Windows. -- Craig Ringer From aorfanakos at gmail.com Mon Jan 31 02:38:21 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 30 Jan 2005 23:38:21 -0800 Subject: Regarding exception handling References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> <41FDD5F4.8030507@gmail.com> Message-ID: <1107157101.859032.37690@f14g2000cwb.googlegroups.com> Coming from C, I think that it's generally a good programming practice to make sure everything you create, closes; whether it's about a socket or a file. This may not be the case with Python though. To be honest, leaving this task to the garbage collector doesn't sound like a good idea to me (since the language gives you the means to do it yourself). From fredrik at pythonware.com Mon Jan 24 09:19:13 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 15:19:13 +0100 Subject: Memory Usage References: Message-ID: "rbt" wrote: > For example, say I have the same Python script running on two WinXP computers that both have > Python 2.4.0. One computer has 256 MB of Ram while the other has 2 GB of Ram. On the machine with > less Ram, the process takes about 1 MB of Ram. On the machine with more Ram, it uses 9 MB of Ram. > > Is this normal and expected behavior? 1 MB sounds low, 9 MB sounds more reasonable for a script that uses a few mega- bytes of data. what tool are you using to determine the process size? From tadmc at augustmail.com Mon Jan 17 23:52:32 2005 From: tadmc at augustmail.com (Tad McClellan) Date: Mon, 17 Jan 2005 22:52:32 -0600 Subject: [perl-python] 20050116 defining a function References: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> Message-ID: Ala Qumsieh wrote: > Xah Lee wrote: > *plonk* Man, you are way behind the curve. I did that over 3 years ago! [1] [1] Message-ID: <7fe97cc4.0111080051.71a0c6f3 at posting.google.com> I followed the link in that post on a hunch, and found he says himself that he is a troll. Go figure... -- Tad McClellan SGML consulting tadmc at augustmail.com Perl programming Fort Worth, Texas From jeff at ccvcorp.com Wed Jan 5 15:32:19 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 05 Jan 2005 12:32:19 -0800 Subject: Python 2.4 on Windows XP In-Reply-To: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> References: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> Message-ID: <10toje56oiebq24@corp.supernews.com> DavidHolt wrote: > I have a problem that I see on two different machines, one running XP > SP1 and one XP SP 2. > > On both I installed Python 2.4. > > I can't seem to start IDLE. When I try to start it, I get an hourglass > cursor for a short time then nothing more happens. This happens whether > I click the IDLE shortcut or click the pythonw.exe directly, or attempt > to launch pythonw from a command line. Maybe I'm misinterpreting you, here, but pythonw.exe is *not* IDLE. It is, instead, a console-less version of the Python interpreter, which can run the Python scripts for IDLE (among other things). My version of Python is older, but in %pythondir%/Tools/idle, there is an idle.pyw file. Try running that. If it doesn't work, then copy & paste any error messages (you'll probably need to run it from a command line for this) to your next post here so that we can try to troubleshoot a bit more effectively. Jeff Shannon Technician/Programmer Credit International From wittempj at hotmail.com Tue Jan 25 15:34:33 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 25 Jan 2005 12:34:33 -0800 Subject: __deepcopy__ without recursive copies? In-Reply-To: <1106677008.086803.76270@c13g2000cwb.googlegroups.com> References: <1106677008.086803.76270@c13g2000cwb.googlegroups.com> Message-ID: <1106685273.094802.41440@c13g2000cwb.googlegroups.com> Here I found something on __deepcopy__ http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/c34431c5fd3c223b/427866340239edd7?q=__deepcopy__+example&_done=%2Fgroups%3Fq%3D__deepcopy__+example+%26hl%3Den%26lr%3D%26safe%3Doff%26sa%3DN%26tab%3Dwg%26&_doneTitle=Back+to+Search&&d#427866340239edd7 if applied on your script it gives something like: -import copy -class DeviceManager(object): - def __init__(self,devFile): - DevFile = open(devFile) - devList = [Device(line) for line in DevFile] - #etc, etc... - - def __deepcopy__(self, memo): - x = DeviceManager.__new__(DeviceManager) - memo[id(self)] = x - for n, v in self.__dict__.iteritems(): - setattr(x, n, copy.deepcopy(v, memo)) - return x - -class Device(object): - def __init__(self,line): - self.copies = [] - #do something with line here - - def __deepcopy__(self, memo): - x = Device.__new__(Device) - memo[id(self)] = x - for n, v in self.__dict__.iteritems(): - setattr(x, n, copy.deepcopy(v, memo)) - return x - -DevMan1 = DeviceManager(r'c:\autoexec.bat') -DevMan2 = copy.deepcopy(DevMan1) - -print DevMan1 is DevMan2 it prints False, so the deepcopy seems to work From benn at cenix-bioscience.com Tue Jan 11 11:37:38 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Tue, 11 Jan 2005 17:37:38 +0100 Subject: shutil.move has a mind of its own In-Reply-To: <1d6cdae3050111033379f5ee14@mail.gmail.com> References: <1d6cdae3050111033379f5ee14@mail.gmail.com> Message-ID: <41E400D2.1070903@cenix-bioscience.com> Daniel Bickett wrote: >Oh, I'm sorry, that was my mistake. The example contained that error, >but my code does not. > >Daniel Bickett > > To be fair though - I would have expected the method to throw an error rather than default to cwd. Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 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 sam.wun at authtec.com Wed Jan 12 02:18:09 2005 From: sam.wun at authtec.com (sam) Date: Wed, 12 Jan 2005 15:18:09 +0800 Subject: Excel module for Python Message-ID: Hi group, I m wondering which Excel module is good to be used by Python? Thanks Sam From steven.bethard at gmail.com Wed Jan 12 20:17:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 18:17:17 -0700 Subject: Why would I get a TypeEror? In-Reply-To: References: Message-ID: <5ZydnVNkUIyAUXjcRVn-pw@comcast.com> It's me wrote: > For this code snip: > > a=3 > .... > b=(1,len(a))[isinstance(a,(list,tuple,dict))] > > Why would I get a TypeError from the len function? You're looking for lazy evaluation or short-circuiting behavior. Python provides one form of short circuiting behavior with 'and' and 'or', though you need to be careful. In your particular circumstances, you could write this code as: b = not isinstance(a, (list, tuple, dict)) and 1 or len(a) Some example code: py> def b(a): ... return not isinstance(a, (list, tuple, dict)) and 1 or len(a) ... py> b(3) 1 py> b([]) 0 py> b([3, 4]) 2 Note however that, due to how 'and' and 'or' short-circuit, you cannot write your code as: b = isinstance(a, (list, tuple, dict)) and len(a) or 1 because when len(a) is 0, 1 will be returned instead of 0: py> def b(a): ... return isinstance(a, (list, tuple, dict)) and len(a) or 1 ... py> b(3) 1 py> b([]) 1 py> b([3, 4]) 2 If you want lazy evaluation, you can do this with lambdas (though I wouldn't advise it): b = (lambda: 1, lambda: len(a))[isinstance(a,(list,tuple,dict))]() Note that I select which function using isinstance as you have before, and then invoke the selected function with the final (). Steve From yunmao at gmail.com Thu Jan 20 20:33:25 2005 From: yunmao at gmail.com (Yun Mao) Date: Thu, 20 Jan 2005 20:33:25 -0500 Subject: problems with duplicating and slicing an array Message-ID: <7cffadfa05012017337858d171@mail.gmail.com> Hi python gurus, I have some questions when I'm using python numeric: 1. When I do v = u[:, :], it seems u and v still point to the same memory. e.g. When I do v[1,1]=0, u[1,1] will be zero out as well. What's the right way to duplicate an array? Now I have to do v = dot(u, identity(N)), which is kind of silly. 2. Is there a way to do Matlab style slicing? e.g. if I have i = array([0, 2]) x = array([1.1, 2.2, 3.3, 4.4]) I wish y = x(i) would give me [1.1, 3.3] Now I'm using map, but it gets a little annoying when there are two dimensions. Any ideas would be deeply appreciated! Thanks!!! -Y From duncan.booth at invalid.invalid Mon Jan 3 04:50:06 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Jan 2005 09:50:06 GMT Subject: Problem remotely shutting down a windows computer with python References: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> <1104726323.505127.139360@c13g2000cwb.googlegroups.com> <1104727810.646660.297480@f14g2000cwb.googlegroups.com> Message-ID: Kartic wrote: > Looks like this is the documented outcome. You could alternatively try > setting a little XML-RPC app to invoke 'shutdown -s' on the remote PC > from your PC (e.g. using Twisted Python). > Or invoke 'shutdown -s -m \\machinename' on the local machine to shutdown a remote machine. From skip at pobox.com Fri Jan 28 10:23:09 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 28 Jan 2005 09:23:09 -0600 Subject: debugging os.spawn*() calls Message-ID: <16890.22749.899414.324589@montanaro.dyndns.org> I have an os.spawnv call that's failing: pid = os.spawnv(os.P_NOWAIT, "ssh", ["ssh", remote, "PATH=%(path)s nice -20 make -C %(pwd)s" % locals()]) When I wait for it the status returned is 32512, indicating an exit status of 127. Unfortunately, I see no way to collect stdout or stderr from the spawned process, so I can't tell what's going wrong. The "ssh remotehost PATH=$PATH nice -20 make ..." command works fine from a similar shell script. Thx, Skip From philippecmartin at sbcglobal.net Tue Jan 18 01:10:51 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Tue, 18 Jan 2005 07:10:51 +0100 Subject: how to find site-packages path (Michael Hoffman) - use distutils Message-ID: <1106028651.6604.11.camel@localhost> >> Why would you want to copy any *.pyc instead of compiling them on site? I know that sounds terrible to the open source community, but I do not intend to release the source code for my product - pls go to philippecmartin.com/applications.html for my _small_ contributions :-)) Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From aleaxit at yahoo.com Mon Jan 31 07:46:38 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 31 Jan 2005 13:46:38 +0100 Subject: variable declaration References: Message-ID: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.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 Since the lack of declarations is such a crucial design choice for Python, then, given that you're convinced it's a very bad thing, I suggest you give up Python in favor of other languages that give you what you crave. The suggestions about using pychecker, IMHO, amount to "band-aids" -- the right way to deal with minor annoying scratches, but surely not with seriously bleeding wounds, and your language ("very bad thing", "very ugly errors") indicates this is a wound-level issue for you. Therefore, using Python, for you, would mean you'd be fighting the language and detesting its most fundamental design choice: and why should you do that? There are zillions of languages -- use another one. > 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! Actually, this while loop never terminates and never prints anything, so that's gonna be pretty hard to ignore;-). But, assume the code is slightly changed so that the loop does terminate. In that case...: It's absolutely trivial to find this bug, if you write even the tiniest and most trivial kinds of unit tests. If you don't even have enough unit tests to make it trivial to find this bug, I shudder to think at the quality of the programs you code. Even just focusing on typos, think of how many other typos you could have, besides the misspelling of 'epsilon', that unit tests would catch trivially AND would be caught in no other way whatsoever -- there might be a <= where you meant a <, a 1.0 where you meant 10, a - where you meant a +, etc, etc. You can't live without unit tests. And once you have unit tests, the added value of declarations is tiny, and their cost remains. A classic reflection on the subject by Robert Martin, a guru of C++ and other languages requiring declarations, is at: . > Even Visual Basic have 'Option Explicit' keyword! May be, python also have > such a feature, I just don't know about it? Python has no declarations whatsoever. If you prefer Visual Basic, I strongly suggest you use Visual Basic, rather than pining for Visual Basic features in Python. If and when your programming practices ever grow to include extensive unit-testing and other aspects of agile programing, THEN you will be best advised to have a second look at Python, and in such a case you will probably find Python's strengths, including the lack of declarations, quite compelling. Some people claim a language should change the way you think -- a frequent poster, excellent Python contributor, and friend, even has that claim in his signature. That may be alright in the groves of academia. If you program to solve problems, rather than for personal growth, on the other hand, changing "the way you think" with each programming language is a rather steep price to pay. As a pragmatist, I prefer a motto that I've also seen about Python: "it fits your brain". I find it's true: Python gets out of my way and let me solve problems much faster, because it fits my brain, rather than changing the way I think. If Python doesn't fit YOUR brain, for example because your brain is ossified around a craving for the declaration of variables, then, unless you're specifically studying a new language just for personal growth purposes, I think you might well be better off with a language that DOES, at least until and unless your brain changes by other means. Alex From peter at engcorp.com Thu Jan 6 10:54:07 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jan 2005 10:54:07 -0500 Subject: 2 versions of python on 1 machine In-Reply-To: References: Message-ID: <0fydnX5CmoCCwkDcRVn-2w@powergate.ca> flupke wrote: > I have version 2.3.4 and 2.4 installed on windows and i thought that by > switching the PYTHONPATH parameter to the dir of the 2.4 version that > that would make python 2.4 active. That is not the purpose of PYTHONPATH. I'd suggest removing any definition of this environment variable that you have, unless you have a specific reason to use it and know what it actually does. I believe the docs on it are fairly clear, so reading them again might help. Note that if you have installed both versions of Python using the regular installer, the PYTHONPATH information would be redundant anyway because each version puts the necessary info in the Windows registry. > However when i envoke python from the commandline, it still runs 2.3.4 > Is it possible to have 2 versions installed and switching versions when > you need to? It's quite possible. It sounds like your problem is that you have the c:\python23 folder in your PATH (note, not PYTHONPATH, just the old DOS PATH variable). If that's the case, you should probably remove it and use batch files to invoke the different versions instead. > How can i do that? On my machine, I have a folder called c:\bin where I put useful batch files. I have a python23.bat and a python24.bat file, which basically just call c:\python23\python.exe or c:\python24\python.exe as required. For various reasons which may or may not apply to you as well, I also have each of them set the PYTHONHOME variable to point to the right folder as well. The content of each batch file is like this: @echo off c:\python23\python.exe %1 %2 %3 %4 %5 %6 %7 %8 %9 -Peter From Scott.Daniels at Acm.Org Tue Jan 4 14:03:17 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 04 Jan 2005 11:03:17 -0800 Subject: Pythonic search of list of dictionaries In-Reply-To: References: Message-ID: <41dae5c0$1@nntp0.pdx.net> Skip Montanaro wrote: > ...lotsa great stuff ... > You might want to sort your lists by the 'English' key. I don't know how to > use the new key arg to list.sort(), but you can still do it the > old-fashioned way: > > oldl.sort(lambda a,b: cmp(a['English'], b['English'])) > newl.sort(lambda a,b: cmp(a['English'], b['English'])) To complete the thought, for 2.4 and after the new-fashioned way is: import operator oldl.sort(key=operator.itemgetter('English')) newl.sort(key=operator.itemgetter('English')) > Once sorted, you can then march through the lists in parallel, which should > give you an O(n) algorithm. But overall you will have O(n log n) because of the sorts. --Scott David Daniels Scott.Daniels at Acm.Org From tjreedy at udel.edu Tue Jan 11 15:07:53 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Jan 2005 15:07:53 -0500 Subject: Game programming in Python References: Message-ID: "Baza" wrote in message news:BE09CC52.2E5B%baza at themauvezone.fsnet.co.uk... > I'm looking for any books or on-line resources on game programming using > Python. Does anyone have any advice? Google "Python game programming" From bokr at oz.net Wed Jan 5 12:58:12 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 05 Jan 2005 17:58:12 GMT Subject: Is there any way/where to subscribe for automated PEP status emails? Message-ID: <41dc24f8.68802652@news.oz.net> I find that threads sometimes mention PEPs that I wasn't aware of, or that an interesting one has been updated without my noticing. I should perhaps check the PEP site more regularly, but ISTM it shouldn't be that hard to implement an automated notification of PEP status changes by email. A cron job could just monitor the PEP source directory and watch for new files and last-mod changes, for starters. Maybe that would be sufficient, without going into classifying the changes in more detail. Subscription/unsubscription could be like an ordinary read-only mail list. You could just bounce replies with some advice as to where to go ;-) Googling didn't hit anything obvious for me. Regards, Bengt Richter From chrisdewinN0SPAM at yahoo.com.au Wed Jan 19 15:03:40 2005 From: chrisdewinN0SPAM at yahoo.com.au (Dfenestr8) Date: Thu, 20 Jan 2005 06:03:40 +1000 Subject: python/cgi/html bug References: <1106137924.918776.9090@f14g2000cwb.googlegroups.com> Message-ID: On Wed, 19 Jan 2005 04:32:04 -0800, Fuzzyman wrote: > This looks very good. > I've been looking for a python messageboard CGI for a long time. > Thanx! No glaring security holes that you noticed? Other than being able to hide things in html tags? > If you wanted to add user accounts/login/admin etc. you could use 'Login > Tools'. This is a python module built especially to do that. It also > provides a convenient way of saving user preferences etc. > > http://www.voidspace.org.uk/python/logintools.html > > If you want any help using it then feel free to ask. > > Regards, From lkirsh at cs.ubc.ca Sat Jan 29 21:35:04 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Sat, 29 Jan 2005 18:35:04 -0800 Subject: is this sort method the same as the one in python 2.4 Message-ID: I'm trying to emulate the sorted() method introduced in python 2.4. The only difference is that it takes a sequence as one of its arguments rather than being a method of the sequence class. Does my method do the same as the sorted()? The obvious difference is that my method is called as sort(seq, cmp, key, reverse) rather than seq.sorted(cmp, key, reverse) def sort(seq, cmp=None, key=None, reverse=False): "return a sorted copy of its input" if sys.version_info > (2,4): return sorted(seq, cmp, key, reverse) if key: toreturn = [ (key(elt), elt) for elt in seq ] else: toreturn = seq[:] if cmp: toreturn.sort(cmp) else: toreturn.sort() if key: toreturn = [ b for (a,b) in toreturn ] if reverse: toreturn.reverse() return toreturn Lowell From usenet_spam at janc.invalid Fri Jan 21 21:42:39 2005 From: usenet_spam at janc.invalid (JanC) Date: Sat, 22 Jan 2005 02:42:39 GMT Subject: nntplib: abstraction of threads References: <1105840367.526347.110160@c13g2000cwb.googlegroups.com> <41EAA458.1020501@holdenweb.com> Message-ID: Steve Holden schreef: > Better still, do a Google search on "mail threading algorithm", > implement the algorithm described in > > http://www.jwz.org/doc/threading.html > > and post your implementation back to the newsgroup :-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From sjmachin at lexicon.net Fri Jan 14 15:32:48 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Jan 2005 07:32:48 +1100 Subject: Pickled text file causing ValueError (dos/unix issue) References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> Message-ID: On Fri, 14 Jan 2005 09:12:49 -0500, Tim Peters wrote: >[Aki Niimura] >> I started to use pickle to store the latest user settings for the tool >> I wrote. It writes out a pickled text file when it terminates and it >> restores the settings when it starts. >... >> I guess DOS text format is creating this problem. > >Yes. > >> My question is "Is there any elegant way to deal with this?". > >Yes: regardless of platform, always open files used for pickles in >binary mode. That is, pass "rb" to open() when reading a pickle file, >and "wb" to open() when writing a pickle file. Then your pickle files >will work unchanged on all platforms. The same is true of files >containing binary data of any kind (and despite that pickle protocol 0 >was called "text mode" for years, it's still binary data). Tim, the manual as of version 2.4 does _not_ mention the need to use 'b' on OSes where it makes a difference, not even in the examples at the end of the chapter. Further, it still refers to protocol 0 as 'text' in several places. There is also a reference to protocol 0 files being viewable in a text editor. In other words, enough to lead even the most careful Reader of TFM up the garden path :-) Cheers, John From orwin42 at mail.be Sun Jan 9 11:20:07 2005 From: orwin42 at mail.be (Nyx42) Date: Sun, 09 Jan 2005 11:20:07 -0500 Subject: Pygame and pyopengl with py2exe ? References: <34crqiF47stihU1@individual.net> Message-ID: <2a89f13576daaaef3f1689eb93a445e8@localhost.talkaboutprogramming.com> Same problem: the window closes immediately. For the first program, I precise that the "pygame window" opens also. From http Sat Jan 8 01:30:32 2005 From: http (Paul Rubin) Date: 07 Jan 2005 22:30:32 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> Message-ID: <7xvfa8l9fb.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > > Usage could be something like: > > >>> res = [ f(i) for i in objects ] where: > > >>> def f(x): > > >>> #do something > > Hmm, this is actually a really interesting idea. Avoiding accidental > namespace conflicts is certainly one of the advantages of using lambdas. I like it too. Seems a little perl-ish, but what the hey. > In fact, any subexpressions in a complicated expression can be > extracted and named for clarity without fear of screwing up the > containing namespace, which would be an enormous boon for software > maintainers. Sure, why not: x = (-b + sqrt(discriminant))/(2*a) where: discriminant = b*b - 4*a*c Maybe you could just have a where: suite that binds variables within the suite: where: def f(x): #do something res = [ f(i) for i in objects ] where: discriminant = b*b - 4*a*c x = (-b + sqrt(discriminant))/(2*a) Syntax is where: suite statement the suite has its own scope so any variable created there is local to the suite plus the following statement. The scope vanishes after the statement. From bulba at bulba.com Sat Jan 8 19:34:38 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 09 Jan 2005 01:34:38 +0100 Subject: Speed revisited References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> Message-ID: <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> On 4 Jan 2005 14:33:34 -0800, "John Machin" wrote: >(b) Fast forwarding 30+ years, let's look at the dictionary method, >assuming you have enough memory to hold all your data at once: > >Step 1: read the "left" table; for each row, if english not in mydict, >then do mydict[english] = MyObject(). In any case, do >mydict[english].left_list.append(row) >Step 2: same for the "right" table. >Step 3: for english, obj in mydict.iteritems(): process(english, obj) >As your datasets are stored in MS Excel spreadsheets, N < 64K so >whether your solution is O(N) or O(N*log(N)) doesn't matter too much. >You are however correct to avoid O(N**2) solutions. Following advice of two posters here (thanks) I have written two versions of the same program, and both of them work, but the difference in speed is drastic, about 6 seconds vs 190 seconds for about 15000 of processed records, taken from 2 lists of dictionaries. I've read "Python Performance Tips" at http://manatee.mojam.com/~skip/python/fastpython.html ..but still don't understand why the difference is so big. Both versions use local variables, etc. Both have their lists initially sorted. Both essentially use a loop with conditional for comparison, then process the record in the same way. The overhead of second version is that it also uses cmp() function and two additional integer variables - that should not slow the program _so much_. I have measured the run of snippet 2 with time checkpoints written to a log (write time delta to log every 200 records), even made a graph of time deltas in spreadsheet and in fact snippet 2 seems after initial slowdown looks exactly linear, like that: ^ (time) | | /----------- | / |/ ---------------> (# of records written) So yes, it would scale to big files. However, why is it so frigging slow?! # snippet 1, this runs in about 6 seconds !def prepend(l): ! map = {} ! for d in l: ! key = d['English'] ! map[key] = d ! return map ! !old_map = prepend(oldl) !new_map = prepend(newl) ! !for engphrase in old_map: ! if engphrase in new_map: ! o = old_map[engphrase] ! n = new_map[engphrase] ! cm.writerow(matchpol(o,n)) # snippet 2, this needs 190 seconds !while 1: ! if len(oldl) == 0 or len(newl) == 0: ! break ! if oldl[o]['English'] == newl[n]['English']: ! cm.writerow(matchpol(oldl[o], newl[n])) ! del oldl[o] ! del newl[n] ! o, n = 0, 0 ! continue ! elif cmp(oldl[o]['English'], newl[n]['English']) < 0: ! if o == len(oldl): ! cm.writerow(newl[0]) ! del(newl[0]) ! o, n = 0, 0 ! continue ! o+=1 ! elif cmp(oldl[o]['English'], newl[n]['English']) > 0: ! if n == len(newl): ! cm.writerow(newl[0]) ! del(oldl[0]) ! o, n = 0, 0 ! continue ! n+=1 -- It's a man's life in a Python Programming Association. From aahz at pythoncraft.com Tue Jan 4 12:52:36 2005 From: aahz at pythoncraft.com (Aahz) Date: 4 Jan 2005 12:52:36 -0500 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1104831798.408560.228940@c13g2000cwb.googlegroups.com> <1104852554.684821.297400@f14g2000cwb.googlegroups.com> Message-ID: In article <1104852554.684821.297400 at f14g2000cwb.googlegroups.com>, wrote: >Aahz: >> >> The first three PSF grants were all in some way not directly related to >> changing the core language. One was for a library, one for improving >> Jython, and one for improving docs. Giving the PSF more money increases >> the chances for additional work. > >Here is the link you forgot to post ;-) > >http://www.python.org/psf/grants/ Didn't forget, was lazy and short of time. >The one about the docs seems more about teaching scientists how to use >Python. True, but that's still an expansion of Python's usability as opposed to changing the core language. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From luismgz at gmail.com Sun Jan 9 15:20:40 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 9 Jan 2005 12:20:40 -0800 Subject: else condition in list comprehension Message-ID: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Hi there, I'd like to know if there is a way to add and else condition into a list comprehension. I'm sure that I read somewhere an easy way to do it, but I forgot it and now I can't find it... for example: z=[i+2 for i in range(10) if i%2==0] what if I want i to be "i-2" if i%2 is not equal to 0? From elephantum at dezcom.mephi.ru Sun Jan 9 06:01:03 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 14:01:03 +0300 Subject: python3: 'where' keyword In-Reply-To: References: <3480qqF46jprlU1@individual.net> Message-ID: <34ch7gF45vrjoU1@individual.net> Peter Hansen wrote: >> >>> print words[3], words[5] where: >> >>> words = input.split() >> >> - defining variables in "where" block would restrict their visibility >> to one expression > > Then your example above doesn't work... print takes a > sequence of expressions, not a tuple as you seem to think. sorry, I used "expression" carelessly. I mean that >>> print words[3], words[5] is a single expression (and that would be in Python 3, when print would be subtituted with write()/writeln()). From pycon at python.org Thu Jan 20 19:06:07 2005 From: pycon at python.org (Steve Holden) Date: Fri, 21 Jan 2005 01:06:07 +0100 (CET) Subject: PyCon Preliminary Program Announced! Message-ID: <20050121000607.DE1261E4010@bag.python.org> Dear Python Colleague: You will be happy to know that the PyCon Program Committee, after lengthy deliberations, has now finalized the program for PyCon DC 2005. I can tell you that the decision-making was very difficult, as the standard of submissions was even higher than last year. You can see the preliminary program at http://www.python.org/pycon/2005/schedule.html and it's obvious that this year's PyCon is going to be even fuller than the last. On innovation is that there will be activities of a more social nature on the Wednesday (and perhaps the Thursday) evening, as well as keynote speeches from Guido and two other luminaries. Remember that the early bird registration rates end in just over a week, so hurry on down to http://www.python.org/pycon/2005/register.html to be sure of your place in what will surely be the premier Python event of the year. As always, I would appreciate your help in getting the word out. Please forward this message to your favorite mailing lists and newsgroups to make sure that everyone has a chance to join in the fun! regards Steve Holden Chairman, PyCON DC 2005 -- PyCon DC 2005: The third Python Community Conference http://www.pycon.org/ http://www.python.org/pycon/ The scoop on Python implementations and applications From news+0409 at henrikholm.com Wed Jan 12 11:24:58 2005 From: news+0409 at henrikholm.com (Henrik Holm) Date: Wed, 12 Jan 2005 10:24:58 -0600 Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> Message-ID: <1gq9u7n.1msmhzw1wzq5alN%news+0409@henrikholm.com> Richard Brodie wrote: > "Henrik Holm" wrote in message > news:1gq9qs9.3snutr1s4mcn2N%news+0409 at henrikholm.com... > > > I suppose I could also use a lambda here -- but is there a different, > > efficient, and obvious solution that I'm overlooking? > > Check the itertools recipes in the library documentation. Thanks, the itertools seem to contain several useful functions. -- "On some great and glorious day the plain folks of the land will reach in their heart's desire at last and the White House will be adorned by a downright moron." -H.L. Mencken (1880-1956) American Writer From tjreedy at udel.edu Thu Jan 6 19:35:29 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Jan 2005 19:35:29 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><25mlt05vtce42ohljk32qish66oj9bq049@4ax.com><7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: "Steve Holden" wrote in message news:rZbDd.68969$Jk5.62111 at lakeread01... > Absolutely not. Some people want to share under very specific conditions, > hence the proliferation of licenses in the open source world. Indeed, Prof. Lessig at Standford University, I believe, recently designed the Creative Commons license with a checklist of options with the intention of allowing and thereby encouraging people to share under the specific conditions they are willing to share under. http://creativecommons.org/licenses/ Terry J. Reedy From aleaxit at yahoo.com Sat Jan 22 03:50:37 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 09:50:37 +0100 Subject: Reload Tricks References: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> Message-ID: <1gqsb7j.1tbzcqn1f431kdN%aleaxit@yahoo.com> Kamilche wrote: > I want my program to be able to reload its code dynamically. I have a > large hierarchy of objects in memory. The inheritance hierarchy of > these objects are scattered over several files. Michael Hudson has a nice custom metaclass for that in Activestate's online cookbook -- I made some enhancements to it as I edited it for the forthcoming 2nd edition of the cookbook (due out in a couple of months), but the key ideas are in the online version too (sorry, no URL at hand). Alex From roland.heiber at web.de Tue Jan 11 06:07:20 2005 From: roland.heiber at web.de (Roland Heiber) Date: Tue, 11 Jan 2005 12:07:20 +0100 Subject: here document In-Reply-To: References: Message-ID: harold fellermann wrote: > f = open("/bin/exe.x","w") > print >>f , """CategoryY = GRIB > etc. > """ This would overwrite the existing /bin/exe.x ... HtH, Roland From steve at holdenweb.com Sat Jan 22 23:04:28 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 22 Jan 2005 23:04:28 -0500 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> Message-ID: Doug Holton wrote: > Fredrik Lundh wrote: > >> and trust me, when things are hard to get right for developers, users >> will >> suffer too. > > > That is exactly why YAML can be improved. But XML proves that getting > it "right" for developers has little to do with getting it right for > users (or for saving bandwidth). What's right for developers is what > requires the least amount of work. The problem is, that's what is right > for end-users, too. Yet again I will interject that XML was only ever intended to be wriiten by programs. Hence its moronic stupidity and excellent uniformity. 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 skip at pobox.com Sat Jan 29 08:28:48 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 29 Jan 2005 07:28:48 -0600 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <41fb646a$0$31784$9b622d9e@news.freenet.de> References: <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> Message-ID: <16891.36752.154869.431676@montanaro.dyndns.org> >> What matters is the code complexity, not whether something is in a >> separate module or not. Martin> A module *is* typically more complex than a single function. And one that deals with cryptography is likely to be even more complex. Skip From francis.girard at free.fr Fri Jan 21 11:54:47 2005 From: francis.girard at free.fr (Francis Girard) Date: Fri, 21 Jan 2005 17:54:47 +0100 Subject: need help on generator... In-Reply-To: <1106325287.19065.50.camel@bucket.localnet> References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501211654.52900.francis.girard@free.fr> <1106325287.19065.50.camel@bucket.localnet> Message-ID: <200501211754.47176.francis.girard@free.fr> Thank you, I immediately download version 2.4, switching from version 2.3. Francis Girard FRANCE Le vendredi 21 Janvier 2005 17:34, Craig Ringer a ?crit?: > On Fri, 2005-01-21 at 16:54 +0100, Francis Girard wrote: > > First, I think that you mean : > > > > consecutive_sets = [ x[offset:offset+subset_size] > > for subset_size in xrange(2, len(x)) > > for offset in xrange(0, len(x) + 1 - subset_size)] > > > > (with square brackets). > > > > I'm just trying to understand and obviously I'm missing the point. > > Yep. This: > > ( x for x in xrange(10) ) > > will return a generator that calculates things as it goes, while this: > > [ x for x in xrange(10) ] > > will return a list. > > Check out: > http://www.python.org/peps/pep-0289.html > http://docs.python.org/whatsnew/node4.html > http://www.python.org/dev/doc/newstyle/ref/genexpr.html > for details. > > -- > Craig Ringer From phr040919 at sympatico.ca Fri Jan 14 01:25:17 2005 From: phr040919 at sympatico.ca (Peter Renzland) Date: Fri, 14 Jan 2005 06:25:17 GMT Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: In <1105495569.479185.166340 at z14g2000cwz.googlegroups.com> On 2005-01-12 humblythegreatest at usa.com wrote: > python.org = 194.109.137.226 > > 194 + 109 + 137 + 226 = 666 > > What is this website with such a demonic name and IP address? What > evils are the programmers who use this language up to? What is the simplest/fastest Python program to determine how many IP addresses sum up to 666? The simplest/fastest enumerator? The simplest/fastest that determines which ones of them are home pages? BTW, www.churchofsatan.org is 216.168.224.70 That adds up to 666 + 12 Are they hedging their bets? :-) -- Peter From vincent at visualtrans.de Tue Jan 25 15:09:31 2005 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 25 Jan 2005 21:09:31 +0100 Subject: Open Folder in Desktop In-Reply-To: References: Message-ID: Jimmy Retzlaff wrote: > Kamilche wrote: > > Folders like My Documents, My Pictures, etc. are special and you need to > determine their actual path before you can open them. The pywin32 > extensions > (https://sourceforge.net/project/showfiles.php?group_id=78018) include a > way to get at this: > > from win32com.shell import shellcon, shell > path = shell.SHGetFolderPath(0, shellcon.CSIDL_MYPICTURES, 0, 0) > os.startfile(path) > > Google for CSIDL to find the constants to use for other special folders. Here's the exact link you'll need (warning, long url ahead ;) http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/enums/csidl.asp -- Vincent Wehren > > Jimmy From sjmachin at lexicon.net Fri Jan 21 18:48:59 2005 From: sjmachin at lexicon.net (John Machin) Date: 21 Jan 2005 15:48:59 -0800 Subject: why am I getting a segmentation fault? In-Reply-To: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> References: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> Message-ID: <1106351339.457714.214940@f14g2000cwb.googlegroups.com> Jay donnell wrote: > I have a short multi-threaded script that checks web images to make > sure they are still there. I get a segmentation fault everytime I run > it and I can't figure out why. Writing threaded scripts is new to me so > I may be doing something wrong that should be obvious :( > def run(self): try: self.site = urllib.urlopen(self.url) self.f=open(self.filename, 'w') self.im = Image.open(self.filename) self.size = self.im.size self.flag = 'yes' self.q = "yadda yadda" That's SIX names that don't need to be attributes of the object; they are used _only_ in this method, so they can be local to the method, saving you a whole lot of typing "self." and saving puzzlement & careful scrutiny by those trying to read your code. Back to your real problem: does it work when you set maxThreads to 1? did it work before you added the threading code? what does your debugger tell you about the location of the seg fault? MOST IMPORTANTLY, sort this mess out: self.q = "update item set goodImage = '" + self.flag + "' where productId='" + str(self.id) + "'" print self.q self.cursor.execute(query) ############################### ### "query" is a global variable[YUK!] (see below) which isn't going to do what you want. Looks like you meant "self.q". self.db.close() db = MySQLdb.connect(host="localhost", user="xxx", passwd="xxx", db="xxx") cursor = db.cursor() query = "select * from item order by rand() limit 0, 100" ### Have you looked in your database to see if the script has actually updated item.goodImage? Do you have a test plan? From adamhum at gmail.com Sat Jan 1 10:58:43 2005 From: adamhum at gmail.com (adamhum at gmail.com) Date: 1 Jan 2005 07:58:43 -0800 Subject: want some extra cash, try this Message-ID: <1104595123.745484.183540@c13g2000cwb.googlegroups.com> want some extra cash, try this THIS REALLY CAN MAKE YOU EASY MONEY!! A little while back, I was on my computer having a grand old time, just like you are now and came across an article similar to this that said you could make thousands dollars within weeks with only an initial investment of $6.00! So I thought, "Yeah, right, this must be a scam", but like most of us, I was curious, so I kept reading. Anyway, it said that you send $1.00 to each of the 6 names and address stated in the article. You then place your own name and address in the bottom of the list at #6, and post the article in at least 200 newsgroups. No catch, that was it. So after thinking it over, and talking to few people first, I thought about trying it. I figured what have I got to lose except 6 stamps and $6.00, right? Like most of us I was a little skeptical and a little worried about the legal aspects of it all, So I checked it out with the U.S. Post Office (1-800-725-2161) and they confirmed that it is indeed legal! Then I invested the measly $6.00. Well GUESS WHAT!!?. Within 7 days, I started getting money in the mail! I was shocked! I figured it would end soon, but the money just kept coming in. In my first week, I made about $25.00. By the end second week I had made a total over $1,000.00! In the third week I had over $10,000.00 and it's still growing. Its Certainly worth $6.00, and 6 stamps, I have spent more than that on the lottery!! Let me tell you how this works and most importantly, why it works?.STEP 1: Get 6 separate pieces of paper and write the following on each piece of paper "PLEASE PUT ME ON YOUR MAILING LIST." Now get 6 US $1.00 bills and place ONE inside EACH of the 6 pieces of paper so the bill will not be seen through the envelope to prevent thievery. Next, place one paper in each stating the above phrase, your name and address, and a $1.00 bill. What you are doing is creating a service by this. THIS IS ABSOLUTELY LEGAL! Mail the 6 envelopes to the following addresses: #1) Jason Barone P.O. Box 1015 Glen Burnie, MD 21060-1015 #2) Jonathon Markwood 3308 Birdsong Way Birmingham, AL 35242 #3) Eben Mcgee 1876 #C Locust, Las Cruces, NM 88001 #4) Ricky DeMaio 471 McCutcheon rd, Hudson WI 54016 #5) P. Ortner 29 Briarlee Dr. Tonawanda, NY 14150 #6) O. Humphrey 8452 E. Louise Dr, Tucson, AZ 85730 STEP 2: Now take the #1 name off the list that you see above, move the other names up and add YOUR Name as number 6 on the list. STEP 3: Change anything you need to, but try to keep this article as close to original as possible. Now, post your amended article to at least 200 newsgroups, message board. All you need is 200, but remember, the more you post, the more money you make!---- Just copy this message, paste it in Word or Notepad, find message boards like this and paste away. Congratulations? THAT'S IT! All you have to do is jump to different newsgroups and post away, after you get the hang of it, and it will take about 30 seconds for each newsgroup! * REMEMBER, THE MORE NEWSGROUPS OR MESSAGE BOARD YOU POST IN, THE MORE MONEY YOU EILL MAKE!! BUT YOU HAVE TO POST A MINIMUM OF 200* That's it! You will begin receiving money from around the world within days! From whereU at now.com Sun Jan 2 06:20:53 2005 From: whereU at now.com (Eric Pederson) Date: Sun, 2 Jan 2005 03:20:53 -0800 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <20050102032053.1006135324.whereU@now.com> Cameron Laird wrote: > > Let me add a cautionary note, though: Big Companies, > including Oracle, Software AG, IBM, Cisco, and so on, have > adopted Tcl over and over. All of them still rely on Tcl > for crucial products. All of them also have employees who > sincerely wonder, "Tcl? Isn't that dead?" > > I offer this as a counter-example to the belief that Adop- > tion by a heavyweight necessarily results in widespread > acceptance. > -- I think the adoption of computer languages is quite complex, but one useful metaphorical model may be gravity, e.g. the clumpy universe of stars, with gravity working on different scales to shape the overall distribution of matter. Adoption by a heavyweight may have some effect if that force is allowed to operate on other bodies, but the overall distribution of "mass" is complex. In the practice of business, companies generally find a need to consciously limit methodological diversity as they grow in size. Control is usually made more centralized, but becomes more distant from the atom (programmer writing code) as the firm grows large, and entropy becomes the enemy, lower level entropy a source of uncertainty and risk. If so, there is some legitimate reason for trying to "standardize" on tools (i.e. programming languages). Less sophisticated business minds may latch onto the notion of gains from economies of scale, which is usually an easy sell (and good route for a fast career rise) but an overly simple optimization. Not to say that such restrictive mindsets and policies are inevitable, but they seem the prevailing wind. Preserving intellectual diversity and innovation may be critical to a big company in the long run, and allowing the use of (for example) Python would seem very in tune with those goals. It might be nice if it was widely understood (in IT) that Python was a language any competent programmer could pick up in an afternoon, such that Java, C, and Perl shops would not be concerned about the need for their staff to learn a new language. Eric Pederson "Linear? What is linear?" Digital M4 (music) 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 andymac at bullseye.apana.org.au Tue Jan 4 06:12:32 2005 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Tue, 4 Jan 2005 22:12:32 +1100 (EST) Subject: ODBC Connection on Windows XP In-Reply-To: <41D99AB3.5090601@novasyshealth.com> References: <41D99AB3.5090601@novasyshealth.com> Message-ID: <20050104220934.E12542@bullseye.apana.org.au> On Mon, 3 Jan 2005, Greg Lindstrom wrote: > I am running Python 2.3 on Windows XP and am trying to connect to an > ODBC datasource. I have done this many times on this same box but this > time I get an error message saying > > dbi.operation-error: [WSOCK32.DLL]Connection refused, is the host > listener running? (#10061) in LOGIN > > Not having seen this before, and having used the odbc module for about a > year now, I'm at a quandary; what does this mean and what do I do to fix it? Exactly what it says... the host you're trying to connect to has refused your connection attempt (at the TCP level). At a guess, the database is down. ------------------------------------------------------------------------- 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 jlenton at gmail.com Wed Jan 12 18:27:07 2005 From: jlenton at gmail.com (John Lenton) Date: 12 Jan 2005 15:27:07 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: <1105572427.761562.135250@f14g2000cwb.googlegroups.com> > If you could help me figure out how to code a solution > that won't be a resource whore, I'd be _very_ grateful. (I'd prefer to > keep it in Python only, even though I know interaction with a > relational database would provide the fastest method--the group I'm > trying to write this for does not have access to a RDBMS.) You don't need a RDBMS; I'd put it in a DBM or CDB myself. From evan at tokenexchange.com Thu Jan 13 18:03:56 2005 From: evan at tokenexchange.com (Evan Simpson) Date: Thu, 13 Jan 2005 17:03:56 -0600 Subject: News Reader In-Reply-To: <41E6F97A.9010100@bowettsolutions.com> References: <41E6F97A.9010100@bowettsolutions.com> Message-ID: <41E6FE5C.6020804@tokenexchange.com> Daniel Bowett wrote: > OK, ask a stupid question.... I wasn't aware I needed a Usenet account. ...and if you don't have one, like me, there's always GMane (http://www.gmane.org/, nntp://news.gmane.org/). Cheers, Evan @ 4-am From PeterMayne at ap.spherion.com Wed Jan 5 20:28:29 2005 From: PeterMayne at ap.spherion.com (PJDM) Date: 5 Jan 2005 17:28:29 -0800 Subject: Import binary extensions from zipfiles, windows only References: <1104809102.966779.18480@f14g2000cwb.googlegroups.com> Message-ID: <1104974909.307793.173930@c13g2000cwb.googlegroups.com> Thomas Heller wrote: > zipextimporter, as published, doesn't handle extensions in packages. > The patch I attached at the end, may fix this - I tested it with PIL. Thanks, that works fine. However, ZopeX3 itself still won't run. As part of the startup, it attempts to load some files relative to imported classes. Since the path dives into a zip file, opening a file such as file://///C|/tmp/zope.zip/zope/app/server/schema.xml doesn't work. Patching things up to avoid this just leads deeper into the mire, so it looks like this avenue is closed. Things would probably be easier if Python had something like Java's Class.getResourceAsStream(), where a resource is found by the class loader. This means that is doesn't matter if the class came from a directory, a JAR file, or a network: if the class loader could load the class, it could also load the resource from the same place. The __loader__ attribute from PEP 302 seems to be the equivalent, but the standard importer doesn't provide it. maynp at nessus:~> python Python 2.3.4 (#1, Jul 31 2004, 11:22:19) [GCC 3.3.1 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.__loader__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute '__loader__' >>> Oh well. PJDM From francis.girard at free.fr Mon Jan 24 10:24:41 2005 From: francis.girard at free.fr (Francis Girard) Date: Mon, 24 Jan 2005 16:24:41 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <200501241409.25598.francis.girard@free.fr> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> Message-ID: <200501241624.41889.francis.girard@free.fr> The following implementation is even more speaking as it makes self-evident and almost mechanical how to translate algorithms that run after their tail from recursion to "tee" usage : *** BEGIN SNAP from itertools import tee, imap import sys def imerge(xs, ys): x = xs.next() y = ys.next() while True: if x == y: yield x x = xs.next() y = ys.next() elif x < y: yield x x = xs.next() else: yield y y = ys.next() def hamming(): def _hamming(): yield 1 hamming2 = hammingGenerators[0] hamming3 = hammingGenerators[1] hamming5 = hammingGenerators[2] for n in imerge(imap(lambda h: 2*h, iter(hamming2)), imerge(imap(lambda h: 3*h, iter(hamming3)), imap(lambda h: 5*h, iter(hamming5)))): yield n hammingGenerators = tee(_hamming(), 4) return hammingGenerators[3] for i in hamming(): print i, sys.stdout.flush() *** END SNAP Here's an implementation of the fibonacci sequence that uses "tee" : *** BEGIN SNAP from itertools import tee import sys def fib(): def _fib(): yield 1 yield 1 curGen = fibGenerators[0] curAheadGen = fibGenerators[1] curAheadGen.next() while True: yield curGen.next() + curAheadGen.next() fibGenerators = tee(_fib(), 3) return fibGenerators[2] for n in fib(): print n, sys.stdout.flush() *** END SNAP Francis Girard FRANCE Le lundi 24 Janvier 2005 14:09, Francis Girard a ?crit?: > Ok, I think that the bottom line is this : > > For all the algorithms that run after their tail in an FP way, like the > Hamming problem, or the Fibonacci sequence, (but unlike Sieve of > Eratosthene -- there's a subtle difference), i.e. all those algorithms that > typically rely upon recursion to get the beginning of the generated > elements in order to generate the next one ... > > ... so for this family of algorithms, we have, somehow, to abandon > recursion, and to explicitely maintain one or many lists of what had been > generated. > > One solution for this is suggested in "test_generators.py". But I think > that this solution is evil as it looks like recursion is used but it is not > and it depends heavily on how the m235 function (for example) is invoked. > Furthermore, it is _NOT_ memory efficient as pretended : it leaks ! It > internally maintains a lists of generated results that grows forever while > it is useless to maintain results that had been "consumed". Just for a > gross estimate, on my system, percentage of memory usage for this program > grows rapidly, reaching 21.6 % after 5 minutes. CPU usage varies between > 31%-36%. Ugly and inefficient. > > The solution of Jeff Epler is far more elegant. The "itertools.tee" > function does just what we want. It internally maintain a list of what had > been generated and deletes the "consumed" elements as the algo unrolls. To > follow with my gross estimate, memory usage grows from 1.2% to 1.9% after 5 > minutes (probably only affected by the growing size of Huge Integer). CPU > usage varies between 27%-29%. > Beautiful and effecient. > > You might think that we shouldn't be that fussy about memory usage on > generating 100 digits numbers but we're talking about a whole family of > useful FP algorithms ; and the best way to implement them should be > established. > > For this family of algorithms, itertools.tee is the way to go. > > I think that the semi-tutorial in "test_generators.py" should be updated to > use "tee". Or, at least, a severe warning comment should be written. > > Thank you, > > Francis Girard > FRANCE > > Le dimanche 23 Janvier 2005 23:27, Jeff Epler a ?crit?: > > Your formulation in Python is recursive (hamming calls hamming()) and I > > think that's why your program gives up fairly early. > > > > Instead, use itertools.tee() [new in Python 2.4, or search the internet > > for an implementation that works in 2.3] to give a copy of the output > > sequence to each "multiply by N" function as well as one to be the > > return value. > > > > Here's my implementation, which matched your list early on but > > effortlessly reached larger values. One large value it printed was > > 6412351813189632 (a Python long) which indeed has only the distinct > > prime factors 2 and 3. (2**43 * 3**6) > > > > Jeff > > > > from itertools import tee > > import sys > > > > def imerge(xs, ys): > > x = xs.next() > > y = ys.next() > > while True: > > if x == y: > > yield x > > x = xs.next() > > y = ys.next() > > elif x < y: > > yield x > > x = xs.next() > > else: > > yield y > > y = ys.next() > > > > def hamming(): > > def _hamming(j, k): > > yield 1 > > hamming = generators[j] > > for i in hamming: > > yield i * k > > generators = [] > > generator = imerge(imerge(_hamming(0, 2), _hamming(1, 3)), > > _hamming(2, 5)) generators[:] = tee(generator, 4) > > return generators[3] > > > > for i in hamming(): > > print i, > > sys.stdout.flush() From francis.girard at free.fr Fri Jan 21 10:05:38 2005 From: francis.girard at free.fr (Francis Girard) Date: Fri, 21 Jan 2005 16:05:38 +0100 Subject: need help on need help on generator... In-Reply-To: <1106318290.19065.11.camel@bucket.localnet> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> Message-ID: <200501211605.40696.francis.girard@free.fr> Hi, I recently read David Mertz (IBM DeveloperWorks) about generators and got excited about using lazy constructs in my Python programming. But besides the fact that generators are either produced with the new "yield" reserved word or by defining the __new__ method in a class definition, I don't know much about them. In particular, I don't know what Python constructs does generate a generator. I know this is now the case for reading lines in a file or with the new "iterator" package. But what else ? Does Craig Ringer answer mean that list comprehensions are lazy ? Where can I find a comprehensive list of all the lazy constructions built in Python ? (I think that to easily distinguish lazy from strict constructs is an absolute programmer need -- otherwise you always end up wondering when is it that code is actually executed like in Haskell). Thank you Francis Girard FRANCE Le vendredi 21 Janvier 2005 15:38, Craig Ringer a ?crit?: > On Fri, 2005-01-21 at 17:14 +0300, Denis S. Otkidach wrote: > > On 21 Jan 2005 05:58:03 -0800 > > > > joh12005 at yahoo.fr (Joh) wrote: > > > i'm trying to understand how i could build following consecutive sets > > > from a root one using generator : > > > > > > l = [1,2,3,4] > > > > > > would like to produce : > > > > > > [1,2], [2,3], [3,4], [1,2,3], [2,3,4] > > > > > >>> def consecutive_sets(l): > > > > ... for i in xrange(2, len(l)): > > ... for j in xrange(0, len(l)-i+1): > > ... yield l[j:j+i] > > Since you have a much faster brain than I (though I ended up with > exactly the same thing barring variable names) and beat me to posting > the answer, I'll post the inevitable awful generator expression version > instead: > > consecutive_sets = ( x[offset:offset+subset_size] > for subset_size in xrange(2, len(x)) > for offset in xrange(0, len(x) + 1 - subset_size) ) > > -- > Craig Ringer From jelle.feringa at ezct.net Thu Jan 20 14:38:35 2005 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Thu, 20 Jan 2005 20:38:35 +0100 Subject: building extensions: ming & python mathlink for win32 Message-ID: <20050120193521.37C7A2800129@mwinf1007.wanadoo.fr> Have been trying to build python extensions from the C libs ming & mathlink. I have been able to produce a .pyd object after studying Mike Fletchers excellent: http://www.vrplumber.com/programming/mstoolkit/ which is a terrific tutorial for anyone trying to compile .pyd on win32! Building mathlink (communicating with mathematica from python!) was semi successful in the sense that it did build a .pyd, Semi, since importing it gave: >>> import mathlink Fatal Python error: Error initializing mathlink extension module This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. Has anyone been able to compile this extension for python? Same thing goes for Ming (c lib for compiling flas .swf files), such a pity no disutils script is included in this very powerful library! ##if you succeeded to build this, please consider sharing it with me! (2.3 is fine as well!) What struck me while trying to compile is that instead of the Active Python 2.4 version I was running I downloaded and installed the python.org version (as recommended by Fletcher), and while launching it, I stated ActivePython 2.4 Build 243 (ActiveState Corp.) based on Python 2.4 HUH! WHAT! No actual difference between the python.org & activestate version??? Cheers, Jelle. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Serge.Orlov at gmail.com Mon Jan 17 04:04:50 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: Mon, 17 Jan 2005 12:04:50 +0300 Subject: how to print unicode structures? References: Message-ID: Serge Orlov wrote: >>>> print unicode([u'???']) > [u'\u0430\u0431\u0432'] > Oops, Outlook Express has screwed the encoding, one more evidence that printing unicode is hard :) I hope this time, the message will be with real Russian characters instead of Latin ones. Serge. From aleaxit at yahoo.com Sat Jan 22 06:00:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 12:00:36 +0100 Subject: need help on need help on generator... References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> Message-ID: <1gqsffz.vgl2rr78gx4xN%aleaxit@yahoo.com> Francis Girard wrote: ... > > A 'def' of a function whose body uses 'yield', and in 2.4 the new genexp > > construct. > > Ok. I guess I'll have to update to version 2.4 (from 2.3) to follow the > discussion. It's worth upgrading even just for the extra speed;-). > > Since you appear to conflate generators and iterators, I guess the iter > > built-in function is the main one you missed. iter(x), for any x, > > either raises an exception (if x's type is not iterable) or else returns > > an iterator. > > You're absolutly right, I take the one for the other and vice-versa. If I > understand correctly, a "generator" produce something over which you can > iterate with the help of an "iterator". Can you iterate (in the strict sense > of an "iterator") over something not generated by a "generator" ? A generator function (commonly known as a generator), each time you call it, produces a generator object AKA a generator-iterator. To wit: >>> def f(): yield 23 ... >>> f >>> x = f() >>> x >>> type(x) A generator expression (genexp) also has a result which is a generator object: >>> x = (23 for __ in [0]) >>> type(x) Iterators need not be generator-iterators, by any means. Generally, the way to make sure you have an iterator is to call iter(...) on something; if the something was already an iterator, NP, then iter's idempotent: >>> iter(x) is x True That's what "an iterator" means: some object x such that x.next is callable without arguments and iter(x) is x. Since iter(x) tries calling type(x).__iter__(x) [[slight simplification here by ignoring custom metaclasses, see recent discussion on python-dev as to why this is only 99% accurate, not 100% accurate]], one way to code an iterator is as a class. For example: class Repeater(object): def __iter__(self): return self def next(self): return 23 Any instance of Repeater is an iterator which, as it happens, has just the same behavior as itertools.repeat(23), which is also the same behavior you get from iterators obtained by calling: def generepeat(): while True: yield 23 In other words, after: a = Repeater() b = itertools.repeat(23) c = generepeat() the behavior of a, b and c is indistinguishable, though you can easily tell them apart by introspection -- type(a) != type(b) != type(c). Python's penchant for duck typing -- behavior matters more, WAY more than implementation details such as type() -- means we tend to consider a, b and c fully equivalent. Focusing on ``generator'' is at this level an implementation detail. Most often, iterators (including generator-iterators) are used in a for statement (or equivalently a for clause of a listcomp or genexp), which is why one normally doesn't think about built-in ``iter'': it's called automatically by these ``for'' syntax-forms. In other words, for x in <<>>: ...body... is just like: __tempiter = iter(<<>>) while True: try: x = __tempiter.next() except StopIteration: break ...body... ((Simplification alert: the ``for'' statement has an optional ``else'' which this allegedly "just like" form doesn't mimic exactly...)) > You're right. I was much more talking (mistakenly) about lazy evaluation of > the arguments to a function (i.e. the function begins execution before its > arguments get evaluated) -- in such a case I think it should be specified > which arguments are "strict" and which are "lazy" -- but I don't think > there's such a thing in Python (... well not yet as Python get more and more > akin to FP). Python's strict that way. To explicitly make some one argument "lazy", sorta, you can put a "lambda:" in front of it at call time, but then you have to "call the argument" to get it evaluated; a bit of a kludge. There's a PEP out to allow a ``prefix :'' to mean just the same as this "lambda:", but even though I co-authored it I don't think it lowers the kludge quotient by all that much. Guido, our beloved BDFL, is currently musing about optional typing of arguments, which might perhaps open a tiny little crack towards letting some arguments be lazy. I don't think Guido wants to go there, though. My prediction is that even Python 3000 will be strict. At least this makes some things obvious at each call-site without having to study the way a function is defined, e.g., upon seeing f(a+b, c*d) you don't have to wonder, or study the ``def f'', to find out when the addition and the multiplication happen -- they happen before f's body gets a chance to run, and thus, in particular, if either operation raises an exception, there's nothing f can do about it. And that's a misunderstanding I _have_ seen repeatedly even in people with a pretty good overall grasp of Python, evidenced in code such as: self.assertRaises(SomeError, f(23)) with astonishment that -- if f(23) does indeed raise SomeError -- this exception propagates, NOT caught by assertRaises; and if mistakenly f(23) does NOT raise, you typically get a TypeError about None not being callable. The way to do the above call, _since Python is strict_, is: self.assertRaises(SomeError, f, 23) i.e. give assertRaises the function (or other callable) and arguments to pass to it -- THIS way, assertRaises performs the call under its own control (inside the try clause of a try/except statement) and can and does catch and report things appropriately. The frequency of this misunderstanding is high enough to prove to me that strictness is not FULLY understood by some "intermediate level" Pythonistas. However, I doubt the right solution is to complicate Python with the ability to have some arguments be strict, and other lazy, much as sometimes one might yearn for it. _Maybe_ one could have some form that makes ALL arguments lazy, presenting them as an iterator to the function itself. But even then the form _should_, I suspect, be obvious at the call site, rather than visible only in the "def"... Alex From carribeiro at gmail.com Sun Jan 9 03:51:42 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sun, 9 Jan 2005 06:51:42 -0200 Subject: python3: 'where' keyword In-Reply-To: <41E0C700.8080604@iinet.net.au> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <7xhdlsw6ov.fsf@ruckus.brouhaha.com> <41E0C700.8080604@iinet.net.au> Message-ID: <864d3709050109005131f943ee@mail.gmail.com> On Sun, 09 Jan 2005 15:54:08 +1000, Nick Coghlan wrote: > Here's another nice one if 'where' is added to compound statements as well: > > @dbc(pre, post) > def foo(): > pass > where: > def pre(): > pass > def post(): > pass Interesting. It solves some of the issues with chosing a clear syntax for "design by contract" and other similar features that were being debated lately. I also thought about his one: ! def foo(x=calculate_default_value()): ! pass ! where: ! def calculate_default_value(): ! ... ! return -- 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 mcturra2000 at yahoo.co.uk Tue Jan 4 10:52:03 2005 From: mcturra2000 at yahoo.co.uk (Mark Carter) Date: Tue, 04 Jan 2005 15:52:03 +0000 Subject: How can engineers not understand source-code control? In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41da713a$0$610$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <41dabba1$0$47624$ed2619ec@ptn-nntp-reader02.plus.net> ;; This buffer is for notes you don't want to save, and for Lisp evaluation. ;; If you want to create a file, first visit that file with C-x C-f, ;; then enter the text in that file's own buffer. Cameron Laird wrote: > Well *that* certainly made my morning unpleasant. Then let's see if I can spoil you afternoon, too ... I was working on a project (that used Excel, alas) that checked the daily allocation of oil and gas. The calculations were very complicated, and liable to error. I thought it would be a good idea if I serialised intermediate calculations so they could be checked. My solution was to save them as a CSV file, with array name in the first column, index variables in subsequent columns, and array value in the last column. That way, they could be checked manually. The standard approach at my company would have been to create honking big spreadsheets to house these values. Anyway, time went on, it was decided that these daily calculations needed to be aggregated to monthly values. Well, it turned out that the solution I had adopted was quite good, because one could just suck the file in, read off the relevant variables, and populate an array. To be compared with what would normally happen of creating a nexus of links to a disk-busting collection of spreadsheets. I shall have my revenge, though. The file serve hierarchy that we have is very complicated, and is due for simplification in the very near future. So all those peeps who did spreadsheets, with hard links to other spreadsheets, are in for a bit of a surprise. I think the I-Ching expressed it better than I ever could: The bird's nest burns up. The wanderer laughs at first, Then must needs lament and weep. Through carelessness he loses his cow. Misfortune. Source: http://www.eclecticenergies.com/iching/hexagram.php?nr=56 I'm thinking that the I-Ching is a vast untapped resource for programming wisdom, plus it makes it funny. Or haikus, maybe they'd be good. From roy at panix.com Sun Jan 23 16:04:41 2005 From: roy at panix.com (Roy Smith) Date: Sun, 23 Jan 2005 16:04:41 -0500 Subject: What is print? A function? References: Message-ID: Frans Englich wrote: > Nah, I don't think it's a function, but rather a builtin "statement". But > it's possible to invoke it as an function; print( "test" ) works fine. That's not calling it as a function. The parens in this case are simply evaluated as grouping operators around the string literal. > So I wonder, what _is_ exactly the print statement? The untraditional way of > invoking it(without paranteses) makes me wonder. It's a statement, just like "write" in Fortran. When C came around, the idea of a language having no built-in print statement and having to call a function to generate output was "untraditional". The function was named "printf" (with an "f" at the end) to emphasize that it was a function call, not a built-in language keyword. Java, and many other quasi-C-based languages also use print functions, and this has become so common that people have come to expect it. It's even a function in Perl, although that language's devil-may-care attitude about punctuation makes it difficult to tell for sure :-) > The reason I thinks about this is I need to implement a debug print for my > program; very simple, a function/print statement that conditionally prints > its message whether a bool is true. Not overly complex. You can certainly define a function which conditionally calls print, you just can't call it "print", because that's a reserved word. But, before you get too far down that path, you might want to explore the logging module. It suffers from a bit of kitchen-sink syndrome, so it may be more complicated than you want to deal with, but it's worth taking a look at. You may discover that what you want to do is already done for you. From mhartl at post.harvard.edu Fri Jan 28 12:13:15 2005 From: mhartl at post.harvard.edu (Michael Hartl) Date: 28 Jan 2005 09:13:15 -0800 Subject: a sequence question In-Reply-To: References: Message-ID: <1106932395.158158.149060@c13g2000cwb.googlegroups.com> For problems like this I use a partition function defined in a utils.py file that I use (based on Peter Norvig's utils file at http://aima.cs.berkeley.edu/python/utils.py). Using partition, the problem you posed can be solved by writing #for a, b in partition([1, 2, 3, 4], 2): # print a, b The implementation of partition I use is simple-minded; the previous posts in this thread suggest some more sophisticated ways to attack it using generators. #def partition(seq, partsize): # """Partition a sequence into subsequences of length partsize.""" # ls = len(seq) # assert ls % partsize == 0, ('length %s, partition size %s\n' # % (ls, partsize)) # return [seq[i:(i+partsize)] for i in range(0, ls, partsize)] Michael From kartic.krishnamurthy at gmail.com Sun Jan 9 19:12:03 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 9 Jan 2005 16:12:03 -0800 Subject: path to python file given module In-Reply-To: <1105315568.887724.260370@c13g2000cwb.googlegroups.com> References: <1105315568.887724.260370@c13g2000cwb.googlegroups.com> Message-ID: <1105315923.520581.280580@c13g2000cwb.googlegroups.com> Try this:; >>> import filegen >>> import inspect >>> print inspect.getsourcefile(filegen.SomeClass) 'C:\\Python23\\Lib\\site-packages\\filegen\filegen.py' Cheers, --Kartic From ialbert at mailblocks.com Thu Jan 27 14:10:06 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 27 Jan 2005 14:10:06 -0500 Subject: python memory blow out In-Reply-To: References: Message-ID: Simon Wittber wrote: > Does anyone have ideas on why this is occuring, or how I might > otherwise prevent memory blow out? I don't know it this is a decent enough solution but if I were you I would try running the SQL service in a subshell. Within this subshell I would terminate then restart the program after a large query and keep it going after small ones. The clients then would need to have some tolerance for the service being offline for short periods. Just a guess. Istvan. From ncoghlan at iinet.net.au Sun Jan 9 06:36:18 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 21:36:18 +1000 Subject: python3: 'where' keyword In-Reply-To: <7xr7ku26zs.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> Message-ID: <41E11732.7@iinet.net.au> Paul Rubin wrote: > Nick Coghlan writes: > >>Trying to push it a level further (down to expressions) would, IMO, be >>a lot of effort for something which would hurt readability a lot. > > > I think we should just try to do things in a simple and general way > and not try to enforce readability. Trying to embed a suite in a Python expression is anything but simple, though :) Attaching an optional local suite to every statement can actually be done quite cleanly (so long as the parser is up to the job). Doing the substitutions on the whole statement using distinct names will work just as well as doing the substitutions directly on the subexpressions using duplicate names, and moves the 'unimportant' bits after the whole thing, instead of sprinkling them throughout the statement. It seems a statement based approach would be: 1. Easier to read 2. Less work to implement 3. Consistent with the rest of the language 4. Works for any statements, including compound statements The only disadvantage relative to expression local namespaces would be that you would still have to watch for namespace conflicts within the statement - and I have grave doubts about the structure of any statement which has that problem. If statement local namespaces were pursued, I would see expression local namespaces as something which hurt readability a lot without providing any new functionality. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From skip at pobox.com Fri Jan 14 05:03:28 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 14 Jan 2005 04:03:28 -0600 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: <16871.39152.202342.414779@montanaro.dyndns.org> Fredrik> no, expressions CAN BE USED as statements. that doesn't mean Fredrik> that they ARE statements, unless you're applying belgian logic. Hmmm... I'd never heard the term "belgian logic" before. Googling provided a few uses, but no formal definition (maybe it's a European phrase so searching for it in English is futile). The closest thing I found was Or is it another case of Belgian logic, where you believe it because theres no evidence or motive whatsoever? Fredrik> no, it's Python, and it's designed this way on purpose. go Fredrik> read the language reference. What he said... While Python borrows stuff from other languages where they fit, it has a few core syntactic features that taken together distinguish it from other languages. Not allowing any statements to be used as expressions is one of them. Note that both "expression" and "statement" are context-sensitive terms. Fredrik applied them in their Python sense ("go read the language reference"), while Paul (perhaps naively, perhaps provocatively) seems bent on forcing a more general definition of the two words on the thread. Skip From fredrik at pythonware.com Mon Jan 24 11:04:22 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 17:04:22 +0100 Subject: Right place for third party modules (here: fixedpoint) References: <35kj2iF4n6sokU1@news.dfncis.de> Message-ID: Sibylle Koczian wrote: > for the first time since getting Python I can't get a third party module to work. > > I got fixedpoint.0.1.2.tar.gz from SourceForge for use with KinterbasDB. After unpacking I had a > directory called "fixedpoint" which I put under my site-packages directory. There are no > installation instructions and just the one module fixedpoint.py (and some documentation and > examples). > > All of this under Windows XP, with Python 2.4. > > Now I try to use the module, but > > import fixedpoint > > says "ImportError: No module named fixedpoint". > > I suppose fixedpoint is no package as described in the tutorial and so "site-packages" might not > be the right place for it. site-packages sure works on my windows xp / python 2.4 configuration. what is your sys.path set to? >>> import sys >>> sys.path ['', 'C:\\WINDOWS\\system32\\python24.zip', ... 'C:\\python24', 'C:\\python24\\lib\\site-packages', ... ] if you fire up a command window and run python -v -v -c "import fixedpoint" you get a list of places where python looks for that module. does it look in right directory? (this can be very verbose; you might wish to do python -v -v -c "import fixedpoint" 2> out notepad out instead) From db3l at fitlinxx.com Thu Jan 6 13:15:01 2005 From: db3l at fitlinxx.com (David Bolen) Date: 06 Jan 2005 13:15:01 -0500 Subject: Another PythonWin Excel question References: <1104968382.403653.267060@f14g2000cwb.googlegroups.com> Message-ID: "It's me" writes: > Yes, I read about that but unfortunately I have no experience with VBA *at > all*. :=( You don't really have to know VBA, but if you're going to try to interact with COM objects from Python, you'll find it much smoother if you at least use any available reference information for the COM object model and interfaces you are using. In the Excel case, that means understanding - or at least knowing how to look in a reference - its object model, since that will tell you exactly what parameters an Add method on a worksheet object will take and how they work. For excel, online documentation can be found in a VBAXL9.CHM help file (the "9" may differ based on Excel release), but it might not always be installed depending on what options were selected on your system. In my English, Office 2000 installation, for example, the files are located in: c:\Program Files\Microsoft Office\Office\1033 You can load that file directly, or Excel itself will reference it from within the script editor help (Tools->Macro->Visual Basic Editor, then F1 for help). If you methods or classes and have the help installed it'll bring in the reference. You can also find it on MSDN on the web, although it can be tricky to navigate down to the right section - the top of the Office 2000 object documentation should be available at: http://msdn.microsoft.com/library/en-us/odeomg/html/deovrobjectmodelguide.asp This is mostly reference information, but there are some higher level discussions of overall objects (e.g., worksheets, workbooks, cells, etc...) too. -- David From kartic.krishnamurthy at gmail.com Thu Jan 6 07:16:25 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 6 Jan 2005 04:16:25 -0800 Subject: navigating/changing directories In-Reply-To: <1105013445.219752.99060@z14g2000cwz.googlegroups.com> References: <1105013445.219752.99060@z14g2000cwz.googlegroups.com> Message-ID: <1105013785.465364.18070@f14g2000cwb.googlegroups.com> Hmmm... I take it back... that is not working! I think it changes the path only during execution time. From tundra at tundraware.com Thu Jan 20 05:53:57 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 20 Jan 2005 05:53:57 EST Subject: [ANN] tconfpy 2.112 Released And Available Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 'tconfpy' Version 2.112 is now released and available for download at: ~ http://www.tundraware.com/Software/tconfpy The last public release was 1.185 (5-2-2004) This is a significant bugfix and feature upgrade release. Existing users are strongly encouraged to upgrade. Be aware that the passed and returned API parameters have changed, as have some of the semantics of the configuration language, so existing code and/or configuration files may need to be edited accordingly. Complete details can be found in the WHATSNEW.txt file included in the distribution. Users are strongly encouraged to join the tconfpy-users mailing list as described in the documentation. What Is 'tconfpy'? - ------------------ 'tconfpy' is an advanced configuration file parser and validator for Python programs. By using 'tconfpy', Python programmers can provide their users with an external configuration file for setting program options, defining defaults, and so on. 'tconfpy' offloads the responsibility for parsing and validating a configuration file from the main application. The Python programmer need only deal with the results and any errors or warnings generated during the parsing process. 'tconfpy' recognizes a rich configuration language and provides a number of sophisticated programming features including: ~ - The ability to breakup large configurations into smaller pieces ~ via the '.include' directive. ~ - Support for string substitution and concatenation throughout the ~ configuration file via string variables. Variables may be ~ locally declared, a reference to a symbol already in the ~ symbol table, or a reference to an environment variable. ~ - A complete set of conditional directives for selective ~ processing of configuration options. Both existential ("If ~ variable exists ...") and comparison ("if string equals/does not ~ equal string ...") forms are provided, as is an '.else' ~ directive. ~ - The ability to instantiate program options prior to reading a ~ configuration file and make them mandatory by declaring those ~ options as Read-Only. ~ - Optional type validation to ensure that a user enters a value ~ appropriate for boolean, integer, floating point, string, or ~ complex data. ~ - Optional value validation to ensure that a configuration option ~ is either within a specified range or one of an enumerated set ~ of possible values. For configuration options which are string ~ types, 'tconfpy', can optionally specify min/max string lengths ~ and enumerate a set of legitimate regular expressions that the ~ string must match. ~ - The ability to define an arbitrary number of lexical namespaces. ~ - The ability to use the various features of 'tconfpy' as a pre- ~ processor for any other text (including source code for other ~ programming languages and Python itself) via the '.literal' ~ directive. ~ - The ability to "template" classes of variables, thereby predefining ~ the type and value restrictions for such variables. This makes ~ 'tconfpy' useful as a building block for data validation tools. ~ - An optional debug capability which returns detailed information ~ about each line parsed. ~ - Includes a test driver program for learning how to program with ~ 'tconfpy' and for debugging and testing your own configuration ~ files. ~ - Comes with approximately 40 pages of documentation including a ~ Programmer's API Reference and a User's Guide to the 'tconfpy' ~ configuration language. Documentation is provided in several ~ formats including Unix 'man', Plain Text, html, pdf, and ~ Postscript. 'tconfpy' is a Pure Python module and is platform-independent. It should work identically on any platform on which Python runs. - ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.6 (Cygwin) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFB744ayjgA+Mact+YRAopHAJ952scQ/LVBz5ye+VARvuhsKk+9cgCfYNSQ LLuefsso1mXxdh38EEovuCo= =ojco -----END PGP SIGNATURE----- From timr at probo.com Fri Jan 21 02:58:10 2005 From: timr at probo.com (Tim Roberts) Date: Thu, 20 Jan 2005 23:58:10 -0800 Subject: global variable, ok for string, bad for int References: <41f07e65$1_2@aeinews.> Message-ID: francisl wrote: > >I have a problem when I declare global variable. >If it is string, dict, array or tuple, everything goes fine, but with int, I get an "used before declaration" error. Excuse me for being dubious, but I don't believe you. Both of the examples you posted work fine in Python 2.3 on Windows XP. Please type the EXACT script you ran, and show us the EXACT error message you get. You can cut-and-paste from the cmd shell script to make sure we see the right output. >here a sample : > >vardict = {'un':1, 'deux':2} > >def print_value(): > print vardict['un'] >######### ok, that works > >-------------------- > >#!/bin/python >varint = 1 > >def print_value(): > print varint >######### ok, that failed > >python 2.3.4 - windows2000 > >(it works in linux!) -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com Sun Jan 9 11:34:11 2005 From: jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com (Miklós P) Date: Sun, 9 Jan 2005 17:34:11 +0100 Subject: Guild of Python consultants? Message-ID: Hello freelancers out there, Is there such a thing somewhere? Yes, I'm aware of the Python Business Forum. But I mean something specifically for (individual) consultants. By searching on Google, I couldn't find a "virtual guild" of consultants who try to make a living from Python and technologies built around it (like Zope, Plone, etc.) I'm thinking of providing mutual marketing help like a webring, passing info about projects and clients, discussing business related issues and technical issues in deploying Python in the enterprise, etc. Any thoughts? Best, Mikl?s --- Jegenye 2001 Bt. Egyedi szoftverk?sz?t?s, tan?csad?s | Custom software development, consulting Magyarul: http://jegenye2001.parkhosting.com In English: http://jegenye2001.parkhosting.com/en From bokr at oz.net Sat Jan 8 05:55:36 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 08 Jan 2005 10:55:36 GMT Subject: Other notes References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> <41DD40F1.5030301@holdenweb.com> <41dda7c5.167823026@news.oz.net> <41def1ea.252340977@news.oz.net> Message-ID: <41dfa77b.298821542@news.oz.net> On Sat, 08 Jan 2005 18:22:53 +1000, Nick Coghlan wrote: >Bengt Richter wrote: >> IOW, I think there is a fix: keep tokenizing greedily and tokenize floating point as >> a sequence of integers and operators, and let be translated by >> the compiler to floating point, and be translated to the >> appropriate generator expression implementation. > >That would be: > > -> float( + "." + ) > -> getattr(int(), ) > -> xrange(, ) > >However, the problem comes when you realise that 1e3 is also a floating point >literal, as is 1.1e3. > Ok, that requires a little more imagination ;-) I think it can be solved, but I haven't explored it all the way through ;-) The key seems to be to be to condition the recognition of tokens as if recognizing an old potentially floating point number, but emitting number-relevant separate tokens so long as there is no embedded spaces. When a number ends, emitting an end marker should permit the compiler to deal with the various compositions. We still aren't looking ahead more than one, but we are carrying context, just as we do to accumulate digits of an integer or characters of a name, but the context may continue and determine what further tokens are emitted. E.g. the 'e' in the embedded numeric context, becomes rather than a name. In the following, :== end of number token 1.1 -> <1><1> 1 .1 -> <1><1> 1.e1 -> <1><1> 1 .e1 -> <1> 1.2e3 -> <1><2><3> 1..2 -> <1><1> 1. .2 -> <1><2> (syntax error) 1 ..2 -> <1><1> I just have the feeling that there is a solution, whatever the hiccups ;-) Regards, Bengt Richter From aahz at pythoncraft.com Thu Jan 6 20:07:19 2005 From: aahz at pythoncraft.com (Aahz) Date: 6 Jan 2005 20:07:19 -0500 Subject: The Industry choice References: <7xhdluxh4i.fsf@ruckus.brouhaha.com> Message-ID: In article , Bulba! wrote: > >Nope. That is not what I'm arguing. Really, I think you have >jumped to conclusion about that: I merely pointed out that >I don't like what I perceive as end effect of what GPL license >writers are attempting to achieve: vendor lock-in. > >I think I stated that clearly. And my counter-argument is that I believe your perception is wrong. If I agreed with your focus on lock-in, I'd say that what the GPL is trying to lock in is a specific legal philosophy by subverting the existing system. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From beliavsky at aol.com Mon Jan 17 10:47:06 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 17 Jan 2005 07:47:06 -0800 Subject: dynamic data types References: <1105969253.296411.301760@f14g2000cwb.googlegroups.com> Message-ID: <1105976826.510706.114900@z14g2000cwz.googlegroups.com> rbt wrote: >I've always thought of it like this... in C, we have to do something >like this when declaring a variable: >int x = 0; >We had to specifically tell the language compiler that x is an integer. >In Python, all we have to do is: >x = 0 >The interpretor knows that x is an integer. We can also change the type >like this: >str(x) >float(x) >long(x) Just to clarify, str(x) does not change x, but x = str(x) does. Probably rbt knows this. I wonder how often this feature should be employed. In my Python programs, most variables keep the same type throughout. This makes a code easier for me to understand, and this constraint should facilitate translation of the code to a statically typed language (perhaps even a variant of Python) in the future, if necessary. The ability to grow a list with "append" is a very convenient feature of Python. The C++ vector is similar but stores elements of the same type, whereas a Python list or tuple can store elements of different types. From deetsNOSPAM at web.de Mon Jan 10 08:21:29 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 10 Jan 2005 14:21:29 +0100 Subject: Port blocking References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> Message-ID: <34fabdF49gjh1U1@individual.net> > Usually you wouldn't run a public corba or pyro service over the > internet. You'd use something like XMLRPC over HTTP port 80 partly > for the precise purpose of not getting blocked by firewalls. What exactly makes sending bytes over port 80 more secure than over any other port? It has always been my impression that this was to create less administrative troubles for firewall admins. But its not inherently more secure. That's a property of the application running. -- Regards, Diez B. Roggisch From ncoghlan at iinet.net.au Sat Jan 8 00:06:44 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 15:06:44 +1000 Subject: What could 'f(this:that=other):' mean? In-Reply-To: <41DF05DC.9060004@pytex.org> References: <41DC52CA.5070104@pytex.org> <10toomjdjcs5v21@corp.supernews.com> <41DCE28B.70806@pytex.org> <10tr8eo5skqo2a3@corp.supernews.com> <41DF05DC.9060004@pytex.org> Message-ID: <41DF6A64.3060000@iinet.net.au> If the caller is meant to supply a namespace, get them to supply a namespace. def f(ns1, ns2): print ns1['a'], ns1['b'], ns2['a'], ns2['b'] f(ns1 = dict(a=1, b=2), ns2 = dict(a=3, b=4)) Hey, where's Steve? Maybe his generic objects should be called namespaces instead of bunches. . . def f(ns1, ns2): print ns1.a, ns1.b, ns2.a, ns2.b f(ns1 = namespace(a=1, b=2), ns2 = namespace(a=3, b=4)) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From sjmachin at lexicon.net Fri Jan 21 23:59:39 2005 From: sjmachin at lexicon.net (John Machin) Date: 21 Jan 2005 20:59:39 -0800 Subject: getting file size In-Reply-To: References: Message-ID: <1106369979.460268.116610@z14g2000cwz.googlegroups.com> Bob Smith wrote: > Are these the same: > > 1. f_size = os.path.getsize(file_name) > > 2. fp1 = file(file_name, 'r') > data = fp1.readlines() > last_byte = fp1.tell() > > I always get the same value when doing 1. or 2. Is there a reason I > should do both? When reading to the end of a file, won't tell() be just > as accurate as os.path.getsize()? > Read the docs. Note the hint that you get what the stdio serves up. ftell() can only be _guaranteed_ to give you a magic cookie that you may later use with fseek(magic_cookie) to return to the same place in a more reliable manner than with Hansel & Gretel's non-magic bread-crumbs. On 99.99% of modern filesystems, the cookie obtained by ftell() when positioned at EOF is in fact the size in bytes. But why chance it? os.path.getsize does as its name suggests; why not use it, instead of a method with a side-effect? As for doing _both_, why would you?? From kartic.krishnamurthy at gmail.com Wed Jan 5 19:31:27 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 16:31:27 -0800 Subject: Another PythonWin Excel question In-Reply-To: References: <1104968382.403653.267060@f14g2000cwb.googlegroups.com> Message-ID: <1104971487.590817.172620@f14g2000cwb.googlegroups.com> Sorry, I was thinking of the move() method. Move() takes the after= argument. See this link for usage. (The left nav bar has all other method of the worksheets collection, so bookmark this page :-) http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrtskhowtoaddnewworksheetstoworkbooks.asp Thanks From yyusenet at yahoo.com Mon Jan 31 18:10:20 2005 From: yyusenet at yahoo.com (YYusenet) Date: Mon, 31 Jan 2005 16:10:20 -0700 Subject: [perl-python] find & replace strings for all files in a dir In-Reply-To: <1107203410.397877.309750@c13g2000cwb.googlegroups.com> References: <1107203410.397877.309750@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > suppose you want to do find & replace of string of all files in a > directory. > here's the code: [snip] > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html > When are you going to take the hint (from everybody in comp.lang.perl.misc and comp.lang.python) to stop posting! Your posts do not help anybody and will only hurt a beginner. *PLEASE STOP POSTING*! -- k g a b e r t (@at@) x m i s s i o n (.dot.) c o m * After "extensive" research, I noticed * that yyusenet at yahoo.com received 12 * spam e-mail messages after just two * posts on usenet groups. If you want * to email me, use the "encrypted" * email address at the beggining of my * signature. From swaroopch at gmail.com Tue Jan 25 15:54:41 2005 From: swaroopch at gmail.com (Swaroop C H) Date: Wed, 26 Jan 2005 02:24:41 +0530 Subject: MySQLdb In-Reply-To: <41F6AF8A.3040102@bowettsolutions.com> References: <41F6AF8A.3040102@bowettsolutions.com> Message-ID: <351e8871050125125434eb6d2@mail.gmail.com> On Tue, 25 Jan 2005 20:43:54 +0000, Daniel Bowett wrote: > I have just started playing around with MySQLdb for a project I am planning. > > As a test I have written a script that executes 3000 insert statements > on a table. The table contains 10 fields with a mix of text and numbers > - its a product table for a website eg UPC, ProductName, Price etc. > > The problem I have is that it takes just over two minuted to execute the > 3000 insert statements which seems really slow! I am running it on a > machine with a 1.5 Ghz Pentium M Processor and Gig Of Ram. I dont think > the machine is to blame for the speed because during execution the > processor sits at about 10% and there is loads of free RAM. I think a better option is to have the rows in a text file and then use `mysqlimport` or 'load data infile' SQL[1] [1]: http://dev.mysql.com/doc/mysql/en/load-data.html -- Swaroop C H Blog: http://www.swaroopch.info Book: http://www.byteofpython.info From grante at visi.com Thu Jan 13 17:31:55 2005 From: grante at visi.com (Grant Edwards) Date: 13 Jan 2005 22:31:55 GMT Subject: how to control the mouse pointer with python? References: <1105650438.311153.167410@f14g2000cwb.googlegroups.com> <34o9npF4et4hiU1@individual.net> <1105654593.637145.321290@z14g2000cwz.googlegroups.com> Message-ID: <41e6f6db$0$5416$a1866201@visi.com> On 2005-01-13, oglycans at yahoo.com wrote: > Sorry, I should have mentioned it's linux (debian). > Thanks. What environment? Console? X11? MGR? ??? -- Grant Edwards grante Yow! My ELBOW is a remote at FRENCH OUTPOST!! visi.com From gh at ghaering.de Tue Jan 4 12:52:16 2005 From: gh at ghaering.de (Gerhard Haering) Date: Tue, 4 Jan 2005 18:52:16 +0100 Subject: DB-API 2.0 in pysqlite and pgdb In-Reply-To: References: Message-ID: <20050104175216.GA830@mylene.ghaering.de> On Sat, Jan 01, 2005 at 06:33:24PM +0300, Roman Suzi wrote: > > Happy New Year to all Pythoneers! > > I am playing with pysqlite and pgdb and their DB-API conformancy. > It was quite interesting to know: > > - sqlite doesn't have mandatory helper-functions Date, Tim, etc. > (due to an error int it's __init__, but this is quite obvious to correct > or just to use mx.Date, mx.Time) Yes, that's an oversight. > more serious mishaps with pgdb (postgresql-python): > it doesn't know how to quote date-time data for the objects > it has constructors itself. [...] You may have better luck with pyPgSQL or psycopg. -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From darrinbaggs at --spamreallysucks--rogers.com Fri Jan 7 19:08:15 2005 From: darrinbaggs at --spamreallysucks--rogers.com (Baggs) Date: Fri, 07 Jan 2005 19:08:15 -0500 Subject: Help uninstalling/installing Python 2.4 Message-ID: Guys/Gals I've messed up my Python 2.4 install. I'm really new to Python (and Linux for that matter) and really wanted to try Python out. I have mandrake 10.1. The first thing I did was uninstalled via rpm Python 2.3 and Tkinter 8.3 (I now realize that was a mistake, since I could have both version installed with no problems). I then downloaded Python2.4 ran ./configure make and make install... voila I had Python installed... Tk calls did not work, the output from Python when running a program stated that I probably did not have TK installed. I got and installed TK 8.4 and the problem persisted (I know I should have written down the exact error, but I didn't... but the story gets worse!) Here is the really stupid part... I figured if I uninstalled and re-installed everything would be ok.... the bad part is I could not find an uninstaller for TK or Python, so I just searched and delted the files and directorys from /usr/local.... when I re-installed I still have problems.. everything installs ok, but now I get the following errors with Python... bash: /usr/bin/python: No such file or directory The interesting thing is the python executable is in /usr/local/bin when I go to /usr/local/bin and type ./python I get Python 2.4 (#6, Jan 7 2005, 18:44:57) [GCC 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. Traceback (most recent call last): File "/etc/pythonrc.py", line 2, in ? import readline ImportError: No module named readline I think some paths are screwed up.. can someone take pity on me and give me a hand. Thanks Darrin PS -- if you want to mail me directly remove the --spamreallysucks-- in my email address. From stephen.thorne at gmail.com Wed Jan 12 22:26:54 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 13:26:54 +1000 Subject: pyserial and com port interrupts In-Reply-To: <41e5e4e2.707756109@news.oz.net> References: <41e5e4e2.707756109@news.oz.net> Message-ID: <3e8ca5c805011219265626a9f8@mail.gmail.com> On Thu, 13 Jan 2005 03:11:23 GMT, Bengt Richter wrote: > On Wed, 12 Jan 2005 14:24:48 -0800, engsol wrote: > > >Has anyone done a script that will rspond to the serial com port(s) > >receive buffer interrupt, as opposed to polling and timeouts? > >Win2000 is the main interest right now. > > Have you looked into letting the OS do it? I.e., reading from COM4: > or whatever port in a thread maybe one byte at a time? Maybe you can > get your end functionality without writing low levels stuff, depending ;-) > > I haven't done this, but it seems an easy thing to try a few experiments with. > The control panel should let you set baud rates and handshaking etc. I would think. PySerial[1] is more than capable of handling all the low level operations with little more than 's.baud = 9600'. The OP was more interested in how to write his program so he could react to com port input in a timely manner in the face of having blocking procedures elsewhere in his code. Regards, Stephen Thorne [1] http://pyserial.sourceforge.net/ From markfanty at yahoo.com Mon Jan 24 22:24:43 2005 From: markfanty at yahoo.com (Mark Fanty) Date: Tue, 25 Jan 2005 03:24:43 GMT Subject: best way to do a series of regexp checks with groups References: Message-ID: <%ZiJd.5729$cx2.3209@trndny03> This is the kind of thing I meant. I think I have to get used to writing small, light-weight classes. You inspired this variation which is a little more verbose in the class definition, but less so in the use: class Matcher: def search(self, r,s): self.value = re.search(r,s) return self.value def __getitem__(self, i): return self.value.group(i) m = Matcher() if m.search(r'add (\d+) (\d+)', line): do_add(m[1], m[2]) elif m.search(r'mult (\d+) (\d+)', line): do_mult(m[1], m[2]) elif m.search(r'help (\w+)', line): show_help(m[1]) As for using regular expressions too much... they are why I've liked perl so much for quick file processing for years. I don't like perl objects at all, which is why I'm trying python, but the re package has not been my favorite so far... "Nick Craig-Wood" wrote in message news:slrncv8ar0.m68.nick at irishsea.home.craig-wood.com... > > There was a thread about this recently under the title > > "regular expression: perl ==> python" > > Here is a different solution... > > class Result: > def set(self, value): > self.value = value > return value > > m = Result() > > if m.set(re.search(r'add (\d+) (\d+)', line)): > do_add(m.value.group(1), m.value.group(2)) > elif m.set(re.search(r'mult (\d+) (\d+)', line)): > do_mult(m.value.group(1), m.value.group(2)) > elif m.set(re.search(r'help (\w+)', line)): > show_help(m.value.group(1)) > > -- > Nick Craig-Wood -- http://www.craig-wood.com/nick From bokr at oz.net Thu Jan 13 19:08:09 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 14 Jan 2005 00:08:09 GMT Subject: newbie q References: <34mgq0F4dq4buU1@individual.net> <34mku4F4c8bdkU1@individual.net> Message-ID: <41e7098e.782680124@news.oz.net> On Thu, 13 Jan 2005 09:16:40 -0500, Steve Holden wrote: [...] > >Any statement of the form > > for i in [x for x in something]: > >can be rewritten as > > for i in something: > >Note that this doesn't mean you never want to iterate over a list >comprehension. It's the easiest way, for example, to iterate over the >first item of each list in a list of lists: > > for i in [x[0] for x in something]: > As I'm sure you know, with 2.4's generator expressions you don't have to build the temporary list. Which could be important if 'something' is (or generates) a huge sequence. for i in (x[0] for x in something): >>> something = ([x] for x in xrange(10,20)) >>> something >>> list(something) [[10], [11], [12], [13], [14], [15], [16], [17], [18], [19]] >>> for i in (x[0] for x in something): print i, ... oops, that list() used it up ;-) >>> something = [[x] for x in xrange(10,20)] >>> for i in (x[0] for x in something): print i, ... 10 11 12 13 14 15 16 17 18 19 Really nice. Regards, Bengt Richter From fuzzyman at gmail.com Fri Jan 28 04:03:37 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 28 Jan 2005 01:03:37 -0800 Subject: urllib2 and proxy question In-Reply-To: References: <1106575675.520424.155310@f14g2000cwb.googlegroups.com> Message-ID: <1106903017.560210.67150@c13g2000cwb.googlegroups.com> rbt wrote: > Fuzzyman wrote: > > urllib2 (under windows) will auto-detect your proxy settings and use > > those. > > > > Normally that's a good thing (I guess), except when it's not ! > > > > How do I switch off this behaviour ? I'm behind a censoring proxy and > > wanting to test things *locally*. IE is set to not use the proxy when > > fetching local adresses, but urllib2 ignores that part of the setting > > and uses the proxy for everything. > > > > The only way I can test are changing my IE settings back and forth > > every time. Most annoying. > > > > I can see how to *add* a new proxy to urllib2, but not how to force it > > to not use a proxy. I may well be missing something obvious though. > > Anyone able to help ? > > Regards, > > > > Fuzzy > > http://www.voidspace.org.uk/python/index.shtml > > > > "Alternatively, the optional proxies argument may be used to explicitly > specify proxies. > It must be a dictionary mapping scheme names to proxy URLs, where an > empty dictionary causes no proxies to be used" > > # Don't use any proxies > filehandle = urllib.urlopen(some_url, proxies={}) The correct equivalent for urllib2 (in answer to my question !) is : >>> proxy_support = urllib2.ProxyHandler({}) >>> opener = urllib2.build_opener(proxy_support) >>> urllib2.install_opener(opener) which is slightly more complicated but does exactly the same job ! Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From wittempj at hotmail.com Wed Jan 12 13:56:52 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 12 Jan 2005 10:56:52 -0800 Subject: Refactoring; arbitrary expression in lists In-Reply-To: References: Message-ID: <1105556212.036972.160470@z14g2000cwz.googlegroups.com> I can not break the original code in 2.4, if I try this: import os, sys class NoMimeError(Exception): pass def detectMimeType( filename ): extension = filename[-3:] basename = os.path.basename(filename) if extension == "php": return "application/x-php" elif extension == "cpp" or extension.endswith("cc"): return "text/x-c++-src" elif extension == "1": return 'BlahBlah' elif extension == "2": return 'BlahBlah' elif extension == "3": return 'BlahBlah' elif extension == "4": return 'BlahBlah' elif extension == "5": return 'BlahBlah' elif extension == "6": return 'BlahBlah' elif extension == "7": return 'BlahBlah' elif extension == "8": return 'BlahBlah' elif extension == "9": return 'BlahBlah' elif extension == "10": return 'BlahBlah' elif extension == "11": return 'BlahBlah' elif extension == "12": return 'BlahBlah' elif extension == "13": return 'BlahBlah' elif extension == "14": return 'BlahBlah' elif extension == "15": return 'BlahBlah' elif extension == "16": return 'BlahBlah' elif extension == "17": return 'BlahBlah' elif extension == "18": return 'BlahBlah' elif extension == "19": return 'BlahBlah' elif extension == "20": return 'BlahBlah' elif extension == "xsl": return "text/xsl" elif basename.find( "Makefile" ) != -1: return "text/x-makefile" else: raise NoMimeError try: print detectMimeType(r'c:\test.php') print detectMimeType('c:\test.xsl') print detectMimeType('c:\test.xxx') except Exception, e: print >> sys.stderr, '%s: %s' %(e.__class__.__name__, e) I get >>> application/x-php text/xsl NoMimeError: >>> So although the dictionary solution is much nicer nothing seems wrong with your code as it is - or am I missing something? From mmokrejs at ribosome.natur.cuni.cz Fri Jan 14 11:12:32 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Fri, 14 Jan 2005 17:12:32 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <1f7befae0501101245679b26f2@mail.gmail.com> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> <41E2E69C.7080104@ribosome.natur.cuni.cz> <1f7befae0501101245679b26f2@mail.gmail.com> Message-ID: <41E7EF70.1020505@ribosome.natur.cuni.cz> Tim Peters wrote: > [Martin MOKREJ?] > >>... >> >>I gave up the theoretical approach. Practically, I might need up >>to store maybe those 1E15 keys. > > > We should work on our multiplication skills here . You don't > have enough disk space to store 1E15 keys. If your keys were just one > byte each, you would need to have 4 thousand disks of 250GB each to > store 1E15 keys. How much disk space do you actually have? I'm > betting you have no more than one 250GB disk. > > ... > > [Istvan Albert] > >>>On my system storing 1 million words of length 15 >>>as keys of a python dictionary is around 75MB. > > >>Fine, that's what I wanted to hear. How do you improve the algorithm? >>Do you delay indexing to the very latest moment or do you let your >>computer index 999 999 times just for fun? > > > It remains wholly unclear to me what "the algorithm" you want might > be. As I mentioned before, if you store keys in sorted text files, > you can do intersection and difference very efficiently just by using > the Unix `comm` utiltity. This comm(1) approach doesn't work for me. It somehow fails to detect common entries when the offset is too big. file 1: A F G I K M N R V AA AI FG FR GF GI GR IG IK IN IV KI MA NG RA RI VF AIK FGR FRA GFG GIN GRI IGI IGR IKI ING IVF KIG MAI NGF RAA RIG file 2: W W W W W W W W W W AA AI FG FR GF GI GR IG IK IN IV KI MA NG RA RI VF AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA From michele.simionato at gmail.com Thu Jan 6 10:15:20 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 6 Jan 2005 07:15:20 -0800 Subject: parameterized metaclass (or metametaclass) In-Reply-To: References: Message-ID: <1105024520.193968.70120@f14g2000cwb.googlegroups.com> > I was wondering if there is some simpler way of building parameterized > metaclasses ? Why not just a function returning metaclasses? def metaFactory(*args): dic = return type("somemetaclass", (type,), dic) Alternatively, a metaclass classmethod returning a metaclass, so that you can use something like __metaclass__ = MyMetaclass.with(*args) # classmethod returning a metaclass Michele Simionato From jeff at ccvcorp.com Fri Jan 7 16:15:13 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 07 Jan 2005 13:15:13 -0800 Subject: sorting on keys in a list of dicts In-Reply-To: References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: <10ttukogfl43p62@corp.supernews.com> Nick Coghlan wrote: > Jeff Shannon wrote: > >> I suppose that your version has the virtue that, if the sortkey value >> is equal, items retain the order that they were in the original list, >> whereas my version will sort them into an essentially arbitrary order. >> Is there anything else that I'm missing here? > > > Stability in sorting is a property not to be sneezed at [...] Agreed. I'd started typing before I realized that it'd provide a stable sort, which pretty much answered my own question, but decided to send it anyhow in case I'd missed anything else... :) Jeff Shannon Technician/Programmer Credit International From cookedm+news at physics.mcmaster.ca Tue Jan 11 16:11:07 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 11 Jan 2005 16:11:07 -0500 Subject: readline, rlcompleter References: <1105429869.770262.14360@c13g2000cwb.googlegroups.com> Message-ID: michele.simionato at gmail.com writes: > This a case where the documentation is lacking. The standard library > documentation > (http://www.python.org/dev/doc/devel/lib/module-rlcompleter.html) gives > this example > try: > import readline > except ImportError: > print "Module readline not available." > else: > import rlcompleter > readline.parse_and_bind("tab: complete") > > but I don't find a list of recognized key bindings. For instance, can I > would > like to bind shift-tab to rlcompleter, is that possible? Can I use > function > keys? I did various attempt, but I did not succed :-( > Is there any readline-guru here with some good pointers? > Michele Simionato Basically, you could use any key sequence that is sent to the terminal. So shift-tab is out (that's not sent as a key to any terminal program). Function keys would have to be specified as the key sequence sent by a function key ("\e[11~" for F1, for instance). Have a look at the readline info page, or the man page. The syntax of readline.parse_and_bind is the same as that of an inputrc file. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From newsgroups at jhrothjr.com Sun Jan 9 17:08:21 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 9 Jan 2005 16:08:21 -0600 Subject: Python3: on removing map, reduce, filter References: <34csn1F4a46hqU1@individual.net> Message-ID: <10u3areb0r8c93b@news.supernews.com> "Andrey Tatarinov" wrote in message news:34csn1F4a46hqU1 at individual.net... > Hi. > > How does GvR suggestions on removing map(), reduce(), filter() correlate > with the following that he wrote himself (afaik): > > http://www.python.org/doc/essays/list2str.html This is fairly old. Note that the fastest version uses the array module, and is quite comprehensible - if you know the array module and how it works. It doesn't use the map function. John Roth > > ? From craig at postnewspapers.com.au Thu Jan 27 01:27:19 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Thu, 27 Jan 2005 14:27:19 +0800 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <1106807239.8583.12.camel@bucket.localnet> On Wed, 2005-01-26 at 22:28 -0500, Davor wrote: > I browsed docs a bit today, and they also confirm what I have believed - > that OO is totally secondary in Python. In fact, > object/classes/metaclasses are nothing but *dictionaries with identity* > in python. Love this approach. I was really impressed with the design of the language, especially this bit. I first "got" it when reading Learning Python 2nd Ed (well *after* I'd been using Python for a while, but it's always good to read even intro books to fill out "obvious" things you might've missed). I love the way the same "It's just a dictionary search" principle applies to inheritance, scoped variable lookups, etc. In Python, even metaclasses just operate on the class dictionary. How pleasantly simple :-) - especially how the step from class factory to metaclass is so small and approachable. I also love the way I can chuck a bunch of objects into a functionally styled processing pipeline, say a series of functions that each just return the result of a listcomp/genexp. -- Craig Ringer From john at grulic.org.ar Thu Jan 13 18:39:00 2005 From: john at grulic.org.ar (John Lenton) Date: Thu, 13 Jan 2005 20:39:00 -0300 Subject: XPath and XQuery in Python? In-Reply-To: References: Message-ID: <20050113233900.GA3727@grulic.org.ar> On Wed, Jan 12, 2005 at 12:09:58AM +0000, Nelson Minar wrote: > Could someone help me get started using XPath or XQuery in Python? I'm > overwhelmed by all the various options and am lacking guidance on what > the simplest way to go is. What library do I need to enable three line > Python programs to extract data with XPath expressions? > > I have this problem a lot with Python and XML. Even with Uche's > excellent yearly roundups I have a hard time finding how to do fancy > things with XML in Python. I think it's a bit like web server > frameworks in Python - too many choices. my own favorite is libxml2. Something like the following: #!/usr/bin/env python import libxml2 import sys def grep(what, where): doc = libxml2.parseDoc(where) for found in doc.xpathEval(what): found.saveTo(sys.stdout, format=True) if __name__ == '__main__': try: what = sys.argv[1] except IndexError: sys.exit("Usage: %s pattern file ..." % sys.argv[0]) else: for where in sys.argv[2:]: grep(what, file(where).read()) although you might want to be smarter with the errors... -- John Lenton (john at grulic.org.ar) -- Random fortune: The whole world is a scab. The point is to pick it constructively. -- Peter Beard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From tom at dtsam.com Tue Jan 4 10:30:09 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Tue, 4 Jan 2005 09:30:09 -0600 Subject: Reaching the real world References: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: "Fuzzyman" wrote in message news:1104850540.610295.152240 at f14g2000cwb.googlegroups.com... > I have a friend who would like to move and program lights and other > electric/electro-mechanical devices by computer. I would like to help - > and needless to say Python would be an ideal language for the > 'programmers interface'. > > What I'd like is an electronic interface that connects to several > relays and a python extension module to switch on and off the relays. > I've had a quick google and can't see anything too similar to what I > want. pyro (python robotics) seems to require expensive (relatively) > robotic equipment. Loosely, what you are looking for is Data Acquisition (DAQ) , Digital I/O, and control that you can do from your pc. Those are the keywords you want to google. Look at www.ni.com and poke around. They will have some introductory material. Look at www.circuitcellar.com . It may look a bit overwhelming at first but look at the ads for pc equipment. These should also lead you to some tutorials. You are looking for simple digital output. You can use an existing serial or parallel port with a bit of external hardware from radio shack to control relays on the cheap. OR You can purchase a Digital I/O adaptor that will plug into your computer bus and give you outputs to control your relays. You will also get instructions and some software to interface (talk!) to the adaptor. Typically you will read and write to the I/O ports on your computer to flip the switches. OR perhaps the easiest and most effective These would be smart devices that talk to your Python (or whatever!) software via the serial port. You would throw simple string commands (eg "ChannelB ON") at the serial port and the microprocessor based controller will turn on the appropriate relay. Your challenge from Python will be to control the computers I/O ports or to communicate with one of the serial ports. I'm sure someone else will point to libraries that will help you with this. Much *much* more but you have to start somewhere :-) Thomas Bartkus From none at none.net Tue Jan 4 02:48:25 2005 From: none at none.net (Iwan van der Kleyn) Date: Tue, 04 Jan 2005 08:48:25 +0100 Subject: Python evolution: Unease Message-ID: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> Please ignore if you are allergic to ramblings :-) Despite a puritan streak I've always tried to refrain from language wars or syntax bickering; call it enforced pragmatism. That's the main reason why I've liked Python: it's elegant and simple and still dynamic and flexible. You could do worse for a clean and pragmatic language. I do know my Smaltalk from my Common Lisp and my Ruby from my C#, so I think I'm quite capable of escaping the "Blub paradox" http://c2.com/cgi/wiki?BlubParadox. I do miss some slick features in Python. But the nice thing about Python is that in those cases I can use its dynamism to implement it myself (and usually somebody else has done it for me, of course). In the end I'm not a language guru nor a framework wizard, but a mere mortal who designs and writes programs for end-users. For that task I need: a better standard ide, an integrated db interface with a proper set of db drivers (!!), a better debugger, a standard widget/windows toolkit, something akin to a standard for web programming, better documentation, a standard lib which is better organized, a formalized set of protocols and patterns for program construction. And an interpreter which is fast enough to avoid using C or Pyrex in most obvious cases. Many will say that Van Rossum's brainstorms/proposals as depicted in http://www.artima.com/weblogs/viewpost.jsp?thread=86641 will help in the above mentioned. And I'm certainly not against Optional ype checking. But I see little to no efforts from the core python team to address my needs as listed above. They seem mainly to focus on the core attributes and syntax of the language. Very little or no efforts are taken to improve the infrastructure around the language. And then I read the following sentence by Van Rossum: "In order to make type inferencing a little more useful, I'd like to restrict certain forms of extreme dynamic behavior in Python" In the end, it's mindset which counts. And I think that mindset is going to be determine the way foreward for Python: more features, increased complexity, less dynamism. Lots of syntax crud, without addressing the need to improve the infrastructure around the language. In short: I symphatize Patrick Logan's feeling: http://patricklogan.blogspot.com/2005/01/road-to-ruin.html Regards, Iwan van der Kleyn From aleaxit at yahoo.com Thu Jan 27 08:29:57 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Jan 2005 14:29:57 +0100 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106814263.835719.181360@z14g2000cwz.googlegroups.com> <1106826024.655143.227050@c13g2000cwb.googlegroups.com> Message-ID: <1gr1xay.2ym8rg9jui8uN%aleaxit@yahoo.com> wrote: ... > Some complexity is not needed, and I am sure even in Python > something could be dropped. But it is difficult to find what can > be removed. Remember that Saint-Exupery quote? Something > like "a work of art is finished when there is nothing left to remove?" Saint-?xupery was an engineer (and a pioneer of flight) and so he was referring to a designer (and no doubt had in mind those planes...), not to an artist (not his fault if he's better remembered as a novelist;-). As for what can be removed from Python, one could start at -- while each of us will find there some "complexity" one loves and uses often (be it lambda, buffer, reload, ...), it's a good start. Alex From grahamd at dscpl.com.au Fri Jan 28 20:33:27 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 28 Jan 2005 17:33:27 -0800 Subject: Who should security issues be reported to? In-Reply-To: References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Message-ID: <1106962407.019438.87470@z14g2000cwz.googlegroups.com> > OP: Did you discover this supposed security hole from black-box observation > of behavior or by being one of the 'lots of people being able to look at > source code', thereby giving evidence to the point? The technique used which is the source of the problem was actually first discovered in a separate package to the Python distribution, but it was known that the same technique was used in a module within the Python distribution. It is quite possible that other third party packages might use it as well, although a few of the main stream packages have been checked and they don't use exactly the same technique so are okay. I could have just ignored the fact that the Python distribution had the problem and worried about the other package only. > a) The OP has provided no info about his/her claim. Since the problem at least affects two packages and because of the potential for mischief, I am hardly about to identify the packages concerned, nor describe anything that is going to allow people to work out what the issue is. > b) The OP's original post is a classical troll: blast volunteer developers > for not having anticipated and planned for a novel situation; argue against > things not said, at least now here, not recently; imply that volunteers own > him something. Most people with the expertise to detect a security hole > would know better. And the reaction is what I have more and more been seeing in Open Source circles. That, is either treat posters like ignoreant newbies who know no better, or assume they are a trolls trying to discredit Open Source. Quite sad really, one tries to do the right thing and gets abused for it. It doesn't matter if a large project may be perceived as being mostly immune to security problems, one could still occur and if it isn't simple to raise such an issue I am sure than some people wouldn't even bother. > c) The noise generated because of b) has alerted any malware writers > monitering c.l.p for hints about exploitable security holes that there > might be one in one of the few modules where such could reasonably be. With approx 200+ modules in the Python distribution I can hardly see how this helps. If I had done what you had wanted in (a) and gave actual information about the problem I would have been narrowing down the problem to less than a dozen modules. You can't have it both ways. > OP: If my doubts are wrong and you really do have something to quietly > report to the 'authority', then do so, and quit making a noise about it. And so it is was and knowledgeable people are looking at the issue. It should not though have necessitated me making a noise in order to find someone to deal with it in a timely manner. When a proprietary company doesn't have an easy way of reporting problems or seems not to care too much, Open Source people are on top of them like wolves. Why can't Open Source people hold themselves to the same standard. Not sure why I have even bothered to respond to you as it is probably just the sort of attention you want. You even appear to have some history of taking issue with people, even though in one of your own posts you state: > Responding to trollish postings. (Jan 26) > > My personal strategy is to read only as much of trollish > threads as I find interesting or somehow instructive, almost never respond, > and then ignore the rest. I also mostly ignore discussions about such > threads. > > Terry J. Reedy Maybe you should simply have not responded. Lets see if you now ignore the followup discussion. :-) From ncoghlan at iinet.net.au Fri Jan 7 12:49:01 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 03:49:01 +1000 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Message-ID: <41DECB8D.40507@iinet.net.au> Jacek Generowicz wrote: > Yes, I was wondering whether I should add lots of caveats to the above. I thought that might be the case. When teaching, I guess I can understand the need to avoid "well, technically, this isn't always true". It sounds like the students were having a tough enough time of it already :) > Usually one or two have trouble grasping that "int" would be perfectly > adequate in this situation. The ability to pass around functions at run-time was probably the hardest thing to get my head around when I started with Python, after a history of working in languages where "the compiler knows about types and functions, and the runtime knows about variables and instances". Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ml at dynkin.com Fri Jan 28 15:18:28 2005 From: ml at dynkin.com (George Yoshida) Date: Sat, 29 Jan 2005 05:18:28 +0900 Subject: Proccess termination In-Reply-To: <1106917700.730538.80320@f14g2000cwb.googlegroups.com> References: <1106917700.730538.80320@f14g2000cwb.googlegroups.com> Message-ID: alexrait1 wrote: > I use popen.popen2 or popen.popen3 to start a new process and read from > it's stdout/ write to it's stdin. > But I need a way to know when a process terminates. > Do you know about a library that provides these tools other then the > standard os module... or should I use it otherwise? popen2.Popen3, popen2.Popen4 and subprosess.Popen have poll/wait methods. These will do what you're looking for. -- George From danperl at rogers.com Wed Jan 5 12:48:19 2005 From: danperl at rogers.com (Dan Perl) Date: Wed, 5 Jan 2005 12:48:19 -0500 Subject: Cookbook 2nd ed Credits References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> Message-ID: "Alex Martelli" wrote in message news:1gpvtjk.3jf7dc1cch7yfN%aleaxit at yahoo.com... > Premshree Pillai wrote: >> Btw, is there a comprehensive list of ALL contributors put up anywhere? > > Not yet -- do you think I should put it up on my website? Updating the status of the recipes on the web site would be nice. Dan > > Alex From bulba at bulba.com Thu Jan 6 19:04:31 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 01:04:31 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> <41DD4E62.1020404@holdenweb.com> <10tr15fabtpnf97@corp.supernews.com> Message-ID: On Thu, 06 Jan 2005 10:38:53 -0800, Jeff Shannon wrote: >It's also noteworthy to consider that many times, waste happens not >because of corruption or self-interest, but simply because of errors >of judgement. Precisely. That is one of the main points I was trying to get across in discussion with Alex. I have no reason to make conspiracy theories that bribes were involved in that bad decision at that German company. No, it _seemed_ like it was simple mistake, because somebody responsible for this did not research the issue in enough depth. And note that it was definitely not in his personal interest, whoever that was, a person or group of persons, as he/they risked getting fired for that. >Humans being as we are, it's inevitable that over time, >some "obvious" important details will escape our attention, and the >resulting imperfect information will result in poor decisions. This >is a simple fact of human nature, and (ob-Python ;) ) it's one of the >reasons that Python is designed as it is -- it makes a serious effort >to reduce the number of details that might escape detection. I suspect it is one of the reasons why many people switch from learning Perl to learning Python (at least I did - I simply could not remember after a month or two what the hell I concocted in this place in Perl program, it felt as if this were somebody else's code). >(One should also consider that many business failures are a case of >simply having played the odds and lost. Many ventures depend on >outside events playing in a certain way; when by chance those events >happen, the decision-makers are called "bold and insightful", but if >things don't work out, they're called foolish or misguided. Again, I agree with you - all that I can add is that it this is what may be a rational element in the otherwise irrational decisionmaking process - managers may get hit if it goes wrong, but not rewarded if it goes right. Consider this: "Moreover the fact that a CEO can command does not mean that other employees will obey. Instructions can be given, but they need to be obeyed enthusiastically by others for them to mean anything. CEOs have tools to win the enthusiasm of their subordinates: the rhetoric of shared accomplishment of action and vision; the carrots of promotions, salary increases, and bonuses; the sticks of demotion and dismissal. But even with these tools, managing a large bureaucratic organization is a difficult task. And changing its direction away from that of mere business-as-usual requires great skill and luck." http://www.j-bradford-delong.net/Econ_Articles/Command_Corporations.html -- It's a man's life in a Python Programming Association. From ncoghlan at iinet.net.au Fri Jan 7 12:17:23 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 03:17:23 +1000 Subject: sorting on keys in a list of dicts In-Reply-To: References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: <41DEC423.3030506@iinet.net.au> It's me wrote: > What does it mean by "stability in sorting"? > > Can somebody please give a sample for using the code posted? I am a little > lost here and I like to know more about the use of keys.... It's the jargon for what Jeff said - if you are sorting by some value calculated from each list entry, and different list entries may give the same value, then a stable sort guarantees that the order of entries giving the same value will be preserved from the original list. Consider: Py> from operator import itemgetter as item Py> seq = [(1, 1), (2, 1), (2, 3), (1, 5)] Py> seq.sort(key=item(1)) Py> seq #1 [(1, 1), (2, 1), (2, 3), (1, 5)] Py> seq.sort(reverse=True) Py> seq #2 [(2, 3), (2, 1), (1, 5), (1, 1)] Py> seq.sort(key=item(1)) Py> seq #3 [(2, 1), (1, 1), (2, 3), (1, 5)] This snippet sorts the tuples according to the second item, then sorts them in reverse order of the whole tuple, then resorts them according to the second item. Notice that the order of the first two items is different between point #1 and point #3. This is because sorting by the second item makes no distinction between these two tuples, and they retain whatever order they had before the sort began. This is what it means to have a stable sort, and it makes expressing complex sorting quite easy by chaining different sort operations together. Python 2.3 has a stable sort, and Python 2.4 brought the guarantee that it shall remain that way. I'm not sure about Python 2.2 and earlier. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From siona at chiark.greenend.org.uk Tue Jan 25 07:19:34 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 25 Jan 2005 12:19:34 +0000 (GMT) Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <7xoefhtavd.fsf@ruckus.brouhaha.com> Message-ID: Fredrik Lundh wrote: >Sion Arrowsmith wrote: >> I'm probably not thinking deviously enough here, but how are you >> going to exploit an eval() which has very tightly controlled >> globals and locals (eg. eval(x, {"__builtins__": None}, {}) ? >try this: > > eval("'*'*1000000*2*2*2*2*2*2*2*2*2") No thanks. I guess my problem is a tendency view security issues from the point of view of access to data rather than access to processing. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From vishnube at acmet.com Thu Jan 6 01:33:27 2005 From: vishnube at acmet.com (Vishnu) Date: Thu, 6 Jan 2005 12:03:27 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> Message-ID: <003801c4f3b9$af17fa20$0800a8c0@vishnu> logfile = file(r'test.txt','w') logfile.write('datetime') logfile.close() # <- close the file logfile = file(r'test.txt','r') # <- Open the file in read mode test=logfile.readlines() ~Vishnu. -----Original Message----- From: python-list-bounces+vishnube=acmet.com at python.org [mailto:python-list-bounces+vishnube=acmet.com at python.org] On Behalf Of wordsender at gmail.com Sent: Thursday, January 06, 2005 11:53 AM To: python-list at python.org Subject: file.readlines() - gives me error (bad file descriptor) Hey guys, I can't figure this one out, why is this simple script giving me problems? logfile=file(r'test.txt','w') logfile.write('datetime') test=logfile.readlines() When I run it I get the error message: Traceback (most recent call last): File "C:\Documents and Settings\Gregory\My Documents\Get New Great Job\testfile.py", line 3, in ? test=logfile.readlines() IOError: [Errno 9] Bad file descriptor I'm running Windows XP, Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Any help would be greatly appricated. Thanks, Greg -- http://mail.python.org/mailman/listinfo/python-list From marklists at mceahern.com Mon Jan 17 15:25:00 2005 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 17 Jan 2005 14:25:00 -0600 Subject: FTPLIB - retry files? In-Reply-To: References: Message-ID: <41EC1F1C.8020900@mceahern.com> Peter A.Schott wrote: > Is there any way to retry sending files with some delay up to a set > number on > failure? Sometimes we encounter a locked file on our server or the > destination > server and we want to retry that file in X seconds. > > In general, what's wrong with this: import time retryCount = 10 retrySleep = 5 for x in range(retryCount): try: [ftp commands] except [ftp exceptions]: time.sleep(retrySleep) else: break // m From sp1d3rx at gmail.com Tue Jan 25 16:31:00 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 25 Jan 2005 13:31:00 -0800 Subject: Question Regarding SocketServer References: <1106684900.771730.218060@f14g2000cwb.googlegroups.com> Message-ID: <1106688660.694617.290330@c13g2000cwb.googlegroups.com> I tried to reply earlier... basically your "SocketServer.py" file is messed up. That line "AF_INET{,6}: IP (Internet Protocol) sockets (default)" should be commented out. It should be part of a block of lines that are all commented out. From tim.peters at gmail.com Fri Jan 14 09:12:49 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 14 Jan 2005 09:12:49 -0500 Subject: Pickled text file causing ValueError (dos/unix issue) In-Reply-To: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> Message-ID: <1f7befae05011406127d76759e@mail.gmail.com> [Aki Niimura] > I started to use pickle to store the latest user settings for the tool > I wrote. It writes out a pickled text file when it terminates and it > restores the settings when it starts. ... > I guess DOS text format is creating this problem. Yes. > My question is "Is there any elegant way to deal with this?". Yes: regardless of platform, always open files used for pickles in binary mode. That is, pass "rb" to open() when reading a pickle file, and "wb" to open() when writing a pickle file. Then your pickle files will work unchanged on all platforms. The same is true of files containing binary data of any kind (and despite that pickle protocol 0 was called "text mode" for years, it's still binary data). From Serge.Orlov at gmail.com Tue Jan 11 08:56:19 2005 From: Serge.Orlov at gmail.com (Serge.Orlov at gmail.com) Date: 11 Jan 2005 05:56:19 -0800 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> Message-ID: <1105451779.544442.204920@f14g2000cwb.googlegroups.com> Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: > Hi ! > > >>> and plain Latin letters > > But not all letters (no : ? ? ? ? ? ? ? etc.) > > > > Therefore, the Python's support of Unicode is... limited. > So is the support of Unicode in virtually every computer language because they don't support ... digits except 0..9. Does anyone know a language that supports? Serge. From fredrik at pythonware.com Sun Jan 30 13:15:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Jan 2005 19:15:15 +0100 Subject: Disassembling strings and turning them into function parameters References: <1107107283.694377.286360@c13g2000cwb.googlegroups.com> Message-ID: wrote: > I'm pretty new to Python, to programming overall...so how would I make > something where the user inputs multiple words in a string - like > "connect 123.123.123.123 21 user password" or similar, and then I can > split this string up to pass these arguments to a function like > ftp_connect(ip, port, user, pw) etc...? I have no idea how to "break" > the string up so I can get these out of it.. you can use the split() method to split on whitespace: >>> s = "connect 123.123.123.123 21 user password" >>> s.split() ['connect', '123.123.123.123', '21', 'user', 'password'] btw, the cmd module might be useful for your project: http://effbot.org/librarybook/cmd.htm http://docs.python.org/lib/module-cmd.html From http Sat Jan 22 11:38:25 2005 From: http (Paul Rubin) Date: 22 Jan 2005 08:38:25 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> Message-ID: <7xvf9p2zcu.fsf@ruckus.brouhaha.com> "A.M. Kuchling" writes: > It was discussed in this thread: > http://mail.python.org/pipermail/python-dev/2003-April/034959.html > > Guido and M.-A. Lemburg were leaning against including crypto; everyone else > was positive. But Guido's the BDFL, so I interpreted his vote as being the > critical one. That's interesting, so it's an export issue after all. But export from the US is handled by sending an email to the DOC, and Martin mentions that's already been done for some Python modules. I had been under the impression was that the concern was over causing possible problems for users in some destination countries, and possibly having to maintain separate distros for the sake of users like that. But maybe I was wrong about that. From craig at postnewspapers.com.au Mon Jan 3 06:09:00 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Mon, 03 Jan 2005 19:09:00 +0800 Subject: Developing Commercial Applications in Python In-Reply-To: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <1104750540.26918.5.camel@rasputin.localnet> On Mon, 2005-01-03 at 19:00, eeykay at gmail.com wrote: > Hello All, > I am trying to convince my client to use Python in his new product. He > is worried about the license issues. Can somebody there to point me any > good commercial applications developed using python ?. The licence > clearly says Python can be used for commercial applications. Is there > any other implications like that of GPL to make the source open ? My understanding is that you're dead safe with Python its self, as AFAIK you can even bundle (possibly modified) the Python sourcecode into your application. You'd simply need to keep an eye on the licenses of any extensions you used, like ReportLab, PIL, mx, database interfaces, twisted, etc. Many are licensed under the same license as Python or an MIT-like license, but of course some Python extensions are not and you would need to consider that. -- Craig Ringer From breamoreboy at aol.com Sat Jan 15 12:47:46 2005 From: breamoreboy at aol.com (BrainDead) Date: 15 Jan 2005 09:47:46 -0800 Subject: 20050115, for statement In-Reply-To: <41E9397A.90301@holdenweb.com> References: <1105783084.748174.307680@f14g2000cwb.googlegroups.com> <41E9397A.90301@holdenweb.com> Message-ID: <1105811266.627500.64590@z14g2000cwz.googlegroups.com> Steve Holden wrote: > Michael Hoffman wrote: > > > Xah Lee wrote: > > > >> ? a = range(1,51) > >> ? for x in a: > >> ? if x % 2 == 0: > >> ? print x, 'even' > > > > > > Now he's mixing tabs and spaces. Hideous. > > > > Are you doing things wrong on purpose? > > Actually Xah is to be commended, since he's united the Perl and Python > camps. Both agree he's a nuisance who is ill-informed about Perl *and* > Python ;-) > > I can only presume it's egocentricity that keeps him cross-posting this > nonsense to c.l.py and c.l.pe.misc despite the many deficiencies that > have been remarked upon in both newsgroups. > > fraternal-greetings-to-the-perl-wordl-ly y'rs - 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 I humbly suggest that Xah Lee Foxtrot Oscar, failing that would he/she stand up as the voice is rather muffled. Hardly original I know, but this crap is getting up my nose. I would much rather read the Timbot discussing things which mention the best operating system in the world, i.e. VMS, which for the uninitiated stands for Very Much Safer. Mark Lawrence. From venkatbo at yahoo.com Thu Jan 13 17:59:01 2005 From: venkatbo at yahoo.com (Venkat B) Date: Thu, 13 Jan 2005 14:59:01 -0800 Subject: newbie ?s Message-ID: <1105656971.768148@sj-nntpcache-5> Hi folks, I'm looking build a CGI-capable SSL-enabled web-server around Python 2.4 on Linux. It is to handle ~25 hits possibly arriving "at once". Content is non-static and built by the execution of py cgi-scripts talking to a few backend processes. 1) I was wondering if anyone has opinions on the ability of CGIHTTPServer (a forking variant) to be able to handle this. 2) If so, would something like pyOpenSSL be useful to make such a webserver SSL-enabled. I checked out John Goerzen's book: Foundations of Python Network Programming (ISBN 1590593715) and searched around. While I found how one can write py scripts that could communicate with SSL-enabled webservers, tips on building SSL-enabled webservers isn't obvious. I was hoping to build a cleaner solution around the CGIHTTPServer variant instead of say something like mini-httpd/OpenSSL/Python. I'd appreciate any pointers. TIA, /venkat From steven.bethard at gmail.com Fri Jan 21 19:37:29 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 17:37:29 -0700 Subject: Unbinding multiple variables In-Reply-To: <1gqrkce.1jtex3qfem7tkN%aleaxit@yahoo.com> References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> <35bnkeF4jpeetU1@individual.net> <1106334800.868412.27650@f14g2000cwb.googlegroups.com> <1gqrkce.1jtex3qfem7tkN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Nevertheless, any modifications to locals() are utterly > futile (within a function). Evil hack that makes modifications to locals() not quite as futile: py> import sys py> import ctypes py> def f(): ... x = 1 ... locals()['x'] = 2 ... ctypes.pythonapi.PyFrame_LocalsToFast( ... ctypes.py_object(sys._getframe()), 0) ... return x ... py> f() 2 Warning! NEVER do this! ;) (Also note that you can't del or add variables in this manner -- only modify them.) Steve From zyqnews at 163.net Sat Jan 29 23:03:28 2005 From: zyqnews at 163.net (zyqnews at 163.net) Date: 29 Jan 2005 20:03:28 -0800 Subject: cx_freeze error In-Reply-To: References: <1107048210.548048.152870@z14g2000cwz.googlegroups.com> <1107054796.999110.18380@c13g2000cwb.googlegroups.com> Message-ID: <1107057808.297752.168780@z14g2000cwz.googlegroups.com> Thanks for your answer. I tried it and the result is: [cxfreeze]$ python Python 2.2.3 (#1, Oct 15 2003, 23:33:35) [GCC 3.3.1 20030930 (Red Hat Linux 3.3.1-6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> re.compile >>> re.__file__ '/usr/lib/python2.2/re.pyc' >>> Is there any hint? From http Sun Jan 2 20:00:58 2005 From: http (Paul Rubin) Date: 02 Jan 2005 17:00:58 -0800 Subject: Continuations Based Web Framework - Seaside. References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> <7xhdlz8jv6.fsf@ruckus.brouhaha.com> <1gpshts.1o7ja8jqfh5moN%dial#####$#$#NOSPAM####$$##$tone@gmail.com> Message-ID: <7xd5wn1g39.fsf@ruckus.brouhaha.com> dial#####$#$#NOSPAM####$$##$tone at gmail.com (Valentino Volonghi aka Dialtone) writes: > Since I've already said Nevow with wolf works the same as borges. > The only thing that wouldn't work without continuations is the back > button. With greenlet module (from Armin Rigo) also the back button will > work. Thanks, I'm not familiar with wolf, borges, or greenlet. I've also been wondering what Rails is. Maybe some configuration of PyPy can supply first-class continuations like the old Stackless did. That would be really cool for all sorts of reasons. Then again, maybe it's reasonable to just fake it all, using ordinary threads and queues. I might try coding something that way. From abpillai at gmail.com Thu Jan 6 04:49:27 2005 From: abpillai at gmail.com (Anand) Date: 6 Jan 2005 01:49:27 -0800 Subject: Cookbook 2nd ed Credits In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> Message-ID: <1105004967.147430.128140@f14g2000cwb.googlegroups.com> Yes, such a list is available. I have uploaded a tentative list of contributors at http://harvestman.freezope.org . The original list is courtesy Alex. For the impatient, here are the direct links... List of first authors: http://harvestman.freezope.org/cookbook/credau.html List of all authors: http://harvestman.freezope.org/cookbook/creds.html Hope this helps! Regards -Anand From rschroev_nospam_ml at fastmail.fm Thu Jan 6 03:39:11 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 06 Jan 2005 08:39:11 GMT Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: Bulba! wrote: > If GPL folks had their way, it would not be possible not to "share" > _anything_ you create. That's generally the goal of the Free Software Foundation: they think all users should have the freedom to modify and/or distribute your code. Most people who use the GPL don't feel that way; they think that each author should have the freedom to choice if and how he chooses to share code. They just see the GPL as an appropriate way to share their code. > It is widely acknowledged that GPL license has the "viral" aspect of > extending itself on your software - can you point to closed-source > licenses that would have this aspect? Can you point to closed-source licenses that allow using the code *at all*? With GPL, you have the choice: either you agree with its terms on distributing the code and then you can use the code, or you don't agree with it and you don't use (which is still no worse than closed source). Some people call that viral, but I think it's a distortion of the truth. > None of the licenses I've read except GPL has > this aspect. LGPL is still a different story, though. Of course, different licenses have different terms. That's why there are different licenses. -- "Codito ergo sum" Roel Schroeven From ncoghlan at iinet.net.au Fri Jan 21 10:21:14 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 22 Jan 2005 01:21:14 +1000 Subject: Dynamic properties In-Reply-To: References: Message-ID: <41F11DEA.4050702@iinet.net.au> michael wrote: > My first try is : > > fget = lambda self: mygetattr(self, attrname) > fset = lambda self, value: mysetattr (self, attrname, value) > fdel = lambda self: mydelattr(self, attrname) > > # fget, fset, fdel are used to reconstruct the byte field > > setattr (self, key, property (fget, fset, fdel)) setattr creates entries in the instance dictionary of the object that is passed in. Properties need to be stored in the object type's dictionary in order to work their magic. I also believe it is required that the class be a new-style class. So try something like (Python 2.4): Py> def mygetattr(self, attr): ... print "Getting %s from %s" % (str(attr), str(self)) ... Py> def mysetattr(self, attr, value): ... print "Setting %s to %s on %s" % (str(attr), str(value), str(self)) ... Py> def mydelattr(self, attr): ... print "Deleting %s from %s" % (str(attr), str(self)) ... Py> class C(object): ... @classmethod ... def make_properties(cls, attrs): ... for attr in attrs: ... # Use default arguments to bind attr *now*, not at call time ... def _get(self, attr=attr): ... return mygetattr(self, attr) ... def _set(self, value, attr=attr): ... mysetattr(self, attr, value) ... def _del(self, attr=attr): ... mydelattr(self, attr) ... setattr(cls, attr, property(_get, _set, _del)) ... Py> properties = ["x", "y"] Py> C.make_properties(properties) Py> C.x Py> c = C() Py> c.x Getting x from <__main__.C object at 0x00A9A990> Py> c.x = 1 Setting x to 1 on <__main__.C object at 0x00A9A990> Py> del c.x Deleting x from <__main__.C object at 0x00A9A990> Py> c.y Getting y from <__main__.C object at 0x00A9A990> Py> c.y = 1 Setting y to 1 on <__main__.C object at 0x00A9A990> Py> del c.y Deleting y from <__main__.C object at 0x00A9A990> The decorator syntax is the only 2.4'ism I'm aware of in that code, so porting to 2.3 or even 2.2 shouldn't be an issue. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From grig.gheorghiu at gmail.com Mon Jan 10 15:11:21 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 10 Jan 2005 12:11:21 -0800 Subject: Importing Problem on Windows References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> <1105385451.560381.57650@c13g2000cwb.googlegroups.com> Message-ID: <1105387881.581610.17840@f14g2000cwb.googlegroups.com> I normall set PYTHONPATH to the parent directory of my module directory tree. If I have my module files in C:\home\mymodules and below, then I set PYTHONPATH to C:\home. This way, I can do "import mymodules" in my code. From http Wed Jan 19 15:25:07 2005 From: http (Paul Rubin) Date: 19 Jan 2005 12:25:07 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41ee6551$1@nntp0.pdx.net> Message-ID: <7xis5tyxng.fsf@ruckus.brouhaha.com> Scott David Daniels writes: > I understand this to be true. Since I am trying to address encryption > in the zipfile module, and I know you actually follow a bit of the > encryption stuff, can you answer a question or two for me? Sure, I can try, so go ahead. There's more crypto expertise in sci.crypt though. Zipfile encryption is totally incompatible with the rotor module, by the way, and traditionally it didn't use AES. There are a couple of replacements for the traditional method that do use AES but that I think are somewhat incompatible with each other. > > The Python maintainers didn't want to deal with imagined legal hassles > > that might develop from including good crypto functions in the > > distribution. Then it became obvious that the same imagined hassles > > could also befall the rotor module, so that was removed. > > Are you saying these hassles are, in fact, imaginary rather than real? Well, I didn't want to say that the hassles were real, but I wasn't trying to insinuate quite as much as it may have sounded. Like, I don't drive my car at 100 mph on Main Street because I can imagine what would happen and it's not pretty. The imagined carnage is a good enough reason not to drive that way. However, I do feel that the Python distributors are being over-cautious, see below. > Is this because you feel python is over-cautious about the USA, or is > this an opinion on "essentially all countries?" This is not a quibble > or a kvetch; I would like your understanding about the world legal > state of dealing with encryption (which, I assure you, I won't take as > definitive). I would hate to think someone in, for example, the UAE, > was busted for downloading or republishing python "out-of-the-box." I think the Python maintainers were more concerned about that UAE situation. However, the most widely deployed encryption software is the SSL stack in just about every web browser (MSIE, Firefox, etc.) and I'm sure lots of people are using those browsers in the UAE. The Mozilla foundation isn't hestitating to ship the encryption as far as I can tell. See http://www.bxa.doc.gov/Encryption for the USA rules. Basically for a free encryption program on the web, you're supposed to notify the Dept. of Commerce by sending them an email when you publish it, telling them where they can get it (address is on that site). As far as anyone can tell, the DOC never does anything with those emails. The rules are more complicated for nonpublished commercial programs, crypto hardware, etc. > Don't get me wrong, I'd love the answer to be "sure its fine," but my > current plans are to provide a way to connect a crypto package to > zipfile without providing any such package myself. I'd say provide a package if you can, unless you have realistic concern about getting in trouble. From erikbethke at gmail.com Sun Jan 2 04:17:41 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 2 Jan 2005 01:17:41 -0800 Subject: Python! Is! Truly! Amazing! Message-ID: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Hello Everyone, I have to say: Python! Is! Truly! Amazing! So I started with python about a month ago and put in 24 hours across three weekends. My first project was to recreate a simple maze-let thingie that I remember as my first program way back on the Vic-20. That was a quick snap and a pleasure. Since then I have settled down into working on a Mahjong game. I have uploaded a current version at my personal website: www.erikbethke.com/Python/mahjong.zip also note screenshots: www.erikbethke.com/Python/screenshot01.jpg www.erikbethke.com/Python/screenshot02.pg www.erikbethke.com/Python/screenshot03.pg www.erikbethke.com/Python/screenshot04.pg www.erikbethke.com/Python/screenshot05.pg So I have been using Python 2.3.4 as that is what was compatible with the excellent PyGame last month. After reading the posts here I am using wing IDE, and over all I like it... some minor issues and I am sure if I RTFM I would have these handled. I will be buying a bunch of licenses for us. I also used this project to learn a little about XML, so I used XML to fully describe the UI, the tilesets and the tile layouts and have it able to go back and forth between 3 different tilesets, and backgounds. The XML is crappy as you can see I am experimenting with putting some data in attributes and elsewhere in elements. So now I have it laying out the tiles, tile picking correctly, and I was even able to write many new little feature-ettes in wickedly fast single edit-run passes such as this to highlight the currently available matches: def findMatchingTiles(self): matchList = [] visibleTiles = [] for i, c in enumerate ( self.tiles ): if c.state != 'clear': visibleTiles.append( c ) for i, c in enumerate ( visibleTiles ): if self.testForClear( c ): for j, d in enumerate ( visibleTiles ): if d != c and d.tileNum == c.tileNum and self.testForClear( d ): matchList.append( [c, d] ) return matchList def showHint(self): matchList = self.findMatchingTiles() for i, c in enumerate( matchList ): c[0].state='clicked' c[1].state='clicked' self.draw() I have NEVER experienced this kind of programming joy. I am a 33 year-old professional game developer (www.gopetslive.com) and have been in the industry for 11 years, and have been programming since 4th grade like all the rest of you guys. And I am not saying all this to brag, no seriously I am delirious in joy right now. I have a bad cold and went to sleep at 1am last night and woke at 5am just to get back to playing with Python! I have been looking into Python to see if it is a good answer for getting a lot of new fresh mini-game and UI work done for our project GoPets, and clearly it is. I haven't yet explored the server-side but I will. The Mahjong game in the future will take its tile art dynamically from the portraits of the users that are your friends and the people your GoPet has visited recently. Anyways, I am now a super gushing fan-boy. I have worked my way up from a scripter working in crappy proprietary languages to a c++ programmer, to now biz guy. But when I walked away from programming I gave it a grim farewell, c++ work is good, but so much mind goes into it to make progree compared to other creative uses of the mind. But Python rocks, it makes programming very fun again and now I finding myself coming home earlier so I can get to work on Python and I have an entire heap of new projects I wanted to get done. Anyways, the Mahjong game code is quite crappy. No effort has been made to optimize it, nor have I handled any sorts of errors whatsoever. I know it sucks. But I posted the code there anyways in case any one else is just coming along and wants some more example code. I also have no real UI going on. Hit R to randomize the tiles, M to try to setup a solvable game (but my algorithm for this is not very effective yet), and H for hints on tiles that can be matched. Other than the tile art anyone can do what the feel with it. Thank you all for posting here, you have already solved dozens and dozens of questions for me with a little help of google groups. Truly thank you. -Erik From jerf at jerf.org Tue Jan 18 16:28:53 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 18 Jan 2005 16:28:53 -0500 Subject: macros (was: RE: generator expressions: performance anomaly?) References: Message-ID: On Tue, 18 Jan 2005 12:59:07 -0800, Robert Brewer wrote: > Especially since you can already do it explicitly with Raymond > Hettinger's cookbook recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 You know, Guido might as well give in now on the Macro issue. If he doesn't come up with something himself, apparently we'll just hack bytecode. I'm not sure that's a gain. (To be fair, I can see some arguments that it is, so that "I'm not sure" isn't a passive-aggressive/sarcastic snipe like most people use it in this context; I mean it literally.) (I expect if we ever do see them, this will be the basic argument used. I guess you could call it Historic Inevitably. :-) ) I'm not just basing it on this one thing, I'm basing this on all the bytecode hacks I've seen. From petite.abeille at gmail.com Wed Jan 26 15:44:43 2005 From: petite.abeille at gmail.com (PA) Date: Wed, 26 Jan 2005 21:44:43 +0100 Subject: python without OO In-Reply-To: <200501262135.30872.francis.girard@free.fr> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <200501262039.23260.francis.girard@free.fr> <1993411a01509c62cae1715b62fe16f5@gmail.com> <200501262135.30872.francis.girard@free.fr> Message-ID: On Jan 26, 2005, at 21:35, Francis Girard wrote: >> Project fails for many reasons but seldomly because one language is >> "better" or "worst" than another one. > > I think you're right. But you have to choose the right tools that fit > your > needs. But I think that's what you meant anyway. Yes. But even with the "best" tool and the "best" intents, projects still fail. In fact, most IT projects are considered failures: http://www.economist.com/business/PrinterFriendly.cfm?Story_ID=3423238 Cheers -- PA http://alt.textdrive.com/ From a.newmane.remove at eastcoastcz.com Mon Jan 10 12:51:28 2005 From: a.newmane.remove at eastcoastcz.com (Alfred Z. Newmane) Date: Mon, 10 Jan 2005 09:51:28 -0800 Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: <34ftl8F48t3b9U1@individual.net> J|rgen Exner wrote: > xah at xahlee.org wrote: >> #python supports complex numbers. > [...] > > So? > >> # Perl doesn't support complex numbers. But there are packages that >> supports it. > > The Math::Complex module is part of the standard installation > already, no need for any "packages" (whatever that might be). 'package' is a keyword, you should know this :-) Thats an important part of most modules. Actually it seems a lot of people use 'module' and 'package' interchangably, both refering to libraries, if you will, the one can include in a script, or another package. From aleaxit at yahoo.com Fri Jan 7 05:45:08 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 11:45:08 +0100 Subject: Excluded and other middles in licensing References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> <75r0b2-ohg.ln1@lairds.us> <1gq0jpn.1es49j7jrk3k5N%aleaxit@yahoo.com> <7x3bxd5ywz.fsf@ruckus.brouhaha.com> Message-ID: <1gq0o3c.1lnjwhxjgcefmN%aleaxit@yahoo.com> Paul Rubin wrote: > Note also from the Heine-Borel theorem that every closed source > program can be covered by some finite collection of open source > programs. Every _compact_ one, surely? Quoting by heart from old memories, but, isn't Heine-Borel about (being able reduce any open covering of X to a finite subcovering) <-> (X is compact) ...? Alex From wittempj at hotmail.com Mon Jan 17 13:58:53 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 10:58:53 -0800 Subject: Assigning to self In-Reply-To: References: <200501171845.46766.frans.englich@telia.com> Message-ID: <1105988333.379592.327600@z14g2000cwz.googlegroups.com> An implementation of what you want can be found here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558 From dave.benjamin at gmail.com Sat Jan 22 02:24:07 2005 From: dave.benjamin at gmail.com (Dave Benjamin) Date: Sat, 22 Jan 2005 00:24:07 -0700 Subject: Zen of Python In-Reply-To: <7xfz0uqe1d.fsf@ruckus.brouhaha.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Tim Peters writes: > >>But at that time, Python didn't have lexical scoping, and it wasn't >>clear that it ever would. So what's the bigger wart? Making >>listcomps exactly equivalent to an easily-explained Python for-loop >>nest, or introducing a notion of lexical scope unique to listcomps, >>hard to explain in terms of the way the rest of the language worked? > > Oops, I'd gotten confused and thought lexical scope came first and > listcomps afterwards. If lexical scope came afterwards, then > implementing listcomps as a for-loop at that time makes more sense. > > Of course in that case, since the absence of lexical scope was a wart > in its own right, fixing it had to have been on the radar. So turning > the persistent listcomp loop var into a documented feature, instead of > describing it in the docs as a wart that shouldn't be relied on, > wasn't such a hot idea. Adding lexical scope and listcomps at the > same time might have also been a good way to solve the issue. Can we get a show of hands for all of those who have written or are currently maintaining code that uses the leaky listcomp "feature"? I guess I've been peripherally aware of it, but I almost always use names like "x" for my loop variables, and never refer to them afterwards. If Python were to change in this regard, I don't think it would break any Python code that I've ever written or maintained... Dave From http Fri Jan 28 17:59:11 2005 From: http (Paul Rubin) Date: 28 Jan 2005 14:59:11 -0800 Subject: Elliptic Code References: Message-ID: <7x3bwl9n40.fsf@ruckus.brouhaha.com> Nick Craig-Wood writes: > > I understand the algorithm quite well but how to code the multiplication > > stage most efficiently in python eludes me. > > You might want to look at > > http://gmpy.sourceforge.net/ > > It has very fast multiplication up to any size you like! I think he's talking about point multiplication on the elliptic curve group, not integer multiplication. From jack at performancedrivers.com Fri Jan 7 17:42:32 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 7 Jan 2005 17:42:32 -0500 Subject: "A Fundamental Turn Toward Concurrency in Software" In-Reply-To: References: Message-ID: <20050107224232.GM1404@performancedrivers.com> On Fri, Jan 07, 2005 at 01:35:46PM -0800, aurora wrote: > Hello! > > Just gone though an article via Slashdot titled "The Free Lunch Is Over: A > Fundamental Turn Toward Concurrency in Software" > [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that the > continous CPU performance gain we've seen is finally over. And that future > gain would primary be in the area of software concurrency taking advantage > hyperthreading and multicore architectures. It got most things right, AMD & Intel are moving towards multiple cores on a chip so programmers will adapt. I don't see this as a big deal, the current trend is rack farms of cheap boxes for heavy computing needs. Multi-core CPUs will help those kinds of applications more than single threaded ones. Existing threaded apps don't have to worry at all. His picking on Intel to graph CPU speeds was a mistake (I'll be generous and not say deliberate). Intel screwed up and pursued a megahertz-at-all-costs strategy for marketing reasons. AMD didn't worry about MHz, just about CPUs that did more work and so AMD is eating Intel's lunch. Intel has abandoned their "faster" line of processors and is using their CPUs that are slower in MHz but get more work done. So the author's "MHz plateau" graph isn't all Moore's law breaking down, it is the result of Intel's marketing dept breaking down. -Jack ps, I started a python corner to my blog, http://jackdied.com/python Only one substantial post yet, and the RSS feed isn't up, but there ya go. From phil_nospam_schmidt at yahoo.com Mon Jan 31 12:45:14 2005 From: phil_nospam_schmidt at yahoo.com (phil_nospam_schmidt at yahoo.com) Date: 31 Jan 2005 09:45:14 -0800 Subject: how to access class methods via their name-as-string Message-ID: <1107193514.516478.155440@f14g2000cwb.googlegroups.com> I'd like to be able to look up a method name by passing a string with the method name. I thought I could use self.__dict__ to get at the method names, but as my example shows, this is obviously not working. I've also tried self.__class__.__dict__ without success. Can anyone point me in the right direction to make this work? Thanks, Phil >>> class a: def m1(self): print 'm1' def __getitem__(self, k): return self.__dict__[k] >>> class b(a): def m2(self): print 'm2' >>> z=b() >>> dir(z) ['__doc__', '__getitem__', '__module__', 'm1', 'm2'] >>> z['m1'] Traceback (most recent call last): File "", line 1, in ? z['m1'] File "", line 5, in __getitem__ return self.__dict__[k] KeyError: 'm1' >>> From peter at engcorp.com Thu Jan 6 10:58:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jan 2005 10:58:00 -0500 Subject: File Handling Problems Python I/O In-Reply-To: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> Message-ID: Josh wrote: > I am having a problem with Python. I am new to Python as a programming > language, but I do have experience in other languages. I am > experiencing strange problems with File handling and wonder if anyone > else has seen this or knows what I am doing wrong. I am simply trying > to open a file for read and iterate through until the end of file. I am > able to do so without a problem, but here's the catch: The open > statement is only working on certain files. I open a simple text file > say file1.txt without any issues, but I change the open statement to > another text file and it error's out stating the file doesn't exist. The usual rookie mistake here is to fail to recognize that backslashes in strings are interpreted as special escape sequences if they precede certain characters such as "t" or "b". You probably have a path that looks like this: "c:\temp\myfile.txt", right? The \t is actually being converted into a TAB character. You can use *forward* slashes in most cases in Windows, except on the command line. The simplest fix is just to convert your backslashes to forward slashes: "c:/temp/myfile.txt" Another approach, somewhat less desirable, is to use "raw" strings instead, to prevent the escape sequences from being recognized: r"c:\temp\myfile.txt" Finally, and by far least desirable, use double-backslashes to escape each backslash and in effect nullify the usual escape handling: "c:\\temp\\myfile.txt" Much less readable that way, but sometimes the right thing to do... -Peter From sylvain.thenault at nospam.logilab.fr Wed Jan 26 04:03:47 2005 From: sylvain.thenault at nospam.logilab.fr (Sylvain Thenault) Date: Wed, 26 Jan 2005 10:03:47 +0100 Subject: Maximum Number of Class Attributes References: Message-ID: On Wed, 26 Jan 2005 02:03:12 +0000, Bob Parnes wrote: > In its default configuration, my version of pylint (0.5.0) sets the > maximum number of class attributes at 7. This seems low to me, but I can > see how an excessive number might make maintenance more difficult. Is this > indeed the best value for a maximum under ordinary conditions? If not, can > anyone suggest a more reasonable value? well, this value is very subjective, and may change from one context to another... For instance at some point I hope that pylint will detect "GUI" classes and allow more attributes (and methods?) to those. Anyway that's just an indicator, not a rule of thumb (and pylint itself has some class with more than 7 attributes...). And FYI, this value has been taken from a post to the testdrivendevelopment at yahoogroups (as most others default values in the "design analysis" checker). Hum, well... After checking it seems that the post said 20 attributes. I don't remember why did i get this number down to 7. If this discussion leads to an agreement for a better number, I can change the default value. -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From smitsky at mindspring.com Sat Jan 8 21:03:07 2005 From: smitsky at mindspring.com (Smitsky) Date: Sun, 09 Jan 2005 02:03:07 GMT Subject: Windows XP Installation References: Message-ID: Thanks Folks. Yes, I did visit the Python site. I just wasn't sure what to try first. :O) Steve From steven.bethard at gmail.com Fri Jan 21 22:09:38 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 20:09:38 -0700 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> Message-ID: Andr? Roberge wrote: > Behind the scene, I have something like: > robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') } > and have mapped move() to correspond to > robot_dict['robot'].move() > (which does lots of stuff behind the scene.) > > I have tested robot_dict[] with more than one robot (each with > its own unique name) and am now at the point where I would like > to have the ability to interpret something like: > > alex = CreateRobot() > anna = CreateRobot() > > alex.move() > anna.move() > > etc. Since I want the user to learn Python's syntax, I don't > want to require him/her to write > alex = CreateRobot(name = 'alex') > to then be able to do > alex.move() If you have access to the user module's text, something like this might be a nicer solution: py> class Robot(object): ... def __init__(self): ... self.name = None ... def move(self): ... print "robot %r moved" % self.name ... py> class RobotDict(dict): ... def __setitem__(self, name, value): ... if isinstance(value, Robot): ... value.name = name ... super(RobotDict, self).__setitem__(name, value) ... py> user_code = """\ ... alex = Robot() ... anna = Robot() ... alex.move() ... anna.move()""" py> robot_dict = RobotDict() py> robot_dict['Robot'] = Robot py> exec user_code in robot_dict robot 'alex' moved robot 'anna' moved Note that I provide a specialized dict in which to exec the user code -- this allows me to override __setitem__ to add the appropriate attribute to the Robot as necessary. Steve From b at b.b Sat Jan 8 23:27:32 2005 From: b at b.b (Roose) Date: Sun, 09 Jan 2005 04:27:32 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> Message-ID: OK I've heard of that. But the original poster didn't ask to make a Python machine and then a Python OS. My point was that you can't do a lot of hardware interface programming in pure Python -- there would be so much non-trivial code in C that it would be hard to call it a Python OS. So this basically proves my point -- that you need different hardware altogether in order to make an OS in a high level language like Lisp or Python. And if that Lisp OS on a PC simulator works... that still wouldn't disprove what I'm saying. What does the PC simulator run on? An OS? or it part of the OS? Either way you've got tons of non-trivial code in C/C++/assembly. "Paul Rubin" wrote in message news:7x8y734jlq.fsf at ruckus.brouhaha.com... > "Roose" writes: > > > Is an OS written in Lisp also ludicrous? Because it's been done. > > > > Can you point me to this? I'd like to see how "truly" Lisp it is. > > http://en.wikipedia.org/wiki/Lisp_machine > > > My first guess would be -- not very. And I'd like to install it on my PC. > > Although written with federal funds at a university, it was never > released to the public, but was instead offered for sale from some > companies. The conflicts over this led to the birth of the free > software movement. > > Also, it was never intended to run on PC's (which didn't exist at that > time). It needed special hardware that was built for the purpose of > running Lisp. Lately there are people trying to program PC's to > simulate the Lisp hardware and to get the Lisp Machine software > released (now that the commercial market for it has long since dried > up). However, both of those projects have a ways to go. From phr at localhost.localdomain Mon Jan 24 17:56:55 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Mon, 24 Jan 2005 22:56:55 GMT Subject: simultaneous multiple requests to very simple database References: Message-ID: I agree with you, there's a crying need for something like that and there's no single "one obvious way to do it" answer. Have you looked at bsddb? See also www.sleepycat.com. From gurpreet.sachdeva at gmail.com Thu Jan 6 02:00:03 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Thu, 6 Jan 2005 12:30:03 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> <003801c4f3b9$af17fa20$0800a8c0@vishnu> Message-ID: logfile=file(r'test.txt','a+') logfile.write('datetime') logfile.flush() test=logfile.readlines() print test I added logfile.flush(), the 'datetime' was written in the file correctly but I couldn't get any result... Crazy! Garry From johng2001 at rediffmail.com Sat Jan 22 21:13:04 2005 From: johng2001 at rediffmail.com (johng2001 at rediffmail.com) Date: 22 Jan 2005 18:13:04 -0800 Subject: embedding jython in CPython... In-Reply-To: References: Message-ID: <1106446384.384110.25150@z14g2000cwz.googlegroups.com> > As for using JPype ... well it depends on what you want to script. if > you Java code is the main app, I'd eschew CPython completely and use > Jython to script. If you main app is in Python, and the Java code is > "simply" libraries you wish to use, then I'f go with CPython + Jpype. It > is very easy to manipulate Java objects that way, even to receive callbacks. > > I guess it all comes down to what you mean by scripting, and exaclt what > the structure of your application (as far as what is java and non-java). > If you care to explain your situation a bit more, we'll be better able > to help you. > > Steve Menard > Maintainer of http://jpype.sourceforge.net While we are on topic, I am having some trouble understanding JPype classpath. How do I init the JVM with the folder in which the Python program is located included in the classpath? I tried t = JPackage('.').test That did not work. My environment variable includes current folder in the classpath I tried passing it as an argument to startJVM. Didn't help. I think my main use is going to be using CPython with a few Java custom classes and if anyone has a snippet on this it would really help me. Thanks From craig at postnewspapers.com.au Thu Jan 27 01:47:49 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Thu, 27 Jan 2005 14:47:49 +0800 Subject: exclude binary files from os.walk In-Reply-To: References: <41f8167b$0$8648$a1866201@visi.com> Message-ID: <1106808469.8583.14.camel@bucket.localnet> On Wed, 2005-01-26 at 17:32 -0500, rbt wrote: > Grant Edwards wrote: > > On 2005-01-26, rbt wrote: > > > > > >>Is there an easy way to exclude binary files (I'm working on > >>Windows XP) from the file list returned by os.walk()? > > > > > > Sure, assuming you can provide a rigorous definition of 'binary > > files'. :) > > non-ascii That's not really safe when dealing with utf-8 files though, and IIRC with UCS2 or UCS4 as well. The Unicode BOM its self might (I'm not sure) qualify as ASCII. -- Craig Ringer From bokr at oz.net Mon Jan 17 16:13:06 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 17 Jan 2005 21:13:06 GMT Subject: news feed problem -- anyone else? Message-ID: <41ec1b57.1114913110@news.oz.net> I can see postings on google, but my news service is having a problem since sometime during the weekend. Can get old stuff from other n.g., but no new. Wondering whether I'll see this via google. Regards, Bengt Richter From jstroud at mbi.ucla.edu Sun Jan 9 21:50:40 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 9 Jan 2005 18:50:40 -0800 Subject: a new Perl/Python a day In-Reply-To: References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: <200501091850.40179.jstroud@mbi.ucla.edu> On Sunday 09 January 2005 05:31 pm, Scott Bryce wrote: > Xah Lee wrote: > > frustrated constantly by its inanities and incompetences.) > > I don't see what this has to do with Perl. On Sunday 09 January 2005 04:28 pm, Matt Garrish wrote: > What language are you an expert at? It certainly isn't Perl. Very dry humor indeed! bob = [1,2,3,4] carol = [bob,bob] # not inane dereferencing print carol[1][3] $bob = [1,2,3,4] ; $carol = [ $bob, $bob ] ; # inane dereferencing print "$carol->[1][3]\n" ; -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics 611 Charles E. Young Dr. S. MBI 205, UCLA 951570 Los Angeles CA 90095-1570 http://www.jamesstroud.com/ From yaipa at yahoo.com Wed Jan 19 16:08:57 2005 From: yaipa at yahoo.com (yaipa) Date: 19 Jan 2005 13:08:57 -0800 Subject: finding/replacing a long binary pattern in a .bin file References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> Message-ID: <1106168937.821814.217110@f14g2000cwb.googlegroups.com> John, Thanks for reminding me of the mmap module. The following worked as expected. #-------------------------------------------------------- import mmap source_data = open("source_file.bin", 'rb').read() search_data = open("search_data.bin", 'rb').read() replace_data = open("replace_data.bin", 'rb').read() # copy source.bin to modified.bin open("modified.bin", 'wb').write(open("source_file.bin", 'rb').read()) fp = open("modified.bin", 'r+') mm = mmap.mmap(fp.fileno(), 0) start_addr = mm.find(search_data) end_addr = start_addr + len(replace_data) mm[start_addr:end_addr] = replace_data mm.close() #-------------------------------------------------------- Although, I choose impliment string method approach in the build tool because there are two occurances of *Pattern* in the .bin file to be updated and the string method did both in one shot. Cheers, --Alan John Lenton wrote: > On Wed, Jan 12, 2005 at 10:36:54PM -0800, yaipa wrote: > > What would be the common sense way of finding a binary pattern in a > > .bin file, say some 200 bytes, and replacing it with an updated pattern > > of the same length at the same offset? > > > > Also, the pattern can occur on any byte boundary in the file, so > > chunking through the code at 16 bytes a frame maybe a problem. The > > file itself isn't so large, maybe 32 kbytes is all and the need for > > speed is not so great, but the need for accuracy in the > > search/replacement is very important. > > ok, after having read the answers, I feel I must, once again, bring > mmap into the discussion. It's not that I'm any kind of mmap expert, > that I twirl mmaps for a living; in fact I barely have cause to use it > in my work, but give me a break! this is the kind of thing mmap > *shines* at! > > Let's say m is your mmap handle, a is the pattern you want to find, > b is the pattern you want to replace, and n is the size of both a and > b. > > You do this: > > p = m.find(a) > m[p:p+n] = b > > and that is *it*. Ok, so getting m to be a mmap handle takes more work > than open() (*) A *lot* more work, in fact, so maybe you're justified > in not using it; some people can't afford the extra > > s = os.stat(fn).st_size > m = mmap.mmap(f.fileno(), s) > > and now I'm all out of single-letter variables. > > *) why isn't mmap easier to use? I've never used it with something > other than the file size as its second argument, and with its access > argument in sync with open()'s second arg. > > -- > John Lenton (john at grulic.org.ar) -- Random fortune: > If the aborigine drafted an IQ test, all of Western civilization would > presumably flunk it. > -- Stanley Garn From FBatista at uniFON.com.ar Wed Jan 5 14:40:15 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 5 Jan 2005 16:40:15 -0300 Subject: Python evolution: Unease Message-ID: [John Roth] #- I would like to contribute some documentation to Python. #- I've got the time, I write quite a bit, etc. I've got fairly #- strong opinions about some things that need to be documented, #- (such as all the new style class descriptor stuff from 2.2) #- and I have relatively little difficulty matching the existing style. #- #- However, I don't #- know TEX, Latex, CVS or Sourceforge. (The latter two are #- on my "learn sometime soon so I can put PyFIT where it belongs" #- list.) The easiest way to contribute with documentation is the following: 1. You found something badly documented. 2. You write/correct the docs as you think they should be. 3. Open a bug in SF and attach your text (just plain text if you don't want to produce something more elaborate). Of course, for step 3 you need a SF account: that's only five minutes. . 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 danb_83 at yahoo.com Thu Jan 13 21:33:19 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 13 Jan 2005 18:33:19 -0800 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <1105500724.648914.213880@z14g2000cwz.googlegroups.com> Message-ID: <1105669999.844853.137340@z14g2000cwz.googlegroups.com> DogWalker wrote: > "Luis M. Gonzalez" said: > > >humblythegreat... at usa.com wrote: > >> python.org = 194.109.137.226 > >> > >> 194 + 109 + 137 + 226 = 666 > >> > >> What is this website with such a demonic name and IP address? What > >> evils are the programmers who use this language up to? > >You dared to unveil our secret. > >Now we'll have to kill you... > > > But is 194.109.137.226 the only one? What other sites are in league > with the python? There are 6 853 010 possible dotted quads that add up to 666. Surely python.org is not the only one. From bvande at po-box.mcgill.ca Fri Jan 7 23:07:32 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 07 Jan 2005 23:07:32 -0500 Subject: DOS problem (simple fix??) In-Reply-To: References: Message-ID: <41DF5C84.7010002@po-box.mcgill.ca> Gavin Bauer said unto the world upon 2005-01-07 15:47: > My DOS window (running in windows ME) closes the second it finishes > running my programs. As you can imagine, this makes it hard to see the > Thank you, and please make all answers simple enough to be understood > by a highschool student and his father :) . Hi Gavin, you received some solutions. I have another, and a warning about Paul's. The warning: Paul suggested looking at IDLE. You should; it's a big improvement over notepad or the console. But, do you plan to make GUI application with Tkinter? If so, they will have troubles under IDLE. IDLE itself is a Tkinter application, so if it runs another Tkinter app, the poor beast gets confused about which Tkniter commands go where. (If that doesn't make sense, then you probably aren't yet at a place where it will matter. So, don't worry about it now.) Another popular alternative is SciTe. If you are doing your code in notepad or an interactive window, you really do want to look into an alternative! The other solution: The exact procedure is Windows version specific, but you can change the behaviour of .py files when they are double clicked. Here's what I do on my Win version (ME), which, sadly for both of us, we share: 1) Open a file explorer window. 2) Pick Tool->Folder Options from the menu. 3) Select the File Types tab. 4) Select the .py file type in the alphabetical list of file types that pops up. 5) Click on the Advanced button. 6) Select the Open action. 7) It will start out with something like: "C:\Python24\python.exe" Put a -i immediately thereafter. Mine looks like this "C:\Python24\python.exe" -i "%1" %* The -i makes .py files when double-clicked within Windows. The rest has to do with sending command line parameters, but I'd muff it if I tried to say more ;-) HTH, Brian vdB From martin at v.loewis.de Thu Jan 27 18:22:49 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 28 Jan 2005 00:22:49 +0100 Subject: Missing _bssd in Python 2.4 In-Reply-To: <1106864043.734366.315660@c13g2000cwb.googlegroups.com> References: <1106864043.734366.315660@c13g2000cwb.googlegroups.com> Message-ID: <41F977C9.4020400@v.loewis.de> jalil at feghhi.com wrote: > I compiled and installed python 2.4 on Redhat Linux using default > options but don't seem to be getting _bsddb. I get an error message > that _bssd cannot be imported. > > Does anybody know why this might happen? Do I need to do any special > customization or install any other software? You need to install the bsddb header files and development libraries when building Python from source. Regards, Martin From pyguy2 at gmail.com Wed Jan 5 11:47:28 2005 From: pyguy2 at gmail.com (pyguy2 at gmail.com) Date: 5 Jan 2005 08:47:28 -0800 Subject: Cookbook 2nd ed Credits (was Re: The Industry choice) In-Reply-To: <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> Message-ID: <1104943648.570355.179840@c13g2000cwb.googlegroups.com> Wow I didn't realize that I made that significant of a contribution :-) > 3: 9 u'John Nielsen' Well, I guess I did and I didn't. I worked hard to put postings up before I started taking classes again at a university last fall (with little kids and working full time, classes are a frustrating timesink). I am glad I could make a difference and proud to see what the community could put together. And of course, thanks to Alex and all the editors for their hard work. The cookbook site is, of course, among my default startup pages, so I can peruse what new things pop up there :-) I am slowly building up ideas on more things to post. This spring break, hopefully I'll get my mind enough together to put it all down coherently. john From merkosh at hadiko.de Fri Jan 28 17:18:06 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 28 Jan 2005 23:18:06 +0100 Subject: example needed: sip + Qt In-Reply-To: <39688.82.68.80.137.1106920041.squirrel@82.68.80.137> References: <39688.82.68.80.137.1106920041.squirrel@82.68.80.137> Message-ID: <200501282318.13918.merkosh@hadiko.de> On Friday 28 January 2005 14:47 pm, Phil Thompson wrote: > > The QLabel example in the SIP reference manual yields syntax errors for > > me. > > What syntax errors? If there is a documentation bug then I'll fix it. I'll come to that a little later, that happened in the simple c++ word example. I am currently fiddling around with the QLabel example. I copied the example and tried it out. First problem was that the generated makefile does not attempt to compile the original hello.cpp sources. So I wrote a configure script and a Makefile.am for that. It was not clear to me what type of archive or object was needed, so I first tried creating a normal object file, then libtool archives and then normal archives. It turned out I needed a normal archive an the library search path has to be extended to include the current directory (-L.), i.e. where the libhello.a lies. My only way of doing so was edditing the Makefile generated by configure.py. Is there a way of telling that to configure.py? So now the hello.cpp example compiles. I fire up python: >>> import hello Traceback (most recent call last): File "", line 1, in ? ImportError: ./hello.so: undefined symbol: _ZTV5Hello $ c++filt _ZTV5Hello vtable for Hello The compilation did not give any warnings or error messages. Any ideas? Thanks Uwe -- It would seem that evil retreats when forcibly confronted. -- Yarnek of Excalbia, "The Savage Curtain", stardate 5906.5 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 492 bytes Desc: not available URL: From david at graydragon.net Sat Jan 8 11:34:05 2005 From: david at graydragon.net (David Brown) Date: Sat, 8 Jan 2005 10:34:05 -0600 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <10u02s3deapvkd8@corp.supernews.com> So how would I make an OS Shell? From harold.fellermann at upf.edu Mon Jan 3 08:39:58 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Mon, 3 Jan 2005 14:39:58 +0100 Subject: cosmetic Tkinter question In-Reply-To: References: Message-ID: On 26.12.2004, at 16:38, Sean McIlroy wrote: > I've got a bunch of Frames, all packed into the root window with > side=TOP, and in each Frame I've got a Checkbutton packed with > side=LEFT. I expected the Checkbuttons to be flush with the left edge > of the window, but they're not, and it looks a little gross. How do I > get them to align? if you pack the frames with option fill=X they should be well aligned -- This commands the frame to use all available space in the horizontal direction: your_frame.pack(side=TOP,fill=X) your_button.pack(side=LEFT) - harold - -- What is mind? -- Doesn't matter. What is matter? -- Never mind! -- From anno4000 at lublin.zrz.tu-berlin.de Tue Jan 11 14:00:29 2005 From: anno4000 at lublin.zrz.tu-berlin.de (Anno Siegel) Date: 11 Jan 2005 19:00:29 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: It's me wrote in comp.lang.perl.misc: [reply moved into context] > "Anno Siegel" wrote in message > news:cs145l$8d6 > > > > > > > Like this? > > > > use Math::Complex; > > > > my $z = sqrt( -1); > > print 1 + $z, "\n"; # prints "1+i" > > > > Operator overloading makes it possible to work with complex numbers as if > > they were a native data type. > Operator overloading (and function overloading) helps but not enough. You > have to be aware of the complex type *everywhere* you go and that's very > annoying and error prone. I've been the works with C++, and later with > Modelica. I am very happy that Python included *native* complex number > support. What kind of awareness do you mean? There are some operations (as comparison) that work for reals, but not for complex numbers. If you want your program to run with complex input, you have to avoid such operations, whether the data type is native or not. What other considerations are there? A typical numeric program should just run and give complex output when fed complex input. I made the experiment with the Perl module Statistics::Descriptive, which was certainly written without concern for complex input, and it works without a hitch. I'm not sure if the (complex) variance of several complex numbers is a reasonably interpretable quantity, but I'm certain the maths is done right. What else do you want? Anno From http Wed Jan 5 06:52:47 2005 From: http (Paul Rubin) Date: 05 Jan 2005 03:52:47 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <1104910363.381748.105670@z14g2000cwz.googlegroups.com> Message-ID: <7xzmzo6qk0.fsf@ruckus.brouhaha.com> michele.simionato at gmail.com writes: > Dunno about Fedora, I stopped using Red Hat just because they were > *not* using the standard Python distribution, and the version they > shipped was cripped in various ways. Eh? I used Red Hat for a long while and don't remember their crippling the Python distribution. I do remember their believing the Python advocates that Python was a stable language, and therefore building critical features around it, and being unwilling to upgrade between major Python releases during minor Red Hat release cycles. The result was that RH 7.x shipped with Python 1.5.x for quite a long time after Python 2.x had been released. However I don't remember anything being crippled about the 1.5.x installations. From aahz at pythoncraft.com Mon Jan 31 16:22:59 2005 From: aahz at pythoncraft.com (Aahz) Date: 31 Jan 2005 16:22:59 -0500 Subject: Want to meet any of these people? They are registered for PyCon References: Message-ID: In article , Steve Holden wrote: > >Note that the sort order isn't perfect - I just sorted on the second >"word" in each name. PyCon is a *great* place to meet people and discuss >ideas. Hope to see you there. Good thing I'm not coming this year, eh? ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. 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 From swaroopch at gmail.com Tue Jan 25 14:45:10 2005 From: swaroopch at gmail.com (Swaroop C H) Date: Wed, 26 Jan 2005 01:15:10 +0530 Subject: How to input one char at a time from stdin? In-Reply-To: References: Message-ID: <351e887105012511457b494894@mail.gmail.com> On Tue, 25 Jan 2005 12:38:13 -0700, Brent W. Hughes wrote: > I'd like to get a character from stdin, perform some action, get another > character, etc. If I just use stdin.read(1), it waits until I finish typing > a whole line before I can get the first character. How do I deal with this? This is exactly what you need: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 Title: "getch()-like unbuffered character reading from stdin on both Windows and Unix" This recipe was a lifesaver for me once :-) Regards, -- Swaroop C H Blog: http://www.swaroopch.info Book: http://www.byteofpython.info From snacktime at gmail.com Wed Jan 26 16:54:08 2005 From: snacktime at gmail.com (snacktime) Date: Wed, 26 Jan 2005 13:54:08 -0800 Subject: XOR on string In-Reply-To: References: Message-ID: <1f060c4c05012613541abf5417@mail.gmail.com> > lrc == Linear Redundancy Check? or Longitudinal? Note that > such terms are not precisely defined... generally just acronyms > people make up and stick in their user manuals for stuff. :-) > Longitudinal > import operator > lrc = reduce(operator.xor, [ord(c) for c in string]) That's better than what I had, which as it turned out was working I was just calculating the lrc on one extra digit that I should have been. Chris From aleaxit at yahoo.com Sun Jan 9 06:01:47 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 9 Jan 2005 12:01:47 +0100 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> Message-ID: <1gq4ebf.17qqy8dk9ccr6N%aleaxit@yahoo.com> AdSR wrote: > I don't know haskell, but it looks SQL-ish to me (only by loose Indeed, the fact that many MANY more people are familiar with SQL than with Haskell may be the strongest practical objection to this choice of syntax sugar; the WHERE clause in an SQL SELECT has such wildly different semantics from Haskell's "where" that it might engender huge amounts of confusion. I.e., reasoning by analogy with SQL only, one might reasonably expect that minor syntax variations on: print a, b where a = b could mean roughly the same as "if a==b: print a, b", rather than roughly the same as: a = b print a, b I wonder if 'with', which GvR is already on record as wanting to introduce in 3.0, might not be overloaded instead. Alex From aleaxit at yahoo.com Wed Jan 5 05:19:56 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 5 Jan 2005 11:19:56 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Message-ID: <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> Bulba! wrote: ... > First, even though I disagree with you in places, thanks for > this reply - it enhanced my knowledge of the topic in some You're welcome! > What you wrote regards especially strong the industries you pointed > at: fashion, jewellery, esp. I think in those industries those factors > may be decisive. When this street is renown in the city to have > "good jewellers" located there, the choice for a new jeweller in this > city is almost like this: get located there or die. > > However, I'd argue that industries with those kinds of dependencies > are actually pretty rare. And yet the phenomenon appears in quantitatively similar ways (to different scales) in many industries where either the supply side or demand side benefits of clustering apply. > >Now consider a new company Z set up to compete with X, Y and Z. Where Ooops, typo, sorry, call the new company T!-) > >will THEY set up shop? Quarter Q has the strong advantage of offering > >many experienced suppliers nearby -- and in many industries there are > >benefits in working closely with suppliers, too (even just to easily > >have them compete hard for your business...). > > I grant that this model is neat and intuitive - but I'd argue it is > not very adequate to real world. Read on. Apart from its being exogenous (the model does not try to explain why X Y and Z were already located in Q -- only why, given this state of affair, T has advantages to setting things up in Q, too, which may well offset the costs such as higher rents), I don't think so -- but, I _am_ reading;-). > >YOU going to set up shop? Rents in that piazza are high, BUT - that's > >where people who want to buy new hats will come strolling to look at the > >displays, compare prices, and generally shop. > > That will only be true if the hats from Piazza dell'Orologio are much > better than elsewhere. No, this is not necessary (it's not even strictly necessary that they're _believed_ to be better, say because they traditionally were). A sufficient inducement to the would-be customers to go shopping there rather than elsewhere is that in that Piazza they get more choices for the same effort, so shopping there is more effective. Say that the city has ten hat shops of the same quality. One is in Piazza dell'Unita`, all the way to the Northern border of the city. One is in Piazza Saragozza, all the way to the Southern border. The other eight are in Piazza dell'Orologio, smack in the middle of downtown. Each shop offers hats taken from the same random distribution: we can say that a normal curve measuring the utility function for the customer (some function of price, quality, looks, fit, ...), with identical average and variance, represents the best hat available today from a given shop from the POV of a given customer. Say that a customer has one day to shop for their new hat, and the locations are too far apart for a customer to visit more than one location within that day. If a customer chooses to visit the one southern shop, or the one northern shop, the customer expects to be presented with the choice of hat from said normal curve. If the customer goes downtown, they expect a choice which overall lies along a DIFFERENT curve -- the best-of-eight samples from the normal curve. Sorry I can't model that analytically, but both intuitively and from any little simulation (easy to code in Python) you can see the customer's expectations are much better if they choose the location where they can do more comparison shopping! If you change this handwaving into numbers you can model this demand-side push of hatsellers towards clustering vs the forces pushing in the other direction, such as the supply-side issue of higher rents which may be assumed, all other things being equal, to make each shop's curve slightly _worse_ in the downtown location (higher costs, all other things being equal, must mean higher prices). It's not just fashion. I can look at the historical location of fishmongers in Bologna, still to some extent observable today, and I see them generally spread all over BUT with two obvious centers of downtown aggregation: a minor one at the Mercato delle Erbe (center-south side of downtown) and a major one at via Pescherie Vecchie (which just happens to mean "street of the Old Fishmongers" -- that concentration goes back many, many centuries). When I'm just getting, say, some fresh anchovies to fry for a pasta sauce, I'm likeliest to shop at a fishmonger near my home (the University side of downtown, northerly) or get them as part of a generic grocery shopping trip at a supermarket. But sometimes I'm preparing for a meal where fish plays a big role, maybe with company, and then I want the best, and then I head for Pescherie Vecchie. It's always very crowded with shoppers there, particularly at the times when people are likeliest to be shopping for fresh fish. It's obvious to even the most casual observer that just the same mechanism is at play: there are demand-driven centripetal forces because shoppers sometimes like to comparison-shop and get a lot of choice. This demand-side process doesn't operate much for "commodities" -- goods with quality and prices so flat and standardized that comparison shopping does not matter much. Much fashion-industry ware is that way, spewed out at commodity levels by the same factories. Some concentration may nevertheless remain for purely historical reasons: I'm thinking for example of the concentration of bookstores in Charing Cross Road, and of electronics shops in the nearby Tottenham Court Road, in London. Being in London only rarely nowadays, if I'm shopping for books I'm likely to head for Charing Cross, because I know I'll get choice; if I was a resident, though, and shopped for books often enough, I guess I'd find out about other places that may be cheaper or otherwise better. In any case, this more detailed demand-side sketch already shows that transaction costs are the key consideration in explaning clustering. Considering that they're also key in the very EXISTENCE of firms, according to standard economic theory, it's hardly surprising that they should play a large role in shaping the firm's foundational decisions, including, of course, location. But the demand-side model focuses on the _customers_' transaction costs, their advantage in comparison shopping. Similarly, a supply-side model can focus on suppliers' issues. Focusing within the firm, we can get insight on the pluses and minuses to the firm of being in a single place vs spreading itself around, but clustering of separate firms is clearly a different issue. > If the quality and prices of products converged, the gain for the > customers to go there isn't high. And the prices for customers > have to be higher, as the high rents drive some suppliers out, > so the supply of hats is lower, ergo customer prices are higher. ...which is why you know a priori that some equilibrium point is likely: there are costs as well as advantages to clustering (rents can often be an important slice of the costs, but other inputs that are costly to transport could also become scarce, though maybe not to the same point as land and suitable buildings and other fixed infrastructure). But there's nothing intrinsic to predict that the amount of clustering at equilibrium will be low. Transaction costs are often connected to acquiring and checking information; "knowing" (or believing one knows) where the hatsellers are may be enough of an advantage to maintain a clustering, once it's historically formed, even when you can hardly find any more present evidence of materials-costs advantage to it... the information-cost part of the transaction costs may well suffice. > >That's close to where > >felt-makers are, since they sell to other hat-makers. Should your > >business soon flourish, so you'll need to hire a worker, that's where > >you can soon meet all the local workers, relaxing with a glass of wine > >at the local osteria after work, and start getting acquainted with > >everybody, etc, etc... > > That is true in the model. However, I don't find it very true > in practice in a lot of industries: > > - "physical proximity" in this city very often means navigating > through jammed roads, so the transportation costs in terms of > time and money may very well increase rather than decrease by > locating "in a cluster", even though physical distance may > be smaller. physical distance != temporal distance & a cost > of getting there. Congestion can be a part of transaction costs, sure, just as higher rents can. But if your suppliers or customers are clustered in Hollywood, or the City of London, etc, etc, you don't diminish your congestion-driven costs much by going elsewhere, as you still need to see your customers or suppliers often -- you just add the costs of getting to LA / London / etc to those of moving within it -- in this sense congestion costs behave very differently from rents. > - since everything is more expensive, so is labor; even > if you pay this worker a little bit less elsewhere, he might > find it more attractive to commute shortly to work and > have lower costs of living in a different area, so this very > well may work as a motivation to relocate Sure, you get more competition: just as it's easier for you to get your competitors' best people, it's easier for your competitors to get yours (to some extent this applies to other inputs, and customers too, but highly skilled labor is the key component in many industries). This raises general costs, roughly equally for all clustered competitors, but another factor may be more prevalent because it differentiates among competitors: if you think you're among the best company in your sector, a more desirable place for your competitors' best personnel to work, then you perceive clustering as desirable because of that; if you think you're an inferior company, so your best people are likely to want to flee, then you perceive clustering as undesirable. Thus, seeking clusters can send the message "we're the best"; avoiding clusters can send the message "we're not so hot". That's how situations of asymmetric information tend to work in economics -- and since Akerlof's seminal work "The Market for Lemons" is 35 years old, and he got the Nobel prize for it (and related work, of course) in 2001, I believe we can call this field reasonably classic by now. Note that I'm not saying there are no forces pushing against clustering: of course there are, varying by industry etc. But they're easy to overstate. Consider the highly skilled worker who has a choice: they can stay in some crowded cluster, say Silicon Valley, and keep facing congestion, high rents, etc, for high salaries and great opportunities to keep hopping to the highest bidder; or, they can accept an offer at a lower salary in some more isolated area, say a minor cluster such as Austin, Tx, and get less congestion, cheaper housing, etc, although also less opportunity to keep enhancing their careers. Which kind of worker will tend to pick which of the two? Somebody who thinks they may be past the peak of their career, and won't get many more lucrative offers in the future anywa, might be more tempted by (say) Austin, while somebody who's keenly competitive and on a sharp upwards path may keep braving the congestion for the (to them) attractive lures and challenges of Silicon Valley. Of course there are a zillion other factors, but in as much as we're talking about factors strictly related to clustering, this is the bias, and therefore (in an Akerlovian model) this is the message which tends to be sent by such choices. I.e., seeking clusters send a message "I'm the best", avoiding them sends "I'm not so hot", for the individual highly skilled worker as much as for the firm in some highly competitive industry. In as much as we live in a "superstar economy" clustering becomes more desirable because of such competitive pressures and messages. > - few large businesses nowadays have customers neatly > clustered in one location, they tend to sell countrywide > or worldwide; so the premium for getting into this expensive > place is low and the costs are high There are exceptions (monopsonies or oligopsonies) but for _large_ firms this generally holds. But a _branch_ of a large firm may be set up specifically to serve a geographically identified market, so the location decision for the branch need not reflect the overall firm's issues, but rather only those specific to said market. > - production nowadays tends to be geographically > distributed as well Not as much as you might think. For example, people who worry about programming jobs moving to India may not realize a vast majority of such jobs go to a SINGLE tiny "spot" within the huge expanse of India, for all of the usual reasons promoting clustering. > - communication costs and transportation costs are DRAMATICALLY > lower nowadays than they used to be (today it costs 1/80 [one > eightieth] to transport a kg of mass using an aircraft in > comparison to what it cost in 1930s; ditto for telecommunication). ...so in the '30s very VERY few goods moved by plane. Not that it's exactly _common_ nowadays to move most goods by plane, mind you; but sure, it's conceivable in some cases. But there are other transaction costs, mostly connected to the need for face-to-face interaction as being the most effective form. I've worked for a SW development firm which tried to coordinate development distributed across many locations via cheap video-based teleconferences spanning timezones from California all the way to India; I've done way more than my share of telecommuting and airport- and plane-hopping for development projects geographically distributed and/or mostly located far from the customers and/or other stakeholders; I know whereof I speak... > Consider real world examples: Microsoft in Redmond or Boeing in > Seattle. Microsoft needs quite a lot of programmers. It would be > rather hard to find enough programmers born and educated in > Redmond, wouldn't it? Of course, or, at MS's scale, in any other single location. So, as they grew, they had to face the usual within-firm tension between the advantages of a single location and that of many; right now, quoting their careers webpage, they "employ more than 50,000 people worldwide, including offices in every major U.S. metropolitan city, and subsidiary offices in more than 60 countries.". For example, to attract the kind of highly competitive top-of-career high-tech worker that just will NOT leave the cluster of Silicon Valley, they chose to set up a new campus in Mountain View, CA, focusing on the convergence of entertainment and information technologies and industries; to attract the kind of European scholar who considers living in Europe a must and/or has no patience for the silly hassles put up by the US to keep foreigners out, Microsoft has an excellent Research laboratory at Cambrige, UK; and so on, and so forth. Of course, management-wise, there would be some great advantages to MS to having everybody at the Redmond campus, but even MS must deal with the real world, and the job market in particular: they're very pragmatic, so they get things in the Campus where they can, elsewhere when they must. How a large firm internally decides to site its various locations is really a separate issue from that of how different firms cluster, though of course there are many connections, particularly when you study the siting of one particular location. The two examples I give here are reasonably typical of a focus on supply-side and particularly the availability of highly skilled workers in high-tech areas... and then they show, again, the pluses of clustering. If Microsoft had found it easier to attract the kind of people they wanted, and build the needed connections to other firms in entertainment/information merging, outside the Silicon Valley cluster, there would be no reason for them to site there -- and instead you find them smack in the middle at Mountain View. > Boeing: Seattle?! Why Seattle? Doesn't Boeing sell most of its > new aircrafts in Washington? Obviously they agree with you, since their World Headquarters are in Chicago since over 3 years ago -- not exactly all that near to Washington, DC, but way closer than Seattle;-) "Why Seattle" has obvious purely historical answers -- they were born there, etc, etc. "Why Chicago" is a far more interesting question, since clearly the choice was way more open once they had decided that to keep expanding in Seattle was too costly or inopportune. You can find a lot about that specific decision on the web, of course. > AFAIK, in Europe Boeing does much of its production in > cooperation with Alena in Italy. From this viewpoint it really The spelling is "Alenia" (just in case somebody wants to google for more info). > doesn't matter much if Boeing is located in Seattle or anywhere > else in America really, does it? Not much, though flying to Chicago is marginally easier than flying to Seattle, it's not enough to matter;-) > Right here (Poland), most of the foreign corporations set up their > call centers in Warsaw, which is totally ridiculous given how > expensive that city is. Oh I can understand setting up a warehouse > by HP there because it's close to its biggest customers. But > I really see no good reason behind HP call center being located in > Warsaw, too, AFAIK (or at least that's the city code when I have > to call them sometimes). > > Most of the successful domestic companies I have observed here > have started and still operate in some God-forgotten provincial > towns, where land and labor is cheap and when it comes to > highly skilled professionals, you have to "import" some or all of > them from elsewhere anyway, because not even a big city is > likely to have precisely all the kinds of ultra-specialized > professionals that you may need. And there's less crime, and > shuttling kids to school isn't a nightmare, and the costs of living > are lower. Plus there's less of other things to do, so your workers > tend to focus more on work. :-) I remember glancing at some costly booklet called something like "Poland Infrastructure Report" back when an employer was considering setting up a branch office somewhere in Poland (selling and customizing SW for the mechanical industry), and back then issues such as internet and other telecom access, easy availability of top graduates, ease for expatriates from Italy to live in the place for a while knowing only English and Italian, at most German and French, and not Polish or Russian, closeness to good international airports and other good transportation, closeness to partner firms and potential customers' decision-makers, all appeared to point to Warsaw, if I recall correctly. Mechanical engineers with some programming experience or viceversa, good translators, and good salespeople with connections in the mechanical industry, are not as ultra-specialized as all that, after all. > >Risk avoidance is quite a secondary issue here (except if you introduce > >in your model an aspect of imperfect-information, in which case, > >following on the decisions made by locals who may be presumed to have > >better information than you is an excellent strategy). Nor is there any > >"agency problem" (managers acting for their interests and against the > >interest of owners), not a _hint_ of it, in fact -- the hatmaker acting > >on his own behalf is perfectly rational and obviously has no agency > >problem!). > > I find no justification in most of foreign companies setting up their > call centers in a ridiculously overpriced capital city - so from > my viewpoint the risk avoidance is the only explanation that is > left. The firm I was working for had a consensus decision-making process (even I was involved) and managers (and other employees) and stockholders were mostly the same people -- it wasn't all that large a firm at the time. Nobody needed to practice risk avoidance. The infrastructure advantages of Warsaw vs other locations loomed HUGELY large, judging of course from some consultants' reports purchased for the purpose -- it may look different to people living in the place, although I'd like to get a second opinion from Warsaw's Chamber of Commerce since you appear to have a very specific individual bone to pick (and I can sympathize: even though Milan may be the economically correct choice for foreign investors, I'd never want to LIVE there myself, being a Bolognese... but I must admit that Milan's infrastructure, connections, location, etc, etc, may in several cases drive a rational decision to set up there). > Not all corporations do that: in this country Coca-Cola has made > their big "green field" investment almost in the middle of nowhere > in this country. GM, Volkswagen, FIAT, and most of other carmakers > have made similar decisions. Doesn't seem like those were bad business > decisions for them. If their needs were for cheap land for greenfield factories, and cheap workers for said factories, then they were acting under very different forces than a midsize company looking to set up a mostly-sales branch office, not an industrial factory. > The cluster I've seen - an IT "corporate area" in Dublin, > Ireland - was specifically created not due to "natural clustering", > but due to govt policy of tax breaks and preparing good > infrastructure in this place rather than some inter-business and > inter-customer dependencies, since e.g. Microsoft (where the company > sent me for training) neither is able to get all the workers it needs > just from this city, nor it sells mostly to local customers, but it > sells all over Europe. That's addressing only the issue of endogenous vs exogenous original causes for clustering. Many attempts to create clusters artificially have happened ever since the economical advantages of clusters were discussed in the literature, together with the crucial point that WHERE the cluster originally happens is in most cases almost random, it's self-reinforcing once it's properly underway. Most such attempts have failed, because governments' powers aren't unlimited; Dublin is a good example of this strategy succeeding. No matter WHY the good infrastructure is there, the tax breaks, the thriving community of high-tech workers, etc, a firm deciding where to set up may perfectly well find it rational to have all of these advantages overwhelm the issues of rents, congestion, competition for good workers. In other words, my disagreement with your thesis that, because the government lowered taxes, taking advantage of that is NOT in the best interests of a firm's stockholders, is now maximal: I find your thesis not just wrong, but by now outright silly. > To me, the issue of manager having to face their superiors > asking him a question - "why on Earth have you decided > to locate our branch in the middle of nowhere in this country? > Why not in capital city? Can't you look at the map? Read some > stats how many inhabitants this city has and what is the > income level there?" is overwhelming: it would take long > time to explain for this manager who e.g. may have already You are wrong, because the same decisions get rationally made by sole-owner sole-manager companies where these considerations cannot apply. Deciding where to site an imporant branch is a BIG decision: of course it takes a long time, *DUH*, and all sorts of factors are taken into consideration. > got his hands dirty in this industry in that country to know > that say, there's little revenue increase to be gained in > locating the facility in capital city, the needed workers are > actually hard to find there, etc. So all of these factors are folded into a huge pile of reports in companies where such decisions are at all likely to be challenged later, and sign-off on the folders is carefully obtained for cover-up purposes. If the local development agencies of the "middles of nowhere in that country" don't do their job, including showering managers planning such decisions with supporting materials, that's a bad sign: maybe due to cultural influences foreign capital, professionals, and managers are NOT welcome there as they would be in a relative metropolis, for example. This is (or was not too long ago) surely the case for some rural parts of the British Islands, and Italy too. It's perfectly rational and consone to stocholders' interests to take this into account and site where you KNOW you'll be welcome. > To me, this is much like decision whether do much of > development in Python or MS VS / VB. "But everybody's > using VisualStudio / VB" is a simple and compelling argument: > "so many people can't be wrong", while explanations that > going Python may actually be better decision in this context > requires long and complex explanations and managers oft can > not even be bothered to read executive summaries. The issue of parallels or otherwise is by now totally secondary, to me, to the main issue that I find your approach to explaining regional clustering problems across industries totally, irredeemably, and horribly WRONG. So, I'm not going to make the post even longer by even trying to address this part. Few, besides the two of us, can be left reading by now, and clearly our disagreements on economics are so total that it's unlikely we can get anywhere by our discussions anyway. > I feel econ models frequently are elegantly designed > abstractions of elegantly designed problems; the problem > is how close those are to the real-world problems. At > the end of the day, it's "human action" that gets all > of that implemented. I've seen too much resources > going down the drain in completely idiotic projects > and decisions to believe managers are rational beings. When you claim managers are acting rationally (if selfishly) to avoid risk to themselves, you can't then justify this claim by adding that they aren't rational at all. Economics does cover, in its modern form, both issues of agency problems (misalignment of incentives between agent and owner) AND ones of "bounded rationality" (all the way from asymmetric information, to transaction costs relating to acquiring and processing information). Trying to throw economics overboard because you can't be bothered to understand it is a kind of behavior that reminds me closely of the "leftists" you excoriate in your signature. Alex From andre.roberge at gmail.com Sun Jan 23 07:40:45 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 23 Jan 2005 04:40:45 -0800 Subject: finding name of instances created In-Reply-To: <41f28f16@nntp0.pdx.net> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> <41f28f16@nntp0.pdx.net> Message-ID: <1106484045.503918.82350@f14g2000cwb.googlegroups.com> Scott David Daniels wrote: > Andr? Roberge wrote: > > Craig Ringer wrote: > > > >> On Fri, 2005-01-21 at 16:13 -0800, Andr? wrote: > >> > >>> Short version of what I am looking for: > >>> > >>> Given a class "public_class" which is instantiated a few times e.g. > >>> > >>> a = public_class() > >>> b = public_class() > >>> c = public_class() > >>> > >>> I would like to find out the name of the instances so that I could > >>> create a list of them e.g. > >>> ['a', 'b', 'c'] > > > > ... > > Behind the scene, I have something like: > > robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') } > > and have mapped move() to correspond to robot_dict['robot'].move() > > (which does lots of stuff behind the scene.) > > ...[good explanation]... > > Does this clarify what I am trying to do and why? > > Yup. Would something like this help? > > parts = globals().copy() > parts.update(locals()) > names = [name for name, value in parts.iteritems() > if isinstance(value, Robot)] # actual class name here > > Note, however, that > > a = b = CreateRobot() > > will give two different names to the same robot. > > And even: > > Karl = CreateRobot() > Freidrich = CreateRobot() > for robot in (Karl, Freidrich): > robot.move() > > Will have two names for "Freidrich" -- Freidrich and robot > > --Scott David Daniels Thanks for your suggestion. It might have been interesting to try, but I am going to try and implement a suggestion given by Nick Coghlan instead. Andr? From claird at lairds.us Mon Jan 3 10:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Mon, 03 Jan 2005 15:08:03 GMT Subject: Industrial organization (was: The Industry choice) References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Message-ID: <0u1oa2-qk4.ln1@lairds.us> In article <1gpsbr7.1otvj5mkq1l96N%aleaxit at yahoo.com>, Alex Martelli wrote: >Bulba! wrote: > >> True. I have a bit of interest in economics, so I've seen e.g. >> this example - why is it that foreign branches of companies >> tend to cluster themselves in one city or country (e.g. > >It's not just _foreign_ companies -- regional clustering of all kinds of >business activities is a much more widespread phenomenon. Although I'm >not sure he was the first to research the subject, Tjalling Koopmans, as >part of his lifework on normative economics for which he won the Nobel >Prize 30 years ago, published a crucial essay on the subject about 50 >years ago (sorry, can't recall the exact date!) focusing on >_indivisibilities_, leading for example to transportation costs, and to >increasing returns with increasing scale. Today, Paul Krugman is >probably the best-known name in this specific field (he's also a >well-known popularizer and polemist, but his specifically-scientific >work in economics has mostly remained in this field). . . . clp actually dropped related names back in April , but I think that was during one of your sabbaticals from the group. The work of Vernon Smith, the unconventionally conventional Nobel co-recipient of 2002, can be viewed as a commentary on clustering and other non-homogeneities. Many US readers have encountered Jane Jacobs, who has made a career (and spawned a following) exploring the significance of cities as economic clusters. From janeaustine50 at hotmail.com Sun Jan 9 06:09:27 2005 From: janeaustine50 at hotmail.com (janeaustine50 at hotmail.com) Date: 9 Jan 2005 03:09:27 -0800 Subject: time module precision In-Reply-To: References: Message-ID: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> Tim Peters wrote: [snip] > Python's time.sleep() calls the Win32 API Sleep() function on Windows. > All behavior is inherited from the latter. See MS's docs: > > Oh, after a short research, I found that time.sleep uses its customized way of sleeping using "select". http://groups.google.com/groups?threadm=ud7i1c9ck.fsf%40ctwd0143.fitlinxx.com So I think its behaviour is more complicated than single MS Sleep call, I suppose. > In particular, MS Sleep() takes an integer argument, giving the number > of milliseconds to sleep. Your 0.0001 case falls under the special > Sleep(0) case due to truncation in float->int conversion. > Oh, I see. > Also Google on > > sleep thread deviation > > to find an interesting CodeProject article quantifying behavior on one > particular tester's Windows box. Also see an article it references > for approaches to the question "how do I handle small intervals?" > (short course: you probably can't, unless we're willing to throw > money at it). Thanks for the references. What I want to do is waiting(not busy-delaying) for a few tens to hundreds of microseconds in some threads. The closet solution I got is using windows QueryPerformanceCounter (in Python, time.clock) with busy looping checking if we have past the target time. However, that makes the cpu usage upto almost 100%. So the problem (waiting tens to hundreds of us without busy looping) still remains... From a at a.invalid Thu Jan 27 20:36:19 2005 From: a at a.invalid (Timo Virkkala) Date: Fri, 28 Jan 2005 01:36:19 GMT Subject: [perl-python] 20050127 traverse a dir In-Reply-To: <1106875259.426213.252030@z14g2000cwz.googlegroups.com> References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> <1106875259.426213.252030@z14g2000cwz.googlegroups.com> Message-ID: The Flow wrote: > Do you want to be taken seriously? > First, stop posting. > Second, learn perl. > Third, learn python. No. Second, learn Python. Third, learn Perl (optional). :) But we do agree on the first. -- Timo Virkkala From deetsNOSPAM at web.de Fri Jan 21 06:45:47 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 21 Jan 2005 12:45:47 +0100 Subject: Class introspection and dynamically determining function arguments References: Message-ID: <35c890F4jse0nU1@individual.net> > The classes I'm dealing with do have attributes since they're > C-Extension types with attributes provided in the "tp_getset" slot. So > this is one case where I can query the class for attributes without > having to create an instance. Thanks for making me think of that, since > looking in the class's __dict__ pretty much gives me what I want. I'm > not sure that that's something I can rely on though which is exactly the > sort of issue where I'd like to know if there's a right way (e.g. an > existing module) to ask a class for its attributes, without poking > around in __dict__ directly and doing some type checking. I guess in a > way I'm asking for introspection with a greater degree of granularity > than "dir". According to this http://www-106.ibm.com/developerworks/library/l-pyint.html not really - and there are no special moduls neccessary, as everything is at your hands using __dict__ and so on. -- Regards, Diez B. Roggisch From http Thu Jan 13 14:18:17 2005 From: http (Paul Rubin) Date: 13 Jan 2005 11:18:17 -0800 Subject: sorted (WAS: lambda) References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <7x7jmh1eek.fsf@ruckus.brouhaha.com> <7xpt09xizb.fsf@ruckus.brouhaha.com> Message-ID: <7xy8exgmti.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > > Oh, same difference. I thought it was a method because I'm not using > > 2.4 yet. The result is the same > > nope. sorted works on any kind of sequence, including forward-only > iterators. sorted(open(filename)) works just fine, for example. Oh cool. However I meant the result is the same in my example, where assigning the temporary result to a variable stopped memory from getting reclaimed until after the function exits. From jelle.feringa at ezct.net Wed Jan 19 05:17:33 2005 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Wed, 19 Jan 2005 11:17:33 +0100 Subject: python & iges (nurbs file format) Message-ID: <20050119101739.E9B0E1C001B7@mwinf0402.wanadoo.fr> Is anyone aware of a module allowing you to read / write .iges data? Currently I'm trying to figure a way of writing out my nurbs data generated in python, but if such a package exists, that would be great, haven't been able to find anything so far. Cheers, Jelle. -------------- next part -------------- An HTML attachment was scrubbed... URL: From MrJean1 at gmail.com Sun Jan 9 14:42:36 2005 From: MrJean1 at gmail.com (python) Date: 9 Jan 2005 11:42:36 -0800 Subject: printing line numbers for debugging purpose In-Reply-To: <41e06e72$1_1@omega.dimensional.com> References: <41e06e72$1_1@omega.dimensional.com> Message-ID: <1105299756.717486.151500@c13g2000cwb.googlegroups.com> Below is a function to get the current line number and file name. /Jean Brouwers - # dashes added to preserve indentation. - - 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() - From evan at tokenexchange.com Mon Jan 17 12:56:07 2005 From: evan at tokenexchange.com (Evan Simpson) Date: Mon, 17 Jan 2005 11:56:07 -0600 Subject: Producer/consumer Queue "trick" In-Reply-To: <34s541F4f5gqiU1@individual.net> References: <34s541F4f5gqiU1@individual.net> Message-ID: <41EBFC37.5030309@tokenexchange.com> Jon Perez wrote: > If the consumer and the producer are separate threads, > why does the consumer thread block when the producer > thread is generating a new board? Or why does it > take forever for the producer thread to be pre-empted? > > Also, I don't understand why the solution works. > How does sleeping for .001 seconds right after putting > a new board on the queue solve the problem? I'm guessing at how things work, and may be totally wrong, but here's what I think happens: In the Queue get() code, the consumer releases the 'fsema' lock. Directly or indirectly, this wakes up and hands control to the producer thread, which was blocked trying to acquire 'fsema'. The sleep() hands control back to the scheduler immediately, which appears to wake up the consumer and let it get on with things. It doesn't take "forever" for the producer to be preempted, just the normal preemption interval. I was bothered, though, by the idea of having it take even a few dozen milliseconds out of the middle of a request that's at most a millisecond or two away from finishing anyway. Cheers, Evan @ 4-am From newsgroups at jhrothjr.com Mon Jan 10 18:14:55 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 10 Jan 2005 17:14:55 -0600 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> Message-ID: <10u6347j23enuc3@news.supernews.com> It doesn't work because Python scripts must be in ASCII except for the contents of string literals. Having a function name in anything but ASCII isn't supported. John Roth "Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle." wrote in message news:41e30aab$0$6434$8fcfb975 at news.wanadoo.fr... Hi ! If Python is Ok with Unicode, why the next script not run ? # -*- coding: utf-8 -*- def ?????(toto): return(toto*3) aret = ?????(4) @-salutations -- Michel Claveau From newsgroups at jhrothjr.com Mon Jan 17 18:19:15 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 17 Jan 2005 17:19:15 -0600 Subject: Assigning to self References: <10uo6hbn040qt24@news.supernews.com> Message-ID: <10uoi0hfluhk0b6@news.supernews.com> "Frans Englich" wrote in message news:mailman.816.1105995336.22381.python-list at python.org... > On Monday 17 January 2005 20:03, John Roth wrote: >> "Frans Englich" wrote in message > > > >> In other words, you're trying to create a singleton. In general, >> singletons are frowned on these days for a number of reasons, >> not least because of the difficulty of testing them. > > Then I have some vague, general questions which perhaps someone can reason > from: what is then the preferred methods for solving problems which > requires > Singletons? Is it only frowned upon in Python code? I don't know of any generic methods that will work in all cases _and_ are easy to apply. There are really two issues: testing and abuse of the pattern. There really are some places where you want a single instance of something that is globally visible. Things that leap immediately to mind include the connection to a data base and a logger facility. However, in a lot of cases, you find singletons used as an "object oriented" substitute for a global variable, which stinks just as badly as a global would. Since Python is a multi-paradigm language, just put in a global at the module level. It's clearer. Otherwise redesign. There are several ways of getting around the testing difficulty. One is the "toolbox" pattern that appears in a number of places. The idea there is to have a single object that proxies all of the singletons so that they can be replace by testing versions at initialization time. A neater and more modern method is to use an IOC (Inversion of Control) container, or at least the pattern involved. All IOC containers I'm aware of support singletons and make testing them almost trivially easy. A third way is to simply take advantage of Python's dynamic nature and have your tests stuff the testing instance into the class object before the first call. This is an ad-hoc variation on the IOC principle. HTH John Roth > > > Cheers, > > Frans > From vincent at visualtrans.de Tue Jan 18 14:06:52 2005 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 18 Jan 2005 20:06:52 +0100 Subject: how to find site-packages path (Michael Hoffman) - use distutils In-Reply-To: References: Message-ID: Philippe C. Martin wrote: >>>Why would you want to copy any *.pyc instead of compiling them on > > site? > I know that sounds terrible to the open source community, but I do not > intend to release the source code for my product That's not why I asked. I'll leave the politics up to you. The thing is, that the path info gets cached in the *.pyc file. This may lead to confusing tracebacks - might they occur - when the user does not install to the exact same drive/path as you did. Additionally: if you *do* want to distribute *.pyc only, I personally wouldn't find it terribly neat if you stuck those into the site-packages directory of my Python installation. I - for one - would want to know what kind of source code you place along *my* sys.path. Maybe you should consider using py2exe to distribute - keeping your *.pyc out of the user's Python directory tree, if any, entirely. Also, you may want to consider using Inno Setup as deployment tool (if Windows is your target platform). Using distutils for a *.py-less installer seems pretty pointless. Regards, -- Vincent Wehren - pls go to > philippecmartin.com/applications.html for my _small_ contributions :-)) > > Regards, > > Philippe > > > From bj_666 at gmx.net Sat Jan 8 16:54:20 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 08 Jan 2005 22:54:20 +0100 Subject: Documenting data members References: Message-ID: In , Frans Englich wrote: > I have a custom module which among others contains a dictionary, acting as a > "constant". I want to document it, but no matter what I do, it doesn't show > up in `pydoc`. For example, the following doesn't work: I'm using epydoc_ for my documentation and there the module level and class level variables are documented in the module/class docstring with special markup. > """ > A dictionary of the namespaces. > """ > xmlns = { > ... > } Will become: """ (Module description) :var xmlns: A dictionary of the namespaces. """ Ciao, Marc 'BlackJack' Rintsch .. _epydoc: http://epydoc.sourceforge.net/ From samantha7395 at hotmail.com Wed Jan 19 11:32:51 2005 From: samantha7395 at hotmail.com (Samantha) Date: Wed, 19 Jan 2005 08:32:51 -0800 Subject: Print to Windows default Printer References: Message-ID: Thanks Tim. I didn't realize it would be so difficult. S "Tim Golden" wrote in message news:mailman.889.1106123987.22381.python-list at python.org... From tdelaney at avaya.com Wed Jan 26 17:24:30 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 27 Jan 2005 09:24:30 +1100 Subject: On benchmarks, heaps, priority queues Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025202DC@au3010avexu1.global.avaya.com> aaronwmail-usenet at yahoo.com wrote: > PQPython23 - the Lib implementation > PQ0 - my insertion sort based variant > PQueue - my "heap" based variant > (like PQPython23, but different). First of all, you should be running these benchmarks using Python 2.4. heapq is considerably faster there ... (Raymond Hettinger rewrote it all in C). http://www.python.org/2.4/highlights.html Tim Delaney From peter at engcorp.com Sun Jan 9 13:37:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 13:37:13 -0500 Subject: Python Installation In-Reply-To: <41E15306.7090108@holdenweb.com> References: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> <1105232505.142279.85810@c13g2000cwb.googlegroups.com> <41E15306.7090108@holdenweb.com> Message-ID: Steve Holden wrote: > Peter Hansen wrote: > >> Simon John wrote: >> >>> I would say install on one machine, then just copy the C:\Python24 >>> directory, but then you'd have to deal with the missing Registry >>> entries.... >> >> >> >> That part is pretty trivial to automate as well. Fredrik >> Lundh has a useful utility on his web site that will do much >> of what is required. Google for his name and "python registry" >> to find out more. >> > Hmm, effbot.org seems to be down just now. Sure it'll be back soon, though. Still down, but clicking on the second link in the result, on the "cached" link, then on the "cached text only" link in the header, will get the relevant source code for you. -Peter From carribeiro at gmail.com Wed Jan 5 14:17:03 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 5 Jan 2005 17:17:03 -0200 Subject: Python evolution: Unease In-Reply-To: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> References: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> Message-ID: <864d370905010511177a231a96@mail.gmail.com> On Wed, 5 Jan 2005 19:25:37 +0100, Alex Martelli wrote: > Carlos Ribeiro wrote: > ... > > > - IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than Pythonwin? > > > > I would like to seee Eric3, with some polish & opensourced on Win > > (which means solving the Qt licensing problem). Perhaps someone could > > convince Trolltech to release a special Qt Win version just for it > > (Eric3). Eclipse is also an interesting approach. > > I love eric3, but if you're an eclipse fan, look at enthought's > "envisage" IDE -- it seems to me that it has superb promise. Hint noted. > > wish I could simply plug & play DBAPI modules in a totally seamlessly > > way. Anyone who tried know how far are we of this dream. > > If you manage to get there, you'll start fighting against the different > dialects of SQL supported by the various back-ends, as is well known by > anybody who tried, say, ODBC or ADO, which do manage good plug&play of > their components but still can't solve the real hard one:-( Ian Bicking's SQLObject goes a long way to solve this problem. It's a ORM, not a complete relational solution, mind you. However, while it's architecturally oriented towards solving the high-level SQL-to-object mapping issues, a good deal of time is spent solving things that a common plug & play API could solve. IOW: the hard problem really does exist. However, we never come to face it because we're still stuck in the "easy" one. :-( -- 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 aleaxit at yahoo.com Thu Jan 6 13:46:05 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 6 Jan 2005 19:46:05 +0100 Subject: File Handling Problems Python I/O References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> <1105034402.428393.283930@c13g2000cwb.googlegroups.com> Message-ID: <1gpzg5n.1ylh8m21c0o5jN%aleaxit@yahoo.com> Josh wrote: ... > He is the function where I am making the call. If I change the open > statment to another file, say "c:\test.txt", a file I know exists, it Are you sure a file exist whose name is, c, colon, tab, e, s, t ...? \t is an escape sequence and it means TAB (character of ascii code 9). Try 'c:/test.txt' -- using normal slash instead the backslash -- and you should be fine. You mention you have some experience with other languages: if those languages include C, or Java, or C++, and many others besides (all which use backslashes for escape sequences in strings), you'd have exactly the same issues. Alex From fuzzyman at gmail.com Fri Jan 14 07:11:59 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 14 Jan 2005 04:11:59 -0800 Subject: huygens lands on titan In-Reply-To: References: Message-ID: <1105704719.374905.239790@f14g2000cwb.googlegroups.com> John Thingstad wrote: > -- > huygens lands on titan > Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ I bet it didn't....... Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From roy at panix.com Wed Jan 12 22:37:33 2005 From: roy at panix.com (Roy Smith) Date: Wed, 12 Jan 2005 22:37:33 -0500 Subject: why are people still using classic classes? References: Message-ID: Simon Wittber wrote: > Is there a legitimate use for classic classes that I am not aware of? Is there a reason NOT to use them? If a classic class works fine, what incentive is there to switch to new style classes? I realize it's not much effort to put "(object)" after your class name, but I'm lazy and don't bother. I don't see how I've been hurt by that. Obviously, if there was some feature of new style classes I wanted to use, it would be a different story. From tom at dtsam.com Tue Jan 4 14:19:39 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Tue, 4 Jan 2005 13:19:39 -0600 Subject: Reaching the real world References: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: "Fuzzyman" wrote in message news:1104850540.610295.152240 at f14g2000cwb.googlegroups.com... > I have a friend who would like to move and program lights and other > electric/electro-mechanical devices by computer. I would like to help - > and needless to say Python would be an ideal language for the > 'programmers interface'. > > What I'd like is an electronic interface that connects to several > relays and a python extension module to switch on and off the relays. > I've had a quick google and can't see anything too similar to what I > want. pyro (python robotics) seems to require expensive (relatively) > robotic equipment. Loosely, what you are looking for is Data Acquisition (DAQ) , Digital I/O, and control that you can do from your pc. Those are the keywords you want to google. Look at www.ni.com and poke around. They will have some introductory material. Look at www.circuitcellar.com . It may look a bit overwhelming at first but look at the ads for pc equipment. These should also lead you to some tutorials. You are looking for simple digital output. You can use an existing serial or parallel port with a bit of external hardware from radio shack to control relays on the cheap. OR You can purchase a Digital I/O adaptor that will plug into your computer bus and give you outputs to control your relays. You will also get instructions and some software to interface (talk!) to the adaptor. Typically you will read and write to the I/O ports on your computer to flip the switches. OR perhaps the easiest and most effective These would be smart devices that talk to your Python (or whatever!) software via the serial port. You would throw simple string commands (eg "ChannelB ON") at the serial port and the microprocessor based controller will turn on the appropriate relay. Your challenge from Python will be to control the computers I/O ports or to communicate with one of the serial ports. I'm sure someone else will point to libraries that will help you with this. Much *much* more but you have to start somewhere :-) Thomas Bartkus From steve at holdenweb.com Tue Jan 18 20:04:15 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Jan 2005 20:04:15 -0500 Subject: file copy portability In-Reply-To: References: Message-ID: Bob Smith wrote: > Is shutil.copyfile(src,dst) the *most* portable way to copy files with > Python? I'm dealing with plain text files on Windows, Linux and Mac OSX. > > Thanks! Yes. 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 aleaxit at yahoo.com Sun Jan 9 06:31:47 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 9 Jan 2005 12:31:47 +0100 Subject: Getting rid of "self." References: Message-ID: <1gq4ery.1v79c2t9lsfinN%aleaxit@yahoo.com> BJ?rn Lindqvist wrote: > I think it would be cool if you could refer to instance variables > without prefixing with "self." I know noone else thinks like me so Some do -- Kent Beck's excellent book on TDD-by-example has a specific grouse against that in the chapter where he develops the unittest module (in Python). But that's how comes Kent is a _Smalltalk_ programmer rather than a _Python_ programmer, see?-) > Python will never be changed, but maybe you can already do it with > Python today? Sure. > impressive in this case but much cooler when there is more instance > variables around. But the solution is very ugly because you have to > write exec(magic()) in every method. So I'm asking here if someone > knows a better way, maybe using decorators or metaclasses or other > black magic? A decorator can entirely rewrite the bytecode (and more) of the method it's munging, so it can do essentially anything that is doable on the basis of information available at the time the decorator executes. You do, however, need to nail down the specs. What your 'magic' does is roughly the equivalent of a "from ... import *" (except it "imports", so to speak, from a namespace that's not a module): it makes a local copy of all names defined in the given namespace, and that's all. The names stay local, any rebinding of a name has no non-local effect whatsoever, etc. Is this indeed what you want -- just give a method this kind of copies? And still have to write self.x=23 for re-binding (without effect on the local copy, note...)? Or what else? Then, you must decide whether this applies to all names the method accesses (which aren't already local). For example, if the method has a statement such as: x = len(y) and does not otherwise as locals len nor y, does this mean x = self.len(self.y) or x = len(self.y) or x = self.len(y) or x = len(y) ...? I.e., which of the names len and y is meant to be a global or builtin, which is meant to be an isntance variable? The decorator must know, because it needs to generate different bytecode. Your approach, injecting an exec statement in the method, makes the compiler punt: the compiler knows, seeing 'exec', that it has no idea about which names are locals or globals any more, so it generates horribly-slow code for completely-general accesses instead of normal local-access-is-optimized code. Is that what you want to do -- slow all of your Python code down by an order of magnitude in order to be able to avoid writing 'self.' in a few cases? If you can give totally complete specifications, I can tell you whether your specs are doable (by a decorator, or other means), how, and at what cost. Without knowing your specs, I can't tell; I can _guess_ that the answer is "probably doable" (as long as you're not demanding the code in the decorator to be an oracle for the future, but are content to limit it to information known when it runs; and as long as you don't care how much you slow everything down) and most definitely not WORTH doing for anything except mental gym. Alex From xah at xahlee.org Fri Jan 14 05:42:37 2005 From: xah at xahlee.org (Xah Lee) Date: 14 Jan 2005 02:42:37 -0800 Subject: [perl-python] 20050113 looking up syntax Message-ID: <1105699357.565028.107750@c13g2000cwb.googlegroups.com> while programing in Python, one can lookup syntax or info for keywords or modules within Python. In the command line, type python to get into the python interactive program. then type help() >From there one can type any keyword or module name to find out the syntax or info. Everything is self-contained and self-explanatory. to exit help, type control-d. if you haven't tried already, you can type 1+1 while running python. The result will be displayed interactively. So in this way, Python can be used as a calculator. --------------------- for perl syntax lookup, use perldoc in the command line. For example: perldoc perl use 'perldoc -f functionName' for specific function. example: perldoc -f qq note that keywords cannot be looked up with -f. For basic keywords like if, while..., use perldoc perlop Master 'perldoc perl' as a way to get familiar of what info are available and what subroutine or aspect of perl is in what section of the documentation associated with what documentation name abbreviation. Master 'perldoc perldoc' to know all its power of options and flexibility. If you use emacs, in particular you want to add the -t option. Master the unix text editor vi to learn the navigation system of perldoc. The basics are: control-f for page down, control-v for page up, q for exit. Also, one may wish to peruse 'perldoc perlfaq' to acquaint yourself about the preamble of nine volumes of perl's FAQ. --------------------------- Note: this post is from the Perl-Python a-day mailing list at http://groups.yahoo.com/group/perl-python/ to subscribe, send an email to perl-python-subscribe at yahoogroups.com if you are reading it on a web page, program examples may not run because they've been changed by yahoo.com or google.com. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From aleaxit at yahoo.com Mon Jan 24 03:38:25 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 24 Jan 2005 09:38:25 +0100 Subject: best way to do a series of regexp checks with groups References: Message-ID: <1gqvzm0.htfjsq10h8nruN%aleaxit@yahoo.com> Nick Craig-Wood wrote: > Here is a different solution... > > class Result: > def set(self, value): > self.value = value > return value > > m = Result() > > if m.set(re.search(r'add (\d+) (\d+)', line)): > do_add(m.value.group(1), m.value.group(2)) > elif m.set(re.search(r'mult (\d+) (\d+)', line)): > do_mult(m.value.group(1), m.value.group(2)) > elif m.set(re.search(r'help (\w+)', line)): > show_help(m.value.group(1)) This is roughly the same as my Cookbook recipe for test-and-set, but if all you're using it for is RE search and MO access you might be better off giving more responsibilities to your auxiliary class, such as: class ReWithMemory(object): def search(self, are, aline): self.mo = re.search(are, aline) return self.mo def group(self, n): return self.mo.group(n) m = ReWithMemory() if m.search(r'add (\d+) (\d+)', line): do_add(m.group(1), m.group(2)) elif m.search(r'mult (\d+) (\d+)', line): do_mult(m.group(1), m.group(2)) elif m.search(r'help (\w+)', line): show_help(m.group(1)) Demeter's Law suggests that the 'm.value.group' accesses in your approach are better handled by having m delegate to its `value'; and the repeated m.set(re.search( ... seem to be a slight code smell, violating "once and only once", which suggests merging into a single `set' method. Your approach is more general, of course. Alex From sjmachin at lexicon.net Tue Jan 4 17:33:34 2005 From: sjmachin at lexicon.net (John Machin) Date: 4 Jan 2005 14:33:34 -0800 Subject: Pythonic search of list of dictionaries In-Reply-To: References: Message-ID: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> Bulba! wrote: [big snip] Forget the csv-induced dicts for the moment, they're just an artifact of your first solution attempt. Whether english = csv_row[1], or english = csv_row_dict["english"], doesn't matter yet. Let's take a few steps back, and look at what you are trying to do through a telescope instead of a microscope. Core basic root problem: you have a table with 3 columns, id, english, polish. Nothing is said about id so let's assume nothing. Evidently contents of "english" is the "key" for this exercise, but it's not necessarily unique. You have two instances of the table, and you want to "diff" them using "english" as the key. You want to collect together all rows that have the same value of "english", and then process them somehow. You need to define an object containing a list of all "left" rows and a list of all "right" rows. Processing the contents of the object: do whatever you have to with obj.left_list and obj.right_list depending on the lengths; you have 3 cases of length to consider (0, 1, many). 3 x 3 = 9 but if you get both zero you have a bug (which you should of course assert does not exist), so that leaves 8 cases to think about. Now, how do we get the rows together: (a) The sort method Step 1: sort each dataset on (english, id, polish) or (english, polish, id) -- your choice; sorting on the whole record instead just english makes the ordering predictable and repeatable. Step 2: read the two sorted datasets ("left" and "right") in parallel: when left key < right key: do_stuff(); read another left record when left key > right key: converse when left ley == right key: do_stuff(); read another record for both where do_stuff() includes appending to left_list and right_list as appropriate and at the right moment, process a completed object. This is a little tricky, and handling end of file needs a little care. However this algorithm can be implemented with minimal memory ("core"), no disk drive at all :-O and a minimum of 3 (preferably 4+) serially-readable rewindable re-writable storage devices e.g magnetic tape drives. Once upon a time, it was *the* way of maintaining a database (left = old database, right = transactions, output file -> new database). (b) Fast forwarding 30+ years, let's look at the dictionary method, assuming you have enough memory to hold all your data at once: Step 1: read the "left" table; for each row, if english not in mydict, then do mydict[english] = MyObject(). In any case, do mydict[english].left_list.append(row) Step 2: same for the "right" table. Step 3: for english, obj in mydict.iteritems(): process(english, obj) As your datasets are stored in MS Excel spreadsheets, N < 64K so whether your solution is O(N) or O(N*log(N)) doesn't matter too much. You are however correct to avoid O(N**2) solutions. Hoping this sketch of the view through the telescope (and the rear-vision mirror!) is helpful, John From bjourne at gmail.com Fri Jan 7 11:51:13 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 7 Jan 2005 17:51:13 +0100 Subject: Getting rid of "self." In-Reply-To: References: <740c3aec05010705393048a374@mail.gmail.com> <1105114214.359029.152240@f14g2000cwb.googlegroups.com> Message-ID: <740c3aec050107085166d99e50@mail.gmail.com> Thank you for your replies. But they don't deal with my original question. :) I have read the thousands of posts all saying "self is good" and they are right. But this time I want to be different m-kay? I figure that there might be some way to solve my problem by doing this: .def instancevar2locals(method): . # Do something magic here so that exec(magic()) is automagically run each time . # the function is invoked. . newmethod = method . return newmethod And then in the class definition something like this: .class A: . def __init__(self): . self.hi = "hi" . def meth(self): . print hi . meth = instancevar2locals(meth) But beyond that, I have no idea and I would be grateful if someone would like to help me with it. -- mvh Bj?rn From hwlgw at hotmail.com Wed Jan 19 12:04:08 2005 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 19 Jan 2005 09:04:08 -0800 Subject: delay and force in Python References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Message-ID: <1106154248.364547.301430@c13g2000cwb.googlegroups.com> Yes you are right, if you just want to carry an expression around then lambda does it; but delay was not intended as a top-level function. Perhaps you think that my silly stream implementation in the original post builds the whole list, but it does not: >>> o = stream_enumerate_interval(11,121) >>> print o [11, at 0x00BA8670>] >>> f = o[1] >>> r = f() >>> print r [12, at 0x00BA86B0>] instead it builds a list of lambda's, and that is so desirable Others suggested generators indeed, and I can imagine now a usage pattern like >>> s = stream_generator(initValue, next, stop, other_params) >>> stream_hd(stream_tl(stream_filter(isEven,s))) where the idea is to pass a generator to a function all the time. What I don't like though is that I then, as I understand it, have to code some for-loop inside that function, I try to avoid for-loops. But a functional form defined with a for-loop does not seem all that bad. Anyway I have some reading-up to do, about things some posters use and I forgot to keep up with since I have been coding Python 1.5.2 style for ages now: properties, itertools, ...printed some stuff already, thanks! From jeff at ccvcorp.com Wed Jan 26 19:59:01 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 26 Jan 2005 16:59:01 -0800 Subject: Browsing text ; Python the right tool? In-Reply-To: <1106783975.472873.21420@z14g2000cwz.googlegroups.com> References: <10vdpohm549g44a@corp.supernews.com> <1106707324.874852.208520@z14g2000cwz.googlegroups.com> <10vfqra5knegoa3@corp.supernews.com> <1106783975.472873.21420@z14g2000cwz.googlegroups.com> Message-ID: <10vgerafeom164b@corp.supernews.com> John Machin wrote: > Jeff Shannon wrote: > >>[...] For ~10 or fewer types whose spec >>doesn't change, hand-coding the conversion would probably be quicker >>and/or more straightforward than writing a spec-parser as you >>suggest. > > I didn't suggest writing a "spec-parser". No (mechanical) parsing is > involved. The specs that I'm used to dealing with set out the record > layouts in a tabular fashion. The only hassle is extracting that from a > MSWord document or a PDF. The "specs" I'm used to dealing with are inconsistent enough that it's more work to "massage" them into strict tabular format than it is to retype and verify them. Typically it's one or two file types, with one or two record types each, from each vendor -- and of course no vendor uses anything similar to any other, nor is there a standardized way for them to specify what they *do* use. Everything is almost completely ad-hoc. >>If, on the other hand, there are many record types, and/or those >>record types are subject to changes in specification, then yes, it'd >>be better to parse the specs from some sort of data file. > > "Parse"? No parsing, and not much code at all: The routine to "load" > (not "parse") the layout from the layout.csv file into dicts of dicts > is only 35 lines of Python code. The routine to take an input line and > serve up an object instance is about the same. It does more than the > OP's browsing requirement already. The routine to take an object and > serve up a correctly formatted output line is only 50 lines of which > 1/4 is comment or blank. There's a tradeoff between the effort involved in writing multiple custom record-type classes, and the effort necessary to write the generic loading routines plus the effort to massage coerce the specifications into a regular, machine-readable format. I suppose that "parsing" may not precisely be the correct term here, but I was using it in parallel to, say, ConfigParser and Optparse. Either you're writing code to translate some sort of received specification into a usable format, or you're manually pushing bytes around to get them into a format that your code *can* translate. I'd say that my creation of custom classes is just a bit further along a continuum than your massaging of specification data -- I'm just massaging it into Python code instead of CSV tables. >>I suspect >>that we're both assuming a case similar to our own personal >>experiences, which are different enough to lead to different >>preferred solutions. ;) > > Indeed. You seem to have lead a charmed life; may the wizards and the > rangers ever continue to protect you from the dark riders! :-) Hardly charmed -- more that there's so little regularity in what I'm given that massaging it to a standard format is almost as much work as just buckling down and retyping it. My one saving grace is that I'm usually able to work with delimited files, rather than column-width-specified files. I'll spare you the rant about my many job-related frustrations, but trust me, there ain't no picnics here! Jeff Shannon Technician/Programmer Credit International From fredrik at pythonware.com Mon Jan 24 13:39:24 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 19:39:24 +0100 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> Message-ID: Steven Bethard wrote: >>>>>a = 1, 2, 3 >>>>>b = a[:] >>>>>a is b >> True > > My impression was that full tuple copies didn't actually copy, but that slicing a subset of a > tuple might. Not exactly sure how to test this, but: > > py> a = 1, 2, 3 > py> a[:2] is a[:2] > False yup. and to figure out why things are done this way, consider this case: >>> a = give_me_a_huge_tuple() >>> len(a) (a rather large number) >>> b = a[:2] >>> del a (IIRC, I proposed to add "substrings" when I implemented the Unicode string type, but that idea was rejected, for the very same "and how do you get rid of the original object" reason) From BOOGIEMANPN at YAHOO.COM Mon Jan 3 17:38:32 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Mon, 3 Jan 2005 23:38:32 +0100 Subject: How do I make Windows Application with Python ? References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> Message-ID: <1j5b7xzffmtry$.xdy044lkg71u$.dlg@40tude.net> On Mon, 03 Jan 2005 22:57:22 +0100, Jarek Zgoda wrote: > Close your eyes, see this model-view-controller in your application, > rewrite it in Python using one of its MVC frameworks. > > You see? It's easy, like that! Yes, only if I'd know what you're talking about :( From tds at gmx.de Sun Jan 2 18:07:14 2005 From: tds at gmx.de (Wolfgang) Date: Mon, 03 Jan 2005 00:07:14 +0100 Subject: UserDict deprecated In-Reply-To: <1gpqh6l.65jemkskbo5eN%aleaxit@yahoo.com> References: <1gpqh6l.65jemkskbo5eN%aleaxit@yahoo.com> Message-ID: Hello, Alex Martelli wrote: > The DictMixin class from the UserDict module is *not* deprecated -- only > the UserDict class from the same module. (If you found info saying > otherwise pls provide a URL: the info is wrong and I'll try to get it > fixed -- thanks!). DictMixin's purpose is exactly as you state: letting > you make a complete mapping class out of one which only supplies the > very basics, by mix-in inheritance. If UserDict is deprecated why is it still used in the os module ? (in python V. 2.4) The std lib should be a good example for python coding, if something is deprecated it should not be used in the std lib. Some weeks ago I had ten minutes of spare time and rewrote the 'os' module to use dict and there was no problem with it. But due to lack of time I was not able to run tests and submitted no patch. I will try this next week. bye by Wolfgang From tjreedy at udel.edu Sat Jan 29 20:42:54 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 29 Jan 2005 20:42:54 -0500 Subject: {Spam?} Re: naive doc question References: <5175a81c050129163826fcd734@mail.gmail.com> Message-ID: "Gabriel B." wrote in message news:5175a81c050129163826fcd734 at mail.gmail.com... > I wanted a list of all the methods of dict for example... where can i > find it? Lib Ref 2.3.8 Mapping Types. Do browse chapter 2 so you know what is there. Terry J. Reedy From ovazquez at gmail.SPAM.com Tue Jan 25 00:28:23 2005 From: ovazquez at gmail.SPAM.com (Orlando Vazquez) Date: Tue, 25 Jan 2005 05:28:23 GMT Subject: Retrieving modification time of file class was declared in In-Reply-To: <1IkJd.53158$06.43207@clgrps12> References: <1106627951.152900.135310@z14g2000cwz.googlegroups.com> <1IkJd.53158$06.43207@clgrps12> Message-ID: Actually, what my comment wass supposed to say was "Checking the modification time of the file the Thread class was defined in", but I'm sure you understood what I meant. ;-) Orlando Vazquez wrote: > nathan_kent_bullock at yahoo.ca wrote: > >> Assume I am using a class Foo. I want to find out the modification time >> of the file that that class was defined in. How would I go about this? >> >> If I could find out the name of the file that Foo was defined in then >> it is easy, I could use os.path.getmtime(), but I can't even figure >> that out. >> >> I realize that this wouldn't be a completely accurate way to tell the >> last time this class was modified because it could inherit info from >> other classes, or use functions from other modules that have been >> modified, etc. >> >> Nathan Bullock >> > > Off the top of my head, without having done too much experimentation > here's what you could try. Caveat: there may be a more robust/cleaner > way of doing this: > > # Checking the modificationtime of the Thread class in the threading > # module > > >>> import threading > >>> import time > >>> > >>> module_filename = vars()[threading.Thread.__module__].__file__ > >>> > >>> mtime = os.path.getmtime(module_filename) > >>> > >>> print time.ctime(mtime) > Sun Nov 14 20:29:42 2004 > > > I hope that answer's your question :-) > From bokr at oz.net Wed Jan 12 22:01:33 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 03:01:33 GMT Subject: dict.updated References: <5GiFd.8571$Vj3.3354@newssvr17.news.prodigy.com> Message-ID: <41e5e359.707363114@news.oz.net> On Wed, 12 Jan 2005 23:47:13 GMT, "Rick Morrison" wrote: >I could live with creating a new dict, sure (although it seems wasteful). I >realize that something like this probably doesn't stand a chance of ever >making it into the std library for what might be called "philosophical" >reasons. I just want it for me (my personal philosophy runs more to the >pragmatic -- well at least for coding). > >I suppose the in-place version would be more along the lines of: > >>>> def updated(d, updates): >... d.update(updates) >... return d >... >>>> [updated(d, {'c':3}) for d in [{'a':1, 'b':2}, {'x':10, 'y':'11'}]] >[{'a': 1, 'c': 3, 'b': 2}, {'y': '11', 'x': 10, 'c': 3}] > It's kind of a strange list comp, but I guess you're just illustrating something. But for this case you could just write >>> [d.update({'c':3}) or d for d in [{'a':1, 'b':2}, {'x':10, 'y':'11'}]] [{'a': 1, 'c': 3, 'b': 2}, {'y': '11', 'x': 10, 'c': 3}] taking advantage of normal d.update() returning None and so forcing the 'or' term. Regards, Bengt Richter From bokr at oz.net Fri Jan 7 17:02:19 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 07 Jan 2005 22:02:19 GMT Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Message-ID: <41df023c.256518524@news.oz.net> On 07 Jan 2005 14:38:01 +0100, Jacek Generowicz wrote: [...] > >[*] Funnily enough, getting them to understand that "lambda x: fn(x)" > is just a very silly way of writing "fn", can be quite a struggle > at times ... but that's probably a consequence of the context in > which lambda is introduced. Actually, it may _usually_ be silly, but it could be a way of deferring a name lookup instead of using the current binding of a name: >>> def bar(): return 'this is bar' ... >>> def foo(f=bar): print f() ... >>> def bar(): return 'this is updated bar' ... >>> foo() this is bar >>> def foo(f=lambda:bar()): print f() ... >>> foo() this is updated bar >>> def bar(): return 'this updated bar was picked up by silly lambda' ... >>> foo() this updated bar was picked up by silly lambda Regards, Bengt Richter From bjourne at gmail.com Sun Jan 9 19:51:07 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 10 Jan 2005 01:51:07 +0100 Subject: Getting rid of "self." In-Reply-To: <10u2dlj4p45psf0@news.supernews.com> References: <1gq4ery.1v79c2t9lsfinN%aleaxit@yahoo.com> <10u2dlj4p45psf0@news.supernews.com> Message-ID: <740c3aec05010916515326ac4a@mail.gmail.com> Thank you for your replies. It is very nice to see that a thread you started is generating so much discussion, but please, I have read the previous debates so I know all about what people think about self. Spare the "you shouldn't do that" and "self is here to stay" replies to the threads in which people are actually suggesting changing the syntax. :) I know the solution I presented is not working ideally, because you have to use self to assign to instance attributes like "self.hi = 'baby'". > Sean Ross: > http://starship.python.net/crew/mwh/hacks/selfless.py That's excellent! There is one small problem with the code though: .class Hi(Selfless): . __attrs__ = ["x"] . def __init__(x): . self.x = x In this case, I think the Python interpreter should realise that the parameter x shadows the attribute x. But the selfless code has problems with that. I want it to work exactly like how the situation is handled in Java and C++. > Alex Martelli: >> Bj?rn Lindqvist: >> I think it would be cool if you could refer to instance variables >> without prefixing with "self." I know noone else thinks like me so > Some do -- Kent Beck's excellent book on TDD-by-example has a specific > grouse against that in the chapter where he develops the unittest module I have to get myself that book. > Alex Martelli: > A decorator can entirely rewrite the bytecode (and more) of the method > it's munging, so it can do essentially anything that is doable on the > basis of information available at the time the decorator executes. Which I believe means that the instance variables have to be declared in the class? I am content with declaring them like the selfless approach does: __attrs__ = ["hi", "foo"] It's not optimal because it would lead to some "name duplication" when a class is __init__:ed. .__attrs__ = ["hi", "foo"] .def __init__(_hi, _foo): . hi = _hi . foo = _foo I guess you can solve that adequately by using one of the recipes from the Cookbook that automagically initialises an objects variable depending on which variables was passed in the parameter list. Another alternative would be not to declare the variables in an __attr__ list, and instead let them be "declared" by having them initialised in the __init__. I.e: .def __init__(hi, foo): . self.hi = hi . self.foo = foo When the metaclass then does it magic, it would go through the code of the __init__ method, see the assignments to "self.hi" and "self.foo", decide that "hi" and "foo" are attributes of the object and replace "hi" and "foo" in all other methods with "self.hi" and "self.foo". The downside is that it probably could never be foolproof against code like this: .def __init__(hi, foo): . if hi: . self.hi = hi . else: . self.foo = foo But AFAIK, that example is a corner case and you shouldn't write such code anyway. :) > Alex Martelli: > You do, however, need to nail down the specs. What your 'magic' does > is roughly the equivalent of a "from ... import *" (except it > ... > Then, you must decide whether this applies to all names the method > accesses (which aren't already local). For example, if the method > has a statement such as: > x = len(y) All names should be checked like this: 1. Is the name in the parameter list? If so, do not rebind it. 2. Is the name in the objects attribute list? If so, prepend "self." 3. Do stuff like normal. Example: .class Foo(Selfless): . def __init__(x): . print x . self.x = x*2 . def meth(): . x = x + 10 . print x . def meth2(x): . print x . print self.x . self.x = x . .o = Foo(50) .print o.x .o.meth() .o.meth2(12) .print o.x Outputs: 50 100 110 12 110 12 > Alex Martelli: > If you can give totally complete specifications, I can tell you > whether your specs are doable (by a decorator, or other means), how, > and at what cost. Without knowing your specs, I can't tell; I can > _guess_ that the answer is "probably doable" (as long as you're not > demanding the code in the decorator to be an oracle for the future, This is promising, I'm content with whatever slowdowns necessary as long as I can prove those who say "you can't do it" wrong. :) It seems to me that it should be doable by having the metaclass that modifies the class go through the class and bytecode-rewrite all its methods. So there has to be a big slowdown when the class is created, but after that, it should execute at pure Python speed? That doesn't seem to hard, and pretty robust too since bytecode doesn't change so often. And THEN I'll rewrite python-mode so that it syntax highlights member attributes! It will be cool. -- mvh Bj?rn From kent3737 at yahoo.com Thu Jan 20 13:59:43 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Thu, 20 Jan 2005 13:59:43 -0500 Subject: Overloading ctor doesn't work? In-Reply-To: References: <35ab8oF4idc25U1@individual.net> Message-ID: <41effd30$1_1@newspeer2.tds.net> > Martin H?cker wrote: > >> Hi there, >> >> I just tried to run this code and failed miserably - though I dunno >> why. Could any of you please enlighten me why this doesn't work? Here is a simpler test case. I'm mystified too: from datetime import datetime class time (datetime): def __init__(self, hours=0, minutes=0, seconds=0, microseconds=0): datetime.__init__(self, 2001, 10, 31, hours, minutes, seconds, microseconds) print time(1,2,3,4) # => 0001-02-03 04:00:00 print time() # => TypeError: function takes at least 3 arguments (0 given) What happens to the default arguments to time.__init__? What happens to the 2001, 10, 31 arguments to datetime.__init__? I would expect the output to be 2001-10-31 01:02:03.000004 2001-10-31 00:00:00.000000 Kent From peter at somewhere.com Wed Jan 26 06:55:38 2005 From: peter at somewhere.com (Peter Maas) Date: Wed, 26 Jan 2005 12:55:38 +0100 Subject: "pickle" vs. f.write() In-Reply-To: References: Message-ID: Johan Kohler schrieb: > class person: > name ="" > age = 0 > friends=[] > comment="""""" > > me = person() > > Otherwise, what is the best "Python" way to write and read this data > structure? import pickle class person: name ="" age = 0 friends=[] comment="""""" me = person() # store pf = file('/tmp/pickletest', 'w') pickle.dump(me, pf) pf.close() # load pf = file('/tmp/pickletest', 'r') me2 = pickle.load(pf) pf.close() This is sequential access. If you want to have random access, look for shelve. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From adam at cognitcorp.com Thu Jan 6 17:58:03 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Thu, 06 Jan 2005 17:58:03 -0500 Subject: Download .jpg from web In-Reply-To: References: Message-ID: <1105052283.3737.9.camel@localhost.localdomain> On Thu, 2005-01-06 at 13:49, GMane Python wrote: > Hello All. > Using a network camera with built-in webserver, I'd like to have a python > program download .jpg files on a local lan. the location is > http:///jpg/image.jpg. > > Currently, I'm importing urllib and using urlopen to the address, then > read()-ing it, saving it to a binary file. All that is working great, but > maybe a bit slowly. I'm getting ~2.3 frames per second, and would like > between 5-10 frames per second. I don't think that connection persistance is the problem you are facing. Perhaps the camera's TCP stack is really slow, but I just don't see the overhead of reconnecting being anywhere near high enough to account for the difference between what you have and what you think you should have. * What kind of camera are you using ... is it capable of handling more frames per second? I sounds like what you really want is a camera that can stream an avi or mpeg. * What is the bandwidth between the camera cluster and your server and what is the average size of an image? Lets be sure you are not bandwidth constrained. * Are you doing any post processing on these images? If all you are doing is: open( "somefilename.jpg").write( urllib.open( ... ).read() ) then what you are looking to do is a premature optimization. Also, you may want to consider saving the images in a format other than a stream or jpegs. The Ogg Vorbis Theora codec is pretty mature right now and, assuming that consequtive images are similar, will compress way better than just saving jpegs. - Adam > > Am I approaching this incorrectly? I have to do a urlopen, then .read() > for each image. Is there any way to 'persist' the urlopen so I just have to > keep read()-ing or maybe is there a type of streaming read? I have many > cameras, so there are many threads simultaneously reading and dropping them > in a central Queue for saving later. > > I appreciate it! > -Dave > > WebImage = urllib.urlopen("http:///jpg/image.jpg").read() > QueuePacket = [] > QueuePacket.append(WebImage) > Adam DePrince From maxm at mxm.dk Fri Jan 14 05:09:12 2005 From: maxm at mxm.dk (Max M) Date: Fri, 14 Jan 2005 11:09:12 +0100 Subject: oddities in the datetime module Message-ID: <41e79a1a$0$264$edfadb0f@dread12.news.tele.dk> # -*- coding: latin-1 -*- """ I am currently using the datetime package, but I find that the design is oddly asymmetric. I would like to know why. Or perhaps I have misunderstood how it should be used? I can make a datetime easily enough >>> datetime(2005, 1, 1) datetime.datetime(2005, 1, 1, 0, 0) What I find odd is that I cannot make a new datetime object from the timetuple() like this: >>> d1 = datetime(2005, 1, 1, 12, 13, 10) >>> d2 = datetime(*d1.timetuple()) Traceback (most recent call last): ... TypeError: function takes at most 8 arguments (9 given) >>> d1.timetuple() (2005, 1, 1, 12, 13, 10, 5, 1, -1) Because if I subclass datetime, I often need to convert between my subclass and the built in datetime module. But there is no direct way to do it. Instead I have to do it in a somewhat more clunky way: >>> datetime(* (d1.timetuple()[:6] + (0, d1.tzinfo))) datetime.datetime(2005, 1, 1, 12, 13, 10) if I want to convert a date to a datetime it is easy, even though I still have to truncate the timetuple. >>> d = date(2005, 1, 1) >>> datetime(*d.timetuple()[:6]) datetime.datetime(2005, 1, 1, 0, 0) The other way around is also easy. >>> dt = datetime(2005, 1, 1, 12, 0, 0) >>> date(*dt.timetuple()[:3]) datetime.date(2005, 1, 1) But it's a clunky design that I have to do it that way. I think it would be nice if date and datetime at least had a pair of datetimetuple() and from_datetimetuple() methods that could be used for easily converting between datetime types. Like the ones I have made below. That would make them a lot more symmetric. >>> datetimetuple = (2005,1,1,12,0,0,0,None) >>> datetime2.from_datetimetuple(datetimetuple) datetime2(2005, 1, 1, 12, 0) >>> dtt = datetime2(2005,1, 1).datetimetuple() >>> dtt (2005, 1, 1, 0, 0, 0, 0, None) >>> d2 = date2.from_datetimetuple(dtt) >>> d2 date2(2005, 1, 1) >>> datetime2.from_datetimetuple(d2.datetimetuple()) datetime2(2005, 1, 1, 0, 0) """ from datetime import datetime, date class datetime2(datetime): def datetimetuple(self): return self.timetuple()[:6] + (0, self.tzinfo) def from_datetimetuple(dt_tuple): return datetime2(*dt_tuple) from_datetimetuple = staticmethod(from_datetimetuple) class date2(date): def datetimetuple(self): return self.timetuple()[:6] + (0, None) def from_datetimetuple(dt_tuple): return date2(*dt_tuple[:3]) from_datetimetuple = staticmethod(from_datetimetuple) #from datetime import datetime # #ical = Calendar() #print ical.ical() if __name__ == "__main__": import os.path, doctest, x # import and test this file doctest.testmod(x) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From chrisdewinN0SPAM at yahoo.com.au Fri Jan 28 17:21:24 2005 From: chrisdewinN0SPAM at yahoo.com.au (Dfenestr8) Date: Sat, 29 Jan 2005 08:21:24 +1000 Subject: An mysql-python tutorial? Message-ID: Hi. Been told by the admin of my (free!) server that he'd rather I should learn to use mysql if I want to continue writing cgi scripts there. Not even sure exactly what mysql is. Is there a simple tutorial anywhere on the web about using python + mysql? From http Fri Jan 7 05:08:02 2005 From: http (Paul Rubin) Date: 07 Jan 2005 02:08:02 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> <7xpt0h66yf.fsf@ruckus.brouhaha.com> Message-ID: <7x65291ri5.fsf@ruckus.brouhaha.com> adamc writes: > I've not experienced problems installing wxPython on Debian (unstable). > It just *works* out of the box with apt-get. Perhaps this is more of a > problem with the package maintainers? I think the problem I encountered was that the version of WxWidgets currently on the WxWidgets.com site was trying to use some obsolete function in GTK. If Debian is using an older version of GTK than what comes with FC3, then it might work. From detlev at die-offenbachs.de Sun Jan 23 10:34:54 2005 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 23 Jan 2005 16:34:54 +0100 Subject: ANN: eric3 3.6.0 released Message-ID: Hi, this is to let you know about a new release of eric3, the Python IDE. It has a bunch of new functions. The most prominent ones are listed below. - added some dialog wrappers that make eric3 use KDE dialogs, if KDE and PyKDE are installed - added a previewer for UI files - added a previewer for translation files - added a "Continue to cursor" command to the debugger - added view profiles and a correspondig configuration dialog - added capability to show the coverage annotations in the editor - added capability to select the protocol of the VCS server at login time - added support for alternative keyboard shortcuts - changed variables viewer to keep the state of the tree while debugging - added multiple selection capabilities to the browsers - added capability to enter variables filter patterns to the variables viewer windows - added an icon previewer to the configuration dialog icons page and some more little things. It is available via http://www.die-offenbachs.de/detlev/eric3.html I hope you enjoy it. What is eric3 ------------- eric3 is Python IDE written using the PyQt wrappers. If the PyKDE wrappers are installed as well, it will work as a KDE application and use KDE dialogs. It has a built in debugger, profiler, help viewer, unlimited number of editors with syntax highlighting, autocompletion and many more. Eric3 interfaces to CVS and subversion and has a built in documentation generation facility. For all the other details and snapshots please see the above URL. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From michele.simionato at gmail.com Tue Jan 11 05:06:06 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 11 Jan 2005 02:06:06 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] Message-ID: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> Paul Rubin wrote: > How about macros? Some pretty horrible things have been done in C > programs with the C preprocessor. But there's a movememnt afloat to > add hygienic macros to Python. Got any thoughts about that? "Movement" seems quite an exaggeration. Maybe 2-3 people made some experiments, but nobody within the core Python developers seems to be willing to advocate the introduction of macros. > Why should you care whether the output of a macro is ugly or not, > if no human is ever going to look at it? But at least some human eye have to look at it! Did you ever debug a macro? More seriuosly, I have given some thought to the issue, and I am very much against the introduction of macros in Python. Here are a few reasons: 1. I like defmacro in Lisp. Problem is, Lisp is an s-expression based language, Python is not. We cannot implement defmacro in Python and even if we could, if would be too ugly to be used (at least, IMHO). 2. One could proposed hygienic pattern-matching macros in Python, similar to Scheme syntax-rules macros. Again, it is not obvious how to implement pattern-matching in Python in a non-butt-ugly way. Plus, I feel hygienic macros quite limited and not worth the effort. 3. We would add to Python the learning curve of macros and their subtilities and we do not want it. 4. Macros would complicate a lot Python module system. 5. We have Guido providing a good syntax for us all, why we should be fiddling with it? More seriously, if some verbosity is recognized in the language (think to the "raison d'etre" of decorators, for instance) I very much prefer to wait for Guido to take care of that, once and for all, than having 100 different custom made solutions based on macros. I am sure I could find other reasons if I think a bit more, but these should suffice for the moment ;) What I would be interested in is a Lisp/Scheme implementation compiling to Python bytecode, but I am not aware of any project in that direction. Michele Simionato P.S. some pointers for people interested on the topic: http://logix.livelogix.com/ (a Python-like language with macros) https://sourceforge.net/projects/pymac/ (an experimental Dylan-inspired macro system for Python) From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Mon Jan 24 10:37:54 2005 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Mon, 24 Jan 2005 16:37:54 +0100 Subject: Right place for third party modules (here: fixedpoint) Message-ID: <35kj2iF4n6sokU1@news.dfncis.de> Hello, for the first time since getting Python I can't get a third party module to work. I got fixedpoint.0.1.2.tar.gz from SourceForge for use with KinterbasDB. After unpacking I had a directory called "fixedpoint" which I put under my site-packages directory. There are no installation instructions and just the one module fixedpoint.py (and some documentation and examples). All of this under Windows XP, with Python 2.4. Now I try to use the module, but import fixedpoint says "ImportError: No module named fixedpoint". I suppose fixedpoint is no package as described in the tutorial and so "site-packages" might not be the right place for it. But where does it belong? I think it should go somewhere in the Python directory tree, not among my own scripts. Thank you, Koczian -- Dr. Sibylle Koczian Universitaetsbibliothek, Abt. Naturwiss. D-86135 Augsburg Tel.: (0821) 598-2400, Fax : (0821) 598-2410 e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From j-clark at lineone.net Fri Jan 7 13:10:30 2005 From: j-clark at lineone.net (Jonathan Clark) Date: 7 Jan 2005 10:10:30 -0800 Subject: HTML purifier using BeautifulSoup? In-Reply-To: References: Message-ID: <1105121430.950052.97940@z14g2000cwz.googlegroups.com> Dan Stromberg wrote: > Has anyone tried to construct an HTML janitor script using BeautifulSoup? > > My situation: > > I'm trying to convert a series of web pages from .html to palmdoc format, > using plucker, which is written in python. The plucker project suggests > passing html through "tidy", to get well-formed html for plucker to work > with. > > However, some of the pages I want to convert are so bad that even tidy > pukes on them. > > I was thinking that BeautifulSoup might be more tolerant of really bad > html... Which led me to the question this article started out with. :) > > Thanks! I have used BeautifulSoup for screen scraping, pulling html into structured form (using XML). Is that similar to a janitor script? I used it because tidy was puking on some html. BS has been excellent. From xah at xahlee.org Mon Jan 17 12:43:19 2005 From: xah at xahlee.org (Xah Lee) Date: 17 Jan 2005 09:43:19 -0800 Subject: [perl-python] 20050117, filter, map In-Reply-To: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: <1105983799.202346.9710@f14g2000cwb.googlegroups.com> erratum: the Mathematica Apply should've been Select. ... Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From ramen at lackingtalent.com Mon Jan 31 01:57:50 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 31 Jan 2005 06:57:50 -0000 Subject: Nested scopes and class variables Message-ID: I ran into an odd little edge case while experimenting with functions that create classes on the fly (don't ask me why): >>> def f(x): ... class C(object): ... x = x ... print C.x ... >>> f(5) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in f File "", line 3, in C NameError: name 'x' is not defined "x" clearly is defined, but apparently Python is not looking at the nested variable scope to find it. What's stranger is that if I rename the parameter "x" to "y", the error goes away: >>> def f(y): ... class C(object): ... x = y ... print C.x ... >>> f(5) 5 So, it's not like nested scopes aren't supported in the class block. Rather, when it sees "x = x", it seems like Python is determining at that point that "x" is a class variable, and refuses to search any further. At the top-level, it works as expected: >>> x = 5 >>> class C(object): ... x = x ... >>> C.x 5 Any implementation gurus have some insight into what's going on here? -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. "talking about music is like dancing about architecture." From removethis.kartic.krishnamurthy at gmail.com Sat Jan 29 01:41:37 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Sat, 29 Jan 2005 06:41:37 GMT Subject: An mysql-python tutorial? In-Reply-To: References: Message-ID: Dfenestr8 said the following on 1/28/2005 5:21 PM: > Hi. > > Been told by the admin of my (free!) server that he'd rather I should > learn to use mysql if I want to continue writing cgi scripts there. > > Not even sure exactly what mysql is. > > Is there a simple tutorial anywhere on the web about using python + mysql? Did you try googling? There are two items in the very first page that should be of use to you. One is the Python-MySQL module, which you should have installed. http://sourceforge.net/projects/mysql-python There is an examples directory that has some concrete stuff to help you learn. Another hit is a basic tutorial, simple to follow and learn :- http://images.devshed.com/Server_Side/Python/PythonMySQL/PythonMySQL.pdf And here is one more site, good stuff here too:- http://www.kitebird.com/articles/pydbapi.html You might also want to check the "Charming Python" pages at IBM.com but I dont know if they have articles covering mysql. HTH! Thanks, --Kartic From mfuhr at fuhr.org Sat Jan 8 18:36:18 2005 From: mfuhr at fuhr.org (Michael Fuhr) Date: 8 Jan 2005 16:36:18 -0700 Subject: printing line numbers for debugging purpose References: Message-ID: <41e06e72$1_1@omega.dimensional.com> "Philippe C. Martin" writes: > All of the methods from my program return None on error (i.e; I do not > want to assert and have the program exit). > > Is it possible to print the current source file name/line number ? Someone else posted an example using an exception handler. See also the traceback module. -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From jerf at jerf.org Sun Jan 16 08:08:04 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 16 Jan 2005 08:08:04 -0500 Subject: Newbie inheritance question. References: Message-ID: On Sun, 16 Jan 2005 22:08:13 +0800, bwobbones wrote: > Hi all, > > I'm a java programmer struggling to come to terms with python - bear > with me! Christophe already identified the problem, I wanted to address another Javaism in your code, for your educational benefit. Speaking "idiomatically" (since this is all small sample code), in Python you'd normally code your driver as follows: ---------- import two t = two() # or something, there's a name conflict here, too many "two"s t.printHello() t.printTestVar() ---------- Things that aren't objects shouldn't be forced to be objects and I don't think there is any shame in having a non-OO top level. (I go on about this at http://www.jerf.org/writings/bowersLaw.html#4 in more detail.) From arobert at townisp.com Wed Jan 5 10:58:42 2005 From: arobert at townisp.com (Andrew Robert) Date: Wed, 05 Jan 2005 10:58:42 -0500 Subject: screen clear question In-Reply-To: References: <10teqpdvramua3@corp.supernews.com> <8ucft0tf456g07iuuavgu31m6dhrgjbmh3@4ax.com> Message-ID: <10to3kns044v63f@corp.supernews.com> Nick Coghlan wrote: > Alan Gauld wrote: > >> But the bottom line is that there is no builtin command because the >> mechanism is different on each platform. > > > I'd have said it was because the inpreter is line-oriented rather than > screen-oriented, but YMMV. > > Cheers, > Nick. > I would try doing a test against the resident OS the program is running against and set the clear command based on that. -- Thank you, Andrew Robert E-mail: arobert at townisp.com Ur: http://shardservant.no-ip.info From skip at no-spam.net Thu Jan 6 04:24:02 2005 From: skip at no-spam.net (skip) Date: Thu, 6 Jan 2005 04:24:02 -0500 Subject: navigating/changing directories Message-ID: A simple script like the one below lets me jump through a directory structure. However, if I run it from /this/directory and within it to go to /a/totally/different/directory... I'm still actually going to be in /this/directory when I exit the script. Is it possible to have a script that can drop me off into a different directory than where I initiated it from? import os process = 1 while (process): # Display directories for i in os.listdir(os.getcwd()): if (os.path.isdir(os.path.join(os.getcwd(),i))): print i # Change directory goto_dir = raw_input(": ") if (goto_dir in os.listdir(os.getcwd())): os.chdir(os.path.join(os.getcwd(),goto_dir)) else: process = 0 # Exit From Dennis.Benzinger at gmx.net Tue Jan 25 18:42:40 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Wed, 26 Jan 2005 00:42:40 +0100 Subject: string.atoi and string.atol broken? In-Reply-To: References: Message-ID: <41f6d96f$1@news.uni-ulm.de> Mike Moum wrote: > I think there may be a bug in string.atoi and string.atol. Here's some > output from idle. > > >>Python 2.3.4 (#2, Jan 5 2005, 08:24:51) >>[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2 >>Type "copyright", "credits" or "license()" for more information. >> >> **************************************************************** >> Personal firewall software may warn about the connection IDLE >> makes to its subprocess using this computer's internal loopback >> interface. This connection is not visible on any external >> interface and no data is sent to or received from the Internet. >> **************************************************************** >> >>IDLE 1.0.4 >> >>>>>import string as s >>>>>s.atoi('2',3) >> >>2 >> >>>>>s.atoi('4',3) >> >>Traceback (most recent call last): >> File "", line 1, in -toplevel- >> s.atoi('4',3) >> File "/usr/lib/python2.3/string.py", line 220, in atoi >> return _int(s, base) >>ValueError: invalid literal for int(): 4 >> >>>>>s.atoi('12',11) >> >>13 >> >>>>>s.atoi('13',4) >> >>7 >> >>>>>s.atoi('12',4) >> >>6 >> >>>>>s.atoi('8',4) >> >>Traceback (most recent call last): >> File "", line 1, in -toplevel- >> s.atoi('8',4) >> File "/usr/lib/python2.3/string.py", line 220, in atoi >> return _int(s, base) >>ValueError: invalid literal for int(): 8 >> > > s.atoi('4',3) should result in 11 > > s.atoi('13',4) should result in 31 > > s.atoi('12',4) should result in 30 > > s.atoi('8',4) is legitimate, but it generates an error. > > Is this a bug, or am I missing something obvious? > [...] That's not a bug, you'r missing something obvious. The second parameter of string.atoi (or the int builtin) is the base (or radix) in which the number you want to convert is given. For example string.atoi("777", 8) results in 511, because 7 * 8**2 + 7 * 8**1 + 7 * 8**0 = 511. Just out of curiosty: What did you think what atoi does? I don't understand how you came to expect that atoi('4',3) should result in 11. Bye, Dennis From http Tue Jan 11 01:46:01 2005 From: http (Paul Rubin) Date: 10 Jan 2005 22:46:01 -0800 Subject: reference or pointer to some object? References: Message-ID: <7x4qhoh39y.fsf@ruckus.brouhaha.com> Torsten Mohr writes: > i'd like to pass a reference or a pointer to an object > to a function. The function should then change the > object and the changes should be visible in the calling > function. Normally you would pass a class instance or boxed object, and let the function change the instance or object: def bump(b): b[0] += 123 # change x = [5] bump(x) print x # prints [128] From flamesrock at gmail.com Thu Jan 27 14:03:11 2005 From: flamesrock at gmail.com (flamesrock) Date: 27 Jan 2005 11:03:11 -0800 Subject: Question about 'None' Message-ID: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Well, after playing with python for a bit I came across something weird: The statement (1 > None) is false (or any other value above 0). Why is this? (The reason I ask is sortof unrelated. I wanted to use None as a variable for which any integer, including negative ones have a greater value so that I wouldn't need to implement any tests or initializations for a loop that finds the maximum of a polynomial between certain x values. Anything is greater than nothing, no?) From chris.cavalaria at free.fr Sat Jan 29 18:05:41 2005 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Sun, 30 Jan 2005 00:05:41 +0100 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) References: Message-ID: <362j65F4qsgbiU1@individual.net> Steven Bethard wrote: > Fuzzyman wrote: > > Cameron Laird wrote: > > [snip..] > > > >>This is a serious issue. > >> > >>It's also one that brings Tcl, mentioned several > >>times in this thread, back into focus. Tcl presents > >>the notion of "safe interpreter", that is, a sub- > >>ordinate virtual machine which can interpret only > >>specific commands. It's a thrillingly powerful and > >>correct solution to the main problem Jeff and others > >>have described. > > > > A better (and of course *vastly* more powerful but unfortunately only > > a dream ;-) is a similarly limited python virutal machine..... > > Yeah, I think there are a lot of people out there who would like > something like this, but it's not quite clear how to go about it. If > you search Google Groups, there are a lot of examples of how you can use > Python's object introspection to retrieve "unsafe" functions. > > I wish there was a way to, say, exec something with no builtins and with > import disabled, so you would have to specify all the available > bindings, e.g.: > > exec user_code in dict(ClassA=ClassA, ClassB=ClassB) > > but I suspect that even this wouldn't really solve the problem, because > you can do things like: > > py> class ClassA(object): > ... pass > ... > py> object, = ClassA.__bases__ > py> object > > py> int = object.__subclasses__()[2] > py> int > > > so you can retrieve a lot of the builtins. I don't know how to retrieve > __import__ this way, but as soon as you figure that out, you can then > do pretty much anything you want to. > > Steve Wouldn't it be better to attach to all code objets some kind of access right marker and to create an opcode that calls a function while reducing the access rights ? After all, security would be easier to achieve if you prevented the execution of all the dangerous code rather than trying to hide all the entry points to it. From tim.peters at gmail.com Fri Jan 21 10:24:16 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 21 Jan 2005 10:24:16 -0500 Subject: PyCon Preliminary Program Announced! In-Reply-To: References: <20050121000607.DE1261E4010@bag.python.org> <41F061C3.3000802@gmail.com> Message-ID: <1f7befae0501210724627c0f14@mail.gmail.com> [A.M. Kuchling] > Suggestions for improvement are welcome. Perhaps the Wiki version of > the schedule, at http://www.python.org/moin/PyConDC2005/Schedule, > may be better. It is, but the 2004 schedule was really what I had in mind (very readable!): http://www.python.org/pycon/dc2004/schedule.html From aahz at pythoncraft.com Sat Jan 29 11:57:45 2005 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2005 11:57:45 -0500 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <41FB080E.1070308@iinet.net.au> Message-ID: In article , Skip Montanaro wrote: > > Nick> Upgrading your Python interpreter (even to a new maintenance > Nick> branch release) in a production environment is usually a fairly > Nick> involved exercise requiring a significant amount of testing, and > Nick> the fact of the matter is, you're unlikely to do so unless there > Nick> is some feature or bug-fix in a new version that you really > Nick> need. (I'm still using Python 2.2.2 at work - it's entirely > Nick> adequate for our needs, so there's no real pressure to upgrade on > Nick> the current project. For a new project, I'd probably start with > Nick> 2.4, planning to go to 2.4.1 in a couple of months time, but there > Nick> aren't really any post-2.2 additions to Python that I can't handle > Nick> living without). > >Still, if a security bug was serious enough, my guess is that someone would >step up to supply patches (or Windows installers) for any of a number of >versions that were affected by the bug, even 2.1 or 1.5.2. That someone >might or might not be part of the core development team. That nothing like >that has been done before doesn't preclude it being done in the future. While true, such coordination also requires public discussion, given the way the Python community works. Which obviates the OPs request for private correspondence. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From http Sat Jan 29 21:34:23 2005 From: http (Paul Rubin) Date: 29 Jan 2005 18:34:23 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> <41fbcc01$0$12030$9b622d9e@news.freenet.de> Message-ID: <7xoef71w7k.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > mxCrypto is primarily unsuitable for the core because Marc-Andre Lemburg > will never ever contribute it. He is very concerned about including > crypto code with the Python distribution, so he certainly won't > contribute his own. Oh wait, I confused mxcrypto and m2crypto. Sorry. Anyway, the technical considerations are similar. From wordsender at gmail.com Thu Jan 6 01:22:48 2005 From: wordsender at gmail.com (wordsender at gmail.com) Date: 5 Jan 2005 22:22:48 -0800 Subject: file.readlines() - gives me error (bad file descriptor) Message-ID: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> Hey guys, I can't figure this one out, why is this simple script giving me problems? logfile=file(r'test.txt','w') logfile.write('datetime') test=logfile.readlines() When I run it I get the error message: Traceback (most recent call last): File "C:\Documents and Settings\Gregory\My Documents\Get New Great Job\testfile.py", line 3, in ? test=logfile.readlines() IOError: [Errno 9] Bad file descriptor I'm running Windows XP, Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Any help would be greatly appricated. Thanks, Greg From alan.gauld at btinternet.com Fri Jan 7 19:36:43 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Jan 2005 00:36:43 +0000 (UTC) Subject: Securing a future for anonymous functions in Python References: Message-ID: On Fri, 07 Jan 2005 08:44:57 -0700, Steven Bethard wrote: > > The unfamiliar argument doesn't work for me. After all most > > people are unfamiliar with complex numbers (or imaginary) numbers > > complex numbers. Lambdas, on the other hand, show up in all kinds of > code, and even though I hardly ever use them myself, I have to > understand them because other people do (over-)use them. That's a fair point I suppose but I still don't see much point in introducing new names and syntaxes when the existing name is a sensible one, even if unfamiliar to many. After all it works in Lisp and Haskell - Haskell even uses Lambda as its emblem... And besides it may just encoursage some to go and explore Lambda calculus, it did for me... And my programing improved enormously as a result. So maybe having the name as a stimulant to research is a good thing... OTOH I do accept the point made by another poster that Pythons single expression limitations mean that they are a poor imitation of lambdas in other languages. And provided I get some kind of anonymous code block to pass around I don't care too much if the name lambda disappears, provided the concept remains! And the syntax is reasonably simple to use where lambdas get used now. (Without lambdas of any kind I might finally make the jump to Ruby that I've been toying with for a while but I just hate those Perl-like @ symbols...) We often see people stating that programming shouldn't be called a science because there is no mathematical basis, such claimants usually haven't seen Predicate or Lambda calculus. I know, I used to be in that category and while I don't explicitly use either when programming (or only rarely) awareness of the principles suddenly made a lot of the "rules of programming" that I'd been taught make perfect sense (no side-effects, avoid globals, etc) Its like the fact that I rarely use Maxwell's equations when designing electronic circuits - but its nice to know what the underlying theory is actually based on! All IMHO of course! :-) Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From francis.girard at free.fr Wed Jan 26 17:41:07 2005 From: francis.girard at free.fr (Francis Girard) Date: Wed, 26 Jan 2005 23:41:07 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501241624.41889.francis.girard@free.fr> Message-ID: <200501262341.07327.francis.girard@free.fr> Le mardi 25 Janvier 2005 09:01, Michael Spencer a ?crit?: > Francis Girard wrote: > > The following implementation is even more speaking as it makes > > self-evident and almost mechanical how to translate algorithms that run > > after their tail from recursion to "tee" usage : > > Thanks, Francis and Jeff for raising a fascinating topic. I've enjoyed > trying to get my head around both the algorithm and your non-recursive > implementation. > Yes, it's been fun. > Here's a version of your implementation that uses a helper class to make > the algorithm itself prettier. > > from itertools import tee, imap > > def hamming(): > def _hamming(): > yield 1 > for n in imerge(2 * hamming, imerge(3 * hamming, 5 * hamming)): > yield n > > hamming = Tee(_hamming()) > return iter(hamming) > > > class Tee(object): > """Provides an indepent iterator (using tee) on every iteration > request Also implements lazy iterator arithmetic""" > def __init__(self, iterator): > self.iter = tee(iterator,1)[0] > def __iter__(self): > return self.iter.__copy__() > def __mul__(self, number): > return imap(lambda x: x * number,self.__iter__()) > > def imerge(xs, ys): > x = xs.next() > y = ys.next() > while True: > if x == y: > yield x > x = xs.next() > y = ys.next() > elif x < y: > yield x > x = xs.next() > else: # if y < x: > yield y > y = ys.next() > > >>> hg = hamming() > >>> for i in range(10000): > > ... n = hg.next() > ... if i % 1000 == 0: print i, n > ... > 0 1 > 1000 51840000 > 2000 8100000000 > 3000 279936000000 > 4000 4707158941350 > 5000 50960793600000 > 6000 409600000000000 > 7000 2638827906662400 > 8000 14332723200000000 > 9000 68024448000000000 > > Interesting idea. > Regards > > Michael From invalidemail at aerojockey.com Thu Jan 6 19:12:54 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 6 Jan 2005 16:12:54 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <1105056774.393244.199250@f14g2000cwb.googlegroups.com> Arich Chanachai wrote: > But > then again, if you don't like C++, you probably won't like Java. They > can be very different languages, but in my experience, the reasons why > one does not like C++ is usually due to a quality/flaw that can also be > found in Java. Oh, brother. The Zen of Python says that "simple is better than complex" and "complex is better than complicated". Java does pretty well here. C++ didn't even get "complicated is better than convoluted" right. There's are a ton of flaws in C++ not found in Java. -- CARL BANKS From cam.ac.uk at mh391.invalid Mon Jan 17 18:38:28 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 17 Jan 2005 23:38:28 +0000 Subject: how to find site-packages path In-Reply-To: References: Message-ID: Philippe C. Martin wrote: > I am using my own install script for my software and am looking for a > flawless way to figure out where python, and more specifically > site-packages is installed. The flawless way would be to use distutils. In fact you shouldn't even need your own install script--it should do most of the work for you. -- Michael Hoffman From tundra at tundraware.com Sat Jan 22 06:08:21 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 22 Jan 2005 06:08:21 EST Subject: Comments in configuration files In-Reply-To: <41f20f4a$0$6599$8fcfb975@news.wanadoo.fr> References: <41f20f4a$0$6599$8fcfb975@news.wanadoo.fr> Message-ID: Pierre Quentel wrote: > Bonjour, > > I am developing an application and I have a configuration file with a > lot of comments to help the application users understand what the > options mean > > I would like it to be editable, through a web browser or a GUI > application. With ConfigParser I can read the configuration file and > edit the options, but when I write the result all the comments are lost > > Are there modules that work on the same kind of ini files (for the needs > of my application, I prefer this format to XML or YAML) and don't remove > the comments ? > > TIA, > Pierre The latest incarnation of 'tconfpy' I just released will get you close: http://www.tundraware.com/Software/tconfpy This program can read a configuration either from memory (a list) or a file. So you could: 1) Read the file into an in-memory list (including the comments). 2) Pass the list to the parser, which would return a populated symbol table. 3) Use your application to read the current values of the symbols from the symbol table. 4) Modify the values in the symbol table as desired. 5) Map the new values in the symbol table back into the original list where the values were set intitially (this is the part that would take some work). 6) Write the list back to disk. Note that the semantics of feature of 'tconfpy' are substantially different than 'ConfigParser', and the languages recognized by each are quite different as well. It is probably fair to say that 'tconfpy' recognizes a superset of the language recognized by 'ConfigParser'. But you have to be careful because the semantics are somewhat different. -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From a at b.c Sat Jan 1 21:13:12 2005 From: a at b.c (Doug Holton) Date: Sat, 01 Jan 2005 20:13:12 -0600 Subject: What can I do with Python ?? In-Reply-To: <1bkzoh3dskuit$.ppe264krg156$.dlg@40tude.net> References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> <1bkzoh3dskuit$.ppe264krg156$.dlg@40tude.net> Message-ID: BOOGIEMAN wrote: > Thanks everybody, I downloaded latest windows version and > Python-Docs-2.4 archive. Is that enough for absolute beginner. > Is there any e-book, step by step guide ... etc for download, > or anything else important what I have to know before I start > learning Python ? The main thing I would do is subscribe to the python-tutor list. It is the best place by far to ask any questions when you are learning to use python: http://mail.python.org/mailman/listinfo/tutor Second, here are some of the best tutorials specifically designed for people with little or no previous programming experience: http://www.honors.montana.edu/~jjc/easytut/easytut/ http://www.freenetpages.co.uk/hp/alan.gauld/ http://www.dickbaldwin.com/tocpyth.htm http://www.ibiblio.org/obp/pyBiblio/ And lastly, really a great way to learn is to look at what's already out there in python. Try out some of the many 3rd party libraries and programs for python: For games: http://pygame.org/ For GUI applications: http://www.wxpython.org/ and others: http://www.python.org/pypi From itsme at yahoo.com Wed Jan 5 13:31:03 2005 From: itsme at yahoo.com (It's me) Date: Wed, 05 Jan 2005 18:31:03 GMT Subject: win32com.client problem Message-ID: I've been using the win32com module with very good success in placing data onto an Excel spreadsheet. However, whenever I have an error in my script (like mapping a non-square array onto the spreadsheet), something breaks. After fixing my error and restart the Python program again, Excel would start up a window with a "Microsoft Excel - BookX" where X is a increasing number (1,2,3,4,....) instead of just 1. Then, the spreadsheet portion of the screen is hidden - I can only see the menu bars (on top). If I restart the computer, run the Python script again and Excel would behave fine and it would start with "Microsoft Excel - Book1" everytime. My guess is that there is a zombie Excel process that got stuck in the system. However I couldn't tell for sure by looking at the Process Manager list. Any idea how I can prevent this? Thanks, -- Me From peter at somewhere.com Thu Jan 6 10:05:50 2005 From: peter at somewhere.com (Peter Maas) Date: Thu, 06 Jan 2005 16:05:50 +0100 Subject: Embedding a restricted python interpreter In-Reply-To: References: <41db7e8f$1@news.unimelb.edu.au> Message-ID: Craig Ringer schrieb: > That is my understanding. In fact, I'd say with Python it's nearly > impossible given how dynamic everything is and the number of tricks that > can be used to obfuscate what you're doing. Think of the fun that can be > had with str.encode / str.decode and getattr/hasattr . It would certainly be difficult to track all harmful code constructs. But AFAIK the idea of a sandbox is not to look at the offending code but to protect the offended objects: files, databases, URLs, sockets etc. and to raise a security exception when some code tries to offend them. Jython is as dynamic as C-Python and yet it generates class files behaving well under the JVM's security regime. > > I looked into this, and my conclusion ended up being "Well, I'm using > Python because I want it's power and flexibilty. If I want a secure > scripting environment, I should use something like Lua or Qt Script for > Applications instead." It would be good for Python if it would offer a secure mode. Some time ago I asked my hosting provider whether I could use mod_python with apache to run Python scripts in the same way as PHP scripts. He denied that pointing to Python security issues and to PHP safe. mode. Python IS powerful but there are many areas where it is of vital interest who is allowed to use its power and what can be done with it. I think it would be a pity to exclude Python from these areas where a lot of programming/computing is done. Python is a very well designed language but progress is made by criticism not by satisfaction ;) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From steven.bethard at gmail.com Wed Jan 12 13:49:14 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 11:49:14 -0700 Subject: Iteration over two sequences In-Reply-To: <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> <1105549514.563799.307030@z14g2000cwz.googlegroups.com> <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> Message-ID: <1oOdnQ8ciYG07HjcRVn-gQ@comcast.com> Henrik Holm wrote: > John Lenton wrote: > > >>>def dotproduct(a, b): >>> psum = 0 >>> for i in range(len(a)): >>> psum += a[i]*b[i] >>> return psum >> >>for this particular example, the most pythonic way is to do nothing at >>all, or, if you must call it dotproduct, >> >>>>>from Numeric import dot as dotproduct > > > Downloading, installing, and getting to know numerical modules for > Python is mext on my list :). However, I was under the impression that > Numarray is preferred to Numeric -- is that correct? Are these two > competing packages? (Hopefully this is not flame war bait...) > Numarray is the replacement for Numeric. Some people are still using Numeric for a variety of reasons, e.g. they use a package that has not been updated to use numarray, they can't afford the performance penalty that numarray has for small arrays, etc. Steve From generate at gmail.com Tue Jan 4 15:52:54 2005 From: generate at gmail.com (generate at gmail.com) Date: 4 Jan 2005 12:52:54 -0800 Subject: Working with flat files [LDIF]. In-Reply-To: <33A3E2B3.7F5CF6F0@whoi.edu> References: <33A3E2B3.7F5CF6F0@whoi.edu> Message-ID: <1104871974.248122.102230@f14g2000cwb.googlegroups.com> Scott A. McIntyre wrote: > > I looked around but didn't see any LDIF tools for perl or python... > > Any assistance or advice is appreciated!! > > Scott Hello Scott, Did you ever get this issue resolved? I have a similar need to merge two LDIF files. I did find a program called mmldif, but I believe it is proprietary to Sun. Cheers, Charles From rroberts at adobe.com Thu Jan 27 15:47:46 2005 From: rroberts at adobe.com (Read Roberts) Date: Thu, 27 Jan 2005 12:47:46 -0800 Subject: Problem with win32net on Windows 2K Message-ID: I am trying to use win32net on a Windows 2000 Japanese system, and discover that it won't import. I found a message describing the problem (see below) but can't find any response, and don't see a bug report on the SourceForge site for this. . Can anyone tell me if this has ben fixed? An early message in 2000 said that win32net is supposed to run on Windows 2000 I find the same problem reported, with more detail, on the py2exe user list, where Thomas Heller commented on 2004-08-26 : > Here"s the rest of the trackback: > File "netbios.pyc", line 1, in ? > File "win32wnet.pyc", line 9, in ? > File "win32wnet.pyc", line 7, in __load > ImportError: DLL load failed: The specified procedure could not be found. The procedure entry point LsaLookupNames2 could not be located in the dynamic link library ADVAPI32.dll This looks like the win32net Python extension requires the LsaLookupNames2 function in ADVAPI32, but this is only available in WinXP and Win2003 Server, according to MSDN, preventing to use win32net on win2k. You should report this to Mark Hammond, and maybe use a later version of pywin32 for now. Thomas From http Fri Jan 28 04:23:51 2005 From: http (Paul Rubin) Date: 28 Jan 2005 01:23:51 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> Message-ID: <7x4qh13o0o.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > And I still stand by those blanket statements. Any new module (i.e. > specific code) should see real users for some time before it can > be incorporated into Python. Let's see, the urandom module was recently released in 2.4, I think initially at my urging. I believe it was written just for 2.4, combining a Windows function used only (as far as I know) by its author, and a wrapper to read /dev/urandom on Posix systems. It didn't have any wide distribution or use before incorporation, and didn't need it. It was simple enough that a reasonable code review and some testing on the relevant platforms was enough to make make sure it worked properly. > > I would say the first thing I'd request would be your sense of how > > plausible it is that the current no-crypto policy might be relaxed. > > There is no such policy in force. Different people have different > opinions, and those opinions change over time. I cannot speak for others. If you can't speak for others, how can you say there's no policy in force? If Guido says "no crypto", is that something other than a policy? And are you speaking for him when you say that? > proposed feature is good, and I said that, for an example, IETF even > requires *two* implementations before deciding that the feature is good. No, that's completely wrong. IETF requires two implementations before publishing a specification--a precise description--as a draft standard, which means agreeing on how the feature should work at the finest level of detail. That's much different than merely deciding that a feature is good and inviting people to work on it. IETF often decides and announces that a feature is good long before any such details are decided or agreed on. For example, they decided that IP connection encryption was a good feature, and appointed a working group a general mandate to go figure out the details (IPSEC) and write a spec. See? IETF announced in advance that IPSEC was a good feature, and the working group members knew of that decision before they committed the resources needed to write the draft. And when they started, there were zero actual IPSEC implementations, because nobody knew what precise characteristics IPSEC would eventually have. The implementations got written in the process of developing the spec and presenting it as a standard. The two-implementation policy means there has to be two implementations before the draft is finally declared complete, not before the IETF can announce that it wants a standard to be written and intends to use whatever the working group comes up with once the draft and two implementations are done. That is what happens in any normal professional process. Nobody commits resources to develop something (other than for experimentation) unless they think the end result will actually be used. Are you really having trouble understanding this? > >>That's not true. PyCrypto does have AES support. > > That's not in any Python distro that I know of. > > Sure, but "Python" is more than the Python core. Tell me again what "batteries included" means. I personally interpret "included" as meaning "included". That means when I install Python, the module is right there in the distro. So if it's not in the distro, Python itself doesn't have it. "Batteries included" is an expression of Pythonic philosophy that says: putting components that end-users need in the distro is superior to making the users get them from somewhere else separately. I realize that the difference might not matter to you, but it does matter to a heck of a lot of other users. > With that attitude, the patches tracker on SF would grow unbounded, > because we *continuously* get patches that no core developer has > any personal interest in. Obviously those require a different type of consideration. I'm talking about patches where there's a core developer with an interest. Let's say the cmath module doesn't exist and someone submits it. It computes functions like cos(z) for complex arguments. If Tim, the numerics expert, then says "this is worth having and I've examined the code and it looks good, let's put it in", I'd say that takes care of it, and I think that's what typically happens with real modules. If nobody on the core team has an informed opinion, then it has to be decided some slower and more formal way. From steve at holdenweb.com Mon Jan 17 12:50:06 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 12:50:06 -0500 Subject: How to prevent the script from stopping before it should In-Reply-To: <1105982387.852448.298900@c13g2000cwb.googlegroups.com> References: <1105981979.853318.269300@c13g2000cwb.googlegroups.com> <1105982387.852448.298900@c13g2000cwb.googlegroups.com> Message-ID: wittempj at hotmail.com wrote: > #import urllib, sys > #pages = ['http://www.python.org', 'http://xxx'] > #for i in pages: > # try: > # u = urllib.urlopen(i) > # print u.geturl() > # except Exception, e: > # print >> sys.stderr, '%s: %s' % (e.__class__.__name__, e) > will print an error if a page fails opening, rest opens fine > More generally you may wish to use the timeout features of TCP sockets. These were introduced in Python 2.3, though Tim O'Malley's module "timeoutsocket" (which was the inspiration for the 2.3 upgrade) was available for earlier versions. You will need to import the socket module and then call socket.setdefaulttimeout() to ensure that communication with non-responsive servers results in a socket exception that you can trap. 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 peter at engcorp.com Sun Jan 23 19:12:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jan 2005 19:12:00 -0500 Subject: Set parity of a string In-Reply-To: References: Message-ID: snacktime wrote: > Is there a module that sets the parity of a string? I have an > application that needs to communicate with a host using even parity > So what I need is before sending the message, convert it from space to > even parity. And when I get the response I need to convert that from > even to space parity. By what means are the messages being delivered? I've rarely seen parity used outside of simple RS-232-style serial communications. Certainly not (in my experience, though it's doubtless been done) in TCP/IP based stuff. And if it's serial, parity can be supplied at a lower level than your code. As to the specific question: a module is not really required. The parity value of a character depends only on the binary value of that one byte, so a simple 128-byte substitution table is all you need, plus a call to string.translate for each string. -Peter From news at outbacklinux.com Tue Jan 11 03:25:48 2005 From: news at outbacklinux.com (Adrian Casey) Date: Tue, 11 Jan 2005 17:55:48 +0930 Subject: Command line and GUI tools : need a single threading solution References: <41e26e79@duster.adelaide.on.net> <34f9lfF4af717U1@individual.net> Message-ID: <41e38d8c@duster.adelaide.on.net> Diez B. Roggisch wrote: >> I'm thinking it may be possible to modify the command line tools to use >> qt >> threads instead of native python threads. Is this the way to go? Are >> there other options? > > Why don't you use python threads in qt - I do so and so far it didn't make > any troubles for me. And I would strongly advise against using qthreads > with your commandline-tools, as these then would only run on machines > where pyqt is installed - which opens a small part of "dependency hell" > for your users. > I have a QThread which polls a queue object via queue.get(). The command line tools spawn a number of threads each of which writes its output to this queue using queue.put(). As soon as the gui gets something off the queue, it creates a QCustomEvent and sets the data property with the data read from the queue. My application has a customEvent() method which reads the data item from the customEvent and processes it accordingly. The odd thing is, I have a non-threaded version of the command line tools which work 100% with the gui. The multi-threaded version of the command line tools all work OK at the console - just not with the gui. I will try your suggestion and replace my QCustomEvent mechanism with a plain python queue. From dalke at dalkescientific.com Fri Jan 7 01:04:01 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 07 Jan 2005 06:04:01 GMT Subject: Other notes References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> <41DD40F1.5030301@holdenweb.com> <41dda7c5.167823026@news.oz.net> Message-ID: Bengt Richter: > But it does look ahead to recognize += (i.e., it doesn't generate two > successive also-legal tokens of '+' and '=') > so it seems it should be a simple fix. But that works precisely because of the greedy nature of tokenization. Given "a+=2" the longest token it finds first is "a" because "a+" is not a valid token. The next token is "+=". It isn't just "+" because "+=" is valid. And the last token is "2". Compare to "a+ =2". In this case the tokens are "a", "+", "=", "2" and the result is a syntax error. > >>> for t in tokenize.generate_tokens(StringIO.StringIO('a=b+c; a+=2; x..y').readline):print t > ... This reinforces what I'm saying, no? Otherwise I don't understand your reason for showing it. > (51, '+=', (1, 8), (1, 10), 'a=b+c; a+=2; x..y') As I said, the "+=" is found as a single token, and not as two tokens merged into __iadd__ by the parser. After some thought I realized that a short explanation may be helpful. There are two stages in parsing a data file, at least in the standard CS way of viewing things. First, tokenize the input. This turns characters into words. Second, parse the words into a structure. The result is a parse tree. Both steps can do a sort of look-ahead. Tokenizers usually only look ahead one character. These are almost invariably based on regular expressions. There are many different parsing algorithms, with different tradeoffs. Python's is a LL(1) parser. The (1) means it can look ahead one token to resolve ambiguities in a language. (The LL is part of a classification scheme which summarizes how the algorithm works.) Consider if 1..3 were to be legal syntax. Then the tokenizer would need to note the ambiguity that the first token could be a "1." or a "1". If "1." then then next token could be a "." or a ".3". In fact, here is the full list of possible choices <1.> <.> <3> same as getattr(1., 3) <1> <.> <.> 3 not legal syntax <1.> <.3> not legal syntax <1> <..> <3> legal with the proposed syntax. Some parsers can handle this ambiguity, but Python's deliberately does not. Why? Because people also find it tricky to resolve ambiguity (hence problems with precedence rules). After all, should 1..2 be interpreted as 1. . 2 or as 1 .. 2? What about 1...2? (Is it 1. .. 2, 1 .. .2 or 1. . .2 ?) Andrew dalke at dalkescientific.com From aldo at nullcube.com Tue Jan 18 19:36:36 2005 From: aldo at nullcube.com (Aldo Cortesi) Date: Wed, 19 Jan 2005 11:36:36 +1100 Subject: inbuilt function buffer() In-Reply-To: <20050120101006.GA1496@mrna.tn.nic.in> References: <20050120101006.GA1496@mrna.tn.nic.in> Message-ID: <20050119003636.GA26701@nullcube.com> Thus spake km (km at mrna.tn.nic.in): > I which context is the inbuilt function buffer() used ? It's an efficiency measure. Say you have a string x. Taking a slice of the string - x[a:a+10] - will implicitly create a new string containing the specified data. Doing the same using buffer - buffer(x, a, 10) - will not. Essentially, buffer() gives you a window into a piece of contiguous data, without the cost of making a copy of the data you want to extract. To see how this might be useful, consider writing a simple web server. The web server reads a local file into memory, and then feeds it bit by bit to a socket until the data is exhausted. Without using buffer, the server would have to create a copy of each snippet of data fed to the socket. Using buffer, however, the copies are avoided, and the data can be consumed more efficently. The code below demonstrates this idea in an elementary fashion - on my system, "takebuf" runs about twice as fast as "take". ------ #!/usr/bin/env python2.3 import time SIZE = 1024*1024*50 data = "O"*SIZE def take(data): for i in range(0, SIZE, 1024): yield data[i:i+1024] def takebuf(data): for i in range(0, SIZE, 1024): yield buffer(data, i, 1024) def main(): start = time.time() for i in take(data): pass print "Plain:\t", time.time()-start start = time.time() for i in takebuf(data): pass print "Buffer:\t", time.time()-start if __name__ == "__main__": main() Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Off: (02) 9283 1131 Mob: 0419 492 863 From tzot at sil-tec.gr Wed Jan 26 12:09:29 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 26 Jan 2005 19:09:29 +0200 Subject: string.atoi and string.atol broken? References: <0ttev01qgb9k6a9f34g185lhohkn2p3evq@4ax.com> <4mffv0dqtj0dpjtsqn7lcf46ndc4ei9bc5@4ax.com> Message-ID: On Wed, 26 Jan 2005 18:07:39 +0100, rumours say that "Fredrik Lundh" might have written: >> You're messing with the time machine again, right? > >no, it was a subversion pilot error, this time. but now that you remind me, >I have to say that this > > http://mail.python.org/pipermail/python-list/2005-February/030720.html > >is a bit scary. I wonder from where I was posting that? And this post is what I was referring to with "again". -- 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 f18m_cpp217828 at yahoo.it Fri Jan 14 10:01:13 2005 From: f18m_cpp217828 at yahoo.it (Francesco Montorsi) Date: Fri, 14 Jan 2005 16:01:13 +0100 Subject: How to list the global functions from a C program Message-ID: <001101c4fa49$e545a5c0$5c673452@genius> Hi all, I'm a Python newbie and I'm trying to add to my C++ program a limited support for scripts written in python. In particular, I'd like to load user scripts written in python, list all the functions he defined in the script file and then call them. To begin I wrote into my C++ program (correctly linked to python 2.3.2): ============================================== /* create the main module */ m_pModule = PyImport_AddModule("__main__"); m_pDict = PyModule_GetDict(m_pModule); m_pGlobals = m_pDict; m_pLocals = m_pDict; // is this right (globals==locals) ?? /* to try out python, I want just to force the creation of a simple function and then call it from C */ PyRun_StringFlags("def donothing():\n\treturn 'hello'\n", Py_file_input, m_pGlobals, m_pLocals, 0); /* scan all the contents of the __main__ module... */ PyObject *list = PyObject_Dir(m_pGlobals); if (!list || PyList_Check(list) == FALSE) return; for (int i=0,max=PyList_Size(list); i Hi there, I just tried to run this code and failed miserably - though I dunno why. Could any of you please enlighten me why this doesn't work? Thanks a bunch. --- snip --- import unittest from datetime import datetime class time (datetime): def __init__(self, hours=0, minutes=0, seconds=0, microseconds=0): print "blah" datetime.__init__(self, 1, 1, 1, hours, \ minutes, seconds, microseconds) class Test (unittest.TestCase): def testSmoke(self): # print time() # bombs, and complains that # the time ctor needs at least 3 arguments self.assertEquals(datetime(1,1,1,1,2,3,4),time(1,2,3,4)) if __name__ == '__main__': unittest.main() --- snap --- The reason I want to do this is that I want to work with times but I want to do arithmetic with them. Therefore I cannot use the provided time directly. Now I thought, just overide the ctor of datetime so that year, month and day are static and everything should work as far as I need it. That is, it could work - though I seem to be unable to overide the ctor. :( Why is that? cu Martin -- Reach me at spamfaenger (at) gmx (dot) net From yuzx at livedoor.cn Fri Jan 14 02:54:13 2005 From: yuzx at livedoor.cn (yuzx) Date: Fri, 14 Jan 2005 15:54:13 +0800 Subject: test Message-ID: <1105689253.3167.0.camel@linux.tister.com> test From cce at clarkevans.com Thu Jan 13 23:37:23 2005 From: cce at clarkevans.com (Clark C. Evans) Date: Thu, 13 Jan 2005 23:37:23 -0500 Subject: file uploading via urllib2 (multipart/form-data) Message-ID: <20050114043723.GA42184@prometheusresearch.com> Hello. I was wondering if anyone has built a module that works with urllib2 to upload file content via POST multipart/form-data. I'm aware of ASPN 146306, however, I need to use urllib2 beacuse I'm using HTTP Digest over SSL. Cheers, Clark From me at no-spam.org Fri Jan 7 23:12:59 2005 From: me at no-spam.org (Michael) Date: Fri, 07 Jan 2005 21:12:59 -0700 Subject: Python/Qt Problem Message-ID: Hi, I am experiencing something very weird with PyQt. I have created several windows based on QWidget using Designer. I can easily hide and show these with the hide and show methods. However I have just created a new window with Designer and the show method works in my main script but not inside the button action method (not using proper temrinology, sorry) of another window. Why is that? This works fine for the other windows. Have I explained my problem properly? Thanks for any advice, Michael From tim.peters at gmail.com Mon Jan 10 21:15:50 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 10 Jan 2005 21:15:50 -0500 Subject: Securing a future for anonymous functions in Python In-Reply-To: <1oFEd.71967$Jk5.45632@lakeread01> References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <1105381339.922714.23200@c13g2000cwb.googlegroups.com> <1oFEd.71967$Jk5.45632@lakeread01> Message-ID: <1f7befae0501101815572999ae@mail.gmail.com> ... [Anna] >> BTW - I am *quite* happy with the proposal for "where:" syntax - I >> think it handles the problems I have with lambda quite handily. [Steve Holden] > Whereas I find it to be an excrescence, proving (I suppose) that one > man's meat is another person's poison, or something. I've been waiting for someone to mention this, but looks like nobody will, so I'm elected. Modern functional languages generally have two forms of local-name definition, following common mathematical conventions. "where" was discussed here. The other is "let/in", and seems a more natural fit to Python's spelling of block structure: let: suite in: suite There's no restriction to expressions here. I suppose that, like the body of a class, the `let` suite is executed starting with a conceptually empty local namespace, and whatever the suite binds to a local name becomes a temporary binding in the `in` suite (like whatever a class body binds to local names becomes the initial value of the class __dict__). So, e.g., i = i1 = 3 let: i1 = i+1 from math import sqrt in: print i1, sqrt(i1) print i1, print sqrt(i1) would print 4 2 3 and then blow up with a NameError. LIke it or not, it doesn't seem as strained as trying to pile more gimmicks on Python expressions. From steve at holdenweb.com Wed Jan 12 18:46:32 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 12 Jan 2005 18:46:32 -0500 Subject: Why would I get a TypeEror? In-Reply-To: References: Message-ID: It's me wrote: > For this code snip: > > a=3 > ..... > b=(1,len(a))[isinstance(a,(list,tuple,dict))] > > Why would I get a TypeError from the len function? > > Thanks, > > because the interpreter evaluates the tuple (1, len(a)) before applying the indexing to it. You are trying to be far too clever. The standard way to write this would be: a = 3 .... b = 1 if isinstance(a,(list,tuple,dict)): b = len(a) Is code length *really* so important? Think carefully ... 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 dscottr at bellatlantic.net Fri Jan 7 16:08:46 2005 From: dscottr at bellatlantic.net (Scott Robinson) Date: Fri, 07 Jan 2005 21:08:46 GMT Subject: The Industry choice References: <10trej2fl8dip65@corp.supernews.com> <10ttqk8k1e64495@corp.supernews.com> Message-ID: On Fri, 07 Jan 2005 12:06:42 -0800, Jeff Shannon wrote: >Bulba! wrote: > >> On 6 Jan 2005 19:01:46 -0500, aahz at pythoncraft.com (Aahz) wrote: >> >> >>>>Note that the so-called 'viral' nature of GPL code only applies to >>>>*modifications you make* to the GPL software. The *only* way in which >>>>your code can be 'infected' by the GPL is if you copy GPL source. >> >> >>>That's not true -- consider linking to a GPL library. >> >> >> Will someone please explain to me in simple terms what's >> the difference between linking to LGPLed library and linking >> to GPLed library - obviously in terms of consequences of >> what happens to _your_ source code? >> >> Because if there isn't any, why bother with distinguishing >> between the two? > >Releasing a product in which your code is linked together with GPL'ed >code requires that your code also be GPL'ed. The GPL goes to some >lengths to define what exactly "linked together" means. That looks like a typo. The LGPL goes to great length to how you can link to LGPL software without using either the LGPL or GPL. The GPL (linked to by fsf.org) merely states: 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: Note that the conditions are all those of any program released under the GPL. Whatever "forming a work based on the Program" means is whatever you and the copyright owner agree to, or whatever copyright law considers a derived work in areas you wish to release your code into. I would suggest consulting a lawyer before getting close to the line, but you can expect that any legally enforceable restrictions claimed by FSF and/or RMS to be legally binding on all software released under the (L)GPL that the FSF owns the copyright of (they encourage programmers to sign over copyright to the FSF itself). > >Releasing a product in which your code is linked together with LGPL'ed >code does *not* require that your code also be (L)GPL'ed. Changes to >the core library must still be released under (L)GPL, but application >code which merely *uses* the library does not. (I've forgotten, now, >exactly how LGPL defines this distinction...) > >Jeff Shannon >Technician/Programmer >Credit International Scott Robinson From news at NOwillmcguganSPAM.com Mon Jan 31 13:12:29 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Mon, 31 Jan 2005 18:12:29 +0000 Subject: stop program in komodo In-Reply-To: <1107194102.482439.272480@c13g2000cwb.googlegroups.com> References: <1107194102.482439.272480@c13g2000cwb.googlegroups.com> Message-ID: <41fe750e$0$327$db0fefd9@news.zen.co.uk> ajikoe at gmail.com wrote: > Hello, > How can we stop this peace of code in KOMODO: > while 1: > print "helo" > > I can't stop it, even using Ctrl+C Are you sure that is what is happening? When I tried it, it appeared as though nothing had happened after pressing the break button. But it was just that the buffer had filled up with a squillion "helo"'s and was busy scrolling away.. Regards, Will McGugan From bob_smith_17280 at hotmail.com Sun Jan 16 11:53:11 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sun, 16 Jan 2005 11:53:11 -0500 Subject: protecting the python code. In-Reply-To: <1105893393.214111.227550@f14g2000cwb.googlegroups.com> References: <1105884196.461107.28120@z14g2000cwz.googlegroups.com> <41EA92A7.3080706@holdenweb.com> <1105893393.214111.227550@f14g2000cwb.googlegroups.com> Message-ID: nell wrote: > Hi Steve, > First the "10x in advance" means thanks in advance. > The main importance of protecting my code is to save headache of > customers that want to be smart and change it and then complain on bugs > and problems. > > 10x > I'd say that's more of a policy issue than a technical issue. You have a contract or agreement with your customers, right? Just place a cluase in it that addresses your concerns. You don't have to support people who have altered your code... nor should they expect to be supported. From cartermark46 at ukmail.com Mon Jan 10 08:15:19 2005 From: cartermark46 at ukmail.com (Mark Carter) Date: Mon, 10 Jan 2005 13:15:19 +0000 Subject: Port blocking In-Reply-To: <34f8ovF47d783U1@individual.net> References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> <34f8ovF47d783U1@individual.net> Message-ID: <34fdf6F4a7t7uU1@individual.net> Mark Carter wrote: > Paul Rubin wrote: >> Usually you wouldn't run a public corba or pyro service over the >> internet. You'd use something like XMLRPC over HTTP port 80 partly >> for the precise purpose of not getting blocked by firewalls. I'm not sure if we're talking at cross-purposes here, but the application isn't intended for public consumption, but for fee-paying clients. From newgene at bigfoot.com Wed Jan 12 21:54:30 2005 From: newgene at bigfoot.com (Newgene) Date: 12 Jan 2005 18:54:30 -0800 Subject: Dynamically add class method causes "SystemError: ... bad argument to internal function" References: <1105572079.630658.242210@c13g2000cwb.googlegroups.com> Message-ID: <1105584870.519768.17210@f14g2000cwb.googlegroups.com> I have noticed that the exception was caused by the call of "self.f()" within my "_generic" function. It will raise SystemError exception whenever I refer to any method or attribute of "self" within "_generic" function. Otherwise, dynamically adding method works fine. I cannot figure out what's the reason there. CW From dbickett at gmail.com Sun Jan 23 07:56:45 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 23 Jan 2005 07:56:45 -0500 Subject: What YAML engine do you use? In-Reply-To: <_cSdnRo1keDOzm7cRVn-ug@comcast.com> References: <35a6tpF4gmat2U1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> <_cSdnRo1keDOzm7cRVn-ug@comcast.com> Message-ID: <1d6cdae3050123045614dfa11@mail.gmail.com> Doug Holton wrote: > You might like programming in XML then: http://www.meta-language.net/ > :) http://www.meta-language.net/sample.html#class-metal I'm not so sure ;-) Daniel Bickett From rowen at cesmail.net Mon Jan 24 15:20:43 2005 From: rowen at cesmail.net (Russell E. Owen) Date: Mon, 24 Jan 2005 12:20:43 -0800 Subject: tkinter socket client ? References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> <1106318469.311179.126140@c13g2000cwb.googlegroups.com> <1106319270.932204.180590@c13g2000cwb.googlegroups.com> Message-ID: In article <1106319270.932204.180590 at c13g2000cwb.googlegroups.com>, "Tonino" wrote: >yeah - had a look at createfilehandler() - was a bit confusing - but >your example helps ;) Be warned that createfilehandler does not work on Windows, though it works well on unix and MacOS X. So my suggestion is one to try any of these (any of which are preferable to threads): - file handlers for non-Windows code - use tcl sockets for cross-platform code. - use Twisted Framework (some work to learn, but supposedly very solid; I confess I've never used it myself). There is a bit of info on the first two options (including a link to the RO package that includes a python interface to tcl sockets) here: -- Russell From adam at cognitcorp.com Tue Jan 4 22:38:12 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Tue, 04 Jan 2005 22:38:12 -0500 Subject: what is lambda used for in real code? In-Reply-To: References: Message-ID: <1104892918.5050.7.camel@localhost.localdomain> On Fri, 2004-12-31 at 17:36, Steven Bethard wrote: > Adam DePrince wrote: > > Lets not forget the "real reason" for lambda ... the elegance of > > orthogonality. Why treat functions differently than any other object? > > > > We can operate on every other class without having to involve the > > namespace, why should functions be any different? > > Yup. I think in most of the examples that I didn't know how to rewrite, > this was basically the issue. On the other hand, I do think that > lambdas get overused, as indicated by the number of examples I *was* > able to rewrite.[1] > > Still, I have to admit that in some cases (especially those involving > reduce), I wish the coder had named the function -- it would have given > me a little bit more documentation as to what the code was trying to do. This is a long standing philosophical issue that really shouldn't impose itself on the language. Do you document, and risk that the documentation doesn't match the code, or do you use the code itself as documentation. Leaving, or even expanding upon, anonymous functions permits the programmer to choose their stance in the above debate; you can still write # If I had to give this function a name, it would be ... before or after the lambda to elect the former option. The removal of anonymous functions, however, forces the former option. Even if option latter is misguided, one of the guiding principles of Python is that we are all consenting adults free to do dumb things. - Adam Adam DePrince From ola.natvig at infosense.no Wed Jan 12 11:39:06 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Wed, 12 Jan 2005 17:39:06 +0100 Subject: Removing M2Crypto debug data in production code Message-ID: <41E552AA.70001@infosense.no> Hi all I'm writing a SSL server and we are using M2Crypto as our SSL engine. What bothers me is that on every accept it prints a lot of 'junk-data' to my stdout. It would be nice if someone knew a way to get M2Crypto out of debug mode and into a more silent mode. LOOP: SSL accept: before/accept initialization LOOP: SSL accept: SSLv3 read client hello A LOOP: SSL accept: SSLv3 write server hello A LOOP: SSL accept: SSLv3 write certificate A LOOP: SSL accept: SSLv3 write key exchange A LOOP: SSL accept: SSLv3 write server done A LOOP: SSL accept: SSLv3 flush data LOOP: SSL accept: SSLv3 read client key exchange A LOOP: SSL accept: SSLv3 read finished A LOOP: SSL accept: SSLv3 write change cipher spec A LOOP: SSL accept: SSLv3 write finished A LOOP: SSL accept: SSLv3 flush data INFO: SSL accept: SSL negotiation finished successfully regards Ola Natvig -- -------------------------------------- Ola Natvig infoSense AS / development From carribeiro at gmail.com Tue Jan 4 12:22:28 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 4 Jan 2005 15:22:28 -0200 Subject: How can engineers not understand source-code control? In-Reply-To: <41dabba1$0$47624$ed2619ec@ptn-nntp-reader02.plus.net> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41da713a$0$610$ed2619ec@ptn-nntp-reader03.plus.net> <41dabba1$0$47624$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <864d3709050104092224047787@mail.gmail.com> On Tue, 04 Jan 2005 15:52:03 +0000, Mark Carter wrote: > I'm thinking that the I-Ching is a vast untapped resource for > programming wisdom, plus it makes it funny. LOL! +1 QOTW! -- 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 aleaxit at yahoo.com Thu Jan 27 13:09:57 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Jan 2005 19:09:57 +0100 Subject: Please suggest on the book to follow References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> Message-ID: <1gr29gd.nnwb87holh83N%aleaxit@yahoo.com> wrote: > "santanu" writes: > > I know a little python (not the OOP part) learnt by studying the online > > tutorial. Now I would like to learn it more thoroughly. > > I think there's supposed to be a new version of Python in a Nutshell Just a 2nd edition. I'm just starting to write it. By the time it's done and out in print, say six months if you're a VERY optimistic guy, I'm pretty sure "santanu" will be an experienced Pythonista and quite ready to take advantage, if he chooses, of the Nutshell's 2nd edition as a convenient desktop reference, which is its main intended role. > coming. That's a more serious book than Learning Python. Speaking as the author of the Nutshell, and a TR for Learning, I think I'm reasonably unbiased (or, equally biased in favor of both;-), and I don't think of Learning as ``less serious'' -- it does have a different role, of course. If a book whose title is "Learning X" (for any X) does its job well, then when you're done with it you can probably put it aside -- as Wittgenstein said of the learner, "he must so to speak throw away the ladder, after he has climbed up on it". A book that is meant mostly as a convenient reference, if _it_ does its job, keeps being useful for a longer time. On the other hand, using the Nutshell for the purpose of learning Python, while certainly feasible if you're well skilled in computer programming (in other languages), may not be as easy as using "Learning Python" for that purpose! All in all, while I'm of course gladder the more copies of the Nutshell are sold, I still think that, for the _learning_ part, most people might be better served by "Learning Python" -- or, for that matter, the already recommended "Practical Python" (it has many significant completely worked-out example programs -- I was a TR for it, too) or "Dive into Python" (VERY fast and meant for already-experienced programmers -- I wasn't a TR for it, but, my _wife_ was...;-) Alex From fpm at u.washington.edu Mon Jan 31 11:02:24 2005 From: fpm at u.washington.edu (Frank Miles) Date: Mon, 31 Jan 2005 16:02:24 +0000 (UTC) Subject: Best python postgres module? References: Message-ID: In article , Robert Brewer wrote: >Roland Heiber wrote: >> i recently migrated from mysql to postgresql and did use >> severel python >> postgres-modules. All do what they are designed for, so >> which one would >> you use? psycopg, pygresql, pypgsql? psycopg seems to be the best >> solution for heavy traffic/multiple connections .... i have no real >> testing environment, so any advice which one to use for different >> usecases would be nice. > >If your "use cases" involve cross-platform development (i.e. Linux and >Windows), pypgsql seems to fit the bill nicely. psycopg is available for WinXX as well, though I'm not sure how long it takes for bleeding-edge (development versions) to get to WinXX. -frank -- From apardon at forel.vub.ac.be Mon Jan 17 09:51:55 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2005 14:51:55 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-17, Just schreef : > In article , > Antoon Pardon wrote: > >> Op 2005-01-17, Steve Holden schreef : > >> > There you go with the minutiae again. How about: >> > >> > "Don't use mutables as hash keys"? >> >> That sounds too dogmatic to my ears. I also find it >> too selective. The problem with mutables as dictionary >> keys is not specific to dictionaries. Everywhere you >> have mutables in a container, it is possible that >> mutating the object in the container will cause >> problem. > > The main difference is: if you mutate a dict key you *always* have a > problem. So don't do that. Mutating (say) a list item *only* is a > problem if you (say) need that list to remain sorted. That is not true. It is a problem every time I expect the list items to remain the same. > Lists don't > magically remain sorted, so people generally sort it before they do some > operation that expects a sorted list. > >> Heck even using mutables as arguments can >> cause trouble. Why else the specific advice against >> >> def foo(p = []) >> >> type of arguments. So should we adopt the principles: >> >> Don't use mutables in containers > > Nonsense. > >> Don't use mutables as default values for parameters > > That's good advice in general. > >> Don't use mutables as arguments. > > Nonsense. > >> Don't assign one mutable to an other. > > Nonsense. Some newbies get surprised by Python's assignment-doesn't-copy > semantics, but it's such basic knowledge (as well as a useful feature) > that I simply don't understand you saying this. Well it is this same sematics that causes the problems with mutable dictionary keys. If it is such basic knowledge then what is the problem with mutable dictionary keys? >> I don't see a big difference between these principles >> and the hash key principle, > > Than you haven't looked hard enough. All of these can get unexpected behaviour because of the assignment-doesn't-copy semantics. The same semantics that can cause problems if you work with mutable dictionary keys. >> so in the end may be we >> should just stick with the more general principle: >> >> Don't use mutables! >> >> and be done with it. > > Ok, so you're indeed a troll. The problems with mutables as dictionary keys is just one particulary case of the problems you can have when your assignmentxs semantics just creates a new reference to the same object. As such it is no different from the problem of mutating one object and finding out this object was also reference through an other name you expected to remain the same or finding out this object was also in a list you expected to remain stable etc. -- Antoon Pardon From ncoghlan at iinet.net.au Fri Jan 21 08:33:04 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 21 Jan 2005 23:33:04 +1000 Subject: Class introspection and dynamically determining function arguments In-Reply-To: <359nmoF4koiepU1@individual.net> References: <359lfnF4hd6e3U1@individual.net> <359nmoF4koiepU1@individual.net> Message-ID: <41F10490.2070805@iinet.net.au> Diez B. Roggisch wrote: > Nick Coghlan wrote: > >>If this only has to work for classes created for the purpose (rather than >>for an arbitrary class): >> > > > Certainly a step into the direction I meant - but still missing type > declarations. And that's what at least I'd like to see - as otherwise you > don't know what kind of editing widget to use for a property. Hmm, true. You really need a name:type dict to define each class that is going to be generated. Perhaps the simplest way is to require all such classes to have a "getExample" class method that produces a fully populated example instance (making it a class method means that you shouldn't need to override it in a subclass if you don't change the signature of __init__). Then the widget generator doesn't need to care about *how* that default example gets generated, and can be something simple like: build_widget(name, data_type): ... build_widget_list(cls): example = cls.getExample() widgets = [] for attr, value in example.__dict__: widgets.append(build_widget(attr, type(value))) return widgets Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ssaeed1973 at yahoo.com Sun Jan 30 15:30:34 2005 From: ssaeed1973 at yahoo.com (ssaeed1973 at yahoo.com) Date: 30 Jan 2005 12:30:34 -0800 Subject: Need programming tip In-Reply-To: <1gr74ck.kncteuqczambN%aleaxit@yahoo.com> References: <1107071340.486489.146580@f14g2000cwb.googlegroups.com> <1gr74ck.kncteuqczambN%aleaxit@yahoo.com> Message-ID: <1107117034.953473.12670@c13g2000cwb.googlegroups.com> Alex, Thanks, I will try this. Salman From peter at engcorp.com Sun Jan 9 13:59:12 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 13:59:12 -0500 Subject: windows mem leak In-Reply-To: References: <41XDd.70234$Jk5.40626@lakeread01> <41E06C18.6050407@hotmail.com> Message-ID: Bob Smith wrote: > Peter Hansen wrote: [snip details of Bob's platform] > WinXP Home, Service Pack 2, AMD 1400MHz proc, 256MB Ram That's not really much RAM for a WinXP box. Do you have lots of physical memory available before running? >> (I presume you're using a version of nmap that's compiled >> for Windows XP then? > Yes, I am. > >> It's certainly not standard. > That's a matter of opinion. Nmap works fine on the WinXP machine. Perhaps my use of "standard" was obscure, since it's definitely not a matter of opinion, the way I intended it. What I meant was "nmap is certainly not included in the standard Win XP distribution". >> How have >> you proven that it is not *that* program which is at fault?) > > I have not. All I know is that on WinXP, the program uses 100% CPU at > times and consumes more Ram than is available (the page file grows to > 700 or 800MB). It runs OK for a few hours and then produces a 'not > enough resources' error. Is it certain that this memory is being consumed by the Python process? I could imagine, for example, there being dozens of new processes spawned with os.system. Does the Task Manager back up the theory that this "python.exe" instance is the one causing the trouble? Presumably it should be clear even before the machine grows unusable. Note that you can select which columns are shown in the "Processes" tab of the Task Manager window, to get more detail on a given process. (The Performance Monitor found under Control Panel, Administrative Tools can be even more useful and precise.) > And, the machine is generally unuserable. On > Linux, it has no impact whatsoever on resources. Granted, the Linux > machine is much more robust, but one wouldn't expect this great a > difference. I can rewrite it so that it's pure Pyhton (no calling nmap) > if you think that would be a good idea. Perhaps that would at least > remove nmap from the equation. A simpler test might be to change the nmap call to something guaranteed benign, like a call to "dir", and try with that. That's assuming you don't actually need the output of nmap to reproduce the problem, which of course isn't sure. Still, it would be an easy test, and might show a problem elsewhere. > I can run it if you like and take a screen shot of the error. You'll > have to give me a few hours though ;) I trust that you are getting the error dialog you say you are. :-) I have a feeling that the message by itself helps little, however, and that you'll have to try a few different approaches to observe the problem as it grows, via Task Manager or another tool, rather than just trying to guess what happened after the machine is already effective kaput. -Peter From deetsNOSPAM at web.de Thu Jan 20 07:12:39 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 20 Jan 2005 13:12:39 +0100 Subject: Class introspection and dynamically determining function arguments References: Message-ID: <359lfnF4hd6e3U1@individual.net> Mark English wrote: > The only way I can imagine to do this is to create an instance of the > class in question, and then start poking around in its attributes > dictionary (initially just using dir). So firstly, if there is instead a > way to do this without creating an instance I'd be interested. This is the only way to go, as python has no attribute declarations as static compiled languages have. But of course not all classes may feature default constructors so that creating an instance is impossible. Or you create unwanted sideeffects - think of the notorious class DeleteMyHarddisk.... As youself already mentioned that maybe you have to impose certain prerequisites, you maybe want to extend this to the point where for each class you want to make dynamically instantiatable you need some declaration. This of course depends on your desired application - whatfor is it planned? -- Regards, Diez B. Roggisch From sjmachin at lexicon.net Sun Jan 23 04:49:08 2005 From: sjmachin at lexicon.net (John Machin) Date: 23 Jan 2005 01:49:08 -0800 Subject: getting file size References: <6qc6v0hhfedf0uncp9gieahj38srh46khk@4ax.com> Message-ID: <1106460795.516946.246150@f14g2000cwb.googlegroups.com> Tim Roberts wrote: > Bob Smith wrote: > > >Are these the same: > > > >1. f_size = os.path.getsize(file_name) > > > >2. fp1 = file(file_name, 'r') > > data = fp1.readlines() > > last_byte = fp1.tell() > > > >I always get the same value when doing 1. or 2. Is there a reason I > >should do both? When reading to the end of a file, won't tell() be just > >as accurate as os.path.getsize()? > > On Windows, those two are not equivalent. Besides the newline conversion > done by reading text files, Doesn't appear to me to go wrong due to newline conversion: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 >>> import os.path >>> txt = 'qwertyuiop\nasdfghjkl\nzxcvbnm\n' >>> file('bob', 'w').write(txt) >>> len(txt) 29 >>> os.path.getsize('bob') 32L ##### as expected >>> f = file('bob', 'r') >>> lines = f.readlines() >>> lines ['qwertyuiop\n', 'asdfghjkl\n', 'zxcvbnm\n'] >>> f.tell() 32L ##### as expected > the solution in 2. will stop as soon as it sees > a ctrl-Z. ... and the value returned by f.tell() is not the position of the ctrl-Z but more likely the position of the end of the current block -- which could be thousands/millions of bytes before the physical end of the file. Good ol' CP/M. > > If you used 'rb', you'd be much closer. And be much less hassled when that ctrl-Z wasn't meant to mean EOF, it just happened to appear in an unvalidated data field part way down a critical file :-( From bj_666 at gmx.net Mon Jan 3 17:59:26 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 03 Jan 2005 23:59:26 +0100 Subject: XML: Better way to accomplish this? References: <1104728060.417168.277780@c13g2000cwb.googlegroups.com> Message-ID: In <1104728060.417168.277780 at c13g2000cwb.googlegroups.com>, flamesrock wrote: > # > # > [...] > # > # > [...] > # > # > [...] > # > # Don't you think it's better to use an attribute for the city nr.? Something like ````. At least if you intent to write a DTD or Schema this might be better. Ciao, Marc 'BlackJack' Rintsch From peter at engcorp.com Tue Jan 4 22:16:32 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 Jan 2005 22:16:32 -0500 Subject: Python evolution: Unease In-Reply-To: <7xoeg4txrp.fsf@ruckus.brouhaha.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Jeremy Bowers writes: >>So, nobody should have to write the docs because they should already be >>there, but "somebody" should have to write the docs? >> >>You need to think more clearly about the pronouns you are slinging around. >>Who is this "they" that should write the docs? > > The Python advocates who claim that Python is well-documented and take > exception to when someone say it isn't. Their idea of "it's > well-documented" seems to be "if there's parts that you think are > poorly documented, feel free to document it". What kind of nonsense > is that? "Python code runs just as fast as C code. If you think it's > slower, feel free to speed it up". "Python's standard library > includes a database module. If it isn't there, feel free to add one". > "Programming in Python cures cancer. If your cancer doesn't clear up > when you code in Python, feel free to submit a patch". I think you're throwing out strawman arguments here. The key distinction is that "well-documented" is clearly a judgment call, a personal opinion, while the others are all measurable absolutes. (The "as fast as C" one borders on being an opinion, since most people actually say things that mean something more like "as fast as I need it to, so C has no advantage".) Saying, in effect, as they are, "Python's docs are well enough documented for my purposes and, I believe, for those of many other people" certainly isn't nonsense, and saying "and if you don't agree you should consider improving them yourself instead of asking me or others who feel as I do" is certainly not nonsense. > And no, I don't feel a responsibility to do the missing work, since > I'm not the one making those advocacy claims. So those who claim Python is well-documented are the ones who should improve the documentation, but those claiming that the documentation is poor should feel no responsibility to make the improvements? Does this make any sense to you? To me, *this* is the nonsense. -Peter From fredrik at pythonware.com Mon Jan 17 10:30:24 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Jan 2005 16:30:24 +0100 Subject: Install Python 2.4 on Fedora 3 Core References: <1105975262.047782.6010@z14g2000cwz.googlegroups.com> Message-ID: "Bill" wrote: > 2. I looked in the package editor and there was no way to uninstall > 2.3? Should I? If so, how can I? If not,what are the problems, if > any, of having both. if your OS comes with Python, there's a certain chance that it includes utilities that rely on a specific Python version. removing or replacing that version is usually a rather bad idea. having multiple Python installations on a machine is usually no problem at all. From claird at lairds.us Mon Jan 3 10:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Mon, 03 Jan 2005 15:08:04 GMT Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><7xekh423b6.fsf@ruckus.brouhaha.com> <_rTBd.66275$Jk5.46@lakeread01> Message-ID: In article , Terry Reedy wrote: > >"Steve Holden" wrote in message >news:_rTBd.66275$Jk5.46 at lakeread01... >> Well clearly there's a spectrum. However, I have previously written that >> the number of open source projects that appear to get stuck somewhere >> between release 0.1 and release 0.9 is amazingly large, and does imply >> some dissipation of effort. > >And how do the failure and effort dissipation rates of open source code >compare to those of closed source code? Of course, we have only anecdotal >evidence that the latter is also 'amazingly large'. And, to be fair, the >latter should include the one-programmer proprietary projects that >correspond to the one-programmer open projects. > >Also, what is 'amazing' to one depends on one's expectations ;-). It is >known, for instance, that some large fraction of visible retail business >fail within a year. And that natural selection is based on that fact that . . . The usual measurements and estimates are generally between 15% and 30%. "Desirable" businesses--restaurants, for example, or computing consultancies--are even more likely to fail. From klingens at web.de Mon Jan 17 09:13:07 2005 From: klingens at web.de (A. Klingenstein) Date: Mon, 17 Jan 2005 15:13:07 +0100 Subject: Native widgets for Python Message-ID: <41EBC7F3.5050807@web.de> Which other GUI library for Python other than wxpython has native widgets for MS Windows ? I know there is MFC and GDI, but I want something easier to use than wx, not harder :) wxpython has to problem that it handles much more like a C++ library than a Python one sometimes. Alex From aahz at pythoncraft.com Sun Jan 2 12:07:57 2005 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2005 12:07:57 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> Message-ID: In article , Steve Holden wrote: >Aahz wrote: >> In article <7xacrs230c.fsf at ruckus.brouhaha.com>, >> Paul Rubin wrote: >>> >>>I was pretty skeptical of Java's checked exceptions when I first used >>>them but have been coming around about them. There's just been too >>>many times when I wrote something in Python that crashed because some >>>lower-level function raised an exception that the upper level hadn't >>>been expecting, after the program had been in use for a while. I'd >>>sure rather find out about that at compile time. >> >> That's funny -- Bruce Eckel talks about how he used to love checked >> exceptions but has come to regard them as the horror that they are. >> I've learned to just write "throws Exception" at the declaration of >> every method. > >Pretty sloppy, though, no? And surely the important thing is to have a >broad handler, not a broad specification of raisable exceptions? Yes, it's sloppy, but I Don't Care. I'm trying to write usable code while learning a damnably under-documented Java library -- and I'm *not* a Java programmer in the first place, so I'm also fighting with the Java environment. Eventually I'll add in some better code. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From invalidemail at aerojockey.com Fri Jan 28 19:18:48 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 28 Jan 2005 16:18:48 -0800 Subject: what's OOP's jargons and complexities? In-Reply-To: References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: <1106957928.805628.69820@z14g2000cwz.googlegroups.com> Dan Perl wrote: > I will not get into your "history" of the "OOP hype". The best thing to is just ignore him. But, if he bothers you too much to let it slide, then don't take issue with anything he writes. Just post a follow-up warning the newbies that he's a pest, that his claims are untrue and his advice is not good, and that he appears that his posts are just trolling in disguise. (Or, you could do what I do when I feel a need to reply: follow-up with a Flame Warriors link. For Xah, it would probably be this: http://tinyurl.com/4vor3 ) -- CARL BANKS From richie at entrian.com Fri Jan 28 07:26:13 2005 From: richie at entrian.com (Richie Hindle) Date: Fri, 28 Jan 2005 12:26:13 +0000 Subject: Who should security issues be reported to? In-Reply-To: References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> Message-ID: [Duncan] > I'm intrigued how you managed to come up with something you > consider to be a security issue with Python since Python offers no > security. Perhaps, without revealing the actual issue in question, you > could give an example of some other situation which, if it came up in > Python you would consider to be a security issue? I can't speak for the OP, but one hypothetical example might be a buffer overrun vulnerability in the socket module. -- Richie Hindle richie at entrian.com From ola.natvig at infosense.no Thu Jan 27 08:02:19 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Thu, 27 Jan 2005 14:02:19 +0100 Subject: Please suggest on the book to follow In-Reply-To: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> Message-ID: santanu wrote: > Hi all, > > I know a little python (not the OOP part) learnt by studying the online > > tutorial. Now I would like to learn it more thoroughly. > > I have access to 'Programming Python' which I liked (on flipping > through the > pages), but the problem is it deals only with version 2.0 of Phython. > > So, I would be glad if you could suggest me whether it would be really > a good > idea to learn from this book. In other words, will I have to unlearn > too much > after I complete this book (by the time I am done with this book, I > believe > we will be having Python 2.6 or so). > > Please suggest. > > Regards, > Santanu > I realy would recomend Practival Python it's a wery good book which I think it's written for 2.2 or 2.3, but it's got all the basic modern python aspects like new style classes. http://www.amazon.com/exec/obidos/tg/detail/-/1590590066/qid=1106830797/sr=8-1/ref=sr_8_xs_ap_i1_xgl14/104-9460635-7128701?v=glance&s=books&n=507846 -- -------------------------------------- Ola Natvig infoSense AS / development From vincent at visualtrans.de Tue Jan 18 01:08:57 2005 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 18 Jan 2005 07:08:57 +0100 Subject: how to find site-packages path (Michael Hoffman) - use distutils In-Reply-To: References: Message-ID: Philippe C. Martin wrote: >>>The flawless way would be to use distutils. In fact you shouldn't even >>>need your own install script--it should do most of the work for you. > > > The reason I have not so far is I have not found a way to get what I > want done: > > 1) create directories in site-packages (I gather this shoudl be easy > enough) > 2) copy already compiled (.pyc) and source (.py) files to those > directories Why would you want to copy any *.pyc instead of compiling them on site? -- Vincent Wehren > 3) create directories and copy files in a directory kept in an > environment variable > > > Can distutils do this for me? > > > Regards, > > Philippe > > > > > From prakis at gmail.com Sat Jan 22 06:40:57 2005 From: prakis at gmail.com (kishore) Date: 22 Jan 2005 03:40:57 -0800 Subject: dynamic call of a function In-Reply-To: References: <3BCFE666.C8C6136C@c-s.fr> Message-ID: <1106394057.320879.319110@f14g2000cwb.googlegroups.com> Hi Luigi Ballabio, Thankyou very much for your reply, it worked well. Kishore. Luigi Ballabio wrote: > At 10:37 AM 10/19/01 +0200, anthony harel wrote: > >Is it possible to make dynamic call of a function whith python ? > > > >I have got a string that contains the name of the function I > >want to call but I don't want to do something like this : > > > >if ch == "foo" : > > self.foo( ) > >elif ch == "bar" > > self.bar( ) > >.... > > Anthony, > here are two ways to do it---I don't know which is the best, nor > whether the best is yet another. Also, you might want to put in some error > checking. > > class Test: > def foo(self): > print 'Norm!' > def bar(self): > print 'Dum-de-dum' > def dynCall1(self,methodName): > eval('self.%s()' % methodName) > def dynCall2(self,methodName): > method = vars(self.__class__)[methodName] > method(self) > > >>> t = Test() > >>> t.dynCall1('foo') > Norm! > >>> t.dynCall2('bar') > Dum-de-dum > > Bye, > Luigi From Mark.English at liffe.com Mon Jan 24 06:05:34 2005 From: Mark.English at liffe.com (Mark English) Date: Mon, 24 Jan 2005 11:05:34 -0000 Subject: Class introspection and dynamically determining function arguments Message-ID: <40E605146701DE428FAF21286A97D309022FC92E@wphexa02.corp.lh.int> Thanks for the pointers to traits, BasicProperty, and harold fellermann's sample code... ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From FBatista at uniFON.com.ar Mon Jan 24 11:51:13 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 24 Jan 2005 13:51:13 -0300 Subject: Tuple slices Message-ID: [George Sakkis] #- Why does slicing a tuple returns a new tuple instead of a #- view of the existing one, given that #- tuples are immutable ? I ended up writing a custom #- ImmutableSequence class that does this, but I #- wonder why it is not implemented for tuples. What exactly is "a view of the existing one"? And how do you return it without creating a new object? Could you send an example? Thanks. . 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 pierre.barbier at cirad.fr Tue Jan 18 04:01:02 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Tue, 18 Jan 2005 10:01:02 +0100 Subject: extension module, thread safety? In-Reply-To: References: <41ecbaae$0$1046$626a14ce@news.free.fr> Message-ID: <41eccfe4$0$16621$636a15ce@news.free.fr> Nick Coghlan a ?crit : > Pierre Barbier de Reuille wrote: > >> With the current CPython, it's very hard to mix Python and C in a >> multithreading application (with C-threads, not Python-threads). In >> fact I never really succeeded in that task because of that GIL ! I >> have a multi-thread application but every bit of Python code must be >> run into a Python thread. To be more precise, I wanted to be able to >> call Python code in response to some GUI events, and I didn't want to >> instanciate a new interpreter for I wanted to be able to access the >> environment of my main Python interpreter. > > > I don't understand. This is what PyGILState_Ensure and > PyGILState_Release are for - so C code can leave the GIL unlocked by > default, and only grab it when they want to call into the C/Python API. > > Regards, > Nick. > Ok, I wondered why I didn't know these functions, but they are new to Python 2.4 ( and I didn't take the time to look closely at Python 2.4 as some modules I'm working with are still not available for Python 2.4). But if it really allows to call Python code outside a Python thread ... then I'll surely use that as soon as I can use Python 2.4 :) Thanks for the hint :) Pierre From nick at craig-wood.com Tue Jan 25 03:30:03 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 25 Jan 2005 08:30:03 GMT Subject: Classical FP problem in python : Hamming problem References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> Message-ID: Francis Girard wrote: > def hamming(): > def _hamming(): > yield 1 > hamming2 = hammingGenerators[0] > hamming3 = hammingGenerators[1] > hamming5 = hammingGenerators[2] > for n in imerge(imap(lambda h: 2*h, iter(hamming2)), > imerge(imap(lambda h: 3*h, iter(hamming3)), > imap(lambda h: 5*h, iter(hamming5)))): > yield n > hammingGenerators = tee(_hamming(), 4) > return hammingGenerators[3] If you are after readability, you might prefer this... def hamming(): def _hamming(): yield 1 for n in imerge(imap(lambda h: 2*h, iter(hamming2)), imerge(imap(lambda h: 3*h, iter(hamming3)), imap(lambda h: 5*h, iter(hamming5)))): yield n hamming2, hamming3, hamming5, result = tee(_hamming(), 4) return result PS interesting thread - never heard of Hamming sequences before! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From steven.bethard at gmail.com Thu Jan 20 00:02:51 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 19 Jan 2005 22:02:51 -0700 Subject: list item's position In-Reply-To: References: Message-ID: Bill Mill wrote: > 2 solutions: > > In [98]: bars = ["str", "foobaz", "barbaz", "foobar"] > > In [99]: for bar in bars: > ....: if 'bar' in bar and 'baz' in bar: > ....: print bar > ....: print bars.index(bar) > ....: > barbaz > 2 > > In [100]: for i in range(len(bars)): > .....: if 'bar' in bars[i] and 'baz' in bars[i]: > .....: print bars[i] > .....: print i > .....: > barbaz > 2 > > The first one is slow and pretty, the second one is fast and (a bit) > ugly. I believe that you should avoid range(len(x)) when you can, but > use it when you need to know the index of something without an > additional x.index() call. See Mark's post, if you "need to know the index of something" this is the perfect case for enumerate (assuming you have at least Python 2.3): py> bars = ["str", "foobaz", "barbaz", "foobar"] py> for i, bar in enumerate(bars): ... if 'bar' in bar and 'baz' in bar: ... print bar ... print i ... barbaz 2 The only time where I even consider using range(len(x)) is when I don't also need to look at the item -- which I find to be quite uncommon... Steve From eddie at holyrood.ed.ac.uk Fri Jan 28 12:32:23 2005 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 28 Jan 2005 17:32:23 +0000 (UTC) Subject: HTML Tree View with
    and References: Message-ID: Gregor Horvath writes: >Hi, >Before I reinvent the wheel I`d like to ask if someone has done this >before since I did not find an advice at Google. >The goal is to create a dynamic Tree View in HTML. >Say I have a data strucure like this: >structList = >{'Sun':{'Sun.1':['Sun1.1','Sun1.2'],'Sun.2':['Sun2.1','Sun2.2']},'Kupa':['Kupa1']} >I want to transform this into HTML: >
      >
    1. Sun
    2. >
        >
      1. Sun.1
      2. >
          >
        1. Sun1.1
        2. >
        3. Sun1.2
        4. >
        >
      3. Sun.2
      4. >
          >
        1. Sun2.1
        2. >
        3. Sun2.2
        4. >
        >
      >
    3. Kupa
    4. >
        >
      1. Kupa1
      2. >
      >
    >If the user clicks on a branch-link say 'Sun.1' then the branch below >opens/closes (not printed by the servlet). Like a tree view control in >an native GUI app. >Has this, or a similar approach, been done before in python ( I am using >webware/cheetah)? Here is a browser side solution that you can have a play with: ---------------------------- htmltree.py --------------------------- import sys id = 0 def new_id (): global id id += 1 return id def mk_expander (id, lab='+'): return '%s' % (id,id,lab) def start_invisible (id): return '') def build_tree (dst, node): dst.write ('
      \n') for branch in node: ##sys.stderr.write ('-- %s\n'%branch) id = new_id() if type(node) == type([]): dst.write ('
    1. %s\n' % branch) else: dst.write ('
    2. %s\n%s' % (mk_expander (id,branch), start_invisible(id))) build_tree (dst, node[branch]) finish_invisible (dst) style_stuff = ''' ''' print 'BLAH' print '' print style_stuff print ''' ''' structList = {'Sun':{'Sun.1':['Sun1.1','Sun1.2'],'Sun.2':['Sun2.1','Sun2.2']},'Kupa':['Kupa1']} build_tree (sys.stdout, structList) print '\n\n' ----------------------------------------------------------------- and the javascript file that goes with it ---------------------------------hier.js -------------------------- visibility_state = new Array(); highlighted = new Array(); selected_node = null; selected_id = null; function get_visibility (id) { var m = visibility_state[id]; if (m == undefined) m = "none"; return m; } function set_visibility (id, e, vis) { e.style.display = vis; visibility_state[id] = vis; } function togglen(id) { toggle_branch (id); do_select (id); return false; } function toggle_branch(id) { var e = document.getElementById(id); var m = get_visibility (id); if (m == "none") m = "inline"; else m = "none"; set_visibility (id, e, m); } function show_branch (id) { var e = document.getElementById(id); set_visibility (id, e, "inline"); } function hide_branch (id) { var e = document.getElementById(id); set_visibility (id, e, "none"); } function do_select (id) { if (selected_id != null) { var e = document.getElementById("e."+selected_id); e.style.backgroundColor = 'transparent'; } var n = document.getElementById("e."+id); n.style.backgroundColor = 'red'; selected_node = document.getElementById(id); selected_id = id; } function set_visibility_all (n, vis) { if (n == null) return false; if (n.nodeType == 1) { if (n.tagName == "DIV" && n.id != "") set_visibility (n.id, n, vis); for (var c = n.firstChild; c != null; c = c.nextSibling) set_visibility_all (c, vis); } } ------------------------------------------------------------------- the javascript code is extracted from a larger set of functions that include a popup menu with inbuilt search (which opens tree levels as necessary), if you're interested. Eddie From peter.sch231aefer at gmx.de Thu Jan 20 16:55:36 2005 From: peter.sch231aefer at gmx.de (Peter Schaefer) Date: Thu, 20 Jan 2005 22:55:36 +0100 Subject: Python and SOAP Message-ID: Hello! I'd like to write a SOAP client and a SOAP server in Python. Is SOAPy still the way to go, or are there better methods? Regards, Peter -- Meine E-Mail Adresse enth?lt keine Zahlen. My email address doesn't contain numbers. From steven.bethard at gmail.com Fri Jan 7 17:35:21 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 15:35:21 -0700 Subject: switching an instance variable between a property and a normal value In-Reply-To: References: Message-ID: Robert Brewer wrote: > Steven Bethard wrote: > >>I'd like to be able to have an instance variable that can >>sometimes be >>accessed as a property, and sometimes as a regular value, >>e.g. something >>like: > > ... > >>py> c.x is c.x # I'd like this to be False > > > You'd like 'c.x is c.x' to be FALSE? You can't be serious. Must be a > typo. Hmm... maybe I better give the larger context. The short answer is no, I'm serious. I'm playing around with a mapping type that uses setdefault as suggested in http://www.python.org/moin/Python3_2e0Suggestions. The default value for a missing key is either a simple value, or a value generated from a function. If it's generated from the function, it should be generated new each time so that, for example, if the default is an empty list, d[1] and d[2] don't access the same list. This is why 'c.x is c.x' should be False if I'm using the function. Some more context: Before I added the ability to use a function, my code looked something like: py> class D(dict): ... def __init__(self): ... self._default = None ... def __getitem__(self, key): ... if not key in self: ... self[key] = self._default ... return dict.__getitem__(self, key) ... def setdefaultvalue(self, value): ... self._default = value ... py> d = D() py> d[0] py> d.setdefaultvalue(0) py> d[1] 0 py> d[2] += 1 py> d {0: None, 1: 0, 2: 1} To add the ability to use a function to create the default value, it would have been nice to leave basically the same code I already had and do something like: py> class D(dict): ... def __init__(self): ... self._default = None ... def __getitem__(self, key): ... if not key in self: ... self[key] = self._default ... return dict.__getitem__(self, key) ... def setdefaultvalue(self, value): ... self._default = value ... def setdefaultfunction(self, func, *args, **kwds): ... self._func, self._args, self._kwds = func, args, kwds ... self._default = D._defaultfunc ... def _get(self): ... return self._func(*self._args, **self._kwds) ... _defaultfunc = property(_get) ... Of course, this doesn't work for the reasons that I discussed, but the idea would be that D would use a regular attribute when a simple value was needed, and a property when a value had to be generated by a function each time. The best option I guess is to rewrite this with a _getdefault() function instead of a property: py> class D(dict): ... _undefined = object() ... def __init__(self): ... self._value = None ... self._func = self._undefined ... def __getitem__(self, key): ... if not key in self: ... self[key] = self.getdefault() ... return dict.__getitem__(self, key) ... def getdefault(self): ... if self._value is not self._undefined: ... return self._value ... if self._func is not self._undefined: ... return self._func(*self._args, **self._kwds) ... def setdefaultvalue(self, value): ... self._value = value ... self._func = self._undefined ... def setdefaultfunction(self, func, *args, **kwds): ... self._func, self._args, self._kwds = func, args, kwds ... self._value = self._undefined ... But I was hoping to avoid having two separate attributes (self._value and self._func) when only one should have a value at any given time. Steve From timr at probo.com Fri Jan 7 01:51:13 2005 From: timr at probo.com (Tim Roberts) Date: Thu, 06 Jan 2005 22:51:13 -0800 Subject: smtp question References: Message-ID: "Philippe C. Martin" wrote: >Hi, > >I am testing the smtp module and have the following question: > >in the code below (taken from net sample) prior to adding the "Subject:" >field, the email client found the "From" and the "To". Without the >"Subject:" field on I get this: > >Email client = Evolution: the "From" field is blank >Email client = KMail: the "To" field is blank > >Any clue ? Absolutely. >server = smtplib.SMTP('smtp.sbcglobal.yahoo.com') >server.set_debuglevel(1) >server.login ('xxxxx','yyyyyyy') >server.sendmail(fromaddr, toaddrs, 'Subject:from python\n\n'+msg) >server.quit() You have two newlines following the Subject: line. That inserts a blank line, which terminates the headers. Everything else, including the From: and To: lines, will be taken as part of the message body. I assume you meant to use \r\n, but \n will work just as well and is less error prone. >print "Message length is " + repr(len(msg)) Easier is: print "Message length is", len(msg) More efficient is: print "Message length is %d" % len(msg) -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ysharma at catprosystems.com Thu Jan 13 15:01:39 2005 From: ysharma at catprosystems.com (Yogesh Sharma) Date: Thu, 13 Jan 2005 12:01:39 -0800 Subject: Embedding Multiplr Python interpreter in C++ Message-ID: Hi, I have following setup: OS Linux Fedora Core 3 Python 2.3.4 How can I embed two python interpreters in one C++ program ? Thanks From steven.bethard at gmail.com Tue Jan 25 13:52:15 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 11:52:15 -0700 Subject: Classical FP problem in python : Hamming problem In-Reply-To: References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> Message-ID: <6PKdnVpD-4f3CGvcRVn-gQ@comcast.com> Nick Craig-Wood wrote: > Steven Bethard wrote: > >> Nick Craig-Wood wrote: >> >>>Thinking about this some more leads me to believe a general purpose >>>imerge taking any number of arguments will look neater, eg >>> >>>def imerge(*generators): >>> values = [ g.next() for g in generators ] >>> while True: >>> x = min(values) >>> yield x >>> for i in range(len(values)): >>> if values[i] == x: >>> values[i] = generators[i].next() >>> >> >> This kinda looks like it dies after the first generator is exhausted, >> but I'm not certain. > > > Yes it will stop iterating then (rather like zip() on lists of unequal > size). Not sure what the specification should be! It works for the > hamming problem though. Actually, it stops iterating on lists of equal size too: py> def imerge(*iterators): ... iterators = [iter(i) for i in iterators] ... values = [i.next() for i in iterators] ... while True: ... x = min(values) ... yield x ... for i, val in enumerate(values): ... if val == x: ... values[i] = iterators[i].next() ... py> list(imerge([1, 4, 7], [2, 5, 8], [3, 6, 9])) [1, 2, 3, 4, 5, 6, 7] Note that 8 and 9 are not in the list. Steve From fredrik at pythonware.com Sat Jan 22 07:54:52 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 13:54:52 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com><797fe3d405011911465ab59acd@mail.gmail.com><1106177050.630141.33090@c13g2000cwb.googlegroups.com><972ec5bd0501191641166972b0@mail.gmail.com><7xis5szpdj.fsf@ruckus.brouhaha.com><7xekggbrns.fsf@ruckus.brouhaha.com><7x651rwbib.fsf@ruckus.brouhaha.com><7xfz0uqe1d.fsf@ruckus.brouhaha.com><1gqsayh.th49i518ixczeN%aleaxit@yahoo.com> <7xpszxljra.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Some languages let you say things like: > for (var x = 0; x < 10; x++) > do_something(x); > and that limits the scope of x to the for loop. depending on the compiler version, compiler switches, IDE settings, etc. From invalidemail at aerojockey.com Sat Jan 8 21:06:23 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 8 Jan 2005 18:06:23 -0800 Subject: python3: accessing the result of 'if' References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> Message-ID: <1105236383.521393.40680@c13g2000cwb.googlegroups.com> Nick Coghlan wrote: > I have a different suggestion for this. > > 'as' is used for renaming in import statements. 'as' will be used for exception > naming in Python 3k. > > So let's use it for expression naming in 'if' statements, too. > > if someregexp.match(s) as m: > # blah using m > elif someotherregexp.match(s) as m: > # blah using m What if the condition you wanted to test wasn't the same as the thing you want to save? In other words, how would you convert this? . where: . m = something() . if m > 20: . do_something_with(m) What you propose works for typical regexps idiom but not for the slightly more general case. However, I could see why some people might not like the where...if syntax I proposed; it's kind of choppy and not exactly easy to follow at a first glance. As a compromise, howabout: . if m > 20 where m=something(): . do_something_with(m) In this case, the m=something() is NOT an assignment statement, but merely a syntax resembling it. The "where m=something()" is part of the if-statement, not the if-expression. It causes m to be visisble in the if-expression and the if-block. It (or your suggestion) could work with a while-loop too. . while line where line=f.readline(): . do_something_with(line) The main problem here (as some would see it) is that you can't do something this: . if m > 20 where (def m(): a(); b()): -- CARL BANKS From jack at performancedrivers.com Mon Jan 24 21:41:31 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 24 Jan 2005 21:41:31 -0500 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: Message-ID: <20050125024131.GG1607@performancedrivers.com> On Mon, Jan 24, 2005 at 09:17:24PM -0500, Roy Smith wrote: > Rocco Moretti wrote: > > The OP doesn't mention his application, but there is something to be > > said about domain specific scripting languages. A well designed > > domain-specific scripting language(*) with the appropriate high level > > constructs can make script writing simpler. > > This is a bit of a sore point with me. > > I've been involved with several projects where people felt the need to > invent their own scripting languages. It usually starts with "we don't > need the power of a full programming language, we only need to be able > to do X, Y, and Z". So they write a little language which lets them do > X, Y, and Z. > > Then they discover they need more complex data structures than they > originally thought. And nested loops. And functions. And more > sophisticated variable scoping rules. And a regex library. And 47 > other things. So they duct-tape all those into the system. > > A few years later, you end up with most of a real programming language, > except with a whole bunch of warts. > > The syntax is usually quirky (the one I'm working with today does not > allow any space before the open paren of a function call, but requires > it before the opening paren of an "if" statement). It generally has > poor error reporting. It doesn't have the whole family of free tools > that grow up around any real language (editor customization packages, > syntax checkers, debuggers, extensions, etc). You doesn't have a gaggle > of tutorial books written about it that you can buy from your favorite > on-line bookseller. > > Worse, when you need more brains/bodies on the project, you can't put an > add on Hot Jobs for "experienced OurOwnScriptingLanguage programmer" and > expect to get anybody who can be productive quickly. > > What it does have is a body of code dependent on it which is now so > large that porting it to something else is an unthinkably large task. > And it's got a small cadre of language gurus who spend all day defending > the language with answers like, "But, it was never *intended* that > people would do stuff like this with it". > Me Too! I mean, did you used to work at CDNOW too? I don't miss that want-to-gouge-out-your-own-eyes feeling. -Jack From snacktime at gmail.com Sun Jan 23 21:32:10 2005 From: snacktime at gmail.com (snacktime) Date: Sun, 23 Jan 2005 18:32:10 -0800 Subject: Set parity of a string In-Reply-To: References: Message-ID: <1f060c4c05012318322329166d@mail.gmail.com> On Sun, 23 Jan 2005 21:00:25 -0500, Peter Hansen wrote: > Peter Hansen wrote: > > snacktime wrote: > >> Is there a module that sets the parity of a string? > > > > As to the specific question: a module is not really required. > > But here's one for you anyway. It raises an exception if any > input character is non-ASCII, otherwise when you call set_parity() > with a string and a parity parameter of 'even', 'mark', 'none', > 'odd', or 'space', it returns a string of the same length with > the high (parity) bits set appropriately. Thanks for the code example, I'm not quite up to speed on python enough to make this a trivial exercise as of yet. Chris From http Tue Jan 11 02:56:43 2005 From: http (Paul Rubin) Date: 10 Jan 2005 23:56:43 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> <1105355380.040837.189270@c13g2000cwb.googlegroups.com> <7xis65a5w6.fsf@ruckus.brouhaha.com> <1105357839.696387.309900@c13g2000cwb.googlegroups.com> <7xr7kt314a.fsf@ruckus.brouhaha.com> <1105364925.848973.73080@c13g2000cwb.googlegroups.com> <7xllb1jsdz.fsf@ruckus.brouhaha.com> Message-ID: <7xpt0ciekk.fsf@ruckus.brouhaha.com> Steve Holden writes: > Well I for one disagreed with many of your estimates of the zen's > applicability to macros, but I just couldn't be arsed saying so. Well, I was being somewhat flip with them, as I felt Carl was being snotty in referring me to the Zen list. The point there is that one can interpret each of the Zen points in many ways regarding macros. I don't feel there's a conflict between macros and the Zen list. Macros in Python are a deep subject and gurus have been discussing them for a long time. I think that with PyPy it will become easier to experiment with possible approaches. In other posts I've suggested a moratorium on new Python syntax until after PyPy is deployed. > > An amazing amount of the headaches that both newbies and experienced > > users have with Python, could be solved by macros.... It's not clear > > what the best way to do design them is, but their existence can have a > > profound effect on how best to do these ad-hoc syntax extensions like > > "where". > This is not a justifiable assertion, IMHO, and if you think that > newbies will have their lives made easier by the addition of ad hoc > syntax extensions then you and I come from a different world (and I > suspect the walls might be considerably harder in mine than in yours). I'm saying that many proposals for ad hoc extensions could instead be taken care of with macros. Newbies come to clpy all the time asking how to do assignment expressions, or conditional expressions, or call-by-reference. Sometimes new syntax results. Lots of times, macros could take care of it. > I don't really understand why, if macros are so great (and you are > reading the words of one who was using macros back in the days of > Strachey's GPM) why somebody doesn't produce a really useful set of > (say) M4 macros to prove how much they'd improve Python. You can't really do Python macros with something like M4. How would M4 even generate multi-line output that's indented to the right depth for the place where the macro was called? How would you write an m4 macro like cond(x,y,z) that does the equivalent of (x ? y : z)? Even if you could, it doesn't begin to address the hassle of running Python scripts through m4 before you can execute the scripts, especially in an interactive environment. From c.helmbold at gmx.de Mon Jan 17 03:55:27 2005 From: c.helmbold at gmx.de (Christian Helmbold) Date: Mon, 17 Jan 2005 09:55:27 +0100 Subject: =?iso-8859-15?q?Einrichtung_von_de=2Ecomp=2Elang=2Epython_-_Dein?= =?iso-8859-15?q?e_Stimme_z=E4hlt!?= Message-ID: Hallo, wenn du m?chtest, dass die Gruppe news:de.comp.lang.python eingerichtet wird, bitte ich dich, deine Stimme daf?r abzugeben. Du brauchst dazu nur unten stehenden Wahlschein auszuf?llen und an votetaker at gvv.th-h.de zu schicken. Weitere Einzelheiten zum Verfahren finden sich in news:de.admin.news.anncounce sowie in news:de.admin.news.groups -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 1. CfV (Aufruf zur Abstimmung) zur Einrichtung der Gruppe de.comp.lang.python Programmieren mit Python. Charta - ------ In dieser Gruppe geht es um die Programmiersprache Python und alles, was damit unmittelbar zusammenh?ngt (Installation, alternative Implementierungen, externe Module etc.). Status - ------ unmoderiert Begr?ndung - ---------- In der Diskussion, die mit der Nachricht <314dsqF373djsU1 at individual.net> begann, wurde ?berwiegend Zustimmung zu der Einrichtung ge?u?ert. Proponent - --------- Christian Helmbold Abstimmungsmodalit?ten - ---------------------- Wahlleiter: Thomas Hochstein Abstimmadresse: dclp-0501 at gvv.th-h.de Abstimmungsende: Mit Ablauf des 13. Februar 2005 (MEZ) Wahlschein: Untenstehendes Formular ist zu verwenden. M?glich sind bei jedem Abstimmungspunkt JA, NEIN und ENTHALTUNG. Besonderer Hinweis ------------------ Die am 23.12.2004 begonnene Abstimmung ?ber die Einrichtung der Gruppe de.comp.lang.python wurde am Abend desselben Tages vom Wahlleiter abgebrochen. Die damals abgegebenen Stimmen wurden verworfen und nicht gewertet. Mit diesem 1. CfV beginnt ein neues Abstimmungsverfahren; wer an der Abstimmung teilnehmen m?chte, mu? also jetzt (erneut) abstimmen, auch wenn er schon in dem ersten, abgebrochenen Verfahren eine Stimme abgegeben hat. Es gelten die "Einrichtung von Usenet-Gruppen in de.*" in der bei Beginn der Abstimmung g?ltigen Fassung, die in de.admin.infos und unter auch im WWW ver?ffentlicht sind. Sie erl?utern das Wahlverfahren detailliert und sollten vor der ersten Teilnahme an einer Abstimmung gelesen werden. Gez?hlt werden nur per E-Mail bei der Abstimmadresse eingegangene Stimmen. Diese werden einzeln per E-Mail best?tigt. Das Ergebnis wird nach dem Ende der Wahl ver?ffentlicht. Namen, E-Mail-Adresse und Inhalt der Stimmabgabe aller Abstimmenden werden im Ergebnis genannt. Mit R?cksicht auf das deutsche Datenschutzrecht ist daher die gesonderte Zustimmung zur Speicherung und Ver?ffentlichung der abgegebenen Stimme entsprechend Hinweis im Wahlschein n?tig. Auf die weiteren Hinweise auf sei verwiesen. =-=-=-=-=-=-=-=- Alles vor dieser Zeile bitte loeschen =-=-=-=-=-=-=-=- WAHLSCHEIN fuer Einrichtung der Gruppe de.comp.lang.python Dein Realname, falls nicht im FROM-Header: Wenn du keinen Real-Namen angibst, wird deine Stimme fuer ungueltig erklaert werden. Nr [Deine Stimme] Gruppe/Abstimmungsgegenstand ======================================================================== #1 [ ] Einrichtung von de.comp.lang.python Zur Verarbeitung des Wahlscheines und inbesondere der Veroeffentlichung des Ergebnisses ist deine Zustimmung zur Speicherung, Auswertung und Veroeffentlichung deiner Stimmdaten (Name und E-Mail-Adresse in Verbindung mit dem Stimmverhalten) im Rahmen dieses Verfahrens erforderlich. Wenn du im Feld unterhalb dieses Absatzes "JA" eintraegst, erklaerst du dich damit einverstanden. In allen anderen Faellen wird der Wahlschein mit Ruecksicht auf das deutsche Bundesdatenschutzgesetz verworfen und nicht gewertet. #a [ ] Datenschutzklausel - Zustimmung: Ich bin mit der Verarbeitung meiner Daten wie oben beschrieben einverstanden =-=-=-=-=-=-=-=- Alles nach dieser Zeile bitte loeschen =-=-=-=-=-=-=-=- -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iQCVAwUBQerEb2FKEBFIVyalAQLUvAQAi/S0OSvwYnhkvvlCnYmhVLdi8D4XkMv4 oCYHzADyiNpLDNF3w1dszSL2uXeRuSoXOWd07xcTYS6MpQTWzri8BPyBYyW4Zywz u46rkfDFTpwr5oLHP2Ss3OJr6rqY7zWL28o7bAYdemDd9GIg0vPt4AE8HXyhL5ud CePdwFnaN3s= =z5dB -----END PGP SIGNATURE----- Danke, Christian From asda at sdarta.com Sat Jan 8 21:16:09 2005 From: asda at sdarta.com (worzel) Date: Sun, 9 Jan 2005 10:16:09 +0800 Subject: tuples vs lists References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dff650$0$29357$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41e093e8$0$21144$5a62ac22@per-qv1-newsreader-01.iinet.net.au> yes, "tyoopl" - thats what I meant by 'choo-ple' (not v good at the phonetics) As a scouse git (though living in Australia), I would definitely say 'tyoopl'. "Steve Holden" wrote in message news:w5WDd.69983$Jk5.66802 at lakeread01... > worzel wrote: > >> Cheers - thanks for the feedback guys - pretty much answers the question >> for me. >> >> 'Two-Pull' it is then, thanks. >> > Well, it might be "Two-Pull" in American, but in English it's "tyoopl" -- > NOT "choopl" (blearch!). I've also heard people say "tuppl". > > So, basically, say whatever you want. Language is about communication :-) > > you-say-tomato-ly y'rs - 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 frans.englich at telia.com Tue Jan 11 01:54:54 2005 From: frans.englich at telia.com (Frans Englich) Date: Tue, 11 Jan 2005 06:54:54 +0000 Subject: PyChecker messages Message-ID: <200501110654.54193.frans.englich@telia.com> Hello, I take PyChecker partly as an recommender of good coding practice, but I cannot make sense of some of the messages. For example: runner.py:878: Function (main) has too many lines (201) What does this mean? Cannot functions be large? Or is it simply an advice that functions should be small and simple? runner.py:200: Function (detectMimeType) has too many returns (11) The function is simply a long "else-if" clause, branching out to different return statements. What's wrong? It's simply a "probably ugly code" advice? A common message is these: runner.py:41: Parameter (frame) not used But I'm wondering if there's cases where this cannot be avoided. For example, this signal handler: #------------------------------------------- def signalSilencer( signal, frame ): """ Dummy signal handler for avoiding ugly tracebacks when the user presses CTRL+C. """ print "Received signal", str(signal) + ", exiting." sys.exit(1) #------------------------------------------- _must_ take two arguments; is there any way that I can make 'frame' go away? Also, another newbie question: How does one make a string stretch over several lines in the source code? Is this the proper way? print "asda asda asda asda asda asda " \ "asda asda asda asda asda asda " \ "asda asda asda asda asda asda" Thanks in advance, Frans PS. Any idea how to convert any common time type to W3C XML Schema datatype duration? From missiplicity at yahoo.com Tue Jan 25 17:30:28 2005 From: missiplicity at yahoo.com (missiplicity at yahoo.com) Date: 25 Jan 2005 14:30:28 -0800 Subject: Question Regarding SocketServer In-Reply-To: <1106691478.621949.44020@z14g2000cwz.googlegroups.com> References: <1106684900.771730.218060@f14g2000cwb.googlegroups.com> <1106688660.694617.290330@c13g2000cwb.googlegroups.com> <1106691478.621949.44020@z14g2000cwz.googlegroups.com> Message-ID: <1106692228.117977.104720@f14g2000cwb.googlegroups.com> I figured out my problem. I initially had named my program SocketServer.py and then compiled it. It created a file SocketServer.pyc Then I changed the name of the program to TestServer3.py but when I imported SocketServer, it was importing from the compiled file left in the current folder (SocketServer.pyc) I guess. I deleted it and everything worked. Please bear with my ignorance. Thanks once again for the help, Kris From james.keasley at gmail.invalid Mon Jan 17 19:43:24 2005 From: james.keasley at gmail.invalid (James Keasley) Date: 18 Jan 2005 00:43:24 GMT Subject: Fuzzy matching of postal addresses References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 2005-01-18, Andrew McLean wrote: > I have a problem that is suspect isn't unusual and I'm looking to see if > there is any code available to help. I've Googled without success. I have done something very similar (well, near as dammit identical, actually), unfortunately, I did this in Perl[1]. I can give you some general pointers of the way to go about this type of thing, but can't actually provide any code, as it is at work. > Basically, I have two databases containing lists of postal addresses and > need to look for matching addresses in the two databases. More > precisely, for each address in database A I want to find a single > matching address in database B. In my implementation this is the exact same setup, database A (OS/RM addresspoint data) contained a metric shitload of addresses, with addresses to be matched against them coming from client supplied data. > I'm 90% of the way there, in the sense that I have a simplistic approach > that matches 90% of the addresses in database A. But the extra cases > could be a pain to deal with! There is no way to guarantee 100% accuracy if one (or both) of the datasets is collated from a non-authoratative source, ie the actual homeowners. ;) > It's probably not relevant, but I'm using ZODB to store the databases. > The current approach is to loop over addresses in database A. I then > identify all addresses in database B that share the same postal code > (typically less than 50). The database has a mapping that lets me do > this efficiently. Then I look for 'good' matches. If there is exactly > one I declare a success. This isn't as efficient as it could be, it's > O(n^2) for each postcode, because I end up comparing all possible pairs. > But it's fast enough for my application. OK, this is a good start, the first thing to do is to clean the data, especially the postcodes. something along the lines of: (pseudocode, can't remember the exact python implementation I did) postcode = resultarray[postcode] len = length(postcode) for (i = 0; i < len; i++): # if the fourth character is a digit or a space append it to the string if (i == 3 && postcode[i] =~ /(\d|\s)/: cleanPostcode .= postcode[i] # if this isn't the fourth character and it is an aplhanumeric character # append it to the string else if (postcode[i] =~ /(\w|\d): cleanPostcode .= postcode[i] That puts all the postcodes into the format that the Royal Mail uses. Then search on postcode ;) The next thing I did was to split each individual word out fom it field, and matched that in a specific order (I found starting with elements such as house name, number, and street name was the best approach). If a word matched it was assigned a score (1 for a exact match, 0.7 for a metaphone match and 0.6 for a soundex macth IIRC), and when the searching was finished I took the resulting score and divided it by the number of word elements. If that score was higher than any of the prevous scores then it was put in a given variable. If there where a number of equally good(bad?) matches then they were appended onto an array, and if there was no clear winner yb the time that the last of the records for that postcode had been process it spat out a multiple choice list. The trick is picking a threshold level below which no matches are put into the DB, even if they are the best scoring. (I used a threshold of 0.3 This can be refined, the current, extremely baroque, perl script that does this currently drops out certain values from the data array if there is an exact match with certain fields, such as house name. It doesn't reduce the value of the integer that the result is divided by though, thus favouring results that return an exact match on a couple of given fields. > The challenge is to fix some of the false negatives above without > introducing false positives! > > Any pointers gratefully received. Hope this is a) understandable, and b) useful ;) FWIW, the perl script (an I would expect a similarly implemented python script to perform about as well) running a somewhat flaky set of user collated data against the Royal Mail Addresspoint data managed a 75% hit rate, with an additional 5% requiring user intervention, and as near as I have been able to ascertain a >1% false positive count, from a dataset of nearly 17,000 addresses. With cleaner and more up to date data I would expect the results to be noticably better. [1] It is still my main language, I don't use python enough to think in it as easily as I think in perl ;) - -- James jamesk[at]homeric[dot]co[dot]uk "Consistency is the last resort of the unimaginative." - -- Bob Hope -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.5 (GNU/Linux) iD8DBQFB7FurqfSmHkD6LvoRAgdVAJ4t2HCaT52qbuqyT5yN59X+az0ZQwCfZgOH L5nTnPj+TF95Z+FCM65CzV0= =UkeW -----END PGP SIGNATURE----- From xah at xahlee.org Sat Jan 15 04:58:04 2005 From: xah at xahlee.org (Xah Lee) Date: 15 Jan 2005 01:58:04 -0800 Subject: [perl-python] 20050115, for statement Message-ID: <1105783084.748174.307680@f14g2000cwb.googlegroups.com> ? # this is an example of for statement ? # the % symbol calculates the remainder ? # of division. ? # the range(m,n) function ? # gives a list from m to n-1. ? ? a = range(1,51) ? for x in a: ? if x % 2 == 0: ? print x, 'even' ? ? # note that in this example, for goes over a list. ? # each time making x the value of the element. ? ? ------------------------------------ ? # this is similar code in perl ? ? @a=(1..50); ? for $x (@a) { ? if ( $x%2 ==0){ ? print $x, " even\n"; ? }} ? ? # PS each daily tip can be run. Just ? # copy the python part and save to a ? # file and run it as "python ? # file.py". Try it. ? ? ? Note: this post is from the Perl-Python ? a-day mailing list at ? http://groups.yahoo.com/group/perl-python/ ? to subscribe, send an email to ? perl-python-subscribe at yahoogroups.com if ? you are reading it on a web page, ? program examples may not run because ? groups.google.com changes the post slightly. ? ? Xah ? xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html From ianb at colorstudy.com Sun Jan 9 03:51:31 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Sun, 09 Jan 2005 02:51:31 -0600 Subject: The best way to do web apps with Python? In-Reply-To: <41E02FD5.5080703@holdenweb.com> References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41E02FD5.5080703@holdenweb.com> Message-ID: <41E0F093.4090002@colorstudy.com> Steve Holden wrote: > More ways than you can shake a stick at, but nowadays you should > consider using WSGI if you want your code to be portable across many > frameworks. The Web SIG worked very hard last year on defining this > gateway interface, with the intention that it should become widely > available, and implementations are available now on environments as > diverse as mod_python and CherryPy. > > You can read about it in Philip Eby's excellent PEP at > > http://www.python.org/peps/pep-0333.html WSGI isn't really something an application programmer can use; or at least it's not likely to be a very satisfying experience if they do. I'm optimistic that at some point most of the actively developed Python web frameworks we have now will be ported to WSGI. Ultimately, I think WSGI should be something a more casual Python web programmer wouldn't even realize exists. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From ncoghlan at iinet.net.au Tue Jan 11 07:57:59 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 11 Jan 2005 22:57:59 +1000 Subject: "Architecture of Python" was removed ? In-Reply-To: <004801c4f7cb$f62d1d30$1d02a8c0@cr> References: <004801c4f7cb$f62d1d30$1d02a8c0@cr> Message-ID: <41E3CD57.1020904@iinet.net.au> cr999 wrote: > I found the "Architecture of Python" ( http://wiki.cs.uiuc.edu/cs427/PYTHON By Jim Jackson, Kar-Han Tan )is very useful for my understanding of the Python's architecture. But I found the link is not link to that document today. It seems that the document was removed. Who knows what happened? > > Does anyone here have a copy of that document? Or who can tell me what is the email address of Jim Jackson or Kar-Han Tan. http://web.archive.org/web/20031222201953/http://wiki.cs.uiuc.edu/cs427/PYTHON Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ebolonev at mail.ru Sat Jan 15 15:52:54 2005 From: ebolonev at mail.ru (Egor Bolonev) Date: Sun, 16 Jan 2005 06:52:54 +1000 Subject: How can I get the names of the files in a directory? References: Message-ID: On Sat, 15 Jan 2005 15:16:02 GMT, .removethis. <"(.removethis.)kartic.krishnamurthy"@gmail.com> wrote: > Sara Fwd said the following on 1/15/2005 8:10 AM: >> Can you guys also help me find a module that looks in >> a directory and print out the names of the files in there? > > You can use glob: > > >>> import glob > >>> from os.path import isfile > >>> print filter(isfile, glob.glob('/tmp/*')) # can use patterns > > (will print a list of all files in the given directory, matching the > given pattern) > > If you want to traverse a directory tree recursively, please take a look > at this recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/200131 import os, os.path def get_all_files(path): if len(path) > 0: if path[-1] == ':': path = path + '\\' try: for i in os.listdir(path): j = os.path.join(path, i) if os.path.isdir(j): for ii in get_all_files(j): yield ii else: yield j except:pass for i in get_all_files('c:\\'): print i From kartic.krishnamurthy at gmail.com Sun Jan 9 20:10:04 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 9 Jan 2005 17:10:04 -0800 Subject: path to python file given module In-Reply-To: <1105317971.205487.82770@c13g2000cwb.googlegroups.com> References: <1105315568.887724.260370@c13g2000cwb.googlegroups.com> <1105315923.520581.280580@c13g2000cwb.googlegroups.com> <1105317971.205487.82770@c13g2000cwb.googlegroups.com> Message-ID: <1105319404.902746.179690@c13g2000cwb.googlegroups.com> That is because your module in not in a standard location that python can find it in. It is not that inspect.getsourcefile() is not working. Actually if you try reloading your filegen module after the os.chdir(), you will see that import fails. If you copy your filegen directory to the site-packages directory of python, you will get the complete path of the module no matter where you are inside your script. From grante at visi.com Sun Jan 16 21:03:03 2005 From: grante at visi.com (Grant Edwards) Date: 17 Jan 2005 02:03:03 GMT Subject: List problems in C code ported to Python References: <41ead925$0$87061$a1866201@visi.com> Message-ID: <41eb1cd7$0$10879$a1866201@visi.com> On 2005-01-16, Lucas Raab wrote: >>>Please see both the Python and C code at >>>http://home.earthlink.net/~lvraab. The two files are ENIGMA.C >>>and engima.py >> >> http://www.catb.org/~esr/faqs/smart-questions.html > > I didn't expect to get bitched out just because I didn't > follow "protocol." You didn't get "bitched out". You did get some very sound advice. You want help solving a problem, and there are ways you can greatly increase the chances that you'll get help with your problem. After being told the best ways to get help, you whined about it rather than following it. Nobody owes you anything. Remember that. [You're darned lucky somebody did take the time to go to your web site and proof your code for you after your posting said in effect "I'm too lazy to compose and post a precise question, so go look at my program and fix it for me."] Now, go back and read the smart questions reference. -- Grant Edwards grante Yow! Hello? Enema at Bondage? I'm calling visi.com because I want to be happy, I guess... From leyambe at cs.uct.ac.za Tue Jan 11 08:19:59 2005 From: leyambe at cs.uct.ac.za (Linda Eyambe) Date: Tue, 11 Jan 2005 15:19:59 +0200 Subject: including folders with McMillan Installer Message-ID: <001401c4f7e0$40950720$c8619e89@cs.uct.ac.za> Hi everyone, After months of hacking i managed to get my python software to work properly, and have even managed to turn it into an exe with Mcmillan's Installer (ran into a LookupError with py2exe so i tossed it). Anyway, now i'm wondering how to include entire folders and their content into the distribution directory. I created a COLLECT subclass for each folder something like this: coll1 = COLLECT ( [('file1.txt', 'C:/my/folder1/file1', 'DATA')], [('file2.txt', 'C:/my/folder1/file2', 'DATA')], ... name = folder1 ) coll2 = COLLECT ( [('file1.txt', 'C:/my/folder2/file1', 'DATA')], name = folder2 ) I have to do that for each file and each folder i want to include. How can i do this more efficiently? Also, when i run the exe by double-clicking on it directly from within the distribution directory it works fine, but once i create a shortcut or try to access it with the command-line eg C:/project/dist/project.exe it doesnt seem to be able to find the files that i imported with the COLLECT statement, even though in my source code all the file locations are relative. I get an error that goes something like... Cannot find the file or directory named './icons/splash.bmp' although it is clearly there. Any ideas? Thanks, Linda -------------- next part -------------- An HTML attachment was scrubbed... URL: From deetsNOSPAM at web.de Tue Jan 18 07:49:06 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 18 Jan 2005 13:49:06 +0100 Subject: generator expressions: performance anomaly? References: Message-ID: <354esdF4fouh0U1@individual.net> > Something else I was thinking about. I think it would be nice if the > python compilor could figure out whether a genexp in a list or tuple > expression always generates the same list or tuple and then instead > of generating code would generate the list or tuple in place. This won't ever happen in python - at least not in python otherwise similar to the one we know... The thing you're after is known as "common subexpression elemination" and can only be done in purely functional languages. While that certainly is an interesting property of a language, it e.g. forbids functions like time.time() - a too huge paradigm shift for python. -- Regards, Diez B. Roggisch From bvande at po-box.mcgill.ca Tue Jan 4 13:28:42 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 04 Jan 2005 13:28:42 -0500 Subject: Cookbook 2nd ed Credits (was Re: The Industry choice) In-Reply-To: <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> Message-ID: <41DAE05A.6000700@po-box.mcgill.ca> Alex Martelli said unto the world upon 2005-01-04 11:15: > wrote: > > >>But then I have THREE published recipes!! >>Does that mean that I get three free copies of the cookbook ? ;-) > > > ...ti piacerebbe eh...?-) Sorry, "one each", even though you have > _five_ credits. For the curious, here's the roster of most credited > contributors (remember, significant comments we merged into other's > recipes also count!-)...: > > > If you wished to count only _authored_ recipes (but that's a bit > misleading, since in several recipes-as-published there is a merge of > two or three separately submitted and accepted recipes, and here I'm > counting only the first-listed-author per published-recipe...): > > 1: 25 u'Luther Blissett' > > ...but each still gets ONE free copy...!-) > > > Alex Since I'm certain Luther won't be claiming his copy ;-) perhaps we could auction it off? Best, Brian vdB From snail at objmedia.demon.co.uk Fri Jan 7 08:49:34 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Fri, 7 Jan 2005 13:49:34 +0000 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <0WlDd.8830$5R.1182@newssvr21.news.prodigy.com> Message-ID: <+wsARHFuNp3BFwz6@objmedia.demon.co.uk> In message , Arich Chanachai writes >think). Or what about D? Digital Mars have a D compiler. http://www.digitalmars.com Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From jeff at ccvcorp.com Fri Jan 7 15:32:44 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 07 Jan 2005 12:32:44 -0800 Subject: The Industry choice In-Reply-To: <1gq0k74.1epsxog1dgcgbsN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <10trej2fl8dip65@corp.supernews.com> <1gq0k74.1epsxog1dgcgbsN%aleaxit@yahoo.com> Message-ID: <10tts536kn15a33@corp.supernews.com> Alex Martelli wrote: > Jeff Shannon wrote: > >>Note that the so-called 'viral' nature of GPL code only applies to >>*modifications you make* to the GPL software. The *only* way in which >>your code can be 'infected' by the GPL is if you copy GPL source. > > ... > >>(Problems may come if someone licenses a library under the GPL; that's >>what the LGPL was invented for. But the issue here is not that the >>GPL is bad, it's that the author used the wrong form of it.) > > > Stallman now says that you should use GPL, not Lesser GPL. > > http://www.gnu.org/licenses/why-not-lgpl.html > > Specifically, he wants library authors to use GPL to impose the viral > nature of GPL on other programs just USING the library -- the very > opposite of what you say about "only applies ... if you copy"! Ah, I haven't kept up on Stallman's current opinions, and was speaking from the understanding I had of GPL/LGPL as of a number of years ago (before that article was written). By "copy", above, I meant "use GPL source in your product". The GPL defines what it means to use source in a rather inclusive way. That inclusiveness means that the standard usage of libraries falls under their definition of "using source". This distinction in the normal terms of "usage" is what impelled the FSF to create the LGPL in the first place... So, I think what I said still (mostly) stands, as long as you look at it in terms of whether object code is copied into your executable. ;) It's still true that one can use (in a consumer sense) GPL software for whatever purpose one wishes, and the restrictions only kick in when one includes GPL code in another product. Indeed, I should have used the word "include" rather than "copy"... (It's hardly surprising that Stallman wants to use whatever leverage he can get to encourage FSF-style free software...) Jeff Shannon Technician/Programmer Credit International From simon.brunning at gmail.com Fri Jan 14 05:25:21 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 14 Jan 2005 10:25:21 +0000 Subject: Octal notation: severe deprecation In-Reply-To: <34o8n7F4e6uduU1@individual.net> References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105575689.335040.174490@c13g2000cwb.googlegroups.com> <34o8n7F4e6uduU1@individual.net> Message-ID: <8c7f10c6050114022561944b6c@mail.gmail.com> On Thu, 13 Jan 2005 16:50:56 -0500, Leif K-Brooks wrote: > Tim Roberts wrote: > > Stephen Thorne wrote: > > > >>I would actually like to see pychecker pick up conceptual errors like this: > >> > >>import datetime > >>datetime.datetime(2005, 04,04) > > > > > > Why is that a conceptual error? Syntactically, this could be a valid call > > to a function. Even if you have parsed and executed datetime, so that you > > know datetime.datetime is a class, it's quite possible that the creation > > and destruction of an object might have useful side effects. > > I'm guessing that Stephen is saying that PyChecker should have special > knowledge of the datetime module and of the fact that dates are often > specified with a leading zero, and therefor complain that they shouldn't > be used that way in Python source code. It would be useful if PyChecker warned you when you specify an octal literal and where the value would differ from what you might expect if you didn't realise that you were specifying an octal literal. x = 04 # This doesn't need a warning: 04 == 4 #x = 09 # This doesn't need a warning: it will fail to compile x= 012 # This *does* need a warning: 012 == 10 -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From rbt at athop1.ath.vt.edu Sun Jan 2 14:28:14 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sun, 02 Jan 2005 14:28:14 -0500 Subject: arbitrary number of arguments in a function declaration In-Reply-To: References: Message-ID: Nick Coghlan wrote: > rbt wrote: > >> How do I set up a function so that it can take an arbitrary number of >> arguments? For example, I have a bunch of expenses which may grow or >> shrink depending on the client's circumstance and a function that sums >> them up... hard coding them is tedious. How might I make this dynamic >> so that it can handle any amount of expenses? >> >> def tot_expenses(self, e0, e1, e2, e3): >> pass > > > The Python Tutorial is a wonderful thing. . . But so is this list ;) > > Anyway, you can either set up your function to take a proper list, and > then discover that the sum function already exists to add up the > contents of a list: > > def tot_expenses(self, expenses): > self.total_expenses = sum(expenses) > > Or, have the function take a variable number of arguments, and do the > same thing: > > def tot_expenses(self, *args): > self.total_expenses = sum(args) > > Cheers, > Nick. > Many thanks! From grante at visi.com Tue Jan 25 23:49:00 2005 From: grante at visi.com (Grant Edwards) Date: 26 Jan 2005 04:49:00 GMT Subject: py2exe problem References: Message-ID: <41f7213c$0$2343$a1866201@visi.com> On 2005-01-26, Club-B42 wrote: > i've compiled my programm using command "python setup.py py2exe >1" > > python script works fine, but .exe version fails with > LookupError: no codec search functions registered: can't find encoding Googling for the error message will find you the answer. I don't remember what it is, but that's how I found it. IIRC, it's the very first in when you google Usenet. You need to tell py2exe to include some module-or-other that it doesn't by default. I don't remember the exact recipe, but I've got it at work. If you can't figure it out by tomorrow, let me know and I'll post a snippet from my setup.py file. -- Grant Edwards grante Yow! Sometime in 1993 at NANCY SINATRA will lead a visi.com BLOODLESS COUP on GUAM!! From ncoghlan at iinet.net.au Wed Jan 26 06:04:05 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 21:04:05 +1000 Subject: Tuple slices In-Reply-To: <41F7F5CF.5040902@freemail.gr> References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> <10vdj4s9ib19fe3@corp.supernews.com> <41F7F5CF.5040902@freemail.gr> Message-ID: <41F77925.1000505@iinet.net.au> jfj wrote: > Jeff Shannon wrote: > >> >> >> So, what problem is it, exactly, that you think you'd solve by making >> tuple slices a view rather than a copy? >> > > I think views are good for > 1) saving memory > 2) saving time (as you don't have to copy the elements into the new tuple) 1. Applies only if you are making large slices, or a lot of slices with each containing at least 3 elements. A view can also *cost* memory, when it looks at a small piece of a large item. The view will keep the entire item alive, even though it needs only a small piece. 2. Hell no. The *elements* aren't copied, pointers to the elements are. If you *don't* copy the pointers, then every item access through the view involves an indirection as the index into the original sequence gets calculated. So views *may* save memory in some applications, but are unlikely to save time in any application (except any saving resulting from the memory saving). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From none.by.e-mail Thu Jan 6 22:31:10 2005 From: none.by.e-mail (Mike Thompson) Date: Fri, 07 Jan 2005 14:31:10 +1100 Subject: Another PythonWin Excel question In-Reply-To: References: <41ddb59e$0$8338$afc38c87@news.optusnet.com.au> Message-ID: <41de0285$0$5108$afc38c87@news.optusnet.com.au> It's me wrote: > Yes, Mike, > > Others pointed that out as well. For good reason. > > The difficulty is that they are all in VBAs. Most of them can be > translated to Python fairly easily, and some I can get from looking at the > recorded macro - but some requires quite a bit of head scratching. > > For instance, I wanted to figure out how create a new window. So, I went > through the record macro process and looked at the VBA code, it says: > > ActiveWindow.NewWindow app.ActiveWindow.NewWindow() > > Okay. Now what??? > > And for switching window, it says: > > Windows("Book1:1").Activate app.Windows.Item("Book1:1").Activate() --------------------------------------------------------------------- from win32com.client import Dispatch, constants app = Dispatch("Excel.Application") app.Visible = True workbook = app.Workbooks.Add() defaultWorksheet = workbook.Worksheets(1) app.ActiveWindow.NewWindow() app.ActiveWindow.NewWindow() # grab the capation (like 'Book1:1') from one of the windows thridWindowsCaption = app.Windows[2].Caption print thridWindowsCaption app.Windows.Item(thridWindowsCaption).Activate() ------------------------------------------------------------------------ Sometimes its useful to look in the file generated by makepy. It details all the classes and their methods AND there are annotations in the form of comments. Having said that, if you've never looked in a makepy generated module before, you're in for a shock - it takes a while before you figure out what you are looking at. When you get stuck, trial & error and a good debuger are your friend. -- Mike From exarkun at divmod.com Thu Jan 6 10:29:39 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 06 Jan 2005 15:29:39 GMT Subject: Embedding a restricted python interpreter In-Reply-To: Message-ID: <20050106152939.25734.439818807.divmod.quotient.3792@ohm> On Thu, 06 Jan 2005 16:05:50 +0100, Peter Maas wrote: >Craig Ringer schrieb: > > That is my understanding. In fact, I'd say with Python it's nearly > > impossible given how dynamic everything is and the number of tricks that > > can be used to obfuscate what you're doing. Think of the fun that can be > > had with str.encode / str.decode and getattr/hasattr . > > It would certainly be difficult to track all harmful code constructs. > But AFAIK the idea of a sandbox is not to look at the offending code > but to protect the offended objects: files, databases, URLs, sockets > etc. and to raise a security exception when some code tries to offend > them. Jython is as dynamic as C-Python and yet it generates class > files behaving well under the JVM's security regime. > > > > > I looked into this, and my conclusion ended up being "Well, I'm using > > Python because I want it's power and flexibilty. If I want a secure > > scripting environment, I should use something like Lua or Qt Script for > > Applications instead." > > It would be good for Python if it would offer a secure mode. Some > time ago I asked my hosting provider whether I could use mod_python > with apache to run Python scripts in the same way as PHP scripts. > He denied that pointing to Python security issues and to PHP safe. > mode. Python IS powerful but there are many areas where it is of > vital interest who is allowed to use its power and what can be done > with it. I think it would be a pity to exclude Python from these > areas where a lot of programming/computing is done. A Python sandbox would be useful, but the hosting provider's excuse for not allowing you to use mod_python is completely bogus. All the necessary security tools for that situation are provided by the platform in the form of process and user separation. Jp From aorfanakos at gmail.com Sun Jan 30 21:53:21 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 30 Jan 2005 18:53:21 -0800 Subject: Regarding exception handling In-Reply-To: References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> Message-ID: <1107140001.441995.32280@z14g2000cwz.googlegroups.com> I need it because the "various code" may raise other exceptions (not related to sockets). In such case, the "except socket.error, x:" won't catch it, but thanks to the "finally:", it is sure that the socket will close. From tim.golden at viacom-outdoor.co.uk Thu Jan 6 11:11:23 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 6 Jan 2005 16:11:23 -0000 Subject: OT: spacing of code in Google Groups Message-ID: <9A28C052FF32734DACB0A288A3533991035996@vogbs009.gb.vo.local> [Peter Hansen] | [Steve Holden] | > Peter Hansen wrote: | >> But the whole argument is fairly moot... I've needed a rectangle | >> operation only once in the last ten years, and if I hadn't known at | >> the time that my editor could do it (and spent about half an hour | >> figuring out how it worked), I could have written a utility to | >> do the job faster if I'd been using Python at the time... | > | > Or even used cut(1) from the command line. | | Or myybe not :-) | | Microsoft Windows XP [Version 5.1.2600] | (C) Copyright 1985-2001 Microsoft Corp. | | c:\>cut | 'cut' is not recognized as an internal or external command, | operable program or batch file. Thanks goodness for UnxUtils, is what I say: http://unxutils.sourceforge.net/ (But you probably knew that!) Microsoft Windows 2000 [Version 5.00.2195] (C) Copyright 1985-2000 Microsoft Corp. o:\scripts\work_in_progress\tim>c:\tools\cut --help Usage: c:\tools\cut [OPTION]... [FILE]... Print selected parts of lines from each FILE to standard output. 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 daranrife at yahoo.com Fri Jan 28 18:15:15 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 15:15:15 -0800 Subject: LinearAlgebra incredibly slow for eigenvalue problems In-Reply-To: References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> <1106952951.834888.65430@f14g2000cwb.googlegroups.com> Message-ID: <1106954115.502875.155450@f14g2000cwb.googlegroups.com> Hi John, I do have more than one version of Python laying around. To do the build and install I am typing: /d2/python/bin/python setup.by build > &! build.out /d2/python/bin/python setup.by install > &! install.out Should I be doing something different? Daran From P at draigBrady.com Tue Jan 11 05:21:16 2005 From: P at draigBrady.com (P at draigBrady.com) Date: Tue, 11 Jan 2005 10:21:16 +0000 Subject: Python & unicode In-Reply-To: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> Message-ID: Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: > Hi ! > > If Python is Ok with Unicode, why the next script not run ? > > # -*- coding: utf-8 -*- > > def ?????(toto): > return(toto*3) Because the coding is only supported in string literals. But I'm not sure exactly why. It would be nice to do: import math ? = math.pi -- P?draig Brady - http://www.pixelbeat.org -- From ktm-void at altern.org Wed Jan 12 15:05:15 2005 From: ktm-void at altern.org (Ktm) Date: Wed, 12 Jan 2005 21:05:15 +0100 Subject: m2crypto + asynchronous + stunnel Message-ID: Hello, i tried the demo echod_asyn.py without any certification verification (I modified echod_lib.py) and when I connect on the port with stunnel I've got the following error : error: uncaptured python exception, closing channel <__main__.ssl_echo_channel connected 127.0.0.1:34593 at 0xb7c5560c> (M2Crypto.SSL.SSLError:unexpected record [/usr/lib/python2.3/asyncore.py|write|77] [/usr/lib/python2.3/asyncore.py|handle_write_event|397] [echod-async.py|handle_write|33] [/usr/lib/python2.3/site-packages/M2Crypto/SSL/Connection.py|accept_ssl|84]) Thanks for your help, Ktm From corey.coughlin at attbi.com Wed Jan 5 21:24:33 2005 From: corey.coughlin at attbi.com (corey) Date: 5 Jan 2005 18:24:33 -0800 Subject: Concepts RE: Python evolution: Unease In-Reply-To: References: <20050105002302.542768387.EP@zomething.com> Message-ID: <1104978273.225072.19120@z14g2000cwz.googlegroups.com> Roman Suzi wrote: > On Wed, 5 Jan 2005, EP wrote: > > > I can try to write a PEP "Generic Programming Concepts". > That would be great. It's so hard to get your head around an abstract concept (a thought, not a programming concept) without a concrete example in some form of syntax. I think that's what's throwing off most people from the idea. And if you really do want to get it incorporated into whatever Guido is thinking, it would probably be best to hurry. ;) From newsgroups at jhrothjr.com Sat Jan 8 22:32:44 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 8 Jan 2005 21:32:44 -0600 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <1105219440.064891.199690@c13g2000cwb.googlegroups.com> Message-ID: <10u19fmj9086b8b@news.supernews.com> "jtauber" wrote in message news:1105219440.064891.199690 at c13g2000cwb.googlegroups.com... > My experiment, Cleese, was making progress before I got distracted by > other things. > > The approach was a micro-kernel in C made up of the CPython bytecode > interpreter with the file-related calls to libc ripped out and some > bare-metal port read/writes and memory operations exposed to Python as > built-in functions. > > Everything else could then be written in pure Python. Dave Long was > able to write a VGA driver in Python and an implementation of Sokoban > that used it. You could then boot your machine to Sokoban :-) > > I should probably get back to it at some stage. As my ex-wife was fond of saying, "I wish you'd have told me it was impossible before I did it." John Roth > > see http://cleese.sourceforge.net/ > James Tauber > http://jtauber.com/blog/ > From mirnazim at gmail.com Sun Jan 2 08:30:31 2005 From: mirnazim at gmail.com (mirnazim at gmail.com) Date: 2 Jan 2005 05:30:31 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <1104672631.884144.294730@c13g2000cwb.googlegroups.com> I have started a topic that is really vauge. I knew that this topic is very general and abstract but I think it turned out to be more general that I had expected. Let me make an attemp at defining "Non-Content Oriented Web Applications". A "Non-Content Oriented Web Application": (1) will be accessed from web browser(obviously). (2) will be developed using 'W3C' and other open standards(STRICTLY, to ensure compatibility and portablity). (3) will expose some kind of functionality to the user, not just some document to read. (4) functionality can be very simple to very complex. I sat down to define what I actually mean by "Non-Content Oriented Web Applications" with a fairly clear idea, But suddenly every thing vanished from my mind, "OH MY GOD, I AM OUT OF WORDS". I think all of you have been i such situation at least once. So please help me in defining these "Non-Content Oriented Web Applications". To give a example, I think GMAIL comes quite close to what I am talking aout. From dalke at dalkescientific.com Mon Jan 3 18:15:23 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Mon, 03 Jan 2005 23:15:23 GMT Subject: input record sepArator (equivalent of "$|" of perl) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> <1103657476.495700.191020@f14g2000cwb.googlegroups.com> <1103671235.093738.198680@z14g2000cwz.googlegroups.com> <86wtuup21t.fsf@guru.mired.org> Message-ID: Mike Meyer: > Trivia question: Name the second most powerfull country on earth not > using the metric system for everything. The UK? Before going there I thought they were a fully metric country. But I saw weather reports in degrees F, distances in yards and miles, and of course pints of beer. Andrew dalke at dalkescientific.com From eurleif at ecritters.biz Fri Jan 21 02:02:33 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 21 Jan 2005 02:02:33 -0500 Subject: Unbinding multiple variables In-Reply-To: References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> Message-ID: <35bnkeF4jpeetU1@individual.net> John Hunter wrote: > >>>del locals()['x'] The locals() dictionary will only modify values in a module's top-level code (i.e. when the expression "locals() is globals()" is true). From ncoghlan at iinet.net.au Sat Jan 8 01:52:03 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 16:52:03 +1000 Subject: switching an instance variable between a property and a normal value In-Reply-To: References: Message-ID: <41DF8313.6060106@iinet.net.au> Steven Bethard wrote: > where I also accept *args and **kwds when the default value is to be > called. It's certainly doable with a flag, but note that I have to > check the flag every time in both __getitem__ and setdefault. Alternatively, always use a function for the default value, and set _func to lambda: x when working by value :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tom at dev.null.daemon.de Sun Jan 9 07:32:08 2005 From: tom at dev.null.daemon.de (Thomas Linden) Date: 09 Jan 2005 13:32:08 +0100 Subject: static compiled python modules Message-ID: <87u0pqn5pz.fsf@dev.null.daemon.de> Hi, I made a static version of my python modules (2.4), all modules were build statically. The modules were linked into libpython2.4.a which has ~ 8 MB then. The build process then links the python binary against the libpython2.4.a, the resulting binary has ~ 5 MB afterwards (?). The problem is, that python ignores several modules, it tries to load the dynamic versions. E.g. if I do 'import math', it tells that it cannot find a module 'math'. Of course there is no mathmodule.so somewhere, because it is statically build-in. When I use 'nm' to take a look at the python binary, I can find all functions exported by the math module, so it is there, but python ignores it. In contrast, for example the posix module works. Its also compiled in, and doesn't exist as posixmodule.so. How can I tell python to use the compiled in modules and not try to load them from outside? kind regards, Tom -- Thomas Linden (http://www.daemon.de/) tom at co dot daemon dot de From lee at example.com Sat Jan 8 09:22:30 2005 From: lee at example.com (Lee Harr) Date: Sat, 08 Jan 2005 14:22:30 GMT Subject: "A Fundamental Turn Toward Concurrency in Software" References: <10tu7s9tjnbur81@news.supernews.com> Message-ID: >> [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that the >> continous CPU performance gain we've seen is finally over. And that future >> gain would primary be in the area of software concurrency taking advantage >> hyperthreading and multicore architectures. >> > Well, yes. However, it's not as bad as it looks. I've spent a good part > of my professional life with multiprocessors (IBM mainframes) and > I have yet to write a multi-thread program for performance reasons. > All of those systems ran multiple programs, not single programs > that had to take advantage of the multiprocessor environment. > Your typical desktop is no different. My current system has 42 > processes running, and I'd be willing to bet that the vast majority > of them aren't multi-threaded. > Exactly. If every one of your processes had its own 2 Ghz processor running nothing else, I think you would be pretty happy. Your OS had better be well-written to deal with concurrent access to memory and disks, but I think for general application development there will be huge speed boosts with little need for new programming paradigms. From beliavsky at aol.com Thu Jan 27 08:58:00 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 27 Jan 2005 05:58:00 -0800 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106814263.835719.181360@z14g2000cwz.googlegroups.com> <1106826024.655143.227050@c13g2000cwb.googlegroups.com> Message-ID: <1106834280.360742.116380@c13g2000cwb.googlegroups.com> michele.simionato at gmail.com wrote: > >> There is not much than can be done at the Python level. But I would > >> see with interest a Python spinoff geared towards simplicity. > > >I think this would be useless because advanced concepts exist for > >a reason. A simplified spin-off would aquire advanced concepts > >over time and would just become a clone of Python. > > And then we will need another simplified spinoff ;) > There is always a fight between simplificity and complexity. > Some complexity is not needed, and I am sure even in Python > something could be dropped. But it is difficult to find what can > be removed. Remember that Saint-Exupery quote? Something > like "a work of art is finished when there is nothing left to remove?" > M.S. "Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." I know this quote because it is the motto of the F programming language http://www.fortran.com/F/ , a "simplified spinoff" of Fortran 95. From reinhold-birkenfeld-nospam at wolke7.net Sat Jan 22 14:45:49 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 22 Jan 2005 20:45:49 +0100 Subject: default value in a list In-Reply-To: References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> <1gqs9gb.1mmtpcit05ruwN%aleaxit@yahoo.com> Message-ID: <35fordF4llio5U1@individual.net> Michael Spencer wrote: > Alex Martelli wrote: > [explanation and the following code:] > >> >>> a, b, c = it.islice( >> ... it.chain( >> ... line.split(':'), >> ... it.repeat(some_default), >> ... ), >> ... 3) >> ... >> ... >> >>> def pad_with_default(N, iterable, default=None): >> ... it = iter(iterable) >> ... for x in it: >> ... if N<=0: break >> ... yield x >> ... N -= 1 >> ... while N>0: >> ... yield default >> ... N -= 1 > > Why not put these together and put it in itertools, since the requirement seems > to crop up every other week? > > >>> line = "A:B:C".split(":") > ... > >>> def ipad(N,iterable, default = None): > ... return it.islice(it.chain(iterable, it.repeat(default)), N) > ... > >>> a,b,c,d = ipad(4,line) > >>> a,b,c,d > ('A', 'B', 'C', None) Good idea! (+1 if this was posted on python-dev!) Reinhold From tom.blackwell at sympatico.ca Tue Jan 4 17:55:15 2005 From: tom.blackwell at sympatico.ca (Tom Blackwell) Date: Tue, 04 Jan 2005 17:55:15 -0500 Subject: Bug in handling of single underscore identifiers? Message-ID: Today I installed the 'mechanoid' package from sourceforge, but the self-test failed. On looking into it, I noticed odd behaviour in the handling of single underscore module names. Importing into the current namespace with 'from' seems to work, but accessing members of the imported module only works if the imported name is qualified by the containing module name. For example: >>> from mechanoid import _mechanoid_Common >>> from _mechanoid_Common import Common Traceback (most recent call last): File "", line 1, in ? ImportError: No module named _mechanoid_Common >>> from mechanoid._mechanoid_Common import Common **succeeds** >>> _mechanoid_Common Is this a bug or a feature? The language reference section 2.3.2 'Reserved classes of identifiers' indicates that identifiers starting with a single underscore are not imported by "from module import *". However I can't find any indication that "from module import _name" should work this way. Thanks Tom From jeff at ccvcorp.com Tue Jan 25 20:43:20 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 25 Jan 2005 17:43:20 -0800 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <10vdt2bpr0m84db@corp.supernews.com> Davor wrote: > [...] what I need that Python has and bash&dos don't is: > > 1. portability (interpreter runs quite a bit architectures) > 2. good basic library (already there) > 3. modules for structuring the application (objects unnecessary) > 4. high-level data structures (dictionaries & lists) > 5. no strong static type checking > 6. very nice syntax But modules, lists, and dictionaries *are* all objects, and one uses standard object attribute-access behavior to work with them. > so initially I was hoping this is all what Python is about, but when I > started looking into it it has a huge amount of additional (mainly OO) > stuff which makes it in my view quite bloated now... If you're basing your opinion of OO off of C++ and Java, then it's not too surprising that you're wary of it. But really, the OO in Python is as simple and transparent as the rest of the syntax. You don't need to define your own classes if you don't want to -- it's quite easy to write modules that contain only simple functions. A trivial understanding of objects & object attributes is needed to use the OO portions of the standard library. If you really want, you can still dictate that your own project's code be strictly procedural (i.e. you can use objects but not define objects). > anyhow, I guess > I'll have to constrain what can be included in the code through > different policies rather than language limitations... You mention elsewhere the fear of some developer with a 50-layer inheritance heirarchy. That's not something that normally happens in Python. Indeed, one of the tenets of the Zen of Python is that "flat is better than nested". But more than that, it's just not necessary to do that sort of thing in Python. In statically typed languages like C++ and Java, inheritance trees are necessary so that you can appropriately categorize objects by their type. Since you must explicitly declare what type is to be used where, you may need fine granularity of expressing what type a given object is, which requires complex inheritance trees. In Python, an object is whatever type it acts like -- behavior is more important than declared type, so there's no value to having a huge assortment of potential types. Deep inheritance trees only happen when people are migrating from Java. ;) Jeff Shannon Technician/Programmer Credit International From nick at craig-wood.com Fri Jan 28 13:30:00 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 28 Jan 2005 18:30:00 GMT Subject: debugging os.spawn*() calls References: <16890.22749.899414.324589@montanaro.dyndns.org> Message-ID: Martin Franklin wrote: > Skip Montanaro wrote: > > I have an os.spawnv call that's failing: > > > > pid = os.spawnv(os.P_NOWAIT, "ssh", > > ["ssh", remote, > > "PATH=%(path)s nice -20 make -C %(pwd)s" % locals()]) > > > > When I wait for it the status returned is 32512, indicating an exit status > > of 127. Unfortunately, I see no way to collect stdout or stderr from the > > spawned process, so I can't tell what's going wrong. > > While not a 'real' answer - I use pexpect to automate my ssh scripts > these days as I had a few problems using ssh with the os.* family > perhaps you may find pexpect a wee bit easier... If using 2.4 the subprocess module is a good solution too. It lets you catch stdout/stderr easily. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From mensanator at aol.com Sun Jan 9 23:51:16 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 9 Jan 2005 20:51:16 -0800 Subject: Old Paranoia Game in Python In-Reply-To: References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> <1105318366.966577.107460@c13g2000cwb.googlegroups.com> Message-ID: <1105332676.467941.155980@c13g2000cwb.googlegroups.com> Paul McGuire wrote: > wrote in message > news:1105318366.966577.107460 at c13g2000cwb.googlegroups.com... > > > > Aahz wrote: > > > Trust the computer, the computer is your friend. > > > > However, the computer isn't a fuckin' mind reader. > > > > If you're going to post source code on the usenet, don't > > have lines longer than 72 characters. Otherwise you'll > > find your code has wrapped lines. This not only causes > > syntax errors in your choose and print statements but > > also fucks up the formatting of of printed paragraphs. > > > > Stupid human. > > > > I copy-and-pasted to a file named para1.py, then wrote the > following python script with pyparsing to fix the erroneous > line breaks. > > -- Paul > > =============================== > from pyparsing import * > > extraLineBreak = White(" ",exact=1) + LineEnd().suppress() > text = file("para1.py").read() > newtext = extraLineBreak.transformString(text) > file("para2.py","w").write(newtext) Damn, that was pretty neat! You learn something new every day. From jarausch at skynet.be Mon Jan 3 11:55:40 2005 From: jarausch at skynet.be (Helmut Jarausch) Date: Mon, 03 Jan 2005 17:55:40 +0100 Subject: Is it possible to open a dbf In-Reply-To: References: <0F3Ad.3192$5R.2578@newssvr21.news.prodigy.com> <7xy8fjywar.fsf@ruckus.brouhaha.com> Message-ID: <41D9790C.4080907@skynet.be> Mikl?s P wrote: >>Paul Rubin wrote: >> >> >>>John Fabiani writes: >>> >>>>I'm wondering if there is a module available that will open a dbf >>> >>So far (more than a minute) I have discovered a reader only. So if you > > have > >>a URL or a search string it would be very helpful. > > >>TIA >>John > > > Yes, "dBase Python" yields only some code for reading dBase ... and lots of > enquires about such a thing... > I've been using http://www.fiby.at/dbfpy/ without any problems including writing/modifying dbf files. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From beliavsky at aol.com Sat Jan 8 09:18:39 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 8 Jan 2005 06:18:39 -0800 Subject: Other notes References: <1104287020.804167.9420@f14g2000cwb.googlegroups.com> <863bxpuhlj.fsf@guru.mired.org> <41d35721.1382016815@news.oz.net> Message-ID: <1105193919.577670.176960@f14g2000cwb.googlegroups.com> Bengt Richter wrote: >OTOH, there is precedent in e.g. fortran (IIRC) for named operators of the >form .XX. -- e.g., .GE. for >= so maybe there could be room for both. Yes, but in Fortran 90 "==", ">=" etc. are equivalent to ".EQ." and ".GE.". It is also possible to define operators on native and user-defined types, so that Y = A .tx. B can be written instead of the expression with the F90 intrinsic functions Y = matmul(transpose(A),B) The Fortran 95 package Matran at http://www.cs.umd.edu/~stewart/matran/Matran.html uses this approach to simplify the interface of the Lapack library and provide syntax similar to that of Matlab and Octave. I don't know if the syntax of your idea clashes with Python, but it is viable in general. From vze4rx4y at verizon.net Tue Jan 4 15:59:24 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 04 Jan 2005 20:59:24 GMT Subject: why does UserDict.DictMixin use keys instead of __iter__? References: <1104836152.639270.196200@z14g2000cwz.googlegroups.com> <1RxCd.847728$8_6.18665@attbi_s04> Message-ID: [Steven Bethard] > Sorry, my intent was not to say that I didn't know from the docs that > UserDict.DictMixin required keys(). Clearly it's documented. My > question was *why* does it use keys()? Why use keys() when keys() can > be derived from __iter__, and __iter__ IMHO looks to be a more basic > part of the mapping protocol. Viewed from the present, __iter__() may seem more basic. However, it is a recent innovation. The keys() method, on the other hand, goes back to the beginning. There were no shortage of mapping-like classes defining keys() but not __iter__(). Still, if __iter__() is provided, UserDict.DictMixin will take advantage of it. The same is also true for __contains__(), and iteritems(). Raymond Hettinger From simoninusa2001 at yahoo.co.uk Sat Jan 8 20:01:45 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 8 Jan 2005 17:01:45 -0800 Subject: Python Installation In-Reply-To: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> References: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> Message-ID: <1105232505.142279.85810@c13g2000cwb.googlegroups.com> brolewis wrote: > I need to install Python on a number of laptop computers (at least a > dozen). I am needing to install Python 2.4, pycrypto, win32all, > wxPython, and pyCurl. You could try the recently-announced MOVPY, or NSIS/InnoSetup as you say. Or simply put the five installers on a disk - if it's only a dozen machines, it's not going to take long if you don't have to download each time. They are simple .exe installers, it's not as if you have to compile and deal with dependancies etc. like on Linux. I would say install on one machine, then just copy the C:\Python24 directory, but then you'd have to deal with the missing Registry entries.... From eric_brunel at despammed.com Fri Jan 7 06:03:14 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 07 Jan 2005 12:03:14 +0100 Subject: Tkinter Puzzler In-Reply-To: References: Message-ID: <41de6aa3$0$3508$8fcfb975@news.wanadoo.fr> Tim Daneliuk wrote: > I am trying to initialize a menu in the following manner: > > for entry in [("Up", KeyUpDir), ("Back", KeyBackDir), ("Home", > KeyHomeDir), ("Startdir", KeyStartDir), ("Root", KeyRootDir)]: > > func = entry[1] > UI.ShortBtn.menu.add_command(label=entry[0], command=lambda: > func(None)) > > However, at runtime, each of the menu options binds to the *last* function > named in the list (KeyStartDir). > > Explicitly loading each entry on its own line works fine: > > UI........command=lambda:KeyWHATEVERDir(None) > > Any ideas why the first form does not fly? This has nothing to do with Tkinter, but only with the way nested scopes work: to put it roughly, your "lambda: func(None)" only knows about the *name* func, which is not actually evaluated until the button is pressed. And when the button is pressed, the name func is bound to the last command in the loop. To do what you want, change your code to: for entry in (...): UI.ShortBtn.menu.add_command( label=entry[0], command=lambda func=entry[1]: func(None) ) This way, the value for the func parameter is evaluated when the function is defined and not when it is called. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From frans.englich at telia.com Mon Jan 17 16:03:11 2005 From: frans.englich at telia.com (Frans Englich) Date: Mon, 17 Jan 2005 21:03:11 +0000 Subject: Assigning to self In-Reply-To: <10uo6hbn040qt24@news.supernews.com> References: <10uo6hbn040qt24@news.supernews.com> Message-ID: <200501172103.11294.frans.englich@telia.com> On Monday 17 January 2005 20:03, John Roth wrote: > "Frans Englich" wrote in message > In other words, you're trying to create a singleton. In general, > singletons are frowned on these days for a number of reasons, > not least because of the difficulty of testing them. Then I have some vague, general questions which perhaps someone can reason from: what is then the preferred methods for solving problems which requires Singletons? Is it only frowned upon in Python code? Cheers, Frans From skip at pobox.com Mon Jan 31 17:48:05 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 31 Jan 2005 16:48:05 -0600 Subject: Request for Feedback; a module making it easier to use regular expressions. In-Reply-To: <310120051504352505%kenneth.m.mcdonald@sbcglobal.net> References: <310120051504352505%kenneth.m.mcdonald@sbcglobal.net> Message-ID: <16894.46501.762775.378035@montanaro.dyndns.org> Ken> rex is a module intended to make regular expressions easier to Ken> create and use... Have you checked out Ping's rxb module? http://lfw.org/python/ Skip From evan at tokenexchange.com Mon Jan 17 12:42:33 2005 From: evan at tokenexchange.com (Evan Simpson) Date: Mon, 17 Jan 2005 11:42:33 -0600 Subject: Producer/consumer Queue "trick" In-Reply-To: References: Message-ID: <41EBF909.9010208@tokenexchange.com> I should clarify up front that I may have given an overblown sense of how long the producer thread typically takes to generate a board; It's usually a few tenths of a second, up to a few seconds for especially fecund boards. My concern was that even a few seconds is long enough for fifty requests to get piled up, and I was experiencing mysterious breakdowns where Apache was suddenly totally clogged up and taking *minutes* to respond. Jeremy Bowers wrote: > Looking over your information about "how to play", my only guess is that > you're generating all possible words that may exist in the board, at the > time of board generation. Yep. I do this in order to minimize the cost of the most common request that WEBoggle handles, which is checking a submitted word to see whether it is a valid word on the board, a valid word not on the board, or an invalid word. With the current code, this averages 1ms. > But it also looks like you score once at the end (as you have to anyhow in > order to cancel out words found by multiple people, according to the rules > of Boggle). WEBoggle is a little different than regular Boggle, in that your score is the plain sum of the scores for all of the words that you found, with no cancellation. I'm planning to add a "vs." feature eventually that will involve cancellation, but even then I'll retain the immediate feedback upon guessing a word. In addition, many players enjoy seeing the list of "Words not found by anyone". > (The other thing I can think of is that you are trying to verify that the > board contains some minimal number of words, in which case I submit that > boards with only 20-ish words is just part of the game :-) I've never sat > down and really studied the Boggle dice, but I've always expected/hoped > that there is at least one or two dice with all vowels; even so the odds > of no vowels are small and easily algorithmically discarded. ) Believe it or not, before I added code to filter them out, I was generating enough boards with *zero* valid words on them to get complaints. > Also, entirely separate plug, you may be interested in my XBLinJS project Very nifty! Well beyond my current needs, but good to know about. Cheers, Evan @ 4-am From roy at panix.com Wed Jan 5 17:05:40 2005 From: roy at panix.com (Roy Smith) Date: 5 Jan 2005 17:05:40 -0500 Subject: Building unique comma-delimited list? Message-ID: I've got a silly little problem that I'm solving in C++, but I got to thinking about how much easier it would be in Python. Here's the problem: You've got a list of words (actually, they're found by searching a data structure on the fly, but for now let's assume you've got them as a list). You need to create a comma-delimited list of these words. There might be duplicates in the original list, which you want to eliminate in the final list. You don't care what order they're in, except that there is a distinguised word which must come first if it appears at all. Some examples ("foo" is the distinguised word): ["foo"] => "foo" ["foo", "bar"] => "foo, bar" ["bar", "foo"] => "foo, bar" ["bar", "foo", "foo", "baz", "bar"] => "foo, bar, baz" or "foo, baz, bar" The best I've come up with is the following. Can anybody think of a simplier way? -------------------- words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] # Eliminate the duplicates; probably use set() in Python 2.4 d = dict() for w in words: d[w] = w if d.has_key ("foo"): newWords = ["foo"] del (d["foo"]) else: newWords = [] for w in d.keys(): newWords.append (w) s = ', '.join (newWords) print s -------------------- From elephantum at dezcom.mephi.ru Sat Jan 8 06:44:44 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sat, 08 Jan 2005 14:44:44 +0300 Subject: python3: 'where' keyword In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> Message-ID: <349vdcF45c9crU2@individual.net> Nick Coghlan wrote: >> It also allows the necessary but uninteresting setup for an expression >> to be moved "out of the way", bringing the expression that does the >> real work to prominence. > Killer app for this keyword: > > class C(object): > > x = property(get, set) where: > def get(self): > return "Silly property" > def set(self, val): > self.x = "Told you it was silly" oh, that's great! I can't imagine prettier example From steve at holdenweb.com Mon Jan 24 10:52:04 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Jan 2005 10:52:04 -0500 Subject: Right place for third party modules (here: fixedpoint) In-Reply-To: <35kj2iF4n6sokU1@news.dfncis.de> References: <35kj2iF4n6sokU1@news.dfncis.de> Message-ID: Sibylle Koczian wrote: > Hello, > > for the first time since getting Python I can't get a third party module > to work. > > I got fixedpoint.0.1.2.tar.gz from SourceForge for use with KinterbasDB. > After unpacking I had a directory called "fixedpoint" which I put under > my site-packages directory. There are no installation instructions and > just the one module fixedpoint.py (and some documentation and examples). > > All of this under Windows XP, with Python 2.4. > > Now I try to use the module, but > > import fixedpoint > > says "ImportError: No module named fixedpoint". > > I suppose fixedpoint is no package as described in the tutorial and so > "site-packages" might not be the right place for it. But where does it > belong? I think it should go somewhere in the Python directory tree, not > among my own scripts. > > Thank you, > Koczian > Instead, just move the "fixedpoint.py" file to your site-packages directory. You can then delete the empty fixedpoint directory, as it won't do anything except get in the way. Packages are implemented as directories, but modules are single Python files. "Site-packages" is a perfectly acceptable place to put "site modules" as well ;-) 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 jelle.feringa at ezct.net Mon Jan 17 09:27:14 2005 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Mon, 17 Jan 2005 15:27:14 +0100 Subject: OCAMl a more natural extension language for python? In-Reply-To: <41ebb95e$0$6625$8fcfb975@news.wanadoo.fr> Message-ID: <20050117142655.8D02C1C001EC@mwinf0203.wanadoo.fr> Hmmmm. Not familiar with erlang at all... > Subject: Re: OCAMl a more natural extension language for python? > > Hi ! > > OCAML is very complementary at Python : > > unreadable vs readable That's depending on how you compare; I find OCAML quite readable compared to C / Fortran > functionnel vs procedural/POO/etc. OCAML is not a true functional language, its also OO > compiled vs interpreted (or compil JIT) > very fast vs mean velocity What I'm looking for! > hard to learn vs easy to easy to learn Is it in comparison to C? > Yes, OCAML is very complementary, too much, much too, complementary at > Python... > > But, C is not complementary to Python (in the same state of mind). So some additional arguments to the hypotheses of OCAMl being a natural extension language to Python? Cheers, Jelle. From perrin.aybara81 at gmail.com Tue Jan 18 10:03:41 2005 From: perrin.aybara81 at gmail.com (Perrin Aybara) Date: Tue, 18 Jan 2005 20:33:41 +0530 Subject: bind error!!!!! Message-ID: hi.. my code was working pretty well until yesterday.suddenly it started giving me bind error: address already in use. but i have logged out and again logged in, but still the problem is not solved can somebody give me solution for this thankx perrin From peter at engcorp.com Sun Jan 9 13:48:57 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 13:48:57 -0500 Subject: Guild of Python consultants? In-Reply-To: References: Message-ID: Mikl?s P wrote: > Hello freelancers out there, > > Is there such a thing somewhere? Yes, I'm aware of the Python Business > Forum. But I mean something specifically for (individual) consultants. > By searching on Google, I couldn't find a "virtual guild" of consultants who > try to make a living from Python and technologies built around it The term "consultant" means different things to different people, unfortunately. I know of many people for whom "consultant" is synonymous with "contract programmer", meaning somebody who looks for temporary positions at (usually) an hourly rate somewhat higher than what a permanent employee gets (but without benefits), and who simply joins a team as a regular member, doing whatever they are told. Some have special expertise, many do not. I also know of many people (myself included) who restrict the term to those who have a deep expertise in one or more areas and who look for projects where they can be brought in to apply that expertise, usually by telling the customer what to do (or what not to do any more, perhaps). This sort of work can be hourly, or quite often daily or even at a fixed price (say, for specialized "emergency" troubleshooting, or for a design task). There is obviously overlap between those two descriptions but, in my experience, very little overlap between the sorts of work which those two breeds of "consultants" actually want to perform. (The second type will take on jobs that the former would take, often grudgingly if work is scarce, while the former are rarely qualified to take on the sort of work that interests the latter.) As a result, I suspect that any organization that doesn't make it clear which type of "consultant" is involved could cause a great deal of confusion amongst its members and their clients. Which type do you mean? -Peter From tzot at sil-tec.gr Wed Jan 26 05:51:19 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 26 Jan 2005 12:51:19 +0200 Subject: string.atoi and string.atol broken? References: <1106700417.482871.45140@z14g2000cwz.googlegroups.com> Message-ID: On Wed, 26 Jan 2005 08:58:45 +0100, rumours say that Peter Otten <__peter__ at web.de> might have written: >By the way, does anyone know the Greek name for 36? triakontahexadecimal would be a nice compromise of greek and the "hexadecimal" convention of having six before ten -- "???" ("hexi") is six, "????" ("deka") is ten, "?????????" ("triakonta") is thirty. I think in ancient Greek sometimes units came before tens, just like in German (another similarity is the verb in the end of the sentence, as Mark Twain also noted sometime in a humourous article AFAIR.) In current Greek hexadecimal is "????????????" ("dekaexadikon"). -- 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 michele.simionato at gmail.com Tue Jan 4 05:55:29 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 4 Jan 2005 02:55:29 -0800 Subject: The Industry choice In-Reply-To: <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> Message-ID: <1104836129.741586.179510@c13g2000cwb.googlegroups.com> But then I have THREE published recipes!! Does that mean that I get three free copies of the cookbook ? ;-) Michele From http Sat Jan 8 05:34:08 2005 From: http (Paul Rubin) Date: 08 Jan 2005 02:34:08 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> Message-ID: <7xhdlsw6ov.fsf@ruckus.brouhaha.com> AdSR writes: > > Killer app for this keyword: > > class C(object): > > x = property(get, set) where: > > def get(self): > > return "Silly property" > > def set(self, val): > > self.x = "Told you it was silly" > > Hey, this is super-elegant! Heh, even further: z = C() where: class C(object): ... Lets you make anonymous classes and singleton objects. From skip at pobox.com Sat Jan 8 08:49:51 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 8 Jan 2005 07:49:51 -0600 Subject: Pre/Postconditions with decorators In-Reply-To: <1105190031.287227.319360@c13g2000cwb.googlegroups.com> References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> <34814fF43bm4cU1@individual.net> <1105190031.287227.319360@c13g2000cwb.googlegroups.com> Message-ID: <16863.58623.491403.349653@montanaro.dyndns.org> >> Eiffel (language) has both type checking and design by contract. >> Python lacks both. Actually, Python is strongly typed. It's just dynamically instead of statically typed. Skip From cwittern at yahoo.com Wed Jan 12 21:59:14 2005 From: cwittern at yahoo.com (Christian Wittern) Date: 12 Jan 2005 18:59:14 -0800 Subject: Re Wide Unicode build for Windows available somewhere? Message-ID: <5d5d851f.0501121859.56c33f0c@posting.google.com> > Wide unicode is currently not supported on Windows. A number of > internal APIs (in particular for the registry, and for the "mbcs" > codec) assume that sizeof(Py_UNICODE) is 2. Contributions are > welcome. >Even with that fixed, Pythonwin would still need a major rework > to support wide Unicode. Thanks Martin for your reply. So this looks rather dim. I usually work on a Mac, where wide support is just a matter of ./configure --enable-unicode=ucs4 make so I foolishly thought it must be similar on Windows. All the best, chris From skip at pobox.com Sun Jan 2 20:52:05 2005 From: skip at pobox.com (Skip Montanaro) Date: Sun, 2 Jan 2005 19:52:05 -0600 Subject: Calling Function Without Parentheses! In-Reply-To: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> Message-ID: <16856.42309.676788.850210@montanaro.dyndns.org> Kamilche> I called a function without the ending parentheses. I sure do Kamilche> WISH Python would trap it when I try to do the following: Kamilche> MyFunc Kamilche> instead of: Kamilche> MyFunc() Google for pychecker. Skip From kartic.krishnamurthy at gmail.com Wed Jan 12 15:39:05 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 12 Jan 2005 12:39:05 -0800 Subject: encryption/decryption help In-Reply-To: <7xwtuibd26.fsf@ruckus.brouhaha.com> References: <7xwtuibd26.fsf@ruckus.brouhaha.com> Message-ID: <1105562345.525224.319120@z14g2000cwz.googlegroups.com> Hi, Can you use ssh tunneling? You will not be changing anything except add an extra ssh layer to tunnel your data through. There is how-to at http://www.ccs.neu.edu/groups/systems/howto/howto-sshtunnel.html (or you can google for tunneling) Please note you can not use MD5 as it is not reversible. Thanks, --Kartic From marklists at mceahern.com Wed Jan 19 22:29:50 2005 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 19 Jan 2005 21:29:50 -0600 Subject: list item's position In-Reply-To: References: Message-ID: <41EF25AE.6060403@mceahern.com> Bob Smith wrote: > Hi, > > I have a Python list. I can't figure out how to find an element's > numeric value (0,1,2,3...) in the list. Here's an example of what I'm > doing: Use enumerate() (new in Python 2.3, IIRC). Otherwise: for i in range(len(sequence)): item = sequence[i] ... > > for bar in bars: > if 'str_1' in bar and 'str_2' in bar: > print bar > > This finds the right bar, but not its list position. The reason I need > to find its value is so I can remove every element in the list before > it so that the bar I found somewhere in the list becomes element 0... > does that make sense? Sure. You want to slice the list starting at the index of the first occurrence: index = min([i for i, item in enumerate(sequence) if 'str_1' in item and 'str_2' in item]) print sequence[index:] // m From steven.bethard at gmail.com Sun Jan 2 14:30:22 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 02 Jan 2005 19:30:22 GMT Subject: arbitrary number of arguments in a function declaration In-Reply-To: References: Message-ID: rbt wrote: > How do I set up a function so that it can take an arbitrary number of > arguments? If you haven't already, you should check out the Tutorial: http://docs.python.org/tut/node6.html#SECTION006730000000000000000 > How might I make this dynamic so > that it can handle any amount of expenses? > > def tot_expenses(self, e0, e1, e2, e3): > pass py> class C(object): ... def tot_expenses(self, *expenses): ... print expenses ... py> C().tot_expenses(110, 24) (110, 24) py> C().tot_expenses(110, 24, 2, 56) (110, 24, 2, 56) Steve From peter at somewhere.com Wed Jan 26 08:10:47 2005 From: peter at somewhere.com (Peter Maas) Date: Wed, 26 Jan 2005 14:10:47 +0100 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: Davor schrieb: > so initially I was hoping this is all what Python is about, but when I > started looking into it it has a huge amount of additional (mainly OO) > stuff which makes it in my view quite bloated now. So you think f.write('Hello world') is bloated and file_write(f,'Hello world') is not? This is the minimum amount of OO you will see when using Python. But I guess you will use OO in the long run to *avoid* bloated code: --------------snip--------------- print "*** Davor's evolution towards an OO programmer ***" print '\n*** Step 1: OO is evil, have to use atomic variables:' name1 = 'Smith' age1 = 35 sex1 = 'male' name2 = 'Miller' age2 = 33 sex2 = 'female' print name1, age1, sex1, name2, age2, sex2 print '\n*** Step 2: This is messy, put stuff in lists:' p1 = ['Smith', 35, 'male'] p2 = ['Miller', 33, 'female'] for e in p1: print e for e in p2: print e print '\n*** Step 3: Wait ..., p[2] is age, or was it sex? Better take a dict:' p1 = dict(name = 'Smith', age = 35, sex = 'male') p2 = dict(name = 'Miller', age = 33, sex = 'female') for e in p1.keys(): print '%s: %s' % (e, p1[e]) for e in p2.keys(): print '%s: %s' % (e, p2[e]) print '\n*** Step 4: Have to create person dicts, invoice dicts, ...better use dict templates:' class printable: def __str__(self): '''magic method called by print, str() ..''' ps = '' for e in self.__dict__.keys(): ps += '%s: %s\n' % (e, str(self.__dict__[e])) return ps class person(printable): def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex class invoice(printable): def __init__(self, name, product, price): self.name = name self.product = product self.price = price per = person(name = 'Smith', age = 35, sex = 'male') inv = invoice(name = 'Smith', product = 'bike', price = 300.0) print per print inv --------------snip--------------- Either your program is small. Then you can do it alone. Or you will reach step 4. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From jbenson at sextans.lowell.edu Tue Jan 25 23:11:49 2005 From: jbenson at sextans.lowell.edu (Jim Benson) Date: Tue, 25 Jan 2005 21:11:49 -0700 (MST) Subject: OT In-Reply-To: Message-ID: On Wed, 26 Jan 2005 phr at sextans.lowell.edu wrote: > That sounds like you're doing a closed source product and need an ENC > exception or something even worse. Python should qualify for the TSU > exception which only requires sending an email. > > http://www.bxa.doc.gov/encryption/PubAvailEncSourceCodeNofify.html > Sorry for the completely off-topic question. Last night and now tonight i have seen legitimate posts from phr that resolves as: Date: Wed, 26 Jan 2005 03:43:49 GMT From: phr at sextans.lowell.edu To: python-list at python.org Newsgroups: comp.lang.python Subject: Re: Crypto in Python: (Was: What's so funny? WAS Re: rotor replacement) However, i know for a fact that phr is _not_ a user at sextans.lowell.edu. Is this a problem with my dns? Thanks Jim From gdamjan at gmail.com Wed Jan 26 08:13:15 2005 From: gdamjan at gmail.com (Damjan) Date: Wed, 26 Jan 2005 14:13:15 +0100 Subject: execute python code from db References: Message-ID: <35pjbbF4n84hrU1@individual.net> > for python_code in c.fetchall(): > execute (python_code) > > Maybe feed python with stdin??. eval -- damjan From sp1d3rx at gmail.com Tue Jan 18 14:51:59 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 18 Jan 2005 11:51:59 -0800 Subject: Fuzzy matching of postal addresses In-Reply-To: References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <1106077919.685449.81300@c13g2000cwb.googlegroups.com> I think you guys are missing the point. All you would need to add to get a 'probable match' is add another search that goes through the 10% that didnt get matched and do a "endswith" search on the data. From the example data you showed me, that would match a good 90% of the 10%, leaving you with a 1% that must be hand matched. You would have to combine this idea with Jeff Shannon's idea to make it work more efficiently. From tundra at tundraware.com Sun Jan 23 06:52:39 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 23 Jan 2005 06:52:39 EST Subject: Insanity In-Reply-To: References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> Message-ID: <3sfcc2-b6v1.ln1@eskimo.tundraware.com> Fredrik Lundh wrote: > Tim Daneliuk wrote: > > >>Given an arbitrary string, I want to find each individual instance of >>text in the form: "[PROMPT:optional text]" >> >>I tried this: >> >> y=re.compile(r'\[PROMPT:.*\]') >> >>Which works fine when the text is exactly "[PROMPT:whatever]" > > > didn't you leave something out here? "compile" only compiles that pattern; > it doesn't match it against your string... Sorry - I thought this was obvious - I was interested more in the conceptual part of the contruction of the re itself. > >>but does not match on: >> >> "something [PROMPT:foo] something [PROMPT:bar] something ..." >> >>The overall goal is to identify the beginning and end of each [PROMPT...] >>string in the line. > > > if the pattern can occur anywhere in the string, you need to use "search", > not "match". if you want multiple matches, you can use "findall" or, better > in this case, "finditer": > > import re > > s = "something [PROMPT:foo] something [PROMPT:bar] something" > > for m in re.finditer(r'\[PROMPT:[^]]*\]', s): > print m.span(0) > > prints > > (10, 22) > (33, 45) > > which looks reasonably correct. > > (note the "[^x]*x" form, which is an efficient way to spell "non-greedy match" > for cases like this) > Thanks - very helpful. One followup - your re works as advertised. But if I use: r'\[PROMPT:[^]].*\]' it seems not to. the '.*' instead of just '*' it matches the entire string ... which seems counterintutive to me. Thanks, -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From miki.tebeka at zoran.com Tue Jan 11 08:26:55 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 11 Jan 2005 15:26:55 +0200 Subject: Exception not captured Message-ID: <20050111132654.GP3808@zoran.com> Hello All, Can someone please explain how is the following code fragment possible? (If you're interested I can place the whole project somewhere). def checkout(dest, log): '''Get latest version from SCM client - SCM client to use dest - Destination directory ''' try: SCM.checkout(dest, log) except SCMError, e: raise NightlyError("Checkout") except Exception, e: import inspect file = inspect.getsourcefile(e.__class__) line = inspect.getsourcelines(e.__class__)[1] print "%s:%d" % (file, line) file = inspect.getsourcefile(SCMError) line = inspect.getsourcelines(SCMError)[1] print "%s:%d" % (file, line) print SCMError is e.__class__ raise SystemExit I get to the second "except" clause, and the printout is: /home/mikit/work/nightly/scm/common.py:3 /home/mikit/work/nightly/scm/common.py:3 False How is this possible? Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From fredrik at pythonware.com Sat Jan 29 02:38:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 29 Jan 2005 08:38:38 +0100 Subject: Pystone benchmark: Win vs. Linux (again) References: Message-ID: Franco Fiorese wrote: > I am relatively new about Python benchmarks. > After some experiments I found that Python on my PC Windows XP has a relevant higher performance > than on Linux. The simple test using pystone.py shows this: > > * Windows XP Pro: 16566.7 pystones/second > * Linux (kernel 2.6.9 NPTL): 12346.2 pystones/second what Python version are you using for these tests? what Windows build? From jaydonnell at gmail.com Fri Jan 21 20:15:27 2005 From: jaydonnell at gmail.com (Jay donnell) Date: 21 Jan 2005 17:15:27 -0800 Subject: why am I getting a segmentation fault? In-Reply-To: References: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> Message-ID: <1106356527.187742.242380@f14g2000cwb.googlegroups.com> Thank you. I made all the changes you recommended and everything seems to be working. From klachemin at comcast.net Tue Jan 25 22:10:49 2005 From: klachemin at comcast.net (Kamilche) Date: 25 Jan 2005 19:10:49 -0800 Subject: Open Folder in Desktop In-Reply-To: <41f6033a$1@news.uni-ulm.de> References: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> <41f6033a$1@news.uni-ulm.de> Message-ID: <1106709049.277503.10270@z14g2000cwz.googlegroups.com> Thanks, startfile worked great for me! From gsakkis at rutgers.edu Wed Jan 26 10:39:26 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Wed, 26 Jan 2005 10:39:26 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> <10vdj4s9ib19fe3@corp.supernews.com> <41f772b2.1858112584@news.oz.net> Message-ID: <35prt9F4rbhh5U1@individual.net> "Bengt Richter" wrote in message news:41f772b2.1858112584 at news.oz.net... > On Wed, 26 Jan 2005 11:55:59 -0800, jfj wrote: > > >Jeff Shannon wrote: > > > >> > >> > >> So, what problem is it, exactly, that you think you'd solve by making > >> tuple slices a view rather than a copy? > >> > > > >I think views are good for > > 1) saving memory > > 2) saving time (as you don't have to copy the elements into the new tuple) > > > >And they are worth it. However, (as in other cases with slicing), it is > >very easy and fast to create a view for a slice with the default step > >'1', while it's a PITA and totally not worth it to create a view for a > >slice with non default step. I think it would be good to: > > > > if slice_step == 1 > > create_view > > else > > create_new_tuple > > > >Actually, i think that slices with step, is a bad feature in general > >and i think I will write a PEP to suggest their removal in python3k. > > > What's the big deal with other than 1 steps? It is just adjusting a few numbers > so that you can either index the new virtual slice with an integer and return the > element, in which case the index into the original tuple will be > someoffset+i*somefactor once you get past the limit checks for the virtual > slice. By the same token, transforming a few numbers of one virtual slice > into similar numbers for a a new virtual slice of that shouldn't be rocket science. > And it wouldn't have to be done more than once. Don't have time to do it now, > but there are plenty around here that could, I'm sure. > > Regards, > Bengt Richter Here's my (undocumented) version of it: http://rafb.net/paste/results/HkxmHp37.html and its unit test: http://rafb.net/paste/results/2LIInT68.html And some useless timing comparisons (I know it's a stupid example, don't flame me for this): $ python /usr/lib/python2.3/timeit.py \ -s "x=tuple(xrange(10000))" \ "[x[1:-1] for n in xrange(100)]" 10 loops, best of 3: 3.84e+04 usec per loop $ python /usr/lib/python2.3/timeit.py \ -s "from immutableseq import ImmutableSequence" \ -s "x=ImmutableSequence(xrange(10000))" \ "[x[1:-1] for n in xrange(100)]" 100 loops, best of 3: 5.85e+03 usec per loop Feel free to comment or suggest improvements. George From newsgroups at jhrothjr.com Sat Jan 8 12:22:45 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 8 Jan 2005 11:22:45 -0600 Subject: "A Fundamental Turn Toward Concurrency in Software" References: <20050108154453.32125.797079096.divmod.quotient.2429@ohm> <41e0131a$1_3@127.0.0.1> Message-ID: <10u05nrjgcge057@news.supernews.com> "Donn Cave" wrote in message news:41e0131a$1_3 at 127.0.0.1... > Quoth Skip Montanaro : > | > | Jp> How often do you run 4 processes that are all bottlenecked on > CPU? > | > | In scientific computing I suspect this happens rather frequently. > > I think he was trying to say more or less the same thing - responding > to "(IBM mainframes) ... All those systems ran multiple programs ... > My current system has 42 processes running ...", his point was that > however many processes on your desktop, on the rare occasion that > your CPU is pegged, it will be 1 process. The process structure of > a system workload doesn't make it naturally take advantage of SMP. > So "there will still need to be language innovations" etc. -- to > accommodate scientific computing or whatever. Your 4 processes are > most likely not a natural architecture for the task at hand, but > rather a complication introduced specifically to exploit SMP. Exactly. I wasn't addressing some of the known areas where one can take advantage of multiple processors, or where one can take advantage of threading on a single processor to avoid delays. At this point in time, though, I see multithreading for compute intensive tasks to be an intermediate step. The final step is to restructure it so it can take advantage of cluster architectures. Then you can simply ignore all of the complexity of threads. That still leaves putting long running tasks (such as printing) into the background so the UI stays responsive. > > Personally I wouldn't care to predict anything here. For all I know, > someday we may decide that we need cooler and more efficient computers > more than we need faster ones. Chuckle. I basically think of shared memory multiprocessing as being perverse: the bottleneck is memory, not compute speed, so adding more processors accessing the same memory doesn't strike me as exactly sane. Nor does pushing compute speed up and up and up when it just stressed the memory bottleneck. > > Donn Cave, donn at drizzle.com From kohlerj at ukzn.ac.za Wed Jan 26 05:16:01 2005 From: kohlerj at ukzn.ac.za (Johan Kohler) Date: Wed, 26 Jan 2005 12:16:01 +0200 Subject: "pickle" vs. f.write() Message-ID: Hi, I have a class with attributes that are string, integer and list. eg. class person: name ="" age = 0 friends=[] comment="""""" me = person() I want to save a whole bunch of instances to a file, a classic "records" file I/O. To write the file, I can do f.write(str([me.name, me.age, me.friends, me.comment]) + "\n" This works nicely for writing, but when reading, I cannot convert the string easily to a list: list(f.readline()) is not the same as [me.name, me.age, me.friends, me.comment] I was wondering whether pickle might make this easier - an example would be much appreciated. Otherwise, what is the best "Python" way to write and read this data structure? Thanks in advance... Johan __ Yes, I do feel stupid asking this, but time's-a-runnin' out.. -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ -------------------------------------------------------------------- Please find our disclaimer at http://www.ukzn.ac.za/disclaimer -------------------------------------------------------------------- <<<>>> From aleaxit at yahoo.com Tue Jan 4 03:11:12 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 4 Jan 2005 09:11:12 +0100 Subject: input record sepArator (equivalent of "$|" of perl) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> <1103657476.495700.191020@f14g2000cwb.googlegroups.com> <1103671235.093738.198680@z14g2000cwz.googlegroups.com> <86wtuup21t.fsf@guru.mired.org> Message-ID: <1gpux8t.usezvs17759pwN%aleaxit@yahoo.com> Mike Meyer wrote: ... > Trivia question: Name the second most powerfull country on earth not > using the metric system for everything. Well, then, just name the 2nd most powerful country on earth, period (I'm not going to get myself in trouble by guessing whether said 2nd country is China, Russia, "Europe" [not a country, I know;-)], ...). TVs and other displays are sold as "20 inches" (or whatever) everywhere, printers' resolutions are always given in pixels per inch, etc. Alex From simon.brunning at gmail.com Wed Jan 26 11:21:47 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 26 Jan 2005 16:21:47 +0000 Subject: Help With Python In-Reply-To: References: Message-ID: <8c7f10c605012608213850ecf0@mail.gmail.com> On Wed, 26 Jan 2005 15:55:28 -0000, Judi Keplar wrote: > I am currently taking a course to learn Python and was looking for > some help. I need to write a Python statement to print a comma- > separated repetition of the word, "Spam", written 511 times ("Spam, > Spam, ? Spam"). > > Can anybody help me get started? I am completely new to programming! Well, I don't want to give it to you on a plate, since it's homework, but you might find this page useful: . I'd also suggest that you have a run through the tutorial - . It's time well spent! If you don't get on with that, there's another couple of tutorials available aimed directly at those new to programming - and . Lastly, although neophytes are more than welcome here, you might find the tutor mailing list a good place to ask questions in the early days of your Python experience. You'll find it here - . Good luck, and welcome to Python! -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From sjmachin at lexicon.net Sun Jan 16 15:38:26 2005 From: sjmachin at lexicon.net (John Machin) Date: 16 Jan 2005 12:38:26 -0800 Subject: How to del item of a list in loop? In-Reply-To: References: Message-ID: <1105907906.257801.216630@f14g2000cwb.googlegroups.com> skull wrote: > According to Nick's article, I added three 'reversed' methods to your provided > test prog. and the result turned out method_reversed is faster than others except the 'three' case. > Following is my modified version: [snip] > def method_reversed_idx(lst): > idx = 0 > for i in reversed(lst): > if i == 2: > del lst[idx] > idx += 1 There appears to be a problem with this one: >>> def method_reversed_idx(lst): ... idx = 0 ... for i in reversed(lst): ... if i == 2: ... del lst[idx] ... idx += 1 ... >>> lst=[1,2,3];method_reversed_idx(lst);print lst [1, 3] >>> lst=[2,1,3];method_reversed_idx(lst);print lst [2, 1] >>> lst=[1,3,2];method_reversed_idx(lst);print lst [3] >>> From wnebfynj at mnovryyb.pbz Wed Jan 19 04:33:12 2005 From: wnebfynj at mnovryyb.pbz (JZ) Date: Wed, 19 Jan 2005 10:33:12 +0100 Subject: IronPython, Boo and ASP.NET (web service) Message-ID: Is there any way for preparing a simple web service (ASP.NET) using IronPython or Boo (http://boo.codehaus.org/)? I cannot find any example. C# uses [WebMethod] attribute for marking remote methods. I do not know how IronPython or Boo deals with it. -- JZ ICQ:6712522 http://zabiello.com From rmemmons at member.fsf.org Thu Jan 6 19:08:22 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Thu, 06 Jan 2005 18:08:22 -0600 Subject: How do I make Windows Application with Python ? References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> <1104929345.364701.19150@z14g2000cwz.googlegroups.com> Message-ID: On Wed, 05 Jan 2005 04:49:05 -0800, Fuzzyman wrote: > Couple of corrections - neither pypy nor starkiller are compilers. > Starkiller isn't available yet and *may* be helpful in building > compilers. Pyrex is an alternative language - a python/C hybrid that > can be compiled. > > If you want to release an application then innosetup, starkit, and upx > might help - but they're not python related. You will need something > like py2exe, cx_freeze, or mcmillan installer. (Which are specific to > python - py2exe seems to be the more mature tool). > > Alternatively you could consider 'Movable Python' - a frozen > distribution of python that doesn't need isntalling. See > http://sourceforge.net/projects/movpy Great summary. I was hoping someone would fill in the blanks. I've been interested in this area for some time -- but have not had time to look into it more than keep a list of interesting projects I wanted to research in the future. I'll add your comments to my list. Again, thanks. Rob From stephen.thorne at gmail.com Wed Jan 12 18:57:01 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 09:57:01 +1000 Subject: else condition in list comprehension In-Reply-To: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: <3e8ca5c805011215574b35bf91@mail.gmail.com> On 9 Jan 2005 12:20:40 -0800, Luis M. Gonzalez wrote: > Hi there, > > I'd like to know if there is a way to add and else condition into a > list comprehension. I'm sure that I read somewhere an easy way to do > it, but I forgot it and now I can't find it... > > for example: > z=[i+2 for i in range(10) if i%2==0] > what if I want i to be "i-2" if i%2 is not equal to 0? z = [i+2-(i%2)*4 for i in range(10)] C'mon, who needs an 'if' statement when we have maths! Stephen. From bokr at oz.net Wed Jan 5 22:15:41 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 06 Jan 2005 03:15:41 GMT Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> Message-ID: <41dcaa00.102858012@news.oz.net> On 05 Jan 2005 07:18:25 -0800, Paul Rubin wrote: >Ville Vainio writes: >> Paul> I can't parse that. It says two contradictory things. >> Paul> Sentence 2 says that if something essential is not in the >> Paul> (Python) distro then the (Python) distro maintainers have >> Paul> screwed up. Sentence 1 says it's the Fedora maintainer's >> Paul> job to deal with it. Huh? >> >> By "distro" I meant the Linux distribution, not the Python >> distribution. Distro is a customary term for a Linux distribution so I >> didn't qualify the word at the time. > >Oh ok, but it's the Python distribution that's missing components that >are essential to Python. Fedora and other Linux distros are >collections of subsystems like Python. Linux distro maintainers get >asked to include a subsystem, they check that the subsystem has a >reasonable reputation (Python does), they install it in the distro and >run some basic tests, and they ship it. They can't be expected to >immerse themselves in its intricacies and hang out on the user forums >to identify all the missing components that they should also hunt down >and ship. So the Python needs to take care of that stuff. > >I realize that in the old days, people used to write big applications >without makefiles, and later when they started using makefiles, they >didn't use configure scripts. So to install a package, you had to do >a bunch of hand configuration for your particular environment before >you could compile it, and maybe you even had to say > cc -O -Dthisflag=thatnumber xyz.c pqr.c frob.c -o frob >on the command line instead of typing "make" to build the program. >That kind of thing really doesn't fly any more. The standards for >what constitutes a properly engineered release of something have >gotten higher. You really need automatic configuration and build and >installation. Likewise, if you're trying to market something as a >complete drop-in system ("batteries included", to use the Python >terminology), it should not be missing any essential pieces that >the user has to hunt down separately. What do you think of automated secure importing/installing from a remote server? You know, you try to import something and it imports a stub that was included as a battery-place-holder and that has basic help info and will give you reasonable options in directing the installation of the full thing (or subset you are interested in). I don't see why every gee whiz thing has to be on your hard disk from the first. And for those that want a big grabbag, the stubs ought to be designed to to be runnable from a configured script, so you can turn it loose and see what's up IRL. Regards, Bengt Richter From stephen.thorne at gmail.com Mon Jan 17 09:20:02 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Tue, 18 Jan 2005 00:20:02 +1000 Subject: Native widgets for Python In-Reply-To: <41EBC7F3.5050807@web.de> References: <41EBC7F3.5050807@web.de> Message-ID: <3e8ca5c805011706207c70579a@mail.gmail.com> there's someone writing 'dabo', which is apparently "wxpython but more python". Stephen. On Mon, 17 Jan 2005 15:13:07 +0100, A. Klingenstein wrote: > Which other GUI library for Python other than wxpython has native > widgets for MS Windows ? > I know there is MFC and GDI, but I want something easier to use than wx, > not harder :) > wxpython has to problem that it handles much more like a C++ library > than a Python one sometimes. > > Alex > -- > http://mail.python.org/mailman/listinfo/python-list > From reinhold-birkenfeld-nospam at wolke7.net Fri Jan 14 14:10:30 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 14 Jan 2005 20:10:30 +0100 Subject: Octal notation: severe deprecation In-Reply-To: References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105575689.335040.174490@c13g2000cwb.googlegroups.com> <34o8n7F4e6uduU1@individual.net> Message-ID: <34qjp6F4dkctuU1@individual.net> Simon Brunning wrote: > On Thu, 13 Jan 2005 16:50:56 -0500, Leif K-Brooks wrote: >> Tim Roberts wrote: >> > Stephen Thorne wrote: >> > >> >>I would actually like to see pychecker pick up conceptual errors like this: >> >> >> >>import datetime >> >>datetime.datetime(2005, 04,04) >> > >> > >> > Why is that a conceptual error? Syntactically, this could be a valid call >> > to a function. Even if you have parsed and executed datetime, so that you >> > know datetime.datetime is a class, it's quite possible that the creation >> > and destruction of an object might have useful side effects. >> >> I'm guessing that Stephen is saying that PyChecker should have special >> knowledge of the datetime module and of the fact that dates are often >> specified with a leading zero, and therefor complain that they shouldn't >> be used that way in Python source code. > > It would be useful if PyChecker warned you when you specify an octal > literal and where the value would differ from what you might expect if > you didn't realise that you were specifying an octal literal. > > x = 04 # This doesn't need a warning: 04 == 4 > #x = 09 # This doesn't need a warning: it will fail to compile > x= 012 # This *does* need a warning: 012 == 10 Well, this would generate warnings for all octal literals except 01, 02, 03, 04, 05, 06 and 07. However, I would vote +1 for adding such an option to PyChecker. For code that explicitly uses octals, it can be turned off and it is _very_ confusing to newbies... Reinhold From skip at pobox.com Tue Jan 4 13:14:06 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Jan 2005 12:14:06 -0600 Subject: Pythonic search of list of dictionaries In-Reply-To: References: Message-ID: <16858.56558.9592.366794@montanaro.dyndns.org> Bulba> I put those dictionaries into the list: Bulba> oldl=[x for x in orig] # where orig=csv.DictReader(ofile ... Bulba> ..and then search for matching source terms in two loops: Bulba> for o in oldl: Bulba> for n in newl: Bulba> if n['English'] == o['English']: Bulba> ... Bulba> Now, this works. However, not only this is very un-Pythonic, but Bulba> also very inefficient: the complexity is O(n**2), so it scales up Bulba> very badly. How about using sets? oenglish = set([item['English'] for item in oldl]) nenglish = set([item['English'] for item in newl]) matching = oenglish & nenglish Once you have those that match, you can constrain your outer loop to just those cases where o['English'] in matching If you're not using 2.4 yet, then get sets via: from sets import Set as set That's still not all that Pythonic, but should be a bit faster. You might want to sort your lists by the 'English' key. I don't know how to use the new key arg to list.sort(), but you can still do it the old-fashioned way: oldl.sort(lambda a,b: cmp(a['English'], b['English'])) newl.sort(lambda a,b: cmp(a['English'], b['English'])) Once sorted, you can then march through the lists in parallel, which should give you an O(n) algorithm. Skip From reinhold-birkenfeld-nospam at wolke7.net Sat Jan 15 02:38:34 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 15 Jan 2005 08:38:34 +0100 Subject: How to del item of a list in loop? In-Reply-To: References: Message-ID: <34rvjqF4f6l70U1@individual.net> skull wrote: > Hi everybody, it is my first post in this newsgroup. > I am a newbie for python though I have several years development experience in c++. > recently, I was stumped when I tried to del item of a list when iteration. > > here is the wrong way I did: > > lst = [1, 2, 3] > for i in lst: > print i > if i == 2: > lst.remove(i) > > the result is: > > 1 > 2 >>>> > > as you would see, '3' is missing. this problem is caused by 'lst.remove(i)'. > apparently, 'marked-and-sweep' is a solution to deal with this issue. > but I think there SHOULD BE more 'wise' trick. I want to get your help. Quick solution: for i in lst[:] iterates over a copy. Reinhold From just at xs4all.nl Mon Jan 17 09:28:30 2005 From: just at xs4all.nl (Just) Date: Mon, 17 Jan 2005 15:28:30 +0100 Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: In article , Antoon Pardon wrote: > Op 2005-01-17, Steve Holden schreef : > > There you go with the minutiae again. How about: > > > > "Don't use mutables as hash keys"? > > That sounds too dogmatic to my ears. I also find it > too selective. The problem with mutables as dictionary > keys is not specific to dictionaries. Everywhere you > have mutables in a container, it is possible that > mutating the object in the container will cause > problem. The main difference is: if you mutate a dict key you *always* have a problem. So don't do that. Mutating (say) a list item *only* is a problem if you (say) need that list to remain sorted. Lists don't magically remain sorted, so people generally sort it before they do some operation that expects a sorted list. > Heck even using mutables as arguments can > cause trouble. Why else the specific advice against > > def foo(p = []) > > type of arguments. So should we adopt the principles: > > Don't use mutables in containers Nonsense. > Don't use mutables as default values for parameters That's good advice in general. > Don't use mutables as arguments. Nonsense. > Don't assign one mutable to an other. Nonsense. Some newbies get surprised by Python's assignment-doesn't-copy semantics, but it's such basic knowledge (as well as a useful feature) that I simply don't understand you saying this. > I don't see a big difference between these principles > and the hash key principle, Than you haven't looked hard enough. > so in the end may be we > should just stick with the more general principle: > > Don't use mutables! > > > and be done with it. Ok, so you're indeed a troll. Just From andersjm at inbound.dk Sat Jan 1 08:20:06 2005 From: andersjm at inbound.dk (Anders J. Munch) Date: Sat, 1 Jan 2005 14:20:06 +0100 Subject: Speed ain't bad References: <0189t05r3226bkp5e1vtmp0gd6odcsf2qp@4ax.com> Message-ID: <41d6a39b$0$33656$edfadb0f@dread16.news.tele.dk> "Bulba!" wrote: > > One of the posters inspired me to do profiling on my newbie script > (pasted below). After measurements I have found that the speed > of Python, at least in the area where my script works, is surprisingly > high. Pretty good code for someone who calls himself a newbie. One line that puzzles me: > sfile=open(sfpath,'rb') You never use sfile again. In any case, you should explicitly close all files that you open. Even if there's an exception: sfile = open(sfpath, 'rb') try: finally: sfile.close() > > The only thing I'm missing in this picture is knowledge if my script > could be further optimised (not that I actually need better > performance, I'm just curious what possible solutions could be). > > Any takers among the experienced guys? Basically the way to optimise these things is to cut down on anything that does I/O: Use as few calls to os.path.is{dir,file}, os.stat, open and such that you can get away with. One way to do that is caching; e.g. storing names of known directories in a set (sets.Set()) and checking that set before calling os.path.isdir. I haven't spotted any obvious opportunities for that in your script, though. Another way is the strategy of "it's easier to ask forgiveness than to ask permission". If you replace: if(not os.path.isdir(zfdir)): os.makedirs(zfdir) with: try: os.makedirs(zfdir) except EnvironmentError: pass then not only will your script become a micron more robust, but assuming zfdir typically does not exist, you will have saved the call to os.path.isdir. - Anders From hwlgw at hotmail.com Wed Jan 19 06:17:10 2005 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 19 Jan 2005 03:17:10 -0800 Subject: delay and force in Python Message-ID: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Here is a question for people who are more comfortable than I am with new Python stuff like generators. I am having fun implementing things from the Wizard book (Abelson, Sussman, "Structure and Interpretation of Computer Programs") in Python. In chapter 3.5 it is about streams as delayed lists. Streams are interesting because they are to lists like xrange is to range. Could save a lot on memory and computations. Below is my straight translation from Scheme code in the Wizard book to Python. It works, but now I want to rewrite the delay and force functions using Python's new stuff, generators or iterators or what-have-you. I have the feeling that that is possible, can you do it? The program below creates a stream with the numbers 1..995 and then filters the stream, keeping only the even numbers, and then prints the second number in the stream (implemented as the first number of the tail, just like in the 3.5 Section in the Wizard book). . # file: teststreams.py . . def delay(exp): return lambda: exp . . def force(o): return o() . . def cons_stream(a,b): return [a, delay(b)] . . def stream_hd(s): return s[0] . . # we use tl for cdr . def tl(x): . if len(x) == 2: return x[1] . else: return x[1:] . . def stream_tl(s): return force(tl(s)) . . def stream_enumerate_interval(low, high): . if low > high: . return None . else: . return cons_stream( . low, . stream_enumerate_interval(low+1, high)) . . def stream_filter(pred, s): . if s is None: . return None . elif pred(stream_hd(s)): . return cons_stream( . stream_hd(s), . stream_filter(pred, stream_tl(s))) . else: . return stream_filter(pred, stream_tl(s)) . . def isEven(n): return n % 2 == 0 . . print stream_hd(stream_tl(stream_filter( . isEven, . stream_enumerate_interval(1,995)))) . # 4 Something else: this crashes with a "maximum recursion reached" . print stream_enumerate_interval(1,998) while this does not crash . print stream_enumerate_interval(1,900) this means Python has a maximum of something like 900 recursions? From aahz at pythoncraft.com Tue Jan 25 23:23:44 2005 From: aahz at pythoncraft.com (Aahz) Date: 25 Jan 2005 23:23:44 -0500 Subject: Textual markup languages (was Re: What YAML engine do you use?) References: <35a6tpF4gmat2U1@individual.net> Message-ID: In article , Alan Kennedy wrote: > >However, I'm torn on whether to use ReST for textual content. On the one >hand, it's looks pretty comprehensive and solidly implemented. But OTOH, >I'm concerned about complexity: I don't want to commit to ReST if it's >going to become a lot of hard work or highly-inefficient when I really >need to use it "in anger". > > From what I've seen, pretty much every textual markup targetted for web >content, e.g. wiki markup, seems to have grown/evolved organically, >meaning that it is either underpowered or overpowered, full of special >cases, doesn't have a meaningful object model, etc. My perception is that reST is a lot like Python itself: it's easy to hit the ground running, particularly if you restrict yourself to a specific subset of featuers. It does give you a fair amount of power, and some things are difficult or impossible. Note that reST was/is *not* specifically aimed at web content. Several people have used it for writing books; some people are using it instead of PowerPoint. >So, I'm hoping that the learned folks here might be able to give me some >pointers to a markup language that has the following characteristics > >1. Is straightforward for non-technical users to use, i.e. can be >(mostly) explained in a two to three page document which is >comprehensible to anyone who has ever used a simple word-processor or >text-editor. > >2. Allows a wide variety of content semantics to be represented, e.g. >headings, footnotes, sub/superscript, links, etc, etc. These two criteria seem to be in opposition. I certainly wouldn't expect a three-page document to explain all these features, not for non-technical users. reST fits both these criteria, but only for a selected subset of featuers. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From cdavisNOSP at NOSPstaffmail.ed.ac.uk Wed Jan 12 05:09:03 2005 From: cdavisNOSP at NOSPstaffmail.ed.ac.uk (Cory Davis) Date: Wed, 12 Jan 2005 10:09:03 +0000 Subject: distutils linux script installation broken? Message-ID: Hi all, I have been successfully deploying my own python package with distutils for some time now, but lately, with Python 2.4, the build_scripts command has been behaving badly. In the part where it is supposed to adjust the first line of the script it now produces #!None instead of #!/whereverpythonis/python Has anyone else encountered this? Cheers, Cory. From jalil at feghhi.com Thu Jan 27 19:48:14 2005 From: jalil at feghhi.com (jalil at feghhi.com) Date: 27 Jan 2005 16:48:14 -0800 Subject: Missing _bssd in Python 2.4 In-Reply-To: <41F977C9.4020400@v.loewis.de> References: <1106864043.734366.315660@c13g2000cwb.googlegroups.com> <41F977C9.4020400@v.loewis.de> Message-ID: <1106873294.357920.7520@c13g2000cwb.googlegroups.com> I actually installed BerkeleyBD4.0 and commented out some sections of Modules/Setup that I found related to this. I got the _bsddb.o in the build environment but I still get the same error from bsddb/__init.py__ that it cannot import _bsddb. Anything I am missing? Where should this _bsddb go exactly? Is it an .so file? Thanks, -JF Martin v. L?wis wrote: > jalil at feghhi.com wrote: > > I compiled and installed python 2.4 on Redhat Linux using default > > options but don't seem to be getting _bsddb. I get an error message > > that _bssd cannot be imported. > > > > Does anybody know why this might happen? Do I need to do any special > > customization or install any other software? > > You need to install the bsddb header files and development libraries > when building Python from source. > > Regards, > Martin From tim.golden at viacom-outdoor.co.uk Fri Jan 7 11:32:37 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 7 Jan 2005 16:32:37 -0000 Subject: [Pyro] Newbie Question Regarding Pyro Message-ID: <9A28C052FF32734DACB0A288A35339910359A1@vogbs009.gb.vo.local> [John French] | I'm putting together a new project which I'm using to learn | Python and have questions about pyro. You're welcome to ask here, but you might find that posting on Pyro's own mailing list produces answers from people who don't follow c.l.py's higher traffic. | If the server needs to send an unsolicited ad hoc message to | a given client, is this possible? | (New message or a reminder, for instance) I suppose I | could poll a server side list from the client but I'm | wondering if the server can initiate the exchange. I think you want to look at the Pyro's Event server, but be careful with terms like Server and Client, because they aren't always so straightforward in the Pyro context. | Also, if a client wishes to converse with another particular | client (in a chat or IM situation, for instance). | What's a good mechanism for this? There are two things here: finding out what "client" (Pyro object) is out there; and communicating with it. To take the second one first, once you've found it, you *are* talking directly to it, so that's fine. To address the first point, though, finding it can either be through the nameserver, which is generally preferable since that's what it's there for, or -- if you know the other object's location and name -- by using the PYROLOC:// mechanism. The only thing with this second approach is that you're likely to find yourself reinventing the name server as you try to keep track of who's "on-line" etc. (assuming your typical IM situation). So I'd recommend going for the nameserver if possible. | Does pyro create a persistent client/server connection? What | happens if a pyro client goes down hard? Does it's process | continue or is there a cleanup mechanism? Hmmm. A little bit involved the answer to this one. In essence, once you've got hold of another object via Pyro it's down to the network to get the message through. If the other end goes down, you can trap the Exceptions coming back and clean up as you see fit. The Pyro plumbing does support an auto-reconnect mechanism for Pyro objects. The details escape me now -- I've never used it myself -- but I seem to remember that you restart your object and its daemon (ie server bit) telling it to reconnect as well as it can. There's no persistence involved (unless you've implemented something yourself) so you'll have to clean up whatever mess there was left over as you come back up. Hope all that helps. 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 engsolnorm at peak.org Fri Jan 14 17:12:41 2005 From: engsolnorm at peak.org (engsol) Date: Fri, 14 Jan 2005 14:12:41 -0800 Subject: Com port interrupts again References: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> <1105734343.547195.301160@f14g2000cwb.googlegroups.com> Message-ID: <3uggu0p51mosuds44f5pjkjfo3bg5irat4@4ax.com> Thanks much..:) On 14 Jan 2005 12:25:43 -0800, "wittempj at hotmail.com" wrote: >A search on google gave me this library, I haven't tested it though: >http://groups-beta.google.com/group/comp.lang.python.announce/browse_frm/thread/6d3263250ed65816/291074d7bd94be63?q=com+port+python&_done=%2Fgroups%3Fhl%3Den%26lr%3D%26safe%3Doff%26q%3Dcom+port+python%26qt_s%3DSearch+Groups%26&_doneTitle=Back+to+Search&&d#291074d7bd94be63 From FBatista at uniFON.com.ar Wed Jan 12 14:07:14 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 12 Jan 2005 16:07:14 -0300 Subject: PyAr - Python Argentina 5th Meeting, tomorrow Thursday, Decimal t alk included Message-ID: The Argentinian Python User Group, PyAr, will have its fifth meeting this Thursday, January 13th at 7:00pm. Please see http://pyar.decode.com.ar/Wiki/ProximaReunion for details (in Spanish.) Agenda ------ Despite our agenda tends to be rather open, this time we would like to cover these topics: - Planning of our first sprint: we actually have two main subjects: Messages Queues Manager with interfaces for SMTP (e-mail), SMPP (SMS) and MM7 (MMS); and Genetic Algorithms. - Website organization & content - Means of promoting the group's activities, in order to increase our member base. There will be also an introduction from me to the Decimal data type that debuted in Python 2.4 (but could be used in 2.3 as well). Where ----- We're meeting at Hip Hop Bar, Hip?lito Yirigoyen 640, Ciudad de Buenos Aires, starting at 19hs. We will be in the back room, so please ask the barman for us. About PyAr ---------- For more information on PyAr see http://pyar.decode.com.ar (in Spanish), or join our mailing list (Also in Spanish. For instructions see http://pyar.decode.com.ar/Members/ltorre/listademail) We meet on the second Thursday of every month. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 farcepest at gmail.com Thu Jan 20 14:01:44 2005 From: farcepest at gmail.com (Andy Dustman) Date: 20 Jan 2005 11:01:44 -0800 Subject: Problem in importing MySQLdb References: Message-ID: <1106247703.982996.14410@z14g2000cwz.googlegroups.com> Gurpreet Sachdeva wrote: > Is there any problem in library files?? Do I need to install anything > I have installed MySQL-shared-3.23.54a-1.i386.rpm, > MySQL-devel-5.0.2-0.i386.rpm, MySQL-client-5.0.2-0.i386.rpm, > MySQL-server-5.0.2-0.i386.rpm You should recheck those version numbers carefully. One of these things is not like the other... From gsakkis at rutgers.edu Tue Jan 25 11:07:34 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 25 Jan 2005 08:07:34 -0800 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> Message-ID: <1106669254.838248.317170@z14g2000cwz.googlegroups.com> An iterator is perfectly ok if all you want is to iterate over the elements of a view, but as you noted, iterators are less flexible than the underlying sequence. The view should be (or at least appear) identical in functionality (i.e. public methods) with its underlying sequence. George From ewanon at gmail.com Sun Jan 2 23:25:23 2005 From: ewanon at gmail.com (EW) Date: 2 Jan 2005 20:25:23 -0800 Subject: Problem remotely shutting down a windows computer with python In-Reply-To: References: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> Message-ID: <1104726323.505127.139360@c13g2000cwb.googlegroups.com> I believe that would shutdown the computer you were physically at, but it wouldn't shutdown the computer down the hall over the LAN like this script was meant to do. From nav+posts at bandersnatch.org Thu Jan 27 08:24:16 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: Thu, 27 Jan 2005 08:24:16 -0500 Subject: Help With Python References: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <1106775090.890952.40590@c13g2000cwb.googlegroups.com> Message-ID: <873bwnc8e7.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> "Matt" writes: > Not to be nit-picky, but you got some issues here ;-). Never forget > the importance of "self"! Teach me to post untested code. *hangs head* 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 apardon at forel.vub.ac.be Mon Jan 31 03:08:29 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 31 Jan 2005 08:08:29 GMT Subject: How to test that an exception is raised ? References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> <41fa400b$0$2029$6c56d894@feed0.news.be.easynet.net> <41faa68f$0$17406$4d4efb8e@read.news.be.uu.net> Message-ID: Op 2005-01-28, StepH schreef : > Antoon Pardon a ?crit : >> Op 2005-01-28, StepH schreef : >> >>>Thanks for you answer. >>>I'm new to Python (coming from C/C++). >>> >>>Do you say that it's not possible to test (using unittest) if an exception >>>is well raised if the tested code catch it ? >>>How to solve this paradoxe ? How to automaticaly test such code ? >> >> >> IMO you want something unittest are not designed for. > > So why the assertRaises function in unittest? To see if an exception is propagated to the caller. > My goal is to test if an > exception is well raised when a bad filename is passed to the mps2xml > function. >> Unittest are supposed to test for particular results, not for particular >> behaviour within. If the expected behaviour is that calling code doesn't >> see an exception raised, then the test passed if no exception was seen. >> > > No (unless i don't well understand you), the expected behavior is to > launch an exception if a bad filename is passed. If no exception is > raised, this is not normal. What do you mean with launch an exception? Should the exception propagate to the caller or not? If it should your code was wrong to catch it. >> You equally can't test which branch of an if statement was taken or >> which parameter was given to a helper function in order to get to >> the desired result. > > I'm agree with out on this point, but not for the exception part... Why not? Exceptions are nothing special. Either you want to propagated them to the caller, in which case they can be seen as somekind of result and this can be tested for with a unittest or you don't want them to be propagted and then they are just an implementation detail of your unit. -- Antoon Pardon From alan.gauld at btinternet.com Sat Jan 1 18:18:58 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Jan 2005 23:18:58 +0000 (UTC) Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <1104511661.928284.10200@z14g2000cwz.googlegroups.com> Message-ID: On Sat, 01 Jan 2005 16:08:07 GMT, claird at lairds.us (Cameron Laird) wrote: > I argue that it's a false opposition to categorize projects in > terms of use of single languages. Many projects are MUCH better > off with a mix In practice I have *never* worked on an industrial scale project that only used one language. The nearest I came was a small protocol convertor that only used C, SQL and some shell and awk - but that's still 4 languages! And the whole project was only 40,000 lines of code in about 20 files. And most projects use many more, I'd guess around 5-8 on an "average project" of around 300-500kloc. The biggest project I worked on had about 3.5Mloc and used: Assembler (680x0 and Sparc), C C++ Lisp(Flavors) awk Bourne shell C shell - this was a mistake discovered too late to "fix" PL/SQL ???? - A UI description language for a tool called TeleUse... Pascal - No, I don't know why... ASN.1 - with a commercial compiler We also had some IDL but since it was tool generated I'll ignore it... We also had an experimental version running on a NeXt box so it used Objective C for the UI instead of ???? and C++... A total of 13 languages... with 5 geographically dispersed teams comprising a total of 200 developers (plus about 40 testers). Interesting times...in the Chinese sense! Alan G Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From petr at tpc.cz Mon Jan 10 18:44:33 2005 From: petr at tpc.cz (McBooCzech) Date: 10 Jan 2005 15:44:33 -0800 Subject: Old Paranoia Game in Python In-Reply-To: References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> <1105318366.966577.107460@c13g2000cwb.googlegroups.com> Message-ID: <1105400673.731851.87080@f14g2000cwb.googlegroups.com> Newbie in Python. I did copy the whole script form the web and save it as para1.py. I did download pyparsing module and save it to C:\\Python23\\Lib\\pyparsing122. I did run following script: import sys sys.path.append('C:\\Python23\\Lib\\pyparsing122') from pyparsing import * extraLineBreak = White(" ",exact=1) + LineEnd().suppress() text = file("Para1.py").read() newtext = extraLineBreak.transformString(text) file("para2.py","w").write(newtext) I did try to run para2.py script, but following message File "para2.py", line 169 choose(4,"You give your correct clearance",5,"You lie and claim ^ SyntaxError: EOL while scanning single-quoted string So my questions are: Why pyparser didn't correct the script? What I am doing wrong? Is it necessary to correct the script by hand anyway? Petr From steven.bethard at gmail.com Tue Jan 18 03:29:25 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 18 Jan 2005 01:29:25 -0700 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Antoon Pardon wrote: > In this case for example there are a number of people who flat out > assert that muatble dict keys in pyhthon is impossible. If you run into any of these folks, please point them to: http://www.python.org/moin/DictionaryKeys It's a pretty good summary of one of the more recent threads on this topic by Peter Maas and myself. If you feel like your point is not covered[1], feel free to add some additional material. (That is, after all, the point of a wiki.) Steve [1] I assume that you feel this way because you have repeated essentially the same point about 5 times in this thread. The wiki is a chance to make your statement once, and then simply post a pointer once per appropriate thread. It might save you some time... From jaydonnell at gmail.com Fri Jan 21 13:01:16 2005 From: jaydonnell at gmail.com (Jay donnell) Date: 21 Jan 2005 10:01:16 -0800 Subject: why am I getting a segmentation fault? Message-ID: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> I have a short multi-threaded script that checks web images to make sure they are still there. I get a segmentation fault everytime I run it and I can't figure out why. Writing threaded scripts is new to me so I may be doing something wrong that should be obvious :( google messes up the python code so here is a link to it. http://kracomp.com/~jay/py.txt This is the output of the script. [jay at localhost scripts]$ ./py.py update item set goodImage = 'yes' where productId='12603' update item set goodImage = 'yes' where productId='18272' update item set goodImage = 'yes' where productId='1927' update item set goodImage = 'no' where productId='12709' update item set goodImage = 'yes' where productId='32087' update item set goodImage = 'no' where productId='25803' Segmentation fault Thanks in advance. From peter at engcorp.com Tue Jan 4 20:57:26 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 Jan 2005 20:57:26 -0500 Subject: python intergration bus ? In-Reply-To: <1104849906.019872.153800@z14g2000cwz.googlegroups.com> References: <1104849906.019872.153800@z14g2000cwz.googlegroups.com> Message-ID: <-LSdnY83pO1i1EbcRVn-vw@powergate.ca> Tonino wrote: > Just an interested question - I friend is testing a few JAVA > intergration bus's that will be used to intergrate his companies > services - I was wondering if there was a python intergration bus ? > other than maybe Pyro ? I'm not sure what that term means, and I don't believe it is a widely recognized term in the field of programming. I can guess, or Google for it, but I suspect most of what I find wouldn't be what you meant... Perhaps you could define what "integration bus" means to you so we could understand what your question really is? (And please do it without just referencing some Java product which none of us will know about.) Thanks, -Peter From aleaxit at yahoo.com Sun Jan 2 18:08:25 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 3 Jan 2005 00:08:25 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Bulba! wrote: > True. I have a bit of interest in economics, so I've seen e.g. > this example - why is it that foreign branches of companies > tend to cluster themselves in one city or country (e.g. It's not just _foreign_ companies -- regional clustering of all kinds of business activities is a much more widespread phenomenon. Although I'm not sure he was the first to research the subject, Tjalling Koopmans, as part of his lifework on normative economics for which he won the Nobel Prize 30 years ago, published a crucial essay on the subject about 50 years ago (sorry, can't recall the exact date!) focusing on _indivisibilities_, leading for example to transportation costs, and to increasing returns with increasing scale. Today, Paul Krugman is probably the best-known name in this specific field (he's also a well-known popularizer and polemist, but his specifically-scientific work in economics has mostly remained in this field). > China right now)? According to standard economics it should > not happen - what's the point of getting into this overpriced > city if elsewhere in this country you can find just as good > conditions for business. Because you can't. "Standard" economics, in the sense of what you might have studied in college 25 years ago if that was your major, is quite able to account for that if you treat spatial variables as exogenous to the model; Krugman's breakthroughs (and most following work, from what I can tell -- but economics is just a hobby for me, so I hardly have time to keep up with the literature, sigh!) have to do with making them endogenous. Exogenous is fine if you're looking at the decision a single firm, the N+1 - th to set up shop in (say) a city, faces, given decisions already taken by other N firms in the same sector. The firm's production processes have inputs and outputs, coming from other firms and (generally, with the exception of the last "layer" of retailers etc) going to other firms. Say that the main potential buyers for your firm's products are firms X, Y and Z, whose locations all "happen to be" (that's the "exogenous" part) in the Q quarter of town. So, all your competitors have their locations in or near Q, too. Where are you going to set up your location? Rents are higher in Q than somewhere out in the boondocks -- but being in Q has obvious advantages: your salespeople will be very well-placed to shuttle between X, Y, Z and your offices, often with your designers along so they can impress the buyers or get their specs for competitive bidding, etc, etc. At some points, the competition for rents in quarter Q will start driving some experimenters elsewhere, but they may not necessarily thrive in those other locations. If, whatever industry you're in, you can strongly benefit from working closely with customers, then quarter Q will be where many firms making the same products end up (supply-side clustering). Now consider a new company Z set up to compete with X, Y and Z. Where will THEY set up shop? Quarter Q has the strong advantage of offering many experienced suppliers nearby -- and in many industries there are benefits in working closely with suppliers, too (even just to easily have them compete hard for your business...). So, there are easily appreciated exogenous models to explain demand-side clustering, too. That's how you end up with a Holliwood, a Silicon Valley, a Milan (for high-quality fashion and industrial design), even, say, on a lesser scale, a Valenza Po or an Arezzo for jewelry. Ancient European cities offer a zillion examples, with streets and quarters named after the trades or professions that were most clustered there -- of course, there are many other auxiliary factors related to the fact that people often _like_ to associate with others of the same trade (according to Adam Smith, generally to plot some damage to the general public;-), but supply-side and demand-side, at least for a simpler exogenous model, are plenty. Say that it's the 18th century (after the corporations' power to stop "foreign" competition from nearby towns had basically waned), you're a hat-maker from Firenze, and for whatever reason you need to move yourself and your business to Bologna. If all the best hat-makers' workshops and shops are clustered around Piazza dell'Orologio, where are YOU going to set up shop? Rents in that piazza are high, BUT - that's where people who want to buy new hats will come strolling to look at the displays, compare prices, and generally shop. That's close to where felt-makers are, since they sell to other hat-makers. Should your business soon flourish, so you'll need to hire a worker, that's where you can soon meet all the local workers, relaxing with a glass of wine at the local osteria after work, and start getting acquainted with everybody, etc, etc... Risk avoidance is quite a secondary issue here (except if you introduce in your model an aspect of imperfect-information, in which case, following on the decisions made by locals who may be presumed to have better information than you is an excellent strategy). Nor is there any "agency problem" (managers acting for their interests and against the interest of owners), not a _hint_ of it, in fact -- the hatmaker acting on his own behalf is perfectly rational and obviously has no agency problem!). So, I believe that introducing agency problems to explain clustering is quite redundant and distracting from what is an interesting sub-field of (quite-standard, by now) economics. There are quite a few other sub-fields of economics where agency problems, and specifically the ones connected with risk avoidance, have far stronger explicatory power. So, I disagree with your choice of example. Alex From thisissantanu at yahoo.com Fri Jan 28 07:28:49 2005 From: thisissantanu at yahoo.com (santanu) Date: 28 Jan 2005 04:28:49 -0800 Subject: Please suggest on the book to follow References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> Message-ID: <1106915329.743430.242080@f14g2000cwb.googlegroups.com> Thanks for the link http://gnosis.cx/TPiP/ It was wonderful. Once I get somewhat more experienced in Python, I guess this site will provide me with some good fun times. For the moment, I decided to follow Programming Python. Once done, I shall learn the newest features from some latest book like the Nutshell one. Thanks to all for replying. Regards, Santanu From stewart.midwinter at gmail.com Tue Jan 25 12:10:48 2005 From: stewart.midwinter at gmail.com (stewart.midwinter at gmail.com) Date: 25 Jan 2005 09:10:48 -0800 Subject: smtplib bug with Windows XP In-Reply-To: References: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> Message-ID: <1106673048.851591.324490@f14g2000cwb.googlegroups.com> thank Peter, elbert, for the suggestions. I hadn't thought of using telnet to try to connect to the SMTP server. and when I do try, telnet can't connect either, at least on port 25. On port 110, it has no problem. So, perhaps the IT people have made some configuration changes; I'll have a chat with them. I'm relieved that it's not a Python problem, though. From pobrien at orbtech.com Wed Jan 19 15:06:34 2005 From: pobrien at orbtech.com (Pat) Date: 19 Jan 2005 12:06:34 -0800 Subject: Solutions for data storage? In-Reply-To: <1106164804.410201.100550@c13g2000cwb.googlegroups.com> References: <356c7tF4g3f64U1@individual.net> <1106164804.410201.100550@c13g2000cwb.googlegroups.com> Message-ID: <1106165194.960959.270210@f14g2000cwb.googlegroups.com> Posting using Google Groups messed up the formatting of those class definition examples. Assume that they contain the usual indentation of typical class definitions. ;-) From km at mrna.tn.nic.in Sun Jan 9 22:23:48 2005 From: km at mrna.tn.nic.in (km) Date: Mon, 10 Jan 2005 08:53:48 +0530 Subject: vi and python Message-ID: <20050110032348.GA1960@mrna.tn.nic.in> Hi all, Is there a way to display inbuilt function syntax as the user starts typing a function name with 'Vi' editor in console mode? tia, KM From bokr at oz.net Tue Jan 18 08:24:52 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 18 Jan 2005 13:24:52 GMT Subject: news feed problem -- anyone else? References: <41ec1b57.1114913110@news.oz.net> <41EC3156.80708@tundraware.com> Message-ID: <41ed0dcf.1176985375@news.oz.net> On 17 Jan 2005 16:48:24 EST, Tim Daneliuk wrote: >Bengt Richter wrote: > >> I can see postings on google, but my news service >> is having a problem since sometime during the weekend. >> Can get old stuff from other n.g., but no new. >> Wondering whether I'll see this via google. >> >> Regards, >> Bengt Richter > >Bengt - > >I've had very good luck using the following *free* newsfeed: > > http://individual.net/ > > >HTH, Thanks, I can see this via normal news now. But that looks good. Regards, Bengt Richter From ruses at users.ch Sat Jan 1 20:05:30 2005 From: ruses at users.ch (not [quite] more i squared) Date: Sun, 02 Jan 2005 02:05:30 +0100 Subject: Red Robin Jython & JDK classes In-Reply-To: References: Message-ID: <33ov84F421s0aU1@individual.net> Henri Sivonen a ?crit : > I am trying to set up the Red Robin Jython Development Tools for > Eclipse. It finds the Python libraries of Jython and my own jars. It > does not find the JDK classes. If I try to add classes.jar from the JDK > to the "Jython Class Path" of the project, the plug-in no longer finds > even my own Java classes. > > How do I make the plug-in see the JDK classes? > > I am using Eclipse 3.0.1, Mac OS X 10.3.7, Java 1.4.2_05, Jython 2.1 and > Red Robin Jython Development Tools 1.3.9. > if i may ask, did you ask the author of the eclipse plugin ? did anybody else answer you ? or could you by any chance, solve it by yourself ? From john at grulic.org.ar Tue Jan 18 08:44:11 2005 From: john at grulic.org.ar (John Lenton) Date: Tue, 18 Jan 2005 10:44:11 -0300 Subject: strange note in fcntl docs In-Reply-To: <16876.34950.976819.654894@montanaro.dyndns.org> References: <20050117053949.GA28456@grulic.org.ar> <16875.54085.712019.524951@montanaro.dyndns.org> <20050117192327.GA4723@grulic.org.ar> <16876.34950.976819.654894@montanaro.dyndns.org> Message-ID: <20050118134411.GA26210@grulic.org.ar> On Mon, Jan 17, 2005 at 09:54:46PM -0600, Skip Montanaro wrote: > > John> And, even if they were, the note is *still* wrong and misleading: > John> fcntl is available on Windows, and os.open's flags won't be. > > Does this read better? > > [snip] yes, and it takes me back to considering why file objects don't have methods suck as lock, stat and mmap where those calls are available through other mechanisms... -- John Lenton (john at grulic.org.ar) -- Random fortune: Yo mando a mi gato y mi gato manda a su rabo. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From kylotan at gmail.com Mon Jan 17 12:34:31 2005 From: kylotan at gmail.com (Ben Sizer) Date: 17 Jan 2005 09:34:31 -0800 Subject: PyChecker messages In-Reply-To: References: Message-ID: <1105983271.574296.37740@c13g2000cwb.googlegroups.com> But you could use a dict of return values, or even just assigning a different return value in each if clause. The end result is that you have a single well-defined exit point from the function, which is generally considered to be preferable. From peter at engcorp.com Mon Jan 17 19:40:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Jan 2005 19:40:05 -0500 Subject: python execution path In-Reply-To: References: Message-ID: Dustin Lee wrote: > I'm wondering if there is a way to get python to show each line as it > is executed, sort of like sh -x does for shell programs. Seems like > this would be a nice debugging aid. The best approach, if it's really intended to be a debugging aid, might be to learn about "pdb", starting perhaps with the following line inserted shortly above where you think your bug might be: import pdb; pdb.set_trace() (run the code, wait for the prompt, type "?" for help, then read the docs ;-) ) -Peter From luisXX_lupe2XX at netvisaoXX.pt Fri Jan 21 12:55:26 2005 From: luisXX_lupe2XX at netvisaoXX.pt (Luis P. Mendes) Date: Fri, 21 Jan 2005 17:55:26 +0000 Subject: xml parsing escape characters In-Reply-To: References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efedf2$0$11622$9b622d9e@news.freenet.de> <35adg4F4jgvpnU1@individual.net> <41F01A86.2040805@v.loewis.de> Message-ID: <41F1420E.9090706@netvisaoXX.pt> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 ~From your experience, do you think that if this wrong XML code could be meant to be read only by somekind of Microsoft parser, the error will not occur? I'll try to explain: xml producer writes the code in Windows platform and 'thinks' that every client will read/parse the code with a specific Windows parser. Could that (wrong) XML code parse correctly in that kind of specific Windows client? Or in other words: Do you know any windows parser that could turn that erroneous encoding to a xml tree, with four or five inner levels of tags? I'd like to thank everyone for taking the time to answer me. Luis -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFB8UIOHn4UHCY8rB8RAgK4AKCiHjPdkCKnirX4gEIawT9hBp3HmQCdGoFK 3IEMLLXwMZKvNoqA4tISVnI= =jvOU -----END PGP SIGNATURE----- From mefjr75 at hotmail.com Sun Jan 30 13:32:55 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 30 Jan 2005 10:32:55 -0800 Subject: Disassembling strings and turning them into function parameters References: <1107107283.694377.286360@c13g2000cwb.googlegroups.com> Message-ID: <1107109975.466479.138590@f14g2000cwb.googlegroups.com> mercuryp... at gmail.com wrote: > Hi, > I'm pretty new to Python, to programming overall...so how would I make > something where the user inputs multiple words in a string - like > "connect 123.123.123.123 21 user password" or similar, and then I can > split this string up to pass these arguments to a function like > ftp_connect(ip, port, user, pw) etc...? I have no idea how to "break" > the string up so I can get these out of it.. > > > thanks for answers, > munin Ok well this is pretty basic but it sounds wrong on some level. Maybe you should post some code, you will get better responses. You could try something like: Py>stuff = "connect 123.123.123.123 21 user password" Py>parts_list = stuff.split()# can handle other seperators Py>print parts_list ['connect', '123.123.123.123', '21', 'user', 'password'] Py>def StrFtp(userinfo): ... parts = userinfo.slpit() ... funktion, ip, port, usedr, pw = parts ... funktion = funktion.lower() ... if funktion == 'connect' ... return ftp_connect(ip, port, user, pw) ... elif funktion == 'other_function_name_here': ... return 'your other action here' ... else: ... return None Py>ftpconnect = StrFtp("connect 123.123.123.123 21 user password") Also add asserts and error checking all through the code for malformed input. hth, M.E.Farmer From invalidemail at aerojockey.com Wed Jan 19 18:24:10 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 19 Jan 2005 15:24:10 -0800 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> Message-ID: <1106177050.630141.33090@c13g2000cwb.googlegroups.com> Skip Montanaro wrote: > Bill> The example that occurs to me is that "import smtplib" is better > Bill> than "import stdlib.inet.services.smtp". > > Sure. There is a balance to be achieved however. "import std.smtplib" > might be better than "import smtplib", simply because making the standard > library a package reduces the possibility of namespace collisions. Yep. "Reorganize the standard library to be not as shallow" is listed right there in PEP 3000. Notice, however, that it doesn't say, "Reorganize the standard library into an intricate feudal hierarchy of packages, modules, and cross-references." :) The gist of "Flat is better than nested" is "be as nested as you have to be, no more," because being too nested is just a mess. -- CARL BANKS From cr999 at ir.hit.edu.cn Mon Jan 17 02:21:51 2005 From: cr999 at ir.hit.edu.cn (cr999) Date: Mon, 17 Jan 2005 15:21:51 +0800 Subject: pythonnt_rc_d.h is missed when building python from source ? Message-ID: <002801c4fc65$36fe04d0$1d02a8c0@cr> I download the source code of Python-2.3.4 from python.org. But I can't build python from source under Win2000. The compiler complained that there is no pythonnt_rc_d.h file which is included in Python-2.3.4\PC\python_nt.rc. Who knows the reason ? Thanks. Best Regards. Robert. -------------- next part -------------- An HTML attachment was scrubbed... URL: From samantha7395 at hotmail.com Thu Jan 20 13:46:00 2005 From: samantha7395 at hotmail.com (Samantha) Date: Thu, 20 Jan 2005 10:46:00 -0800 Subject: Print to Windows default Printer References: Message-ID: The printer is on LPT1, but I sure can't get the temp file to print for some reason. I am using Windows XP SP2. S "Tim Golden" wrote in message news:mailman.959.1106240645.22381.python-list at python.org... > [Samantha] > > [... snip my explanation of PRINT / COPY LPTx: ...] > > | Thanks Tim, > | That is exactly what I want to do. > | How do I map the printer to LPT1? > | S > > Depends on a lot of things: whether the printer is > local or networked; what version of Windows you're > running, &. > > As a very basic starting point: if it's a local printer > (ie plugged into the back of your machine) it's probably > on LPT1: already, or you could go to the Add Printer > wizard and tell it to configure it for LPT1: there. > > If it's networked, then something like: > > NET USE LPT1: \\servername\printerqueue > > should achieve the right effect. > > 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 ram at forefront-tech.No.Lunch.meat.com Wed Jan 12 16:06:57 2005 From: ram at forefront-tech.No.Lunch.meat.com (Rick Morrison) Date: Wed, 12 Jan 2005 21:06:57 GMT Subject: dict.updated Message-ID: Would there be any way to add a method to all dict objects that operated like the .update() method, but also returned a reference to the updated dict? .update() is clumsy to use inside of list comprehensions and the like. Or am I missing something? Thanks, Rick From aahz at pythoncraft.com Sat Jan 29 11:55:59 2005 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2005 11:55:59 -0500 Subject: limited python virtual machine References: <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> Message-ID: In article <1gr5osy.7eipfq7xyz72N%aleaxit at yahoo.com>, Alex Martelli wrote: >Aahz wrote: >> Alex Martelli deleted his own attribution: >>> >>> >>> object.__subclasses__() >> >> One thing my company has done is written a ``safe_eval()`` that uses a >> regex to disable double-underscore access. > >will the regex catch getattr(object, 'subclasses'.join(['_'*2]*2)...?-) Heheh. No. Then again, security is only as strong as its weakest link, and that quick hack makes this part of our application as secure as the rest. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From aurora00 at gmail.com Thu Jan 27 16:28:54 2005 From: aurora00 at gmail.com (aurora) Date: Thu, 27 Jan 2005 13:28:54 -0800 Subject: Transparent (redirecting) proxy with BaseHTTPServer References: <35sfdaF4hka1hU1@individual.net> Message-ID: If you actually want the IP, resolve the host header would give you that. In the redirect case you should get a host header like Host: www.python.org From that you can reconstruct the original URL as http://www.python.org/ftp/python/contrib/. With that you can open it using urllib and proxy the data to the client. The second form of HTTP request without the host part is for compatability of pre-HTTP/1.1 standard. All modern web browser should send the Host header. > Hi list, > > My ultimate goal is to have a small HTTP proxy which is able to show a > message specific to clients name/ip/status then handle the original > request normally either by redirecting the client, or acting as a proxy. > > I started with a modified[1] version of TinyHTTPProxy postet by Suzuki > Hisao somewhere in 2003 to this list and tried to extend it to my needs. > It works quite well if I configure my client to use it, but using > iptables REDIRECT feature to point the clients transparently to the > proxy caused some issues. > > Precisely, the "self.path" member variable of baseHTTPRequestHandler is > missing the and the host (i.e www.python.org) part of the > request line for REDIRECTed connections: > > without iptables REDIRECT: > self.path -> GET http://www.python.org/ftp/python/contrib/ HTTP/1.1 > > with REDIRECT: > self.path -> GET /ftp/python/contrib/ HTTP/1.1 > > I asked about this on the squid mailing list and was told this is normal > and I have to reconstuct the request line from the real destination IP, > the URL-path and the Host header (if any). If the Host header is sent > it's an (unsafe) nobrainer, but I cannot for the life of me figure out > where to get the "real destination IP". Any ideas? > > thanks > Paul > > [1] HTTP Debugging Proxy > Modified by Xavier Defrang (http://defrang.com/) From stephen.thorne at gmail.com Sun Jan 2 02:08:32 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Sun, 2 Jan 2005 17:08:32 +1000 Subject: Frameworks for "Non-Content Oriented Web Apps" In-Reply-To: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <3e8ca5c80501012308353f6c6@mail.gmail.com> On 1 Jan 2005 20:51:06 -0800, mirnazim at gmail.com wrote: > But is there some sort of framework or something that is actually meant > for such web apps,application that make heavy use of forms, have very > high amount of user interaction etc. > Yeah, nevow, by those crazy twisted people, is great. The underlying concept is 'object publishing', and has some very funky technology for live-updating of a client-side web page via javascript (ala gmail). Object publishing is along the lines of, instead of having a 'form', you have an object which represents data. It knows how to handle form submissions, validate data, etc. And you 'publish' that object. The user can then interact with that object. Anyway, I haven't mucked around with nevow for months, you're better off checking out nevow.com and divmod.org yourself. Stephen. From theller at python.net Tue Jan 25 10:02:56 2005 From: theller at python.net (Thomas Heller) Date: Tue, 25 Jan 2005 16:02:56 +0100 Subject: Installer made with bdist_wininst segfaulting... References: Message-ID: Fernando Perez writes: > Hi all, > > I am seeking advice/help from those with more win32 experience than myself. I > am trying to build a proper win32 installer for IPython, after a user did most > of the hard work. For the most part, it's working very well, but I am running > into a nasty problem, which took me a few hours to finally understand. This > smells to me like a python bug, but I could be wrong. Much googling didn't > turn up anything relevant. > > Here is a brief summary: if the installer file is run from a windows drive which > is different from the one where python resides (and hence where ipython will > end up), the installer segfaults. No traceback, nothing, just a segfault > (well, one of those Windows dialogs asking me to send a binary traceback to > Redmond, but not a proper Python traceback). There are a couple of known bugs in bdist_wininst, and you just reported another one. All these bugs are related to using the post_install_script, and show up when either (thats what I currently remember): - the installer is run from a readonly location, - the installer is run from a different drive (as you reported) - the installer installs for Python 2.4 I will fix these issues in Python 2.3.5, which will probably be out as a release candidate this week, and in Python 2.4.1. I urge everyone to install this release candidate, rebuild the installer with it, and test them thoroughly. Thanks, Thomas From ngps at netmemetic.com Mon Jan 31 11:29:48 2005 From: ngps at netmemetic.com (Ng Pheng Siong) Date: Mon, 31 Jan 2005 16:29:48 +0000 (UTC) Subject: Using HTTPSConnection and verifying server's CRT References: <41fe5357@epflnews.epfl.ch> Message-ID: According to Marc Poulhi?s : > I tried to see if the M2Crypto has this possibility, but from my tests > and from what I can find on the website, it seems not :/ How did you test and where on the website does it say not? > Can someone confirm me this is not possible or point me to something > that could help me? 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. ;-) M2Crypto even does client certs. Since Apr 2000, according to the very last blog entry on the ZServerSSL page. -- Ng Pheng Siong http://sandbox.rulemaker.net/ngps -+- M2Crypto, ZServerSSL for Zope, Blog http://www.sqlcrypt.com -+- Database Engine with Transparent AES Encryption From ncoghlan at iinet.net.au Thu Jan 27 05:03:39 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 27 Jan 2005 20:03:39 +1000 Subject: python memory blow out In-Reply-To: <4e4a11f805012617082ebd9b80@mail.gmail.com> References: <4e4a11f805012617082ebd9b80@mail.gmail.com> Message-ID: <41F8BC7B.5060905@iinet.net.au> Simon Wittber wrote: > Does anyone have ideas on why this is occuring, or how I might > otherwise prevent memory blow out? The first thing to check is whether you might be accidentally keeping a reference to the result set alive somewhere. If that's not the case, then try to find out if the result set is created by one big allocation or lots of little ones (If the latter, other responses have pointed out how it may cause your problem). There's also a chance of a problem with the database API wrapper, so it may be worth checking with an API specific list. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From stephen.thorne at gmail.com Thu Jan 13 00:32:53 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 15:32:53 +1000 Subject: Refactoring; arbitrary expression in lists In-Reply-To: <41e5fdce.714136143@news.oz.net> References: <41e5cb07.701137402@news.oz.net> <41e5fdce.714136143@news.oz.net> Message-ID: <3e8ca5c8050112213278d6550@mail.gmail.com> On Thu, 13 Jan 2005 05:18:57 GMT, Bengt Richter wrote: > On Thu, 13 Jan 2005 12:19:06 +1000, Stephen Thorne wrote: > > >On Thu, 13 Jan 2005 01:24:29 GMT, Bengt Richter wrote: > >> extensiondict = dict( > >> php = 'application/x-php', > >> cpp = 'text/x-c-src', > >> # etcetera > >> xsl = 'test/xsl' > >> ) > >> > >> def detectMimeType(filename): > >> extension = os.path.splitext(filename)[1].replace('.', '') > extension = os.path.splitext(filename)[1].replace('.', '').lower() # better > > >> try: return extensiondict[extension] > >> except KeyError: > >> basename = os.path.basename(filename) > >> if "Makefile" in basename: return 'text/x-makefile' # XXX case sensitivity? > >> raise NoMimeError > > > >Why not use a regexp based approach. > ISTM the dict setup closely reflects the OP's if/elif tests and makes for an efficient substitute > for the functionality when later used for lookup. The regex list is O(n) and the regexes themselves > are at least that, so I don't see a benefit. If you are going to loop through extensionlist, you > might as well write (untested) *shrug*, O(n*m) actually, where n is the number of mime-types and m is the length of the extension. > >extensionlist = [ > >(re.compile(r'.*\.php') , "application/x-crap-language"), > >(re.compile(r'.*\.(cpp|c)') , 'text/x-c-src'), > >(re.compile(r'[Mm]akefile') , 'text/x-makefile'), > >] > >for regexp, mimetype in extensionlist: > > if regexp.match(filename): > > return mimetype > > > >if you were really concerned about efficiency, you could use something like: > >class SimpleMatch: > > def __init__(self, pattern): self.pattern = pattern > > def match(self, subject): return subject[-len(self.pattern):] == self.pattern > > I'm not clear on what you are doing here, but if you think you are going to compete > with the timbot's dict efficiency with a casual few lines, I suspect you are PUI ;-) > (Posting Under the Influence ;-) Sorry about that, what I was trying to say was something along the lines of: extensionlist = [ (re.compile(r'.*\.php') , "application/x-crap-language"), (re.compile(r'.*\.(cpp|c)') , 'text/x-c-src'), (re.compile(r'[Mm]akefile') , 'text/x-makefile'), ] can be made more efficient by doing something like this: extensionlist = [ SimpleMatch(".php"), "application/x-crap-language"), (re.compile(r'.*\.(cpp|c)') , 'text/x-c-src'), (re.compile(r'[Mm]akefile') , 'text/x-makefile'), ] Where SimpleMatch uses a slice and a comparison instead of a regular expression engine. SimpleMatch and re.compile both return an object that when you call .match(s) returns a value that can be interpreted as a boolean. As for the overall efficiency concerns, I feel that talking about any of this is premature optimisation. The optimisation that is really required in this situation is the same as with any large-switch-statement idiom, be it C or Python. First one must do a frequency analysis of the inputs to the switch statement in order to discover the optimal order of tests! Regards, Stephen Thorne From http Thu Jan 13 15:57:03 2005 From: http (Paul Rubin) Date: 13 Jan 2005 12:57:03 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: <7xsm559heo.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > >>> Well, it seems that Guido is wrong then. The documentation clearly > >>> states that an expression is a statement. > >> > >> no, it says that an expression statement is a statement. if you don't > >> understand the difference, please *plonk* yourself. > > > > And what else is an expression statement but an expression (list) used > > as a statement. > > Whereas an expression used within a statement is not a statement, and that > is the difference. Huh? Expressions are not statements except when they're "expression statements"? What kind of expression is not an expression statement? And logic would indicate that if we can separate statements from expressions and still have "expression statements", nothing stops us from also being able to have "statement expressions". From skip at pobox.com Sat Jan 29 15:35:36 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 29 Jan 2005 14:35:36 -0600 Subject: limited python virtual machine In-Reply-To: <1gr5th5.13asce21fjmj8tN%aleaxit@yahoo.com> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> <16891.41849.882856.527798@montanaro.dyndns.org> <1gr5th5.13asce21fjmj8tN%aleaxit@yahoo.com> Message-ID: <16891.62360.246625.13784@montanaro.dyndns.org> Alex> I dunno, maybe I'm just being pessimistic, I guess... No, I think you are being realistic. I thought one of the basic tenets of computer security was "that which is not expressly allowed is forbidden". Any attempt at security that attempts to find and plug the security holes while leaving the basic insecure system intact is almost certainly going to miss something. Skip From craig at postnewspapers.com.au Fri Jan 28 12:09:11 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 29 Jan 2005 01:09:11 +0800 Subject: Dynamic class methods misunderstanding In-Reply-To: <797fe3d405012808171954a2b4@mail.gmail.com> References: <35v5jdF4rk3m7U1@individual.net> <797fe3d405012808171954a2b4@mail.gmail.com> Message-ID: <1106932151.4008.81.camel@albert.localnet> On Fri, 2005-01-28 at 11:17 -0500, Bill Mill wrote: > Beautiful! thank you very much. Looking into the "new" module in > python 2.4, that's equivalent to: > > self.m = type(self.__init__)(method, self, Test) > > I didn't know that you could call types to create another type. Well, a type is essentially a class (in the OOP sense, not the python- specific classobj sense). You can call a type or class to create an instance of that class or type. Here, you call the 'instancemethod' type to create an instance of type 'instancemethod'. Makes sense ... in hindsight. -- Craig Ringer From tundra at tundraware.com Fri Jan 7 17:40:34 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 07 Jan 2005 17:40:34 EST Subject: Tkinter, Alt, and Windows Message-ID: <1qf3b2-pdp.ln1@eskimo.tundraware.com> Arrrrrggg. I have a program that runs comfortably across both Unix variants and Windows ... except .... I wish to bind an Alt-ButtonRelease-3 combination to popup a menu. This works flawlessly under Unix, but with windows, the menu appears briefly and then disappears. I'm guessing that Alt under windows generates another event that I am not catching and the default internal Tk message handler is processing it and causing my menu to get destroyed. It seems that any combination involving the Alt key has this issue - for example Control-Alt-ButtonRelease-3 does the same thing. Has anyone else run into this behavior and have a fix??? TIA, ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From FBatista at uniFON.com.ar Tue Jan 11 08:29:20 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 11 Jan 2005 10:29:20 -0300 Subject: Writing huve ge Sets() to disk Message-ID: [Martin MOKREJ?] #- When importing data from a flatfile into mysql table, there's an #- option to delay indexing to the very last moment, when all keys are #- loaded (it doesn't make sense to re-create index after each new #- row into table is added). I believe it's exactly same waste of cpu/io #- in this case - when I create a dictionary and fill it with data, #- I want to create index afterward, not after every key/value pair #- is recorded. "Premature optimization is the root of all evil.". Use dict as is, profile all your code, start optimizing the slower parts, you'll never get to dicts. . Facundo Bitcora 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 harold.fellermann at upf.edu Thu Jan 13 07:53:22 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 13 Jan 2005 13:53:22 +0100 Subject: Pickling a class instead of an instance In-Reply-To: References: Message-ID: <1B26AD62-6562-11D9-B3E0-003065FB7B26@upf.edu> have a look at the thread "copying classes?" some days ago. what goes for copying goes for pickling also, because the modules use the same interface. - harold - On 13.01.2005, at 13:32, Sebastien Boisgerault wrote: > Hi, > > It seems to me that it's not possible with the pickle module > to serialize a class rather than an instance, as in > >>> from pickle import * >>> >>> class C(object): >>> "... doc ..." >>> a = 1 >>> >>> pickstr = dumps(C) > > I mean, it does *something*, there is no error indeed, but > from the string pickstr, I am unable to rebuild the class > C in a brand new context (got a "you're really stupid, all > you deserve is an AttributeError because you know there is > no attribute 'C' in the 'module' object" error). > > Am I wrong ? Why would the "(new-style) classes are regular > objects too" mantra not apply in this case ? Could we imagine > a patch to the pickle module to handle this kind of situation ? > > SB > -- > http://mail.python.org/mailman/listinfo/python-list > > -- If you make people think they're thinking, they'll love you; but if you really make them think they'll hate you. From fumanchu at amor.org Thu Jan 20 03:42:21 2005 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 20 Jan 2005 00:42:21 -0800 Subject: Solutions for data storage? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398225@exchange.hqamor.amorhq.net> Leif K-Brooks wrote: > Robert Brewer wrote: > > Try svn://casadeamor.com/dejavu/trunk if you want a truly > Pythonic query > > syntax. Wait a couple of days, and I'll have version 1.3 ready and > > online at http://www.aminus.org/rbre/python -- lots of changes from > > 1.2.6 which is there now, but at least you can read old > docs online now > > without svn. > > Thanks a lot for the reply. I've skimmed the documentation (very > well-written, by the well), and I really like the looks of what I've > seen so far. I'm a bit confused about where sandboxes get created, > though; in a Web application, would I give each request a > sandbox of its > own, or create one for the entire application, or what? Correct; in a Web application, each request should get its own sandbox. Here's a sample mod_python request.py script, where "cation" is my webapp framework, and "mcontrol" is the name of the app itself, which possesses a Dejavu arena object. ------------ from cation.html.uimodpython import UserInterfaceModPython import mcontrol def handler(req): ui = UserInterfaceModPython(mcontrol.application) ui.sandbox = mcontrol.arena.new_sandbox() ui.request(req) ui.sandbox.flush_all() return ui.status_code ------------ Robert Brewer MIS Amor Ministries fumanchu at amor.org P.S. I've finally tested postgres, mysql, and sqlite on both Debian Linux and Windows 2k, and made the final updates. So the 1.3 release should be _very_ soon. From tjreedy at udel.edu Wed Jan 5 19:37:01 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 5 Jan 2005 19:37:01 -0500 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7xoeg4txrp.fsf@ruckus.brouhaha.com><1104895842.200010.42720@z14g2000cwz.googlegroups.com><7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> Message-ID: "John Roth" wrote in message news:10to8qulnc3vke1 at news.supernews.com... > I would like to contribute some documentation to Python. > I've got the time, I write quite a bit, etc. I've got fairly > strong opinions about some things that need to be documented, > (such as all the new style class descriptor stuff from 2.2) > and I have relatively little difficulty matching the existing style. I would love to see the written better and in the manuals. > However, I don't > know TEX, Latex, CVS or Sourceforge. (The latter two are > on my "learn sometime soon so I can put PyFIT where it belongs" > list.) Neither do I. > I have no desire to install Perl to run the documentation toolchain. > I also have no particular desire to write up a bunch of final > format stuff and drop it on someone else to put into the latex > format so it can be included. Why not? If someone is willing to do the part that is easier for him (format pre-written ascii text), why aren't you willing to do the part that is easier for you (write the text)? I am asking as someone who has done just that, at least on a micro scale of occasional sentences in response to bug reports. Terry J. Reedy From mmokrejs at ribosome.natur.cuni.cz Mon Jan 17 05:53:09 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-2?Q?Martin_MOKREJ=A9?=) Date: Mon, 17 Jan 2005 11:53:09 +0100 Subject: Writing huge Sets() to disk Message-ID: <41EB9915.8080408@ribosome.natur.cuni.cz> Hi, could someone tell me what all does and what all doesn't copy references in python. I have found my script after reaching some state and taking say 600MB, pushes it's internal dictionaries to hard disk. The for loop consumes another 300MB (as gathered by vmstat) to push the data to dictionaries, then releases little bit less than 300MB and the program start to fill-up again it's internal dictionaries, when "full" will do the flush again ... The point here is, that this code takes a lot of extra memory. I believe it's the references problem, and I remeber complains of frineds facing same problem. I'm a newbie, yes, but don't have this problem with Perl. OK, I want to improve my Pyhton knowledge ... :-)) def push_to_disk(self): _dict_on_disk_tuple = (None, self._dict_on_disk1, self._dict_on_disk2, self._dict_on_disk3, self._dict_on_disk4, self._dict_on_disk5, self._dict_on_disk6, self._dict_on_disk7, self._dict_on_disk8, self._dict_on_disk9, self._dict_on_disk10, self._dict_on_disk11, self._dict_on_disk12, self._dict_on_disk13, self._dict_on_disk14, self._dict_on_disk15, self._dict_on_disk16, self._dict_on_disk17, self._dict_on_disk18, self._dict_on_disk19, self._dict_on_disk20) _size = 0 # # sizes of these tmpdicts range from 10-10000 entries for each! for _tmpdict in (self._tmpdict1, self._tmpdict2, self._tmpdict3, self._tmpdict4, self._tmpdict5, self._tmpdict6, self._tmpdict7, self._tmpdict8, self._tmpdict9, self._tmpdict10, self._tmpdict11, self._tmpdict12, self._tmpdict13, self._tmpdict14, self._tmpdict15, self._tmpdict16, self._tmpdict17, self._tmpdict18, self._tmpdict19, self._tmpdict20): _size += 1 if _tmpdict: _dict_on_disk = _dict_on_disk_tuple[_size] for _word, _value in _tmpdict.iteritems(): try: _string = _dict_on_disk[_word] # I discard _a and _b, maybe _string.find(' ') combined with slice would do better? _abs_count, _a, _b, _expected_freq = _string.split() _abs_count = int(_abs_count).__add__(_value) _t = (str(_abs_count), '0', '0', '0') except KeyError: _t = (str(_value), '0', '0', '0') # this writes a copy to the dict, right? _dict_on_disk[_word] = ' '.join(_t) # # clear the temporary dictionaries in ourself # I think this works as expected and really does release memory # for _tmpdict in (self._tmpdict1, self._tmpdict2, self._tmpdict3, self._tmpdict4, self._tmpdict5, self._tmpdict6, self._tmpdict7, self._tmpdict8, self._tmpdict9, self._tmpdict10, self._tmpdict11, self._tmpdict12, self._tmpdict13, self._tmpdict14, self._tmpdict15, self._tmpdict16, self._tmpdict17, self._tmpdict18, self._tmpdict19, self._tmpdict20): _tmpdict.clear() The above routine doesn't release of the memory back when it exits. See, the loop takes 25 minutes already, and it's prolonging as the program is in about 1/3 or 1/4 of the total input. The rest of my code is fast in contrast to this (below 1 minute). -rw------- 1 mmokrejs users 257376256 Jan 17 11:38 diskdict12.db -rw------- 1 mmokrejs users 267157504 Jan 17 11:35 diskdict11.db -rw------- 1 mmokrejs users 266534912 Jan 17 11:28 diskdict10.db -rw------- 1 mmokrejs users 253149184 Jan 17 11:21 diskdict9.db -rw------- 1 mmokrejs users 250232832 Jan 17 11:14 diskdict8.db -rw------- 1 mmokrejs users 246349824 Jan 17 11:07 diskdict7.db -rw------- 1 mmokrejs users 199999488 Jan 17 11:02 diskdict6.db -rw------- 1 mmokrejs users 66584576 Jan 17 10:59 diskdict5.db -rw------- 1 mmokrejs users 5750784 Jan 17 10:57 diskdict4.db -rw------- 1 mmokrejs users 311296 Jan 17 10:57 diskdict3.db -rw------- 1 mmokrejs users 295895040 Jan 17 10:56 diskdict20.db -rw------- 1 mmokrejs users 293634048 Jan 17 10:49 diskdict19.db -rw------- 1 mmokrejs users 299892736 Jan 17 10:43 diskdict18.db -rw------- 1 mmokrejs users 272334848 Jan 17 10:36 diskdict17.db -rw------- 1 mmokrejs users 274825216 Jan 17 10:30 diskdict16.db -rw------- 1 mmokrejs users 273104896 Jan 17 10:23 diskdict15.db -rw------- 1 mmokrejs users 272678912 Jan 17 10:18 diskdict14.db -rw------- 1 mmokrejs users 260407296 Jan 17 10:13 diskdict13.db Some spoke about mmaped files. Could I take advantage of that with bsddb module or bsddb? Is gdbm better in some ways? Recently you have said dictionary operations are fast ... Once more. I want to turn of locking support. I can make the values as strings of fixed size, if mmap() would be available. The number of keys doesn't grow much in time, mostly there are only updates. Thaks for any ideas. martin From paul at prescod.net Tue Jan 18 06:46:24 2005 From: paul at prescod.net (Paul Prescod) Date: Tue, 18 Jan 2005 03:46:24 -0800 Subject: Problem parsing namespaces with xml.dom.minidom In-Reply-To: <41eca38d@clear.net.nz> References: <41eca38d@clear.net.nz> Message-ID: <41ECF710.7000105@prescod.net> You've reversed some function parameters. Here's a program that works fine (note that you don't need to set up a SAX parser): from xml.dom import minidom text = ''' alias Thu Jan 30 15:06:06 NZDT 2003 Nothing ''' # Parse the string into a minidom mydom = minidom.parseString(text) # Look for some elements # This one shouldn't return any (I think). object_el1 = mydom.getElementsByTagName("xte:object") # This one definitely should, at least for what I want. object_el2 = mydom.getElementsByTagNameNS( 'http://www.mcs.vuw.ac.nz/renata/xte',"object", ) print '1: ' + str(object_el1) print '2: ' + str(object_el2) From t-meyer at ihug.co.nz Mon Jan 31 21:26:43 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Tue, 1 Feb 2005 15:26:43 +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. Seems to hang, or does hang? Using print statements will tell you whether that's where it's getting stuck or not. > I don't know what else I can try. Any > suggestions will be welcome. > > import socket, select, os > > PORT = 2005 > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > s.bind((socket.gethostname(), PORT)) > s.listen(1) > work_socket, addr = s.accept() > data = s.recv(1024) [...] This should be 'data = work_socket.recv(1024)'. This script works for me with that change. (i.e. I can run it with port 2005 already in use, connect to the port, and it will finish without error). =Tony.Meyer From tom at dtsam.com Wed Jan 19 12:35:16 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Wed, 19 Jan 2005 11:35:16 -0600 Subject: [OT] Good C++ book for a Python programmer References: <1106136496.719185.87850@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1106136496.719185.87850 at c13g2000cwb.googlegroups.com... > I'm picking up C++ again after years of using almost nothing but > Python. I'm frankly enjoying the experience, and it's certainly > deepening my appreciation of Python (which you can read however you > like). > Gad! After Python, how can you stand it (C++) ? Adding object oriented utility to the C language was an atrocity, albeit perhaps a necessary one given the state of the art when that particular atrocity was committed. Aren't we past this? If it is fast, fully compiled code you seek - couldn't you just C a few slow functions and use them in your Python? Thomas Bartkus From jrlen97 at gmail.com Wed Jan 26 02:07:52 2005 From: jrlen97 at gmail.com (Jan Rienyer Gadil) Date: Wed, 26 Jan 2005 15:07:52 +0800 Subject: How to assign Message-ID: Sort of a newbie question: How am i going to assign to a variable anything the user inputs on a wxTxtCtrl? From bill.mill at gmail.com Fri Jan 28 10:20:30 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 28 Jan 2005 10:20:30 -0500 Subject: Dynamic class methods misunderstanding Message-ID: <797fe3d405012807204828b8c2@mail.gmail.com> Hello all, I have a misunderstanding about dynamic class methods. I don't expect this behavior: In [2]: class test: ...: def __init__(self, method): ...: self.method = method ...: self.method() ...: In [3]: def m(self): print self ...: In [4]: test(m) --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /cygdrive/c/Documents and Settings/Wmill/ /cygdrive/c/Documents and Settings/Wmill/ in __init__(self, method) TypeError: m() takes exactly 1 argument (0 given) ----------------------------------------------------------------------------- Why doesn't m get the implicit self parameter in the self.method() call? How would I make it a proper member of the class, so that a self.method() call would work with the above "m" function? Peace Bill Mill bill.mill at gmail.com From marklists at mceahern.com Thu Jan 27 08:18:14 2005 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 27 Jan 2005 07:18:14 -0600 Subject: exclude binary files from os.walk In-Reply-To: <1106808469.8583.14.camel@bucket.localnet> References: <41f8167b$0$8648$a1866201@visi.com> <1106808469.8583.14.camel@bucket.localnet> Message-ID: <41F8EA16.3060209@mceahern.com> The OP wrote: > Is there an easy way to exclude binary files (I'm working on Windows XP) from the file list returned by os.walk()? Sure, piece of cake: #!/usr/bin/env python import os def textfiles(path): include = ('.txt', '.csv',) for root, dirs, files in os.walk(path): for name in files: prefix, ext = os.path.splitext(name) if ext.lower() not in include: continue filename = os.path.join(root, name) yield filename path = os.getcwd() for name in textfiles(path): print name ;-) // m From marklists at mceahern.com Sun Jan 16 09:22:37 2005 From: marklists at mceahern.com (Mark McEahern) Date: Sun, 16 Jan 2005 08:22:37 -0600 Subject: accessing class variables of private classes In-Reply-To: References: Message-ID: <41EA78AD.1030001@mceahern.com> Uwe Mayer wrote: >Hi, > >I need to access class variables of a class I'd like to make private: > > Use single underscores instead of double underscores--you won't have to workaround the name mangling. Besides, nothing's really private anyway. // m From josh-tmda at yucs.org Thu Jan 20 10:46:13 2005 From: josh-tmda at yucs.org (josh) Date: Thu, 20 Jan 2005 15:46:13 +0000 (UTC) Subject: why no time() + timedelta() ? Message-ID: Why can't timedelta arithmetic be done on time objects? (e.g. datetime.time(5)-datetime.timedelta(microseconds=3) Nonzero "days" of the timedelta could either be ignored, or trigger an exception. From bokr at oz.net Fri Jan 21 23:11:32 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 22 Jan 2005 04:11:32 GMT Subject: Print a string in binary format References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> Message-ID: <41f1b14a.1480920561@news.oz.net> On Sat, 22 Jan 2005 00:45:19 +1000, Nick Coghlan wrote: >neutrino wrote: >> Greetings to the Python gurus, >> >> I have a binary file and wish to see the "raw" content of it. So I open >> it in binary mode, and read one byte at a time to a variable, which >> will be of the string type. Now the problem is how to print the binary >> format of that charater to the standard output. It seems a common task >> but I just cannot find the appropriate method from the documentation. >> Thanks a lot. >> > >FWIW, I work with serial data a lot, and I find the following list comprehension >to be a handy output tool for binary data: > > print " ".join(["%0.2X" % ord(c) for c in data]) > >The space between each byte helps keep things from degenerating into a >meaningless mass of numbers, and using 2-digit hex instead of binary works >towards the same purpose. (I actually currently use the hex() builtin, but the >above just occurred to me, and it will give nicer formatting, and avoids the >C-style "0x" prefixing each byte) > >Here's an interesting twiddle, though (there's probably already something along >these lines in the cookbook): Looks like you also played with this problem, after Alex posted a request for alternative one-liner solutions to a question on an Italian newsgroup last October? ("show_base" reminded me of "number_in_base") http://groups-beta.google.com/groups?hl=en&lr=&q=number_in_base&qt_s=Search+Groups BTW, my final version was (which can be put on one line ;-) def number_in_base(x, N=10, digits='0123456789ABCDEF'): return '-'[:x<0]+''.join([digits[r] for q in [abs(x)] for q,r in iter(lambda:divmod(q, N), (0,0))][::-1]) or digits[0] (it also takes care of sign and lets you encode with alternative digits if you like ;-) > >Py> def show_base(val, base, min_length = 1): >... chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" >... if base < 2: raise ValueError("2 is minimum meaningful base") >... if base > len(chars): raise ValueError("Not enough characters for base") >... new_val = [] >... while val: >... val, remainder = divmod(val, base) >... new_val.append(chars[remainder]) >... result = "".join(reversed(new_val)) >... return ("0" * (min_length - len(result))) + result Hm, learn something every day ;-) It didn't occur to me that a string multiplied by a negative number would default nicely to the same result as multiplying by zero. >... >Py> show_base(10, 2) >'1010' >Py> show_base(10, 2, 8) >'00001010' >Py> show_base(10, 16, 2) >'0A' >Py> show_base(254, 16, 2) >'FE' >Py> show_base(0, 16) >'0' >Py> for base in range(2, 36): >... for testval in range(1000): >... assert testval == int(show_base(testval, base), base) >... >Py> I guess that's a good idea (supplying full set of alphanumeric digits) >>> def number_in_base(x, N=10, digits='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'): ... return '-'[:x<0]+''.join([digits[r] for q in [abs(x)] ... for q,r in iter(lambda:divmod(q, N), (0,0))][::-1]) or digits[0] ... >>> for base in range(2, 36): ... for testval in range(1000): ... assert testval == int(number_in_base(testval, base), base) ... >>> For that matter, might as well go for Z base and negatives too: >>> for base in range(2, 37): ... for testval in range(-500, 500): ... assert testval == int(number_in_base(testval, base), base) ... >>> (assert did not complain) >>> for base in range(2, 37): ... for testval in (-base+2, -base+1, -base, base-2, base-1,base): ... print '%4s:%-4s'%(testval, number_in_base(testval, base)), ... print ... 0:0 -1:-1 -2:-10 0:0 1:1 2:10 -1:-1 -2:-2 -3:-10 1:1 2:2 3:10 -2:-2 -3:-3 -4:-10 2:2 3:3 4:10 -3:-3 -4:-4 -5:-10 3:3 4:4 5:10 -4:-4 -5:-5 -6:-10 4:4 5:5 6:10 -5:-5 -6:-6 -7:-10 5:5 6:6 7:10 -6:-6 -7:-7 -8:-10 6:6 7:7 8:10 -7:-7 -8:-8 -9:-10 7:7 8:8 9:10 -8:-8 -9:-9 -10:-10 8:8 9:9 10:10 -9:-9 -10:-A -11:-10 9:9 10:A 11:10 -10:-A -11:-B -12:-10 10:A 11:B 12:10 -11:-B -12:-C -13:-10 11:B 12:C 13:10 -12:-C -13:-D -14:-10 12:C 13:D 14:10 -13:-D -14:-E -15:-10 13:D 14:E 15:10 -14:-E -15:-F -16:-10 14:E 15:F 16:10 -15:-F -16:-G -17:-10 15:F 16:G 17:10 -16:-G -17:-H -18:-10 16:G 17:H 18:10 -17:-H -18:-I -19:-10 17:H 18:I 19:10 -18:-I -19:-J -20:-10 18:I 19:J 20:10 -19:-J -20:-K -21:-10 19:J 20:K 21:10 -20:-K -21:-L -22:-10 20:K 21:L 22:10 -21:-L -22:-M -23:-10 21:L 22:M 23:10 -22:-M -23:-N -24:-10 22:M 23:N 24:10 -23:-N -24:-O -25:-10 23:N 24:O 25:10 -24:-O -25:-P -26:-10 24:O 25:P 26:10 -25:-P -26:-Q -27:-10 25:P 26:Q 27:10 -26:-Q -27:-R -28:-10 26:Q 27:R 28:10 -27:-R -28:-S -29:-10 27:R 28:S 29:10 -28:-S -29:-T -30:-10 28:S 29:T 30:10 -29:-T -30:-U -31:-10 29:T 30:U 31:10 -30:-U -31:-V -32:-10 30:U 31:V 32:10 -31:-V -32:-W -33:-10 31:V 32:W 33:10 -32:-W -33:-X -34:-10 32:W 33:X 34:10 -33:-X -34:-Y -35:-10 33:X 34:Y 35:10 -34:-Y -35:-Z -36:-10 34:Y 35:Z 36:10 >>> Of course, this is the prefixed-sign and absolute value representation, which is no good if you are using base 2, 8, or 16 to get an idea of underlying bits in a negative two-s complement representation. But that's another thread ;-) Regards, Bengt Richter From rNOSPAMon at flownet.com Mon Jan 3 10:41:32 2005 From: rNOSPAMon at flownet.com (Ron Garret) Date: Mon, 03 Jan 2005 07:41:32 -0800 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <87u0py6elt.fsf@sme.intra.citec.fi> Message-ID: In article , Just wrote: > In article <87u0py6elt.fsf at sme.intra.citec.fi>, > Simo Melenius wrote: > > > I've sometimes replaced sys.stdout (and/or sys.stderr) to > > capture/redirect debugging information in existing code that has > > unwisely just "print"ed error and warning messages, instead of using > > sys.stderr or error logging modules. > > > > py> def with_output_to_string (func): > > ... try: > > ... sys.stdout = StringIO.StringIO () > > ... func () > > ... return sys.stdout.getvalue () > > ... finally: > > ... sys.stdout = sys.__stdout__ > > Aargh, I can't believe how widespread this idiom is :-(. See my other > reply in this thread: DON'T use sys.__stdout__. Ever. It's helpful to provide an explanation when saying things like this. In this case, it's best to save the original value of sys.stdout and restore that, otherwise nested calls to with_output_to_string can fail, e.g. def f(): print 123 def g(): print 456 x = with_output_to_string(f) print 789 with_outupt_to_string(g) # Will miss the 789 rg From http Tue Jan 11 01:10:19 2005 From: http (Paul Rubin) Date: 10 Jan 2005 22:10:19 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <34h7m9F43vomsU1@individual.net> Message-ID: <7xsm58lcms.fsf@ruckus.brouhaha.com> Brion Vibber writes: > MediaWiki should run with PHP configured in CGI handler mode, but > these days mod_php has got its claws just about everywhere anyway. If > you control your own server and don't have multi-user security > worries, mod_php is simple enough to install and will probably perform > better. Thanks, yes, I could run a special apache instance with mod_php installed. I'm pretty good with apache. I have no MySQL admin experience but I suppose enough people are using MySQL that the installation procedures and docs are pretty well developed and I can follow the instructions. What I'm wondering is just how big an adventure I'd be setting off on, simply to get MediaWiki itself installed, configured, and running. Any thoughts about that? > For performance I also highly recommend using Turck MMCache or > equivalent PHP bytecode cache extension. Unlike Python, saving > compiled bytecode is not the default behavior of PHP, and for > non-trivial scripts compilation eats up a lot of runtime. Hmm, that's something I could deal with later, I guess. Is that similar to what Zend does? > > I'll say that I haven't actually looked at > > the Mediawiki code, though I guess I should do so. > > Cover your eyes...! it _is_ PHP after all. ;) Heehee. I like PHP just fine for small projects. I just cringe at the notion of something as complex as MediaWiki being written in PHP and am constantly, involuntarily thinking about how I would do it in Python. I can't help myself. Without looking at even a line of WikiMedia's code, I already want to do a total rewrite ;-). > I would generally recommend you just start with MediaWiki if you > intend to use it. To migrate a non-tiny site later you'll need to work > out a migration script to import your data in some way (some people > have asked about this in the past, I don't know if anyone's ever > completed one or made it public). You're probably right, I'll download Wikimedia and see about installing it. I have tons of server disk space, though the CPU has been getting a bit overloaded lately. > On the other hand if you _do_ write a MoinMoin-to-MediaWiki > conversion script (or vice-versa!) we'd love to include it in the > MediaWiki distribution. I think a rough approximation would be pretty easy to do. Trying to get every detail right would be very difficult. If I do something like that, I'll likely go for the rough approximation. From peter at engcorp.com Sat Jan 8 12:58:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 12:58:00 -0500 Subject: OT: google groups bug, or worse? In-Reply-To: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> References: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> Message-ID: aaronwmail-usenet at yahoo.com wrote: > I'm concerned that google groups is not correctly reflecting the > python lists. A month ago I announced the xsdbXML framework to the > python list and the python-announce list. As you can see from the > links > below the python announce submission was approved by the moderators > (thanks!) > and the python list submission also went out, but the messages cannot > be found at google groups. > > http://mail.python.org/pipermail/python-list/2004-December/254479.html > http://mail.python.org/pipermail/python-announce-list/2004-December/003583.html > > Is it a google bug? Or is it something darker, like an anti-Python > conspiracy at google? You didn't post via Google, right? Just sent to the mailing list? I believe that Google knows nothing about mailing lists, but watches a news feed, so if the list/Usenet gateway failed to deliver those messages, Google would never see them. Furthermore, news delivery is not necessarily guaranteed. (Actually, I don't recall how reliable the protocol is, but I doubt it's foolproof.) If any one of the news servers between yours and Google's happened to drop some messages, it's quite possible Google would never see them. Given the "architecture" of Usenet, I wouldn't be surprised if Google missed messages consistently, a very small percentage of the time. -Peter From deetsNOSPAM at web.de Fri Jan 28 11:27:22 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 28 Jan 2005 17:27:22 +0100 Subject: Installing Numeric with ATLAS and LAPACK References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> Message-ID: <35v7b6F4qie84U1@individual.net> > Could someone please provide instructions for install Numeric > with ATLAS and LAPACK? No idea - but telling us what os and versions of python and numeric you use might make others comment on that. -- Regards, Diez B. Roggisch From davorss at gmail.com Wed Jan 26 00:54:13 2005 From: davorss at gmail.com (Davor) Date: 25 Jan 2005 21:54:13 -0800 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <41f6f4ee$1@nntp.zianet.com> Message-ID: <1106718853.867328.55760@z14g2000cwz.googlegroups.com> thanks for the link > know what's funny: in the Lua mailing list there is currently a > discussion about adding OO to Lua. I guess most of these newer languages have no choice but to support OO if they want to attract a larger user base :-(... davor From "yardholler\" at Nospam,charter.net> Sat Jan 15 07:09:34 2005 From: "yardholler\" at Nospam,charter.net> (Misty) Date: Sat, 15 Jan 2005 06:09:34 -0600 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <1105739748.306557.72120@z14g2000cwz.googlegroups.com> Message-ID: mr_little wrote: > Brian Eable wrote: > >>perl -e '$a="194.109.137.226"; @a = reverse split /\./, $a; for $i > > (0..3) { $sum += $a[$i]*(256**$i) } print "sum = $sum\n"' > >>226 + 35072 + 7143424 + 3254779904 = 3261958626 >> >>http://3261958626/ >> >>Which is NOT 666. > > Comrade, why perl here? :) > Are you afraid python? :) > From No_4 at dsl.pipex.com Tue Jan 11 15:50:06 2005 From: No_4 at dsl.pipex.com (Big and Blue) Date: Tue, 11 Jan 2005 20:50:06 +0000 Subject: complex numbers In-Reply-To: References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: <6-Cdnfjyqs6coXncRVnyuA@pipex.net> It's me wrote: > > I am very happy that Python included *native* complex number > support. And I have always been happy that FORTRAN supports them. > I really like Python's notion of having just one data type: the duck. So have you considered using Python for your problem? -- Just because I've written it doesn't mean that either you or I have to believe it. From jfine at pytex.org Fri Jan 7 16:19:20 2005 From: jfine at pytex.org (Jonathan Fine) Date: Fri, 07 Jan 2005 21:19:20 +0000 Subject: What could 'f(this:that=other):' mean? References: <41DC52CA.5070104@pytex.org> <10toomjdjcs5v21@corp.supernews.com> <41DCE28B.70806@pytex.org> Message-ID: <41DEFCD8.3010407@pytex.org> Jonathan Fine wrote: > I'll post some usage examples later today, I hope. Well, here are some examples. A day later, I'm afraid. ** Pipelines and other composites This is arising for me at work. I produce Postscript by running TeX on a document. And then running dvips on the output of TeX. TeX as a program has parameters (command line options). As does dvips. For various reasons I wish to wrap TeX and dvips. def tex_fn(filename, input_path=None, eps_path=None): '''Run tex on filename. Search for input files on input_path. Search for EPS files on eps_path. ''' pass def dvips_fn(filename, page_size=None, color_profile=None): '''Run dvips on filename. etc.''' pass In reality, these tex and dvips have many options. More parameters will be added later. So now I wish to produce a composite function, that runs both tex and dvips. And does other glue things. def tex_and_dvips_fn(filename, tex:input_path=xxx, dvips:color_profile=yyy): # glueing stuff tex_fn(filename, **tex) # more glueing stuff dvips_fn(filename, **dvips) To avoid a name clash, we use 'tex' for the parameter space, and 'tex_fn' for the function that takes 'tex' as parameter. The point is that parameters can be added to tex_fn and dvips_fn without our having to change tex_and_dvips_fn ** Wrapping functions This is the problem that originally motivated my suggestion. We have coded a new function. def adder(i, j): return i + j We wish to test 'adder'. But unittest is too verbose for us. We wish to define a decorator (?) test_wrap to work as follows. orig_adder = adder adder = test_wrap(adder) new_adder = adder orig_adder(i, j) and new_adder(i, j) to be effectively identical - same return, same side effects, raise same exceptions. So far, def test_wrap(fn): return fn does the job. But now we want new_adder(2, 2, returns=4) new_adder(2, '', raises=TypeError) to be same as orig_adder(2, 2) orig_adder(2, '') (which can be achieved by ignoring 'returns' and 'raises'. The idea here is that we can call adder = new(adder) early on, and not break any working code. And we also want new_adder(2, 2, 5) new_adder('', '', raises=TypeError) to raise something like an AssertionError. OK - so I have an informal specification of test_wrap. Its clear, I think, that test_wrap must be something like def test_wrap(fn): def wrapped_fn(*args, **kwargs): test_args = {} # transfer entries from one dict to another for key in ('returns', 'raises'): if kwargs.has_key(key): test_args[key] = kwargs[key] del kwargs[key] result = fn(args, kwargs) if test_args.has_key(result): assert test_args['result'] = result (I've not coded testing for 'raises'.) Now, the more parameters added by the test_wrap function, the more the chance of a name clash. So why not reduce the chances by using name spaces. One possible namespace syntax is: new_adder(2, 3, test=dict(returns=5)) Another such syntax is: new_adder(2, 3, test:returns=5) Each has its merits. The first works with Python 2.4. The second is, in my opinion, easier on the eye. Anyway, that's my suggestion. Jonathan From cartermark46 at ukmail.com Mon Jan 10 06:55:11 2005 From: cartermark46 at ukmail.com (Mark Carter) Date: Mon, 10 Jan 2005 11:55:11 +0000 Subject: Port blocking In-Reply-To: <7x3bx9sehd.fsf@ruckus.brouhaha.com> References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> Message-ID: <34f8ovF47d783U1@individual.net> Paul Rubin wrote: > Mark Carter writes: > >>Supposing I decide to write a server-side application using something >>like corba or pyro. > Usually you wouldn't run a public corba or pyro service over the > internet. You'd use something like XMLRPC over HTTP port 80 partly > for the precise purpose of not getting blocked by firewalls. Although, when you think about it, it kinda defeats the purposes of firewalls. Not that I'm criticising you personally, you understand. >>Also, is there a good tool for writing database UIs? > > > Yes, quite a few. Ah yes, but is there really? For example, I did a search of the TOC of GTK+ Reference Manual: http://developer.gnome.org/doc/API/2.0/gtk/index.html for the word "data", and there's apparently no widget which is explicitly tied to databases. So in GTKs case, for instance, it looks like one has to roll one's own solution, rather than just using one out of the box. From fumanchu at amor.org Tue Jan 4 17:31:17 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 4 Jan 2005 14:31:17 -0800 Subject: Lambda as declarative idiom Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33980E3@exchange.hqamor.amorhq.net> Michael Spencer wrote: > Roman Suzi wrote: > > > Maybe this is too outlandish, but I see lambdas as a > "quote" mechanism, > > which presents a possibility to postpone (precisely > control, delegate) > > evaluation. That is, an ovehead for lambda must be much > lower but at the > > same time visible to the programmer: > > > > d = a + (lambda x, y: x+ y)(3, 4) > [...] > > I believe that this "possibility to postpone" divides into > two related but separate concepts: controlling the moment > of evaluation, and assembling the arguments required at > that moment. They are both species of 'eval', but > managing arguments is more specialized, because it includes > possibly renaming parameters, assigning default values, > processing positional and keyword arguments, and, perhaps > in the future dealing with argument types. Yes, but the "moment of evaluation" is more complex than just "postponing". In a declarative construct, you probably also want global variables to be bound early, so that the expression does not depend upon *any* free variables. Ditto for closures. A more realistic example: term = input("Enter the amount to add") e = expr(x): x + term ...MUCH code passes, maybe even a new process or thread... d = a + e(3) Robert Brewer MIS Amor Ministries fumanchu at amor.org From ncoghlan at iinet.net.au Wed Jan 26 02:17:48 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 17:17:48 +1000 Subject: python without OO In-Reply-To: <1106718853.867328.55760@z14g2000cwz.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <41f6f4ee$1@nntp.zianet.com> <1106718853.867328.55760@z14g2000cwz.googlegroups.com> Message-ID: <41F7441C.9030008@iinet.net.au> Davor wrote: > thanks for the link > > >>know what's funny: in the Lua mailing list there is currently a >>discussion about adding OO to Lua. > > > I guess most of these newer languages have no choice but to support OO > if they want to attract a larger user base :-(... Tell me, have you ever defined a C structure, and then written various functions to operate on that structure (i.e. taking a pointer to the structure as their first argument)? Have you then put both the structure definition and the function prototypes into a single header file and used that header file from other code? That's OO programming: associating several pieces of information as an 'object', and associating various methods to operate on instances of those objects. Everything else is optional. Problems with OO design generally result from violations of the KISS principle, not from OO itself (although languages like Java and C++ make it hard to avoid violating KISS, since they make you jump through so many hoops to get anything to work at all). KISS (and the XP mantra "Do the simplest thing that could possibly work") are the best means to fight off overengineering, rather than a blanket ban on OO techniques. Jeremy's "Bower's Law" page really does provide a good perspective on the benefits of judicious use of OO techniques (http://www.jerf.org/writings/bowersLaw.html). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From sjmachin at lexicon.net Tue Jan 11 20:12:27 2005 From: sjmachin at lexicon.net (John Machin) Date: 11 Jan 2005 17:12:27 -0800 Subject: Help Optimizing Word Search In-Reply-To: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: <1105492347.701890.124830@f14g2000cwb.googlegroups.com> Case Nelson wrote: > Hi there I've just been playing around with some python code and I've > got a fun little optimization problem I could use some help with. > > Basically, the program needs to take in a random list of no more than > 10 letters, and find all possible mutations that match a word in my > dictionary (80k words). However a wildcard letter '?' is also an > acceptable character which increases the worst case time significantly. > So if the letters are ['a','b','c'] check a, b, c, ab, ac, ba, bc, ca, > cb, abc, acb, bac, bca, cab, cba where only a, ba and cab would be > added to the dict of words. If the letters are ['?','?'] check a-z, aa, > ab, ac, ad, ..., az, ba, bb, bc, bd, ..., zz This appears to be a Computer Science 101 Data Structures and Algorithms question, not a Python question, but here's an answer anyway: You appear to want to find all words that have one or more letters in common with your query or candidate string. Aside: Have you been following the long thread started by the poster who appeared to want to store all possible strings that were _not_ words in a given language but could be generated from its alphabet? Here's a possibility: use a bit mask approach. You attach a bit mask to each word; simple data structure -- a list of 2-tuples, or two parallel lists. !def mask(word): ! m = 0 ! for letter in word: ! m |= 1 << (ord(letter) - ord('a')) ! return m Searching without wildcards: !def nowc_search(candidate, mylistof2tuples): ! candmask = mask(candidate) # treating candidate as str, not list ! for word, mask in mylistof2tuples: ! if mask & candmask: ! # one or more letters in common ! yield word Note: this treats "mississippi" and "misp" the same. If "aa" is in your dictionary, what queries would retrieve it? Depending on your exact requirements, this technique may suit you, or you may want to use it as a fast(?) filter, with the matches it throws up needing further checking. You may need a "count number of bits that are set in an int" function. Ref: Fred J. Damerau, "A technique for computer detection and correction of spelling errors", CACM vol 7 number 3, March 1961. Searching with wild cards: your example of query == "??" seems to yield all two-letter words. I'd like to see what you expect for "a?", "?a", "ab?", and "aa?" before suggesting how to tackle wild cards. Reverse-engineering requirements out of other folks' code is not something I do for fun :-) An alternative for you to think about: instead of a bitmask, store the letter-sorted transformation of the words: cat->act, act->act, dog->dgo, god->dgo. Alternative data structure: key = bitmask or sorted-letters, value = list of all words that have that key. A further suggestion which should always be considered when setting up a search where the timing is worse than average O(1): have a separate dictionary for each different wordlength, or some other impossible-length-avoidance filter; that way, with minimum preliminary calculation you can avoid considering words that are so long or so short that they cannot possibly be matches. For example, with approximate matching based on edit distance, if you are searching for a 10-letter word allowing for 2 errors, you can avoid doing the complicated comparison on words shorter than 8 or longer than 12. HTH, John From Pieter.Claerhout at Creo.com Mon Jan 24 10:43:31 2005 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Mon, 24 Jan 2005 16:43:31 +0100 Subject: Finding a script's home directory? Message-ID: The following should work: os.path.split( os.path.realpath( sys.argv[0] ) )[0] Cheers, pieter -----Original Message----- From: python-list-bounces+pieter.claerhout=creo.com at python.org [mailto:python-list-bounces+pieter.claerhout=creo.com at python.org] On Behalf Of Gabriel Cooper Sent: 24 January 2005 16:40 To: python-list at python.org Subject: Finding a script's home directory? In one of my python programs has a data file I need to load. My solution was to say: if os.path.exists(os.path.join(os.getcwd(), "config.xml")): self.cfgfile = os.path.join(os.getcwd(), "config.xml") Which works fine... as long as you're *in* the script's home directory when you run it (as in, run it as: ./startApp.py as opposed to ./myApp/startApp.py). If I run it from an alternate directory the program looks for the config.xml file in my current directory not the app's home directory. So how do I get the script's home directory? -- http://mail.python.org/mailman/listinfo/python-list From aleaxit at yahoo.com Sat Jan 22 06:10:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 12:10:36 +0100 Subject: list unpack trick? References: <1gqsalx.4ip95k18168r0N%aleaxit@yahoo.com> Message-ID: <1gqshen.6ugqf23hph5qN%aleaxit@yahoo.com> Fredrik Lundh wrote: > Alex Martelli wrote: > > >> or (readable): > >> > >> if len(list) < n: > >> list.extend((n - len(list)) * [item]) > > > > I find it just as readable without the redundant if guard -- just: > > > > alist.extend((n - len(alist)) * [item]) > > the guard makes it obvious what's going on, also for a reader that doesn't > know exactly how "*" behaves for negative counts. It does, but it's still redundant, like, say, if x < 0: x = abs(x) makes things obvious even for a reader not knowing exactly how abs behaves for positive arguments. Redundancy in the code to try and compensate for a reader's lack of Python knowledge is not, IMHO, a generally very productive strategy. I understand perfectly well that you and others may disagree, but I just thought it worth stating my personal opinion in the matter. > once you've seen the > "compare length to limit" and "extend", you don't have to parse the rest of > the statement. Sorry, I don't get this -- it seems to me that I _do_ still have to "parse the rest of the statement" to understand exactly what alist is being extended by. Alex From turian at gmail.com Sun Jan 23 23:52:10 2005 From: turian at gmail.com (Joseph Turian) Date: 23 Jan 2005 20:52:10 -0800 Subject: Fuzzy matching of postal addresses In-Reply-To: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <1106542330.665780.40340@f14g2000cwb.googlegroups.com> Andrew, > Basically, I have two databases containing lists of postal addresses and > need to look for matching addresses in the two databases. More > precisely, for each address in database A I want to find a single > matching address in database B. What percent of addresses in A have a unique corresponding address in B? (i.e. how many addresses will have some match in B?) This is a standard document retrieval task. Whole books could be written about the topic. (In fact, many have been). I suggest you don't waste your time trying to solve this problem from scratch, and instead capitalize on the effort of others. Hence, my proposal is pretty simple: 1. Regularize the punctuation of the text (e.g. convert it all to uppercase), since it is uninformative and---at best---a confounding variable. 2. Use a free information retrieval package to find matches. e.g. LEMUR: http://www-2.cs.cmu.edu/~lemur/ In this case, a "document" is an address in Database B. A "query" is an address in Database A. (Alternately, you could switch A and B to see if that affects accuracy.) Good luck. Joseph From vincent at visualtrans.de Tue Jan 25 14:54:30 2005 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 25 Jan 2005 20:54:30 +0100 Subject: snakespell and myspell In-Reply-To: <1106657932.301181.150050@z14g2000cwz.googlegroups.com> References: <1106657932.301181.150050@z14g2000cwz.googlegroups.com> Message-ID: <41F6A3F6.9020807@visualtrans.de> Fuzzyman wrote: > I'm looking to implement a plugin spell checker. > > I'm probably going to go with PyEnchant, as it looks to be the most > promising currently maintained spell checker. What I would like to know about PyEnchant is how to handle non-ascii input. Through trial & error I've noticed that let's say German Umlauts are stored in the dictionary as using dead accents (is that the term?) (as in 'Mu"tter'), however French accented characters appear to be stored differently (as in '\xc3\xa9levage'. Anybody know what the "system" is? > > I just wondered if anyone knew what happened to snakespell and myspell. Don't know about that. But than there also is a pyrex-driven aspell binding at http://sourceforge.net/projects/uncpythontools Regards, -- Vincent Wehren > Both seem to have dissapeared from the net. People have reported good > results from both - and it seems a shame to lose them. > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml > From petite.abeille at gmail.com Sat Jan 29 09:41:00 2005 From: petite.abeille at gmail.com (PA) Date: Sat, 29 Jan 2005 15:41:00 +0100 Subject: The next Xah-lee post contest In-Reply-To: References: Message-ID: On Jan 29, 2005, at 15:32, rbt wrote: > Unix donkey! You not elegant. You have poor design. > Sloppy Perl monkey! You be lazy! You code very very bad. > > Xah know all! Follow The True Path, follow The Xah Way To Enlightenment: "The Unix Pestilence" http://www.xahlee.org/UnixResource_dir/freebooks.html Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From honor2003 at yahoo.com Tue Jan 4 00:50:29 2005 From: honor2003 at yahoo.com (john) Date: 3 Jan 2005 21:50:29 -0800 Subject: FS: PC Doctor Message-ID: <1104817829.919110.309420@c13g2000cwb.googlegroups.com> Bought from http://www.PCbeginner.com two weeks ago. Now my computer got fixed and I do not need it any more. Asking $15 only. I will ship to you by first class mail. Email: honor2003 at yahoo.com From jhargraveiii at msn.com Sat Jan 22 22:34:55 2005 From: jhargraveiii at msn.com (Jim Hargrave) Date: Sat, 22 Jan 2005 22:34:55 -0500 Subject: embedding jython in CPython... In-Reply-To: References: Message-ID: Sorry - should have given more detail. That's what I get for posting at 1:00AM. What I want to do us write scripts in CPython that access Windows ActiveX such as Word and IE. Obviously Jython can't do this (easily at least). I also have Jython scripts that provide a high level layer on top of various Java libraries. I'd like to write as much code in Python as possible. But I have a mixture of incompatible CPython and Jython scripts - that's why I would like to embed Jython in CPython. If I can call my Jython scripts from CPython I can have the best of both world's! Would I be able to embed Jython using JPype? The PyLucene approach (compile Java source with GCJ then wrap with SWIG) looks interesting - but complicated. Here's an example of embedding Jython in a regular Java app: http://www.jython.org/docs/embedding.html Imagine doing the same in CPython, but with JPype or GCJ/SWIG. From tjreedy at udel.edu Thu Jan 6 23:53:38 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Jan 2005 23:53:38 -0500 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7x4qhw859p.fsf@ruckus.brouhaha.com><7xk6qrnbum.fsf@ruckus.brouhaha.com><41dcaa00.102858012@news.oz.net><7x652bnhx0.fsf@ruckus.brouhaha.com> <7xsm5et0rb.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7xsm5et0rb.fsf at ruckus.brouhaha.com... > "Terry Reedy" writes: >> Would it be possible, at least for Windows, to write a Python script >> implementing a 'virtual distribution'? IE, download Python, install it, >> download next package, install it, etc. -- prefereably table driven? > > I just don't understand why you'd want to do that, instead of putting > all the files in the distro in the first place. For myself, I can imagine writing such a script using existing installers. I have no idea how to put, say, 20 packages together in one installer. Even if I could, I would not personally buy the bandwidth for gigabyte downloads. I could, however, find somewhere to put a 1K or so script. Terry J. Reedy From della at toglimi.linux.it Sun Jan 9 16:27:09 2005 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Sun, 09 Jan 2005 21:27:09 GMT Subject: else condition in list comprehension In-Reply-To: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: Luis M. Gonzalez wrote: > Hi there, > > I'd like to know if there is a way to add and else condition into a > list comprehension. I'm sure that I read somewhere an easy way to do > it, but I forgot it and now I can't find it... > > for example: > z=[i+2 for i in range(10) if i%2==0] > what if I want i to be "i-2" if i%2 is not equal to 0? You could use [(i-2, i+2)[bool(i%2 == 0)] for i in range(10)] or, in a less general but shorter way [(i+2, i-2)[i%2] for i in range(10)] or even [i%2 and i-2 or i+2 for i in range(10)] The "if" clause in comprehensions is used as a filter condition. -- Ciao, Matteo From grante at visi.com Mon Jan 17 10:21:03 2005 From: grante at visi.com (Grant Edwards) Date: 17 Jan 2005 15:21:03 GMT Subject: List problems in C code ported to Python References: <41ead925$0$87061$a1866201@visi.com> <41eb1cd7$0$10879$a1866201@visi.com> <13PGd.1402$Rs.1375@newsread3.news.atl.earthlink.net> Message-ID: <41ebd7df$0$87049$a1866201@visi.com> On 2005-01-17, Lucas Raab wrote: > Sorry about that. I had a bad day. First there was the > migraine and then the fight with my significant other, so > yesterday was not a good day. I apologize for what I said. No worries. As somebody else said, the best way to get help solving problems is to post as small an example as possible that exhibits the problem behavior. This may take a bit of effort, since problems sometimes go away when you try to reproduce them in a small example (less than 50 lines or so). If you can post a small example that doesn't do what you want it to, I gaurantee that somebody will explain why it doesn't do what you want and how to fix it. -- Grant Edwards grante Yow! LOU GRANT froze at my ASSETS!! visi.com From kartic.krishnamurthy at gmail.com Wed Jan 5 14:25:03 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 11:25:03 -0800 Subject: smtp question In-Reply-To: References: Message-ID: <1104953103.469153.98310@z14g2000cwz.googlegroups.com> Philippe, Looks like the problem lies where you have added the Subject header. You have terminated it with a \n\n and then your From and To headers. You may want to rewrite it as: server.sendmail(fromaddr, toaddrs, 'Subject:from python\r\n'+msg) Why dont you consider using the email module - http://python.org/doc/2.4/lib/module-email.html ? It is elegant and easy to use. Thank you, --Kartic From carribeiro at gmail.com Tue Jan 4 12:18:48 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 4 Jan 2005 15:18:48 -0200 Subject: Python evolution: Unease In-Reply-To: References: Message-ID: <864d370905010409183b621715@mail.gmail.com> On Tue, 4 Jan 2005 10:39:10 -0300, Batista, Facundo wrote: > #- need: a better standard ide, an integrated db interface with > #- a proper > #- set of db drivers (!!), a better debugger, a standard widget/windows > #- toolkit, something akin to a standard for web programming, better > #- documentation, a standard lib which is better organized, a > #- formalized > #- set of protocols and patterns for program construction. And an > #- interpreter which is fast enough to avoid using C or Pyrex in most > #- obvious cases. > > Let's take one by one: I'll take only a few ;-) > - IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than Pythonwin? I would like to seee Eric3, with some polish & opensourced on Win (which means solving the Qt licensing problem). Perhaps someone could convince Trolltech to release a special Qt Win version just for it (Eric3). Eclipse is also an interesting approach. > - Integrated DB interface with a proper set of db drivers (what means the > "!!"?): What do you mean with an integrated db interface? An standard API to > access different DB engines? Something like the Database API specification > (http://www.python.org/topics/database/DatabaseAPI-2.0.html)? There's a SIG > on DB at http://www.python.org/sigs/db-sig/ you may want to look at. > Regarding drivers, to what DB do you miss one? At the risk of starting a huge flamewar, let's state my opinion on this. The DBAPI itself is not a problem, despite several debates about improvements and talks about a future version 3. On the other hand, I wish I could simply plug & play DBAPI modules in a totally seamlessly way. Anyone who tried know how far are we of this dream. At the risk of sounding pessimistic, I don't see plug & play interoperability between DBAPI drivers happening anytime soon. The work is simply way too fragmented. There's no real incentive for compatibility, besides the good will of individual developers, who are always busy and also, that have to keep their own code running. The only way it will work, IMHO, is: if a single entity implements a common API, be it the DBAPI2.0 or whatever, for a sufficiently large number of existing database systems. You may call it a "imposed standard". I don't mind. But it would solve the problem. > - Standard widget/windows toolkit: More standard than Tk? I may be wrong, but I think that most business developers expect more than Tk is able to offer... Canvas is great, but anyone who used more advanced toolkits (such as the ones available on Delphi, Java, or C#) surely require a lot more. -- 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 premshree.pillai at gmail.com Wed Jan 5 08:42:49 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Wed, 5 Jan 2005 19:12:49 +0530 Subject: is python more popular than coldfusion? In-Reply-To: <41dbec00$0$23064$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dbe722$0$23057$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dbec00$0$23064$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: On Wed, 5 Jan 2005 21:30:40 +0800, worzel wrote: > Wth respect to coldfusion, is there much doubt about the fact that Python is > a more prominent and important technology? No doubt in my mind at least. > > How is colfusion percieved by the Python community? Many people belive > coldfusion is becomeing irrelavant and is on its death bed - do Python folk > generally feel this way about it? I have no much idea about Coldfusion, but as far as its *use* is concerned, it definitely isn't much. > > Thanks for your input on this by the way. > > "Premshree Pillai" wrote in message > news:mailman.192.1104931284.22381.python-list at python.org... > > On Wed, 5 Jan 2005 21:09:54 +0800, worzel wrote: > >> How seriuosly do folk take the TIOBE index? Is it a good way to ague what > >> you should be keeping up to speed with or just a 'vague' guide? > > > > I use the TIOBE index -- sometimes -- when I give presentations on > > Python (and Ruby) to people who haven't heard of the languages. > > > > The index is not something to be relied upon (take a look at the > > calculation mechanism). However, more often than not, the indices > > seems to reflect what *I* perceive the indices are in reality. So I > > kinda use them. > > > > The thing about introducing a "new" language to a bunch of folks used > > to their "favorite" language is that they wouldn't care much for a > > language it isn't popular, or if it isn't "growing in popularity". > > > > Beyond these things, I don't think anybody uses the index. I mean I > > wouldn't tell people to learn languages that hold the top position on > > TIOBE ;). > > > >> > >> "Premshree Pillai" wrote in message > >> news:mailman.189.1104927428.22381.python-list at python.org... > >> > On Wed, 5 Jan 2005 19:59:21 +0800, worzel wrote: > >> >> > >> >> > >> >> > >> >> is python more popular than coldfusion? > >> > > >> > I don't know if Coldfusion _was_ ever more "popular" than Python, but > >> > Python is definitely more "popular" _now_. > >> > > >> > This might be of some help: http://www.tiobe.com/tpci.htm > >> > > >> >> > >> >> I realsie that is a very general question as one thing does not > >> >> directly > >> >> relate to the other. My issue is that I am ditching coldfusion due to > >> >> there > >> >> being next to no work for it, and I am thinking of taking on python as > >> >> a > >> >> second language to java in the hope of improving my resume. > >> >> -- > >> >> http://mail.python.org/mailman/listinfo/python-list > >> >> > >> >> > >> > > >> > > >> > -- > >> > Premshree Pillai > >> > http://www.livejournal.com/~premshree > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > > > > > > -- > > Premshree Pillai > > http://www.livejournal.com/~premshree > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From bpeng at rice.edu Sat Jan 1 11:27:50 2005 From: bpeng at rice.edu (Bo Peng) Date: Sat, 01 Jan 2005 10:27:50 -0600 Subject: exposing C array to python namespace: NumPy and array module. In-Reply-To: References: Message-ID: <41D6CF86.1040902@rice.edu> Craig Ringer wrote: > On Sat, 2005-01-01 at 08:18, Bo Peng wrote: > > >>Python's array module is built-in, easy to use, but *without* a >>FromLenAndData function! Even the buffer interface provides only 'get >>buffer' but no 'set buffer' functions. Could anyone tell me how I can >>create an array object from existing data? > > > Python has no array objects in the core language, only lists. The > distinction is important when discussing numarray etc, because Python > lists and NumPy etc arrays are very different. > Thank you very much for the detailed reply! Sorry if I was not clear enough. I was talking about the differece between python array module (http://docs.python.org/lib/module-array.html, Modules/arraymodule.c in the source tree) and NumPy array. They both use C-style memory block arrangement for efficient memory access. While NumPy has both, the array module is designed to be used purely in Python so there is no header file and no function to build an array from a pointer. One of the methods you suggested (creating a new type) already implemented in arraymodule.c. I am not sure if it is appropriate to add the file into my project and add a 'CreateFromLenAndBuf' function. Bo From skullw at sina.com.cn Sat Jan 15 15:27:08 2005 From: skullw at sina.com.cn (skull) Date: Sat, 15 Jan 2005 15:27:08 -0500 Subject: How to del item of a list in loop? Message-ID: Hi everybody, it is my first post in this newsgroup. I am a newbie for python though I have several years development experience in c++. recently, I was stumped when I tried to del item of a list when iteration. here is the wrong way I did: lst = [1, 2, 3] for i in lst: print i if i == 2: lst.remove(i) the result is: 1 2 >>> as you would see, '3' is missing. this problem is caused by 'lst.remove(i)'. apparently, 'marked-and-sweep' is a solution to deal with this issue. but I think there SHOULD BE more 'wise' trick. I want to get your help. Thanks in advance. - skull From pythongnome at hotmail.com Mon Jan 17 10:28:56 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Mon, 17 Jan 2005 15:28:56 GMT Subject: List problems in C code ported to Python In-Reply-To: References: Message-ID: Lucas Raab wrote: > I'm done porting the C code, but now when running the script I > continually run into problems with lists. I tried appending and > extending the lists, but with no avail. Any help is much appreciated > Please see both the Python and C code at > http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py > > TIA OK, here's the Python code and the corresponding C code: def init_mach(): import string #setup rotor data i=1 j=0 for j in j<26, j+1: data[4],[j] = (ref_rotor[j] - 'A'+26) % 26 for i in i<4, i+1: step[i-1] = step_data[order[i-1]] for j in j<26, j+1: data[i],[j] = (rotor[order[i-1]],[j]-'A'+26)%26 data[8-i],[data[i],[j]] = j void init_mach( void ) { int i, j; int ds; int u, v; /* setup rotor data */ for (j=0;j<26;j++) data[4][j] = ((int)ref_rotor[j]-'A'+26)%26; for (i=1;i<4;i++) { step[i-1] = step_data[order[i-1]]; for (j=0;j<26;j++) { data[i][j] = ((int)(rotor[order[i-1]][j])-'A' + 26) % 26; data[8-i][data[i][j]] = j; } } Now, do I need to start boning up on lists and how to use them or am I missing the bigger picture?? Again, for the complete code see http://home.earthlink.net/~lvraab. I'm not asking you to do it for me, just some pointers on going about this. From ncoghlan at iinet.net.au Sat Jan 29 20:53:13 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 30 Jan 2005 11:53:13 +1000 Subject: Coding style article with interesting section on white space In-Reply-To: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> Message-ID: <41FC3E09.5020105@iinet.net.au> beliavsky at aol.com wrote: > The suggestions in the cited article, "How Not to Write FORTRAN in Any > Language", are reasonable but elementary and can be followed in Fortran > 90/95/2003 as well as any other language. What infuriates me is that > the author writes as if Fortran has not evolved since the 1960s. It > has. To be specific, Fortran 90 For myself, I'd be more inclined to say you can write Perl in any language, but the fact that the author used Fortan as his own hated source of unreadable code is beside the point - the entire point of the article is that readability counts, no matter what language you're writing in :) And that's why the article got published in spite of the jabs at Fortran - those jabs served to explain the source of the author's detestation of unreadable code. Anyone taking such an admittedly biased opinion and using it to form an opinion on _current_ Fortan has problems far bigger than a single article. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jjl at pobox.com Sat Jan 22 17:30:06 2005 From: jjl at pobox.com (John J. Lee) Date: 22 Jan 2005 22:30:06 +0000 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> <7xacr4ewjk.fsf@ruckus.brouhaha.com> <41ef4a7a.1323588509@news.oz.net> <7xwtu8vb17.fsf@ruckus.brouhaha.com> <41EF72DE.5030305@jessikat.fsnet.co.uk> <7xwtu8pgr4.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes: [...] > Building larger ones seems to > have complexity exponential in the number of bits, which is not too [...] Why? > It's not even known in theory whether quantum computing is > possible on a significant scale. Discuss. (I don't mean I'm requesting a discussion -- it just reads like a physics / philosophy exam essay question, which traditionally end with that word :) John From rkern at ucsd.edu Wed Jan 19 19:57:49 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 19 Jan 2005 16:57:49 -0800 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> Message-ID: Timothy Fitz wrote: > On 19 Jan 2005 15:24:10 -0800, Carl Banks wrote: > >>The gist of "Flat is better than nested" is "be as nested as you have >>to be, no more," because being too nested is just a mess. > > > Which I agree with, and which makes sense. However your "gist" is a > different meaning. It's not that "Flat is better than nested" it's > that "Too flat is bad and too flat is nested so be as nested (or as > flat) as you have to be and no more." Perhaps Tim Peters is far too > concise for my feeble mind If it were scrutable, it wouldn't be Zen. :-) -- 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 http Wed Jan 12 23:05:02 2005 From: http (Paul Rubin) Date: 12 Jan 2005 20:05:02 -0800 Subject: why are people still using classic classes? References: Message-ID: <7xacregej5.fsf@ruckus.brouhaha.com> Simon Wittber writes: > Is there a legitimate use for classic classes that I am not aware of? Yes, new-style classes don't work in older Python installations. Some Python users prefer not to be on such a frequent upgrade treadmill, so they continue to use old versions. Therefore, anyone writing Python code for wide distribution should avoid using new-style classes (and other new Python features) unless they have a good reason. From kartic.krishnamurthy at gmail.com Sat Jan 1 01:07:43 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 31 Dec 2004 22:07:43 -0800 Subject: ftplib strange behaviour In-Reply-To: <1104495025.682424.72160@c13g2000cwb.googlegroups.com> References: <1104495025.682424.72160@c13g2000cwb.googlegroups.com> Message-ID: <1104559663.334186.285970@z14g2000cwz.googlegroups.com> PiErre, I have used ftplib but never for such a huge file (assuming your problem is related to the size of the file). Have you tried downloading the file using another ftp client? Does that download succeed? The reason I ask is because I have attempted downloads from servers that terminate the connection after a certain connection time, in the middle of a download! That is the best I can help you out with the information. Have a happy New Year. Thanks, --Kartic From reinhold-birkenfeld-nospam at wolke7.net Mon Jan 3 03:07:02 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 03 Jan 2005 09:07:02 +0100 Subject: ? about file() and open() In-Reply-To: <1104706607.022890.314500@c13g2000cwb.googlegroups.com> References: <1104706607.022890.314500@c13g2000cwb.googlegroups.com> Message-ID: <33scp6F43hahrU1@individual.net> Sean wrote: > Was wondering if there was any difference between these two functions. > I have read some text that said file() wasn't introduced until 2.2 and > that it was synonymous with open(). Does this mean that I should be > using file() where I used open() before? FYI, I submitted a patch to correct the docs: http://www.python.org/sf/1094011 Reinhold From wittempj at hotmail.com Mon Jan 17 11:46:40 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 08:46:40 -0800 Subject: pychecker - sets.Set need to be overridden In-Reply-To: References: <1105978024.706237.304360@c13g2000cwb.googlegroups.com> Message-ID: <1105980400.516211.53910@z14g2000cwz.googlegroups.com> I don't know pychecker, maybe there's something wrong with it as your code seems valid to me. From sjmachin at lexicon.net Wed Jan 26 19:09:13 2005 From: sjmachin at lexicon.net (John Machin) Date: 26 Jan 2005 16:09:13 -0800 Subject: Responding to trollish postings. In-Reply-To: References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <41F7F520.8040706@po-box.mcgill.ca> Message-ID: <1106784553.583222.218950@f14g2000cwb.googlegroups.com> Terry Reedy wrote: > > No offense taken. My personal strategy is to read only as much of trollish > threads as I find interesting or somehow instructive, almost never respond, > and then ignore the rest. I also mostly ignore discussions about such > threads. > Indeed. Let's just nominate XL to the "Full Canvas Jacket" website (http://www.ratbags.com/ranters/) and move on. From may_I_see_your_passport_please at nospamyahoo.com Fri Jan 7 15:20:31 2005 From: may_I_see_your_passport_please at nospamyahoo.com (Dwarf Electrician) Date: Fri, 07 Jan 2005 14:20:31 -0600 Subject: Recent infoworld column Message-ID: <41DEEF0F.5000300@nospamyahoo.com> from a long time listener... http://www.infoworld.com/article/04/12/30/01OPstrategic_1.html From rittersporn at gmail.com Fri Jan 7 06:09:43 2005 From: rittersporn at gmail.com (Rittersporn) Date: 7 Jan 2005 03:09:43 -0800 Subject: _Re Pre/Postconditions with decorators Message-ID: # Google-News won't let be post a follow-up right now! # Google-Beta-News destroys the formatting :-( # So I'll start a new thread. Hi Stephen I have not read anything about the "framehack lambda replacement" yet, but I do compile the pre- and postconditions. Syntax erros e.g. will be raised if the module is compiled. Although I must admit that your code snippets look more like compiled code ;-) Hi Robert thanks for the link to the Ian Bicking blog. Hi George, it would be nice to see how you have tackled the task. Maybe we will have a checker module in Python one day... ;-) Well, I have attached my latest attempt to model pre/postconditions (without "framehack lambda replacement") which does wrap the original function with a class which delegates attribute access. Now I can split my "condition" into pre- and postcondition and the "tracer" prints the original function name. I have also fixed a bug with keyword arguments. Major difference compared to other examples is probably only that I can refer to function arguments by name: class Delegate(object): def __init__(self,function): self.function=function def __getattr__(self,key): return getattr(self.function,key) def condition(pretext,posttext=""): precode=compile(pretext or "True","","eval") postcode=compile(posttext or "True","","eval") # function -> decorated(function) def decorate_condition(function): argcount=function.func_code.co_argcount var=function.func_code.co_varnames[0:argcount] class EvalCond(Delegate): def __call__(self,*args,**kargs): # FIXME: check if "var" always contains ordered list of arguments # map arguments and args_seq=[(argname,args[pos]) for pos,argname in \ enumerate(var) if (argname not in kargs)] # key-arguments to value kargs_seq=[(k,v) for k,v in kargs.iteritems()] environment=args_seq+kargs_seq # precondition assert eval(precode,{},dict(environment)),pretext tmp=function(*args,**kargs) environment2=environment+[('result',tmp)] # postcondition assert eval(postcode,{},dict(environment2)),posttext return tmp return EvalCond(function) return decorate_condition def trace(function): class Trace(Delegate): def __call__(self,*args,**kargs): print "enter function %s with " % \ self.function.func_name,args,kargs result=self.function(*args,**kargs) print "leave function %s with " % \ self.function.func_name,args,kargs return result return Trace(function) def precondition(prgtext): return condition(prgtext) def postcondition(prgtext): return condition("",prgtext) @precondition("number>0 and number<2") @postcondition("result>=0") def sqrt(number): import math return math.sqrt(number) @trace @precondition("len(seq)>0 is not None and str(more)") @postcondition("sum(seq)==result") def my_sum(seq,more): tmp=0 for element in seq: tmp+=element return tmp print sqrt(1.2) print my_sum([1,2,3],more="more") From __peter__ at web.de Thu Jan 27 03:10:08 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Jan 2005 09:10:08 +0100 Subject: building Python: up arrow broken on SuSE Linux 8.2 References: <41f6c3f7$1@nntp.zianet.com> <41f85dd8@nntp.zianet.com> Message-ID: Erik Johnson wrote: > the Apple Python distribution the OP was asking about.??I?now?notice?this > in the output of configure: > > checking for rl_pre_input_hook in -lreadline... no > checking for rl_completion_matches in -lreadline... no > > > My?system?has?/lib/libreadline.so.4.3.???I?guess?it?does?not?define > these newer functions and so that is why the readline module was not > configured in Setup to start with? That is the presumption I am working > on. Have you ensured (with yast) that readline-devel is actually installed? Peter From tzot at sil-tec.gr Mon Jan 3 16:46:05 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 03 Jan 2005 23:46:05 +0200 Subject: input record sepArator (equivalent of "$|" of perl) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> <1103657476.495700.191020@f14g2000cwb.googlegroups.com> <1103671235.093738.198680@z14g2000cwz.googlegroups.com> Message-ID: On 21 Dec 2004 15:20:35 -0800, rumours say that "John Machin" might have written: >Subtle distinction: A metER is a measuring device. A MetRE is a unit of >distance. In this case, English (compared to American English) is closer to the original "metron" [1]. Now, if only you people wrote the plural of "parenthesis" as "parentheseis" and not "parentheses", that would ease a lot my Greek English... :) [1] through the French "m?tre" of course; great job, those revolutionaries did with the metric system. As Asimov put it, "how many inches to the mile?" -- 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 rogerb at rogerbinns.com Sun Jan 16 01:51:00 2005 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 15 Jan 2005 22:51:00 -0800 Subject: there's a socket.sendall(), so why no socket.recvall()? References: <41e03ccc$0$6208$e4fe514c@news.xs4all.nl> <41e9e854$0$6212$e4fe514c@news.xs4all.nl> Message-ID: >>>> there's a socket.sendall(), so why no socket.recvall()? BTW socket.sendall() doesn't actually work for large amounts of data on Windows 2000 and probably other versions of Windows as well. Eg if you supply a 1MB buffer then you get an exception based on some internal Windows error code. I haven't experimented on Unix yet to see if it has the same issue. The workaround is to write a wrapper that really does send everything. Roger From roland.heiber at web.de Thu Jan 13 07:41:12 2005 From: roland.heiber at web.de (Roland Heiber) Date: Thu, 13 Jan 2005 13:41:12 +0100 Subject: Creating text on images In-Reply-To: <1105591796.422252.190990@f14g2000cwb.googlegroups.com> References: <1105591796.422252.190990@f14g2000cwb.googlegroups.com> Message-ID: morphex wrote: > Hi all, > > I'm trying to create a script that will superimpose text on an image. > I didn't find any great examples out there on how this can be done (I > presume using PIL is necessary), do you know of any examples? > Thanks, > > Morten > Hi, something like this? ### from PIL import Image, ImageFont, ImageDraw import sys im = Image.open(YOUR_IMAGE_HERE) idraw = ImageDraw.Draw(im) idraw.text((1,1),"Hello", fill=128) im.save(YOUR_NEW_IMAGE_HERE, IMAGE_TYPE) ### HtH, Roland From fuzzyman at gmail.com Wed Jan 5 07:49:05 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2005 04:49:05 -0800 Subject: How do I make Windows Application with Python ? In-Reply-To: References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> Message-ID: <1104929345.364701.19150@z14g2000cwz.googlegroups.com> Couple of corrections - neither pypy nor starkiller are compilers. Starkiller isn't available yet and *may* be helpful in building compilers. Pyrex is an alternative language - a python/C hybrid that can be compiled. If you want to release an application then innosetup, starkit, and upx might help - but they're not python related. You will need something like py2exe, cx_freeze, or mcmillan installer. (Which are specific to python - py2exe seems to be the more mature tool). Alternatively you could consider 'Movable Python' - a frozen distribution of python that doesn't need isntalling. See http://sourceforge.net/projects/movpy Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From apardon at forel.vub.ac.be Fri Jan 14 05:46:07 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Jan 2005 10:46:07 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-01-14, Nick Coghlan schreef : > Antoon Pardon wrote: >> No I am applying set logic. Any string that is in the set of >> valid expressions is also in the set of valid statements. > > According to Python's grammar, this is not the case. It requires a NEWLINE or > ";" token on the end to turn the expression into a statement. Actually appending > either of those tokens means the string is no longer an expression. Well you are correct, but by the same logic an expression_stmt isn't a statement either. In point of fact none of the _stmt is a statement including an assignment. But changing "statements" to "simple statements" seems to make the assertion correct. -- Antoon Pardon From tchur at optushome.com.au Mon Jan 3 17:44:11 2005 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 04 Jan 2005 09:44:11 +1100 Subject: How can engineers not understand source-code control? In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> <41d8417e$0$14596$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: <41D9CABB.6050501@optushome.com.au> Cameron Laird wrote: > I've seen the infatuation for Excel (and so on) for years, but > never found it at all tempting myself. I mostly just ignore the > issue--no, actually, I guess I give them Excel, but show at the > same time that they really want the alternative views that I > also provide. See http://www.burns-stat.com/pages/Tutor/spreadsheet_addiction.html for a thoughtful essay by a statistician on this affliction. I think that Python would be an excellent addition to his Treatment Centre pharmacopoeia. Tim C From ptmcg at austin.rr._bogus_.com Sun Jan 9 03:18:31 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 09 Jan 2005 08:18:31 GMT Subject: pyparsing: how to negate a grammar References: <1105229039.136595.180640@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1105229039.136595.180640 at c13g2000cwb.googlegroups.com... > Hi, > > I want to define a rule for a line that does NOT start with a given > Literal. How do I do that? I try the following and my program just hang > there: > > BodyLine = ~Literal("HTTP/1.1") + restOfLine > > Thanks, > Khoa > Khoa - pyparsing can be run in several modes, one of which tokenizes and extracts data according to a given grammar, one of which scans for pattern matches, and one which translates matched patterns into other patterns. Its not clear from your e-mail what you are trying to do. There is nothing in your statement that would cause Python to "just hang there", what else is your program doing? -- Paul From ed at leafe.com Fri Jan 21 12:31:29 2005 From: ed at leafe.com (Ed Leafe) Date: Fri, 21 Jan 2005 12:31:29 -0500 Subject: wx.BoxSizer problem In-Reply-To: <41F11AC1.6040108@geochemsource.com> References: <41F11AC1.6040108@geochemsource.com> Message-ID: <48F31575-6BD2-11D9-9482-003065B11E84@leafe.com> On Jan 21, 2005, at 10:07 AM, Laszlo Zsolt Nagy wrote: > My problem is that only one of the buttons is visible and that one is > not expanded. (System: Windows, Python 2.3.4, wxPython 2.5.3) Works as expected on Mac OS X 10.3.7, python 2.3.4, wxPython 2.5.2.8. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From philippecmartin at sbcglobal.net Sat Jan 8 04:18:04 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Sat, 08 Jan 2005 10:18:04 +0100 Subject: "A Fundamental Turn Toward Concurrency in Software" Message-ID: <1105175884.6873.14.camel@localhost> I remember a _few_ year ago when all specialists (Intel's) included agreed that the 100MHZ barrier would never be passed - so, at least, we did get free lunch for a couple of years :-) I also must add that in my 17 years of realtime/embedded programming, the problem usually was not the CPU speed - since you know _prior_ to the design of your software whether your CPU will change context on time when the hardware IRQ comes in - but rather the fact that all the software/peripherals had to share the same bus ==> that usually was where the bottleneck was. I guess my point is to not focus the performance of a system solely on its CPU's. Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From jacobsmail at postmark.net Mon Jan 24 18:56:54 2005 From: jacobsmail at postmark.net (Jacob H) Date: 24 Jan 2005 15:56:54 -0800 Subject: Help with saving and restoring program state Message-ID: <85b54e91.0501241556.d281f90@posting.google.com> Hello list... I'm developing an adventure game in Python (which of course is lots of fun). One of the features is the ability to save games and restore the saves later. I'm using the pickle module to implement this. Capturing current program state and neatly replacing it later is proving to be trickier than I first imagined, so I'm here to ask for a little direction from wiser minds than mine! When my program initializes, each game object is stored in two places -- the defining module, and in a list in another module. The following example is not from my actual code, but what happens is the same. (code contained in "globalstate" module) all_fruit = [] (code contained in "world" module) class Apple(object): # the class hierarchy goes back to object, anyway def __init__(self): self.foo = 23 self.bar = "something" globalstate.all_fruit.append(self) apple = Apple() I enjoy the convenience of being able to refer to the same apple instance through world.apple or globalstate.all_fruit, the latter coming into play when I write for loops and so on. When I update the instance attributes in one place, the changes are reflected in the other place. But now comes the save and restore game functions, which again are simplified from my real code: (code contained in "saveload" module) import pickle import world def savegame(path_to_name): world_data = {} for attr, value in world.__dict__.items(): # actual code is selective about which attributes # from world it takes -- I'm just keeping this # example simple world_data[attr] = value fp = open(path_to_name, "w") pickle.dump(world_data, fp) fp.close() def loadgame(path_to_name): fp = open(path_to_name, "r") world_data = pickle.load(fp) for attr, value in world_data.items(): setattr(world, attr, value) fp.close() The problem is that the game objects only get overwritten in the world module. The instances in the globalstate.all_fruit list remain unchanged, which is not the behaviour I want. I started to write code to get around this. I figured that with each loadgame call, I could reset all the lists in globalstate to empty, then reappend each game object to the appropriate list. But this possibility got complicated fast, because all game objects belong to more than one list. My apple instance alone would belong to globalstate.all_things, globalstate.all_fruit, globalstate.all_items, and perhaps others. Some of the game objects contained in these lists don't need to be a part of capturing program state in the first place! But I'm stuck, because unpickling (so far as I understand it) creates a brand new instance that doesn't know it used to have references to itself in the globalstate lists. Any advice out there? I'm looking for a clean, elegant way to overwrite the same class instance in two arbitrary places at once. Perhaps the example code I've provided isn't even the best way of saving and restoring program state. Perhaps I can easily update my globalstate lists and I'm just overlooking the simple way. Or perhaps the solution lies in abandoning the concepts of referencing my game objects through module attributes and lists. I'm open to any suggestions. Thanks in advance for any help! Jacob From news at wogan.id.au.invalid Tue Jan 25 01:46:34 2005 From: news at wogan.id.au.invalid (Greg Wogan-Browne) Date: Tue, 25 Jan 2005 14:46:34 +0800 Subject: Clarification on XML parsing & namespaces (xml.dom.minidom) Message-ID: <41f5eb4b$0$10526$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Hi all, I am having some trouble figuring out what is going on here - is this a bug, or correct behaviour? Basically, when I create an XML document with a namespace using xml.dom.minidom.parse() or parseString(), the namespace exists as an xmlns attribute in the DOM (fair enough, as it's in the original source document). However, if I use the DOM implementation to create an identical document with a namespace, the xmlns attribute is not present. This mainly affects me when I go to print out the document again using Document.toxml(), as the xmlns attribute is not printed for documents I create dynamically, and therefore XSLT does not kick in (I'm using an external processor). Any thoughts on this would be appreciated. Should I file a bug on pyxml? Greg 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. >>> import xml.dom.minidom >>> raw = '' >>> doc = xml.dom.minidom.parseString(raw) >>> print doc.documentElement.namespaceURI http://example.com/namespace >>> print doc.documentElement.getAttribute('xmlns') http://example.com/namespace >>> impl = xml.dom.minidom.getDOMImplementation() >>> doc2 = impl.createDocument('http://example.com/namespace','test',None) >>> print doc2.documentElement.namespaceURI http://example.com/namespace >>> print doc2.documentElement.getAttribute('xmlns') >>> From steven.bethard at gmail.com Tue Jan 18 19:38:20 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 18 Jan 2005 17:38:20 -0700 Subject: generator expressions: performance anomaly? In-Reply-To: <41eda453.1215517842@news.oz.net> References: <377Hd.77904$Jk5.30235@lakeread01> <41ED1C0F.4030800@holdenweb.com> <41eda453.1215517842@news.oz.net> Message-ID: Bengt Richter wrote: > Which make me wonder what plans there are for providing a better > mechanism than default arguments as a way of initializing local function > variables. Nested def's to create a closure with initialized values is > pretty crufty for that, IMO. What about using a class? Associating functions with data is pretty much what they're for... > Maybe extending the default argument space > with whatever comes after e.g. a triple star delimiter in the argument list, > but which wouldn't be counted as part of the normal arguments? E.g., > > def foo(x, y=123, *args, **kw, *** i=1, deftime=time.ctime()): > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime If what you want is to have i=1 and deftime=time.ctime() available within foo, you could do something like (untested): class foo(object): def __init__(self): self.i = 1 self.deftime = time.ctime() def __call__(self, x, y=123, *args, **kwds): return x*y, (kw.get('which_time') == 'now' and time.ctime() or self.deftime) foo = foo() Or if you don't like 'foo = foo()', you could probably abuse the __new__ method (also untested): class foo(object): i = 1 deftime = time.ctime() def __new__(cls, x, y=123, *args, **kwds): return x*y, (kw.get('which_time') == 'now' and time.ctime() or self.deftime) I guess my point is that if you want attribute associated with the function, it's often easy enough to write a class instead... Steve From tjreedy at udel.edu Sun Jan 2 17:15:10 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Jan 2005 17:15:10 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com><1104620491.542938.92100@z14g2000cwz.googlegroups.com><7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1><7x8y7cjo57.fsf@ruckus.brouhaha.com> <87zmzsax12.fsf@hector.domek><87pt0na5zf.fsf@hector.domek> <87llbba55t.fsf@hector.domek> Message-ID: "Peter Dembinski" wrote in message news:87llbba55t.fsf at hector.domek... > Besides, shouldn't str be a reserved word or something? It is a name in the builtins module which is automatically searched after globals. Many experienced Pythoneers strongly advise against rebinding builtin names *unless* one is intentionally wrapping or overriding the builtin object. The latter are sometimes valid expert uses of masking builtins. Newbies are regularly warned on this list against making a habit of casual use of list, dict, int, str, etc. None has been reserved because there is no known good use for overriding it. True and False will be reserved someday. There have been proposals to turn on reserved status for all builtins on a per-module status. Terry J. Reedy From __peter__ at web.de Mon Jan 17 16:24:58 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Jan 2005 22:24:58 +0100 Subject: Assigning to self References: <10uo6hbn040qt24@news.supernews.com> Message-ID: Frans Englich wrote: > On Monday 17 January 2005 20:03, John Roth wrote: >> "Frans Englich" wrote in message > > > >> In other words, you're trying to create a singleton. In general, >> singletons are frowned on these days for a number of reasons, >> not least because of the difficulty of testing them. > > Then I have some vague, general questions which perhaps someone can reason > from: what is then the preferred methods for solving problems which > requires Singletons? Is it only frowned upon in Python code? Sorry, no answer here, but do you really want a singleton? Singleton: "Ensure a class only has one instance, and provide a global point of access to it" whereas Flyweight: "Use sharing to support large numbers of fine-grained objects efficiently" as per "Design Patterns" by Gamma et al. Peter From claird at lairds.us Thu Jan 6 09:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 06 Jan 2005 14:08:04 GMT Subject: navigating/changing directories References: Message-ID: In article , Nick Coghlan wrote: >The script is executed in a process separate from your command shell, and hence >has no effect on your shell's current directory. > >There are some things that batch files and shell scripts are still good for - >manipulating the shell :) . . . For more on this subject, see . From tonino.greco at gmail.com Tue Jan 4 09:45:06 2005 From: tonino.greco at gmail.com (Tonino) Date: 4 Jan 2005 06:45:06 -0800 Subject: python intergration bus ? Message-ID: <1104849906.019872.153800@z14g2000cwz.googlegroups.com> Hi, Just an interested question - I friend is testing a few JAVA intergration bus's that will be used to intergrate his companies services - I was wondering if there was a python intergration bus ? other than maybe Pyro ? Thanks Tonino From peter at somewhere.com Fri Jan 14 07:11:41 2005 From: peter at somewhere.com (Peter Maas) Date: Fri, 14 Jan 2005 13:11:41 +0100 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: Craig Ringer schrieb: > And then we have iteration .... > > (generator expressions, list comprehensions, for loops, ...?) over > (sequences, iterators, generators) Just sequences and iterators. Generators are functions which return iterators. Sequences and iterators provide two ways to build containers. My use cases: finite, can be defined by enumeration: use sequence infinite, must be defined algorithmically: use iterator generator: neat way to produce an iterator, can also be viewed as a persistent function call (better than static local variables). Once defined, sequences and iterators have nearly the same interface. To have list comprehensions but no equivalent for iterators would be strange. > I happen to be extremely fond of the flexibility this provides, but one > obvious way to do it there is not. Development of the language, backward compatibility and obviousness are diverging goals. You can't satisfy them all at the same time. And goals provide a direction but are rarely reached. :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From daniel at bowettsolutions.com Wed Jan 5 15:18:42 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Wed, 05 Jan 2005 20:18:42 +0000 Subject: Python evolution: Unease In-Reply-To: References: Message-ID: <41DC4BA2.3090107@bowettsolutions.com> Batista, Facundo wrote: > [Daniel Bowett] > > #- Contribute to where on Sourceforge??? Which domentation are > #- we talking > #- about in general? > > Suppose you're reading Python documentation. Don't know, for example, > os.remove(). There you find that a particular parragraph is difficult > to understand. You say "Hey, this could be better written", so you > write i a more pedagogic way. > > After that you go to SF, Python project > (http://sourceforge.net/projects/python), and go to Bugs. There, if > you are logged in SF, you will see a "Submit new" link. You click on > it and you'll see a form to fill. > > Select some fields (specially bug group in "Documentation") and in > "Detailed Description:" you put something like "This particular > sentence was difficult to read. Attaching a new way to write it". Of > course, then attach the file of your text (if it's short enough you > can put it directly in that field). > > Of course, if you write any NEW documentation about something that is > not documented at all, or find some more serious issues with the docs > (for example, bad argument count in a function) you can follow the > same steps. > > . 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.* > Thanks, typically how long does it take for any documentation to be considered and implemented? From jerf at jerf.org Tue Jan 25 20:26:33 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 25 Jan 2005 20:26:33 -0500 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> Message-ID: On Tue, 25 Jan 2005 15:01:23 -0800, Davor wrote: > Thanks, > > I do not hate OO - I just do not need it for the project size I'm > dealing with - and the project will eventually become open-source and > have additional developers - so I would prefer that we all stick to > "simple procedural" stuff rather than having to deal with a developer > that will be convincing me that his 50 layers inheritance hierarchy is > good since it exists in some weird pattern that he saw somewhere on > some Java design patterns discussion board :-) The difference between Python OO and Java is that Python's *actually solves problems* instead of creating them. Given your experience and goals, I'd recommend going ahead with your plan, but the time will come when the Right Solution is creating a class, and I strongly recommend that you not avoid it because of the bad taste Java has legitimately left in your mouth. Odds are, that time will come sooner rather than later, too. I'd also recommend spending a bit more time with Python before trying to lead a project in it. That's general advice not Python-specific, and I understand that it is also sometimes impractical. However, you will pay for it one way or another. If nothing else, people who have learned Python and are capable of contributing valuable code are going to be very turned off when they submit perfectly reasonable classes to solve problems and get shot down for being OO. (For context on my point of view, I offer up http://www.jerf.org/writings/bowersLaw.html ; trying to create a completely class-free large project in Python will be possible, but it is probably inadvisable, as you are throwing away useful tools that you will probably end up replicating anyhow. What Java teaches about OO is actively harmful in learning Python and must be unlearned. Java is the new Basic.) From steve at holdenweb.com Thu Jan 13 09:29:49 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 13 Jan 2005 09:29:49 -0500 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: <41E685DD.30203@holdenweb.com> Fredrik Lundh wrote: > Antoon Pardon wrote: > > >>Well, it seems that Guido is wrong then. The documentation clearly >>states that an expression is a statement. > > > no, it says that an expression statement is a statement. if you don't > understand the difference, please *plonk* yourself. > OK then, "The documentation clearly states that not all statements can be expressions". Specifically Guido has justified the fact that an assignment does not return any value, and therefore cannot be used as a component of an expression. Mea culpa, but I'm not going to *plonk* myself - then *nobody* would be listening to me :-) 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 flamesrock at gmail.com Sat Jan 8 17:47:34 2005 From: flamesrock at gmail.com (flamesrock) Date: 8 Jan 2005 14:47:34 -0800 Subject: EOF for binary? In-Reply-To: <5kj0u0dodrb324oed4nl9v281b0n43s2i6@4ax.com> References: <1105147072.909665.242360@z14g2000cwz.googlegroups.com> <5kj0u0dodrb324oed4nl9v281b0n43s2i6@4ax.com> Message-ID: <1105224454.358015.216000@c13g2000cwb.googlegroups.com> ahh..that does make sense. But maybe getsize() should have a way of inferring what file is specified. I might actually submit a request.. From apardon at forel.vub.ac.be Fri Jan 14 11:51:32 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Jan 2005 16:51:32 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <1CSFd.30772$Qv5.2842746@phobos.telenet-ops.be> Message-ID: Op 2005-01-14, Roel Schroeven schreef : > Antoon Pardon wrote: >> IMO we have a: dogs are mamals kind of relationship in Python. > > I see what you mean, but I don't think it's true. > >> Every expression can be used where a statement is expected. >> (And this can be worded as: every expression is a statement.) > > Not really. An expression statement is a statement that looks like an > expression, but actually it's more than that: not only does it calculate > the value of the expression, it also prints the value. 1) Only in an interactive environment. 2) That the semantics differ according to where the expression is used doesn't make a difference. That an expression decides which branch of an if statement is executed or what object is pass as an argument in a call are also semantic difference, yet we still have an expression in both cases. > Note that it would be perfectly possible to modify the syntax into > > expression_stmt ::= "exprstmt" expression_list > > so that you would have to write > > exprstmt 6*9 > > instead of just > > 6*9 > > That makes it clearer to see the distinction: 6*9 is an expression, > > exprstmt 6*9 > > is a statement. An expression statement, more precisely. If you change the syntax, of course you will change the strings that will be accepted. I could change the syntax to: if_stmt ::= "if" "ifexpr" expression ... Have I now proved that expressions after an if are not normal expressions? > >> Not every statement can be used where an expression is expected. > > AFAIK *no* statement can be used where an expression is expected. But that was not the implication of what Guido supposedly had said. So that this is not the case doesn't counter what I said. -- Antoon Pardon From skip at pobox.com Thu Jan 13 11:10:38 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 13 Jan 2005 10:10:38 -0600 Subject: from __future__ import decorators In-Reply-To: References: Message-ID: <16870.40318.287644.824824@montanaro.dyndns.org> Jacek> Crazy idea ... would it be possible to shadow 2.3's parser with Jacek> one stolen from 2.4 ? If you're willing to go to that much trouble, why not just upgrade to 2.4? Skip From luke at tatooine.planet Tue Jan 11 14:24:06 2005 From: luke at tatooine.planet (Luke Skywalker) Date: Tue, 11 Jan 2005 20:24:06 +0100 Subject: Windows GUIs from Python References: Message-ID: On Tue, 11 Jan 2005 12:55:42 -0600, Doug Holton wrote: >You might also be interested in PyGUI although it doesn't have a native >Windows implementation yet: >http://nz.cosc.canterbury.ac.nz/~greg/python_gui/ Generally speaking, appart from MFC-style programming with Python32, what are the non-alpha alternatives to write purely Windows apps in Python today, ie. without the weight of extra bagage like wxWidgets? I'm not looking at fancy options, since the apps I write would be fine with just the core Windows widgets along with a few add-ons like a grid and the extended Win95 widgets. Thx Luke. From http Fri Jan 21 01:18:36 2005 From: http (Paul Rubin) Date: 20 Jan 2005 22:18:36 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> Message-ID: <7x651rwbib.fsf@ruckus.brouhaha.com> Steve Holden writes: > But how, in Lisp, would you transliterate the Python list [1, 2, 3, 4]? With a vector. > Clearly the Python list *is* different, and the tradeoff was to > obtain speed of random access, presumably (I wasn't taking an interest > in Python in its early days) anticipating that non-recursive > algorithms would be the norm. Python lists and Lisp vectors are generally used in about the same way. Sometimes in Lisp people use lists of conses in ways where Python would use its vector-like lists. You can still use recursive algorithms on vectors though you would normally pass extra index info to avoid copying the vectors all the time. > > beginning what the final destination is going to be. So once we can > > see where it's going, why not proceed to the finish line immediately > > instead of bothering with the intermediate steps? > > Perhaps because we don't all have your psychic powers? You snipped out the examples I gave, like [x*x for x in range(5)] leaving unnecessary residue in the name space. Was it not obvious from the beginning that that was a kludge? If it was obviously a kludge, was it not obvious that there would be reason to want to fix it someday? I'm saying that if some new feature is going to need a fix later, it's better to fix it before releasing it in the first place. From michele.simionato at gmail.com Tue Jan 4 08:43:32 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 4 Jan 2005 05:43:32 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> Message-ID: <1104846212.355098.186400@c13g2000cwb.googlegroups.com> Holger: > FWIW, i added the recipe back to the online cookbook. It's not perfectly > formatted but still useful, i hope. > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361742 Uhm... on my system I get: >>> german_ae = unicode('\xc3\xa4', 'utf8') >>> print german_ae # dunno if it will appear right on Google groups ? >>> german_ae.decode('latin1') Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 0: ordinal not in range(128) ?? What's wrong? Michele Simionato From erikbethke at gmail.com Wed Jan 19 19:35:23 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 19 Jan 2005 16:35:23 -0800 Subject: ElementTree cannot parse UTF-8 Unicode? References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> Message-ID: <1106181323.553028.290370@z14g2000cwz.googlegroups.com> Hello Fredrik, 1) The exact error is in line 1160 of self._parser.Parse(data, 0 ): xml.parsers.expat.ExpatError: not well-formed (invalid token): line 3, column 16 2) You are right in that the print of the file read works just fine. 3) You are also right in that the digitally encoded unicode also works fine. However, this solution has two new problems: 1) The xml file is now not human readable 2) After ElementTree gets done parsing it, I am feeding the text to a wx.TextCtrl via .SetValue() but that is now giving me an error message of being unable to convert that style of string So it seems to me, that ElementTree is just not expecting to run into the Korean characters for it is at column 16 that these begin. Am I formatting the XML properly? Thank you, -Erik From bob_smith_17280 at hotmail.com Sat Jan 8 12:35:03 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sat, 08 Jan 2005 12:35:03 -0500 Subject: windows mem leak Message-ID: Does the Win32 port of Python have a memory leak? I have some code that runs flawlessly on Linux, but bombs after a few hours on Windows. It's threaded and uses a lot of memory. Thanks! From http Wed Jan 5 13:26:38 2005 From: http (Paul Rubin) Date: 05 Jan 2005 10:26:38 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> Message-ID: <7x3bxfenq9.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > Okay, then start doing the work necessary to incorporate that stuff into the > core. Get Fredrik to say "okay" to including his Tkinter docs, then do what > it takes to incorporate it. The fact that Fredrik can check those docs in > himself but hasn't after several years suggests that he prefers the status > quo for one or more reasons. I thought that we had been through this already, and permission from Frederik was not forthcoming. Either he has his own plans for those docs, or he has some obligation to someone else to not release them. The Tkinter reference at http://infohost.nmt.edu/tcc/help/pubs/lang.html is actually the best doc I've seen on tkinter so far, but it's only available in ps/pdf format and again, would need permission for inclusion in Python. > There is a reference manual section for SocketServer, btw: > > http://www.python.org/doc/current/lib/module-SocketServer.html > > If that needs examples or corrections or is incomplete, feel free to submit > a patch to either SourceForge or by email to docs at python.org. It's been a while since I really had to wrestle with SocketServer, but that its docs were quite inadequate and I had to study the source code for quite a while to grok how to use it. > Look, I don't have much free time, and what free time I do have I mostly > spend moonlighting on other software (much to my wife's chagrin). I imagine > most of the other people who contribute to the Python distribution are > similarly time-afflicted. Here are a couple ideas: Thanks, but I'm not in the business of promoting Python. I like to think I contribute in some minor ways by submitting bug reports and occasional small patches. I made a conscious decision to not spend time on big patches since Python is non-GPL, and I'd rather spend my limited volunteer time on GPL projects, working on non-GPL projects only if I'm getting paid for it. I offered to make an exception once to contribute some functionality that I felt was important for Python users, but it was declined. What I see going on in clpy all the time though, is people asking whether Python is good for some type of project, and always getting told "yes" no matter what the project is. If the "yes" means that in addition to doing your own project, you find out in the middle that you also have to add features to Python that other languages already support, that makes your project finish behind schedule and whoever told you Python was good for your project really did you a disservice. I'm reacting to that phenomenon in this thread, along with possible others. > 1. Do you have more money than time? Donate a few bucks to the PSF: Nah, I'd rather donate to the FSF if I have the bucks to spare. If I want to fund the development of proprietary Microsoft products, I'm better off sending the money directly to Bill G. Of course I'm happy if PSF gets corporate donations, but that's different than someone like me operating as a free software activist. > 2. Do you have more time than money? Write a proposal to the PSF to > implement/improve/polish off some aspect of the distribution: Huh? Do you mean like a funding proposal, where PSF would use some of those donations to hire me to develop something? I guess I'd consider that in principle, but I'm probably not PSF's favorite person right now, and unlikely to get hired. And anyway, I have other commitments right now and couldn't take on anything like that. > Where did I say to go write a browser or a native-code Python compiler? If > that's your bag you can try resurrecting something Grail-like (browser) or > contribute time top PyPy or Psyco. When I said "write", I literally meant > write, as in English text. I don't experience much difference between writing text and writing code. If I say the docs are missing something and you tell me to fix them, that's not much different than telling me to go write missing code. Re browsers and compilers: I think a Python browser depends on a good GUI toolkit and right now Python only has Tkinter. (There are toolkits like wxpython but Python doesn't "have" them; they exist separately). I think the PyPy group is doing real well with compilers, or at least knows what its doing. I want to wait til PyPy is actually deployed before I pay too much attention to Python compilation, since I think supporting good compilation should actually drive the Python 3000 language design, and PyPy will make it much easier to experiment with new or changing language features. > Paul> Having to piece together info from a dozen obscure and > Paul> inconsistent PEP's and stuff in the CVS tree and source comments > Paul> is not what most people think of as "documentation". > > I was suggesting that maybe you might like to take the pieces and > make them something coherent. If it was trivial it would have > probably been done by now. I just avoid using those features. If they're not documented they probably don't work that well either. > I rather like reST (much of www.python.org is being reimplemented in reST), I don't know what that is. > Look here: > > http://www.amk.ca/diary/archives/003336.html > > As Andrew indicated, it's a "half-hour hack", but it might give someone > something to think about. That's pretty cute and python.org should link to it. From philippe at philippecmartin.com Mon Jan 31 18:38:17 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 31 Jan 2005 23:38:17 GMT Subject: serializing data structures References: <41FEBD21.5030306@v.loewis.de> Message-ID: Thanks a lot. Regards, Philippe On Tue, 01 Feb 2005 00:20:01 +0100, Martin v. L?wis wrote: > Philippe C. Martin wrote: >> I once wrote something in C to do that, but since python usually has a >> solution for me .... > > If you use arbitrary data structures, you could use pickle or xmlrpclib > to marshal the data. If you know the data is restricted to a few > well-known data types, you could use XDR (Demo/rpc/xdr.py) or CORBA > (e.g. through fnorb.sf.net) to come up with a wire format. > > Otherwise, if you want to define your own proprietary data format, > you can probably use the struct module to generate messages according > to this format. > > However, in any case, you need to define the wire format. Once you made > a choice, Python can help implement it - but Python cannot chose a wire > format for you (although pickle comes really close, as does Dopy - > http://www.mindhog.net/~mmuller/projects/dopy/) > > Regards, > Martin From http Thu Jan 6 21:46:00 2005 From: http (Paul Rubin) Date: 06 Jan 2005 18:46:00 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> Message-ID: <7xsm5et0rb.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > Would it be possible, at least for Windows, to write a Python script > implementing a 'virtual distribution'? IE, download Python, install it, > download next package, install it, etc. -- prefereably table driven? I just don't understand why you'd want to do that, instead of putting all the files in the distro in the first place. From ncoghlan at iinet.net.au Sat Jan 22 01:22:33 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 22 Jan 2005 16:22:33 +1000 Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) In-Reply-To: References: Message-ID: <41F1F129.6000308@iinet.net.au> Steven Bethard wrote: > I wrote: > > If you really want locals that don't contribute to arguments, I'd be > > much happier with something like a decorator, e.g.[1]: > > > > @with_consts(i=1, deftime=time.ctime()) > > def foo(x, y=123, *args, **kw): > > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime > > > > Then you don't have to mix parameter declarations with locals > > definitions. > > > > Steve > > > > [1] I have no idea how implementable such a decorator would be. I'd > > just like to see function constants declared separate from arguments > > since they mean such different things. > > I played around with this, and I think it's basically implementable: Raymond's constant binding decorator is probably a good model for how to do it: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ncoghlan at iinet.net.au Wed Jan 5 08:08:01 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 05 Jan 2005 23:08:01 +1000 Subject: python 3000 and removal of builtin callable In-Reply-To: References: <33v6l6F40l7hqU1@individual.net> Message-ID: <41DBE6B1.8000709@iinet.net.au> Nicolas Fleury wrote: > Mirko Zeibig wrote: > >> This is not an option for e.g. IDEs as some functions might actually >> do something when called ;-) and I like `callable` for introspection. >> >> Other ways would be to check for the `__call__` attribute or use >> several methods of the `inspect`-Module, both of which are not better >> than `callable` IMHO. > > > I totally agree with you. The callable function could be moved to a > module and be built-in, but it cannot really be removed. Calling a > callable and know if an object is a callable without calling it is > definitely not the same thing. For many of the builtins to be "removed" in Py3k, I believe the actual intent is to move them to a module (e.g. sys), with the removal being "remove from the builtins", not "remove from Python". Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jeff at ccvcorp.com Mon Jan 3 14:35:56 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 03 Jan 2005 11:35:56 -0800 Subject: Speed ain't bad In-Reply-To: <41d6a39b$0$33656$edfadb0f@dread16.news.tele.dk> References: <0189t05r3226bkp5e1vtmp0gd6odcsf2qp@4ax.com> <41d6a39b$0$33656$edfadb0f@dread16.news.tele.dk> Message-ID: <10tj7c9m9sclabd@corp.supernews.com> Anders J. Munch wrote: > Another way is the strategy of "it's easier to ask forgiveness than to > ask permission". > If you replace: > if(not os.path.isdir(zfdir)): > os.makedirs(zfdir) > with: > try: > os.makedirs(zfdir) > except EnvironmentError: > pass > > then not only will your script become a micron more robust, but > assuming zfdir typically does not exist, you will have saved the call > to os.path.isdir. ... at the cost of an exception frame setup and an incomplete call to os.makedirs(). It's an open question whether the exception setup and recovery take less time than the call to isdir(), though I'd expect probably not. The exception route definitely makes more sense if the makedirs() call is likely to succeed; if it's likely to fail, then things are murkier. Since isdir() *is* a disk i/o operation, then in this case the exception route is probably preferable anyhow. In either case, one must touch the disk; in the exception case, there will only ever be one disk access (which either succeeds or fails), while in the other case, there may be two disk accesses. However, if it wasn't for the extra disk i/o operation, then the 'if ...' might be slightly faster, even though the exception-based route is more Pythonic. Jeff Shannon Technician/Programmer Credit International From mike at lookdirect.com.au Sun Jan 30 18:12:06 2005 From: mike at lookdirect.com.au (mike) Date: 30 Jan 2005 15:12:06 -0800 Subject: Microsoft Visual C++ and pyton Message-ID: <1107126726.533325.104300@z14g2000cwz.googlegroups.com> Hi, I am new with python. Is it possible to have an MFC application and develop some module using python? what are the steps in doing this? can anybody give me a url or some documentation for this.. thanks.. mike From peter at monicol.co.uk Tue Jan 11 07:19:35 2005 From: peter at monicol.co.uk (Peter Mott) Date: Tue, 11 Jan 2005 12:19:35 -0000 Subject: Uploading files References: Message-ID: <41e3c4d1$0$23052$bed64819@news.gradwell.net> Thanks for this. Peter "Robert Brewer" wrote in message news:mailman.466.1105385969.22381.python-list at python.org... Peter Mott wrote: > If you upload a file using the cgi module is there any > way to discover the file name that the user submitted > as well as the file data? I've googled till I squint > but I can't find anything. Working example (for ASP, which uses BinaryRead to get the request stream): contentLength = int(env['CONTENT_LENGTH']) content, size = request.BinaryRead(contentLength) content = StringIO.StringIO(content) form = cgi.FieldStorage(content, None, "", env, True) content.close() for key in form: value = form[key] try: filename = value.filename except AttributeError: filename = None if filename: # Store filename, filedata as a tuple. self.requestParams[key] = (filename, value.value) else: for subValue in form.getlist(key): self.requestParams[key] = subValue Robert Brewer MIS Amor Ministries fumanchu at amor.org From esj at harvee.org Tue Jan 18 20:24:19 2005 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 18 Jan 2005 20:24:19 -0500 Subject: simultaneous multiple requests to very simple database In-Reply-To: References: Message-ID: <41EDB6C3.6090607@harvee.org> Thomas Bartkus wrote: > When you write that "super dictionary", be sure to post code! > I could use one of those myself. hmmm it looks like you have just flung down the gauntlet of "put up or quityerwhinging". I need to get the crude implementation done first but I think I can do it if I can find a good XMLRPC multithreading framework. ---eric From craig at postnewspapers.com.au Wed Jan 12 11:52:40 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Thu, 13 Jan 2005 00:52:40 +0800 Subject: Python.org, Website of Satan In-Reply-To: <20050112155821.GA12428@mylene.ghaering.de> References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <20050112155821.GA12428@mylene.ghaering.de> Message-ID: <1105548760.26139.0.camel@bucket.localnet> On Wed, 2005-01-12 at 16:58 +0100, Gerhard Haering wrote: > On Wed, Jan 12, 2005 at 10:15:34AM -0500, Jane wrote: > > [...] Some people have too much time on their hands... > > OMG, PyPy is full of evil, too!!!1 > > print sum([ord(x) for x in "PyPy!!!!!!!!"]) > > or, if you haven't upgraded to 2.4, yet: That'll work fine in Python 2.3. I think you meant: print sum(ord(x) for x in "PyPy!!!!!!!!") which is a different matter entirely (well, regarding compatibility anyway). -- Craig Ringer From reinhold-birkenfeld-nospam at wolke7.net Thu Jan 13 13:17:34 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 13 Jan 2005 19:17:34 +0100 Subject: Free python server. In-Reply-To: <1105632112.104412.183870@f14g2000cwb.googlegroups.com> References: <1105631360.938494.286750@c13g2000cwb.googlegroups.com> <1105632112.104412.183870@f14g2000cwb.googlegroups.com> Message-ID: <34ns9uF4bpbumU1@individual.net> Kartic wrote: > And yes, they have python installed... Python 2.1! Reinhold From michael.bierenfeld at web.de Thu Jan 13 11:08:12 2005 From: michael.bierenfeld at web.de (michael) Date: 13 Jan 2005 08:08:12 -0800 Subject: dynamically inserting function into an object Message-ID: Hi, below is a snipplet that could be seen as a part of a spreadsheet with getter and setter properties and a way how to dynamically insert function to be used when setting the value of a "cell" instance import new import inspect class Cell (object): def __init__ (self, initialvalue = 0): self._func = None self.__value = initialvalue def setvalue (self, newvalue): if self._func: self.__value = self._recalculate (newvalue) else: self.__value = newvalue def getvalue (self): return self.__value def _recalculate (self, value): ret_value = self._func (value) return ret_value def delvalue (self): del self.__value value = property(getvalue, setvalue, delvalue, "I'm the 'value' property.") def curry(self, func, *args): self._func = new.function(func.func_code, func.func_globals, argdefs=args) func = property(curry, "I'm the 'func' property.") def func (value, firstcell, secondcell): return value + firstcell.value + secondcell.value cell0 = Cell (10) cell1 = Cell (20) curriedcell = Cell (100) print "uncurried initial %d " % (curriedcell.value) curriedcell.value = 60 print "uncurried set %d " % (curriedcell.value) curriedcell.curry (func, cell0, cell1) curriedcell.value = 62 print "curried set %d " % (curriedcell.value) Is there a better way to do this or am I totally on the wrong way ? Regards Michael From merman at o2online.de Fri Jan 28 18:53:42 2005 From: merman at o2online.de (T. Kaufmann) Date: Sat, 29 Jan 2005 00:53:42 +0100 Subject: Mac OS and MySQLdb In-Reply-To: <1106924449.079269.65810@z14g2000cwz.googlegroups.com> References: <41f95b17$0$3331$9b622d9e@news.freenet.de> <1106924449.079269.65810@z14g2000cwz.googlegroups.com> Message-ID: <41facd6c$0$11653$9b622d9e@news.freenet.de> Andy Dustman wrote: > The source is for all platforms. Use the Source, Luke. If 1.1.9 does > not compile on Mac OS X, file a bug. Thanks a lot;-). From dbickett at gmail.com Sat Jan 22 15:41:10 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sat, 22 Jan 2005 15:41:10 -0500 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> Message-ID: <1d6cdae305012212417f247f48@mail.gmail.com> Doug Holton wrote: > What do you expect? YAML is designed for humans to use, XML is not. > YAML also hasn't had the backing and huge community behind it like XML. > XML sucks for people to have to write in, but is straightforward to > parse. The consequence is hordes of invalid XML files, leading to > necessary hacks like the mark pilgrim's universal rss parser. YAML > flips the problem around, making it harder perhaps to implement a > universal parser, but better for the end-user who has to actually use > it. More people need to work on improving the YAML spec and > implementing better YAML parsers. We've got too many XML parsers as it is. However, one of the main reasons that XML is so successful is because it's roots are shared by (or, perhaps, in) a markup language that a vast majority of the Internet community knows: HTML. In it's most basic form, I don't care what anyone says, XML is VERY straight forward. Throughout the entire concept of XML (again, in its most basic form) the idea of opening and closing tags (with the exception of the standalone tags, however still very simple) is constant, for all different data types. In my (brief) experience with YAML, it seemed like there were several different ways of doing things, and I saw this as one of it's failures (since we're all comparing it to XML). However I maintain, in spite of all of that, that it can easily boil down to the fact that, for someone who knows the most minuscule amount of HTML (a very easy thing to do, not to mention most people have a tiny bit of experience to boot), the transition to XML is painless. YAML, however, is a brand new format with brand new semantics. As for the human read-and-write-ability, I don't know about you, but I have no trouble whatsoever reading and writing XML. But alas, I don't need to. Long live elementtree (once again) :-) Daniel Bickett From aleaxit at yahoo.com Thu Jan 13 13:17:18 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 13 Jan 2005 19:17:18 +0100 Subject: reference or pointer to some object? References: <10ubcp136drsu97@corp.supernews.com> Message-ID: <1gqcd8e.ehwqcw1n0y6wxN%aleaxit@yahoo.com> Jeff Shannon wrote: > Because Python uses a fundamentally different concept for variable > names than C/C++/Java (and most other static languages). In those > languages, variables can be passed by value or by reference; neither > term really applies in Python. (Or, if you prefer, Python always Java's model is quite similar to Python's, except that Java makes some exception for very low-level types such as int or float. But there is no "passing by reference" in Java, anyway: the semantics of assignment and argument passing (same thing) are VERY close in Java and Python. I hope this is enough to show that static or dynamic is quite a different issue -- Java's more or less statically typed, Python dynamically, but their model of variables is VERY similar anyway. Alex From beliavsky at aol.com Sat Jan 29 23:26:09 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 29 Jan 2005 20:26:09 -0800 Subject: Coding style article with interesting section on white space References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> Message-ID: <1107059169.510996.262480@z14g2000cwz.googlegroups.com> Michael Tobis wrote: > (unwisely taking the bait...) > > If you like your language to look like this > http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html > then more power to you. Thanks for pointing out that interesting article on Fortran 90 bugs. How long would a comparable C++ list be? Even Python has gotchas, for example the difference between deep and shallow copies. > I prefer my languages to be portable, terse and expressive. Fortran programmers are generally happy with the portability of the language. A difficulty with Python portability and maintainability is that some needed functionality is not in the core language but in C extensions. For scientific computation, consider the case of Numeric and Numarray. I don't think Numeric binaries are available for Python 2.4, and Numarray is not perfect substitute, being considerably slower for small arrays, having slightly different functionality in some areas, and as recently as Nov 2004 (c.l.py thread "numarray memory leak") leaking memory when multiplying matrices. The recent "Pystone Benchmark" message says that Python is only 75% as fast on Linux as on Windows. Fortran programs do not suffer this performance hit and are in this respect more portable. In theory, as has been mentioned, one could use a faster compiler to compile CPython on Linux, but AFAIK this has not yet been done. > There is no fundamental reason why a language with expressive power > much like Python's cannot have run-time performance comparable to > Fortran's. Unfortunately, Fortran's dominance of the relatively small > scientific computation universe has prevented such a language from > emerging. Nobody is stopping Python developers from working on projects like Psyco. > The solutions which interest me in the short run are 1) > writing a code generation layer from Python to a compiled language > (possibly F77 though I will try to get away with C) and 2) wrapping > legacy Fortran in Python. The latter is quite regularly subverted by > non-standard binary data structures across compilers and a pretty > profound disinterest in interoperability by the people designing the > Fortran standard that makes their interest look more like turf > protection and less like an interest in the progress of science. So uninterested in interoperability is the Fortran standards committee that they added interoperability with C in Fortran 2003 standard. > Python fundamentally respects the programmer. What does that mean? > Fortran started from a point of respecting only the machine, (which is > why Fortrans up to F77, having a well-defined objective, were > reasonable) I have found that Fortran 90/95 is better at the objective of FORmula TRANslation for array expressions (mostly what I need) than previous versions. > but now it is a motley collection of half-baked and > confusing compromises between runtime performance, backward > compatibility, and awkward efforts at keeping up with trends in > computer languages. This is true to some extent of any language "of a certain age", including C++. > For more see http://www.fortranstatement.com And the rebuttal at http://www.fortranstatement.com/Site/responses.html . From bokr at oz.net Wed Jan 5 14:29:38 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 05 Jan 2005 19:29:38 GMT Subject: type declarations, interfaces, etc as program information composition Message-ID: <41dc2b84.70478372@news.oz.net> I just read Guido's http://www.artima.com/weblogs/viewpost.jsp?thread=86641 "Adding Optional Static Typing to Python -- Part II" and I it struck me that if you step back to a more distant perspective, you can see specific source syntax proposals as a special case of composing program information, and I wondered if the coupling inherent in editing a particular source to add information is always best. Certainly it makes for a handy single-file package of info, unlike C source and header files for example. Not to mention make files and the plethora of information they can direct the composition of. But, e.g., what is the best way to tell python that I intend to use its "sum" builtin to add a list of integers, so that it can figure out that it will be safe to generate machine code using 32-bit integers? Should I have to code a new version with static type declarations? What about stuff I've alrady written, that I'm pretty sure would work fine with floating point, but which has no type information? Should I have to edit that code, that may be in CVS, in order to tell python to generate more specialized code? Or would it be useful to have a specialization tool that I can tell what to do with what existing sources. IOW a pythonic make of some sort. What if specialization info for mylib/myutil.py were in currproj/myutil.pyspec and a pymake or pycc tool knew how to do the right thing? A .pyc file would contain the combined information and specialized code, and a smart inspection tool could show the combined source information in context by going to the relevant sources of myutil.py and myutil.pyspec etc. So the argument that all needs to be in the same file for easy reading is not absolute. Of course, it would be good if the combined presentation format were also a legal input format, for those who want a single specialization in a single file. A specialization tool could well raise exceptions saying a particular source module def foo... can't be specialized as you want, because e.g., it returns both strings and ints, and your interface info says foo(int, int) -> int. Anyway, I consider the Lego-like composability of python programming elements to be one of python's greatest attractions. I hope Guido can figure some way to let us snap in type info without filing existing knobs into new shapes. Regards, Bengt Richter From ptmcg at austin.rr._bogus_.com Mon Jan 31 13:40:34 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 31 Jan 2005 18:40:34 GMT Subject: ANNOUNCE: KirbyBase 1.7 References: <7xy8ea1qgt.fsf@ruckus.brouhaha.com> Message-ID: "Jamey Cribbs" wrote in message news:dMdLd.67932$re1.17016 at fe2.columbus.rr.com... > Paul Rubin wrote: > > That's cute, especially the part about using Python expressions > > instead of SQL to express queries. I don't see anything in the info > > page about what happens when you have multiple clients updating the db > > concurrently. Do you make any attempt to handle that? > > Yep. There are two server scripts included with the distribution. One > (kbsimpleserver.py) does serial, blocking requests, so there are no > concurrent-access issues. The second server script > (kbthreadedserver.py) is threaded and non-blocking. I have code in the > script that manages read and write locks for each table. I'm no rocket > scientist, but I have been using kbthreadedserver.py at work for several > months with no issues so far, so I am beginning to trust the code. :) > > Jamey Before you get too confident, you might try your code on a multiprocessor machine, under some heavy stress test (or ask one of your collaborators if you don't have access to such a thing). Threaded code that runs on uniprocessors can do very different/unexpected/unwanted things on multiprocessors. -- Paul From bokr at oz.net Fri Jan 7 17:29:44 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 07 Jan 2005 22:29:44 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> Message-ID: <41df0cae.259192429@news.oz.net> On Fri, 07 Jan 2005 16:34:48 -0000, mike at hobbshouse.org (Michael Hobbs) wrote: >David Brown wrote: >> Hello. I recently came across a free operating system called Unununium (or >> something like that) and it was developed in Python and Assembly. >> >> Now, I have been looking for a way to make an operating system for a long >> long time and the only possibilities I could find were C++ and assembly. > >The problem when using Python instead of C for OS development is that >C was *specifically designed* to create an OS, while Python was designed >for completely different purposes. If you want to write an OS, it would >be wise to use a language that is suited for that purpose. If you >dislike C so much and prefer Python so much more, your first step should >be to design a Python dialect that is more appropriate for writing OS's. > >(I know that you mentioned C++, not C, but I decided to setup C as a >straw-man to make my argument.) I'd say look at Ada for HLL inspiration, if you want to deal with OS level stuff in Python. Regards, Bengt Richter From ialbert at mailblocks.com Thu Jan 20 12:34:33 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 20 Jan 2005 12:34:33 -0500 Subject: What YAML engine do you use? In-Reply-To: <35a6tpF4gmat2U1@individual.net> References: <35a6tpF4gmat2U1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > You will be amazed, and never think of XML again. XML with elementtree is what makes me never have think about XML again. Istvan. From stephen.thorne at gmail.com Wed Jan 19 02:04:45 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Wed, 19 Jan 2005 17:04:45 +1000 Subject: generator expressions: performance anomaly? In-Reply-To: <_NCdnVV_I9UrZHDcRVn-og@comcast.com> References: <377Hd.77904$Jk5.30235@lakeread01> <41ED1C0F.4030800@holdenweb.com> <41eda453.1215517842@news.oz.net> <41edcc68.1225778626@news.oz.net> <_NCdnVV_I9UrZHDcRVn-og@comcast.com> Message-ID: <3e8ca5c8050118230461949030@mail.gmail.com> On Tue, 18 Jan 2005 23:09:57 -0700, Steven Bethard wrote: > @with_consts(i=1, deftime=time.ctime()) > def foo(x, y=123, *args, **kw): > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime > > Then you don't have to mix parameter declarations with locals definitions. > > [1] I have no idea how implementable such a decorator would be. I'd > just like to see function constants declared separate from arguments > since they mean such different things. (untested) def with_constant(**constants_kwargs): def decorator(f) def closure(*arg, **kwargs): kwargs.update(constants_kwargs) return f(*arg, **kwargs) return closure return decorator Regards, Stephen Thorne From jfouhy at paradise.net.nz Tue Jan 4 22:33:34 2005 From: jfouhy at paradise.net.nz (John Fouhy) Date: 4 Jan 2005 19:33:34 -0800 Subject: Tkinter, iconbitmap and Windows XP Message-ID: Hi all, I have been attempting to change the title bar icon of my Tkinter applications in Windows XP. Chasing round in google, I discovered: - This is a common difficulty. - There aren't any good answers. Eventually, I stumbled across a link to this: http://www.tcl.tk/man/tcl8.4/TkCmd/wm.htm#M18 Here is the significant information: "On the Windows operating system, an additional flag is supported: wm iconbitmap window ?-default? ?image?. If the -default flag is given, the icon is applied to all toplevel windows (existing and future) to which no other specific icon has yet been applied. In addition to bitmap image types, a full path specification to any file which contains a valid Windows icon is also accepted (usually .ico or .icr files), or any file for which the shell has assigned an icon. Tcl will first test if the file contains an icon, then if it has an assigned icon, and finally, if that fails, test for a bitmap." The Tkinter source (Python 2.3.4) includes this: def wm_iconbitmap(self, bitmap=None): """Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given.""" return self.tk.call('wm', 'iconbitmap', self._w, bitmap) I modified this, to look like: def wm_iconbitmap(self, bitmap=None, default=None): """Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given.""" if default: return self.tk.call('wm', 'iconbitmap', self._w, '-default', default) else: return self.tk.call('wm', 'iconbitmap', self._w, bitmap) The following code now does exactly what you would like it to: ##### from Tkinter import * tk = Tk() tk.iconbitmap(default='foo.ico') Label(tk, text='This window now has a custom icon.').pack() t = Toplevel(tk) Label(t, text='This one has the same custom icon.').pack() tk.mainloop() ##### I hope this is helpful to people... (now to see if I can figure out how to submit a patch in Sourceforge) -- John. From pedro.werneck at terra.com.br Fri Jan 21 09:31:02 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Fri, 21 Jan 2005 12:31:02 -0200 Subject: TypeError error on tkinter.createfilehandler dummy example In-Reply-To: <41F0CAF8.3080806@corp.ya.com> References: <41F0CAF8.3080806@corp.ya.com> Message-ID: <20050121123102.6e7dd249.pedro.werneck@terra.com.br> Hi, The createfilehandler is not supported on Windows since Tcl/TK 8.0. tkinter.createfilehandler is None, so you get the NoneType is not callable error. I wrote a simple module with a mix-in class to solve this problem. I had a lote of code using it on linux and needed to run it on Windows. I can send it to you in pvt, if you want. Pedro Werneck On Fri, 21 Jan 2005 10:27:20 +0100 David wrote: > Hi, > > I'm getting the following error: > > > Traceback (most recent call last): > File "..\kk.py", line 37, in ? > tkinter.createfilehandler(filex, tkinter.READABLE, _dispatch) > TypeError: 'NoneType' object is not callable > > > when executing this code on my Windows box: > > > from Tkinter import * > > def _dispatch(self, *args): > print "voila" > > filex = open('d:\\zz.txt', 'r') > tkinter.createfilehandler(filex, tkinter.READABLE, _dispatch) > > > Any ideas? What am I missing? I've been searching for something like > this with no luck. I cannot imagine a simpler code for testing > tkinter.createfilehandler functionality but it does not work :( > > > TIA > > -- > David Santiago > > From fredrik at pythonware.com Sat Jan 22 02:37:41 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 08:37:41 +0100 Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: Paul McGuire wrote: > I asked a very similar question a few weeks ago, and from the various > suggestions, I came up with this: > > expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen] I wouldn't trust whoever suggested that. if you want a function, use a function: def expand(seq, default, minlen): return (seq + [default]*minlen)[:minlen] From tadmc at augustmail.com Sun Jan 30 08:09:30 2005 From: tadmc at augustmail.com (Tad McClellan) Date: Sun, 30 Jan 2005 07:09:30 -0600 Subject: [perl-python] sending email References: <1107041765.890014.112530@c13g2000cwb.googlegroups.com> Message-ID: J?rgen Exner wrote: > Xah Lee wrote: > [...] >> Here's how the situation stands as of 2001 March: > ^^^^^^^^^^ > > Well, at least now we know why Mr. Lee is a little bit behind .... Mr. Lee is a *big* behind! -- Tad McClellan SGML consulting tadmc at augustmail.com Perl programming Fort Worth, Texas From cdieterich at geosci.uchicago.edu Wed Jan 26 17:33:48 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Wed, 26 Jan 2005 16:33:48 -0600 Subject: inherit without calling parent class constructor? In-Reply-To: <8IadnVLUPfL7bmrcRVn-tg@comcast.com> Message-ID: <58D77AEA-6FEA-11D9-8B47-000A9582377C@geosci.uchicago.edu> On D? C?adaoin, Ean 26, 2005, at 13:45 America/Chicago, Steven Bethard wrote: > Note that: > @deco > def func(...): > ... > is basically just syntactic sugar for: > def func(...): > ... > func = deco(func) Oh, I learned something new today :-) Nice thing to know, these descriptors. > Note that b.size and d.size are only calculated once each, and if > d.size is never accessed, you'll never incur the costs of calculating > it. That's exactly what I need. It works fine for Python 2.2 and 2.3. So, I'll try to implement that into my package. Thanks a bunch for your help, Christian From bokr at oz.net Tue Jan 18 19:55:24 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 19 Jan 2005 00:55:24 GMT Subject: generator expressions: performance anomaly? References: <354esdF4fouh0U1@individual.net> <354kntF4g4crnU1@individual.net> Message-ID: <41eda8bf.1216649950@news.oz.net> On Tue, 18 Jan 2005 15:29:06 +0100, "Diez B. Roggisch" wrote: >> I don't see how generating byte code for a = 9; when seeing the >> expression a = 3 + 6, would be a problem for non-functional >> languages. > >Most probably. But I don't see much code of that type that it would be worth >optimizing for, either. The cost for re-evaluation such an expression >doesn't really account for any performance problems you hit - in python, of >course. >See this: > >deets at kumquat:/usr/lib/python2.3$ python timeit.py -c "[4*5 for i in >xrange(10000)]" >100 loops, best of 3: 5.5e+03 usec per loop >deets at kumquat:/usr/lib/python2.3$ python timeit.py -c "[20 for i in >xrange(10000)]" >100 loops, best of 3: 4.3e+03 usec per loop > > >Now of course the longer the expressions get, the more time it costs - but >how many long arithmetical expression of constant evaluation value do you >have? > >> >> I agree that things like [time.time() for i in xrange(10)] shouldn't >> be pregenerated and that the problem is more complicated as I thought. >> >> But during compilation the compilor could do an anlysis of the code >> do determine whether there are side effects or not. If the compilor >> then would store a code in the byte code for functions that are >> guaranteed side-effect free and only pregenerated objects generated >> by expressions with no side-effect, some common subexpression >> elimination could be done even in a non-functional language. > >This analysis would only be possible for the most primitive of examples, >the reason beeing that due to the dynamic features syntactically equivalent >expressions can have totally different semantics. So its not really worth >the effort. IOM that doesn't mean there might not be an alternative interesting angle. E.g., what if we had a yield_constant (instant bf here ;-) as well as a yield. IOW an explicit promise that the generator would always yield the same thing for the same input args. This could potentially allow tuple(x for x in foo(1234)) to be pre-calculated, or marked for sticky internal caching or such, if repeat use benefit could not be determined. I guess we can write memoizing decorators now, so how would you e.g., spell memoizing a generator expression? No end to probably impractical ideas ;-) IMO it's more a matter of RO[D]I (return on [development] investment) and restraints on bloat than whether optimizations and other ideas are feasible. I think practicality vs purity drives actual implementation, but purity issues drive a lot of interesting, if not too practical, discussions. Of course, if someone has the energy to become champions of their ideas, and actually implement them for testing and evaluation, more power to them. I don't think we should beat up on Antoon for his interest in exploring theoretical possibilities. Sometimes a spark may fly off and provide some useful illumination. OTOH, interesting is in the eye of the beholder ;-) Regards, Bengt Richter From zathras at thwackety.com Fri Jan 7 00:50:33 2005 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 07 Jan 2005 05:50:33 +0000 Subject: Embedding a restricted python interpreter References: Message-ID: <41ddd257$0$29355$ed2e19e4@ptn-nntp-reader04.plus.net> Rolf Magnus wrote: > I would like to embed a python interpreter within a program, but since > that program would be able to automatically download scripts from the > internet, I'd like to run those in a restricted environment, which > basically means that I want to allow only a specific set of modules to be > used by the scripts, so that it wouldn't be possible for them to remove > files from the hard drive, kill processes or do other nasty stuff. > Is there any way to do that with the standard python interpreter? Current advice seems to be essentially "no". I've been pondering adding limited scripting to some personal apps I've written and due to this toyed around with the idea of simple but parser that only used ":" and whitespaces for indicating blocks with the aim of being a generic/"universal"(*) language parser that could be used for many little "languages". (ie no keywords, just "pure" structure) (*) By "universal" I mean something that allows a variety of different styles of syntax to be used, whilst technically still sharing the same underlying syntax. (Since that's a rather bogus statement, that's why it has quotes :) In the end I sat down and wrote such a beast largely as a fun exercise. (It uses PLY and is an SLR grammar) It *doesn't* have any backend so you get to decided how restricted it can be, but, for example, the following code would parse happily: (It's not quite python, but it's close syntactically) class Grammar(object): from Lexer import Tokens as tokens precedence = ( ( "left", "DOT")) def p_error(self,p): print "Syntax error at", p end end This parses as follows: A class function is provided with 3 arguments: * Grammar(object) * A code block * A lexical token "end" (Which could be anything) The code block then contains 3 statements * The first is a function call, to a function called "from" * The second is an assignment statement * The third is a function call to the function "def" (which in turn takes 3 arguments - a signature, a codeblock and a trailing token (the trailing token allows "else" clauses and try/except style blocks) etc However it will also parse happily: EXPORT PROC compare(field::PTR TO person,type=>NIL) OF person: DEF result=FALSE IF type: SELECT type: CASE NAME: result:=compare_name(self.name,field) CASE PHONE: result:=compare_telephone(self.telephone,field) CASE ADDRESS: result:=compare_address(self.address,field) ENDCASES ENDSELECT ELSE: result:=compare_name(self.name,field,ORDER) # if type = NIL, ordering ENDIF ENDPROC result And also programs of the form: shape square: pen down repeat 4: forward 10 rotate 90 end pen up end repeat (360/5): square() rotate 5 end and so on. If you're prepared to write backends to traverse an AST then you might find it useful. (I also wrote the parser as an exercise in trying to generate a parser in a test first manner) If you're curious as to the sorts of languages it could parse the test cases are here: * http://thwackety.com/viewcvs/viewcvs.cgi/Scratch/SWP/progs/ Some rather random examples are: 29, A copy of the parser file at that point in time, but rewritten in a python-esque language parsable by the parser 33, A simple program in a logo type language 34, A simple program based on declarative l-systems for modelling biological growth systems. 35, A simple SML-like language file implementing a stack 37, An implementation of a "Person" object module in an Amiga-E like language. (NB, here "language" means whatever AST a given backend might understand, since they're all technically the same language) http://thwackety.com/viewcvs/viewcvs.cgi/Scratch/SWP/README?rev=1.1 Describes the grammar, etc. (31 explicit rules, or alternatively 13 aggregate rules) If you think it might be useful to you, feel free to do an anonymous checkout: cvs -d :pserver:anonymous at cerenity.org:2401/home/cvs/cvsroot login cvs -d :pserver:anonymous at cerenity.org:2401/home/cvs/cvsroot co Scratch/SWP/ Since there is *no* backend at all at present this would be a bit of work. (I've been tempted to investigate putting a lisp backend on the back, but not found the time to do so. If I did though this would be a brackets free lisp :) You can fine PLY here: http://systems.cs.uchicago.edu/ply/ . Best Regards, Michael. From jfj at freemail.gr Mon Jan 3 15:54:48 2005 From: jfj at freemail.gr (jfj) Date: Mon, 03 Jan 2005 12:54:48 -0800 Subject: Python! Is! Truly! Amazing! In-Reply-To: References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: <41D9B118.3050902@freemail.gr> Ron Garret wrote: > In article <1104657461.868175.252380 at c13g2000cwb.googlegroups.com>, > "Erik Bethke" wrote: > > >>I have NEVER experienced this kind of programming joy. > > > Just wait until you discover Lisp! > > ;-) I've had it with all those lisp posts lately ;-) There were functional and non-functional programming languages (the first being *much* simpler to implement). There is a *reason* people chose C over lisp. It's not that we were all blind and didn't see the amazingness of lisp. Procedural languages are simply better, and I'm not replying to this flamewar. Thank you:) G. From bokr at oz.net Tue Jan 25 07:52:39 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 25 Jan 2005 12:52:39 GMT Subject: is there better 32 clock() timing? References: <41f61372.1768192005@news.oz.net> Message-ID: <41f63d79.1778950866@news.oz.net> On Tue, 25 Jan 2005 11:42:35 +0000, Stephen Kellett wrote: >>>that time.clock() is inaccurate. The problem is that the "time.clock()" >>>statement takes several hundred microseconds to execute. > >The statement is incorrect. clock() itself isn't slow, but it is >accessing a resource, the accuracy of which is no better than 1ms. I believe that is quite wrong as a general statement. It may be right on some benighted system, but not on win32/NT python 2.4. How do you account for getting deltas of 6-7 microseconds in abs(clock()-clock()) ? If the "resource" only had ~1ms granularity, the minimum would be zero, as it is if you call time.time() in a tight loop, since it doesn't tick over often enough. time.clock does tick over fast enough that you can't snag the same reading on two successive clock() calls on a 300mhz P2. > >There are various timers available, documented and undocumented, all of >which end up at 1ms or 1.1ms, give or take. For anything shorter you >need QueryPerformanceCounter() (but that *is* a slow call), or use the Have you timed it, to make that claim? What do you mean by "slow"? >RDTSC instruction which is fast but gives a count of instruction cycles >executed and is thus not totally accurate (multiple execution pipelines, >plus multithreading considerations). Accurate for what. A single clock AFAIK drives RDTSC > >You have to choose the system that works best for you. In many cases >RDTSC works OK. I wrote an extension to access it directly, and was agble to get down to 23 cycles IIRC for a C call pair like above on a 300 mhz P2. 23/300 us I guess, less than 100 ns between the clock reads of two calls. The main problem with a CPU clock based reading is that it's very stable unless there's variable clock rate due to power management. Why am I doing this? ;-) Regards, Bengt Richter From steven.bethard at gmail.com Tue Jan 11 02:35:26 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 11 Jan 2005 00:35:26 -0700 Subject: Handing a number of methods to the same child class In-Reply-To: <6cWdnTY8IPa5hH7cRVn-sg@rcn.net> References: <6cWdnTY8IPa5hH7cRVn-sg@rcn.net> Message-ID: Dave Merrill wrote: > Somewhat silly example: I know you've hedged this by calling it a "silly" example, but I would like to point out that your set_X methods are unnecessary -- since Python allows you to overload attribute access, getters and setters are generally unnecessary. > class Address: > def __init__(): > self.displayed_name = '' > self.adr = '' > self.city = '' > self.state = '' > def set_name(name): > self.displayed_name = name > def set_adr(adr): > self.adr = adr > def set_city(city): > self.city = city > def set_state(state): > self.state = state > > class Phone: > def __init__(): > self.displayed_name = '' > self.number = '' > def set_name(name): > self.displayed_name = name > def set_number(number): > self.number = number > > class Customer: > def __init__(): > self.last_name = '' > self.first_name = '' > self.adr = Adr() > self.phone = Phone() > def set_adr_name(name): > self.adr.set_name(name) > def set_adr_adr(adr): > self.adr.set_adr(adr) > def set_adr_city(city): > self.adr.set_city(city) > def set_adr_state(state): > self.adr.set_state(state) > def set_phone_name(name): > self.phone.set_name(name) > def set_phone_number(number): > self.phone.set_number(number) > > IOW, all the adr methods go to the corresponding method in self.adr, all the > phone methods go to self.phone, theorectically etc for other rich > attributes. > > What I'd really like is to say, "the following list of methods pass all > their arguments through to a method of the same name in self.adr, and the > following methods do the same but to self.phone." Is there some sane way to > express that in python? py> class Address(object): ... def __init__(self, city, state): ... self.city = city ... self.state = state ... py> class Customer(object): ... def __init__(self, name, addr): ... self.name = name ... self.addr = addr ... def __getattr__(self, attr): ... if attr.startswith('adr_'): ... return getattr(self.addr, attr[4:]) ... raise AttributeError(attr) ... py> c = Customer("Steve", Address("Tucson", "AZ")) py> c.adr_city 'Tucson' py> c.adr_state 'AZ' I've used a slightly different example from yours, but hopefully you can see how to apply it in your case. The __getattr__ method is called when an attribute of an object cannot be found in the normal locations (e.g. self.__dict__). For all attributes that begin with "adr_", I delegate the attribute lookup to the self.addr object instead. Steve From pekka.niiranen at wlanmail.com Mon Jan 3 14:41:41 2005 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Mon, 03 Jan 2005 21:41:41 +0200 Subject: HELP: Tkinter idiom needed: SOLUTION In-Reply-To: <41d6b0c9$0$16584$39db0f71@news.song.fi> References: <41d6b0c9$0$16584$39db0f71@news.song.fi> Message-ID: <41d99fae$0$20423$39db0f71@news.song.fi> Hi there, got it. Note the root.distroy()-command. -pekka- ----- CODE STARTS ---- from Tkinter import * from ScrolledText import ScrolledText import tkFont class Message_box: # Graphical message box for printing unicode texts def __init__(self, myParent): self.myContainer1 = Frame(myParent) self.myContainer1.pack(side=TOP, expand=1, fill=BOTH) self.button1 = Button(self.myContainer1) self.button1["text"]= "Close" self.button1.pack(side=BOTTOM) self.button1.bind("", self.button1Click) self.font = tkFont.Font(family="Arial Unicode MS", size=8) self.text = ScrolledText(self.myContainer1, font=self.font,\ state=NORMAL, height=40, width=120, wrap=NONE) self.text.pack(side=TOP, expand=1, fill=BOTH) def button1Click(self, event): self.myContainer1.quit() def write(self,s): self.text.insert(END, s) def enable_write(self): self.text.config(state=NORMAL) def disable_write(self): self.text.config(state=DISABLED) if __name__ == '__main__': # first window root = Tk() print "blah1" root.title(' Message window') root.protocol("WM_DELETE_WINDOW", NONE) widget = Message_box(root) m = "blah2" widget.write("%s\n" % m) widget.disable_write() root.mainloop() root.destroy() print "blah3" # second window root = Tk() root.title(' Message window') root.protocol("WM_DELETE_WINDOW", NONE) widget = Message_box(root) m = "blah4" widget.write("%s\n" % m) widget.disable_write() root.mainloop() root.destroy() print "blah5" ----- CODE ENDS ---- Pekka Niiranen wrote: > Hi there, > > after reading TkInter/thread -recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 > I wondered if it was possible to avoid using threads > for the following problem: > > I have script started from W2K console that normally > prints ascii messages to the screen. However, I have > command line "debug" -flag that might cause printing > of UTF-8 data to the screen. This fails occassionally > due to Console encoding, of course. > > What I need is Tkinter window where some printouts > are directed when script is run in Debug -mode > (Redirection of stdout is out of question). > > While testing, I have got this far already: > > ---script starts---- > > from Tkinter import * > from ScrolledText import ScrolledText > import os, sys, tkFont, codecs > > class Pyg_message_box: > def __init__(self, parent): > self.myParent = parent > self.myContainer1 = Frame(parent) > self.myContainer1.option_add("*font",\ > tkFont.Font(family="Arial Unicode MS", size=8)) > self.myContainer1.pack() > self.text = ScrolledText() > self.text.pack() > self.button1 = Button(self.myContainer1, text="Quit",\ > command=self.button1Click) > self.button1.pack(side=LEFT) > self.button1.bind("", self.button1Click) > > def button1Click(self, event): > self.myContainer1.quit() > > def write(self, s): > self.text.insert(END, s) > > root = Tk() > widget = Pyg_message_box(root) > sys.stdout = widget > a = codecs.open("d:\\test.txt", "r", "utf_16").readlines() > for x in a: > print x > root.mainloop() > > ---script ends---- > > My questions are: > - Can I open Tk -window without enclosing the whole script > between "root=Tk()" and "root.mainloop()"? > - What is the idiom of opening Tk -window only when Debug -flag > is encountered (the script stops running until window is closed)? > > Something like: > > if not my_debug == "ON": > print "message" # prints to console > else: > # 1) open temporary ScrolledText() Tk -window > # 2) Print stuff to window > # 3) Ask user to close window > > I would no like to always open Tkwindows just in case user runs script > with debug -flag on. > > -pekka- From mirnazim at gmail.com Thu Jan 6 08:05:03 2005 From: mirnazim at gmail.com (mirnazim at gmail.com) Date: 6 Jan 2005 05:05:03 -0800 Subject: Nevow Tutorial and sample app Message-ID: <1105016703.493588.308570@z14g2000cwz.googlegroups.com> Hi, Can any one redirect me to a good nevow tutorial and/or a an appliction that is niether too big nor too small and can be help in learning nevow. Nevow tutorial with the distrubution is too simple and it doesnot even skim the surface. Another one http://www.nevow.com/Nevow2004Tutorial.html is good but the does not conform to the current nevow relaese(0.3). e.g. its says from nevow.rend import htmlfile while as htmlfile is actually in loaders module. thanks ---- Mir Nazim From b at b.b Sat Jan 8 03:28:12 2005 From: b at b.b (Roose) Date: Sat, 08 Jan 2005 08:28:12 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> Message-ID: > But I thought Python was an all-purpose language. After all, OS's > have been written in Lisp before too. It is a general purpose APPLICATION language. I am surprised that this hasn't been mentioned on this thread. An OS is NOT an application. It is a completely different kind of program. Do you guys understand the difference between user and kernel mode? Do you know what address spaces and hardware interrupts are? Python is not equipped to handle these things. You would end up doing so much in C extensions that it could barely be called Python. I am not trying to be insulting... but unless someone would like to educate me otherwise, the idea of an OS written in Python is almost ludicrous. As I said, I think you might mean an OS SHELL, which would be a reasonable (although maybe unconventional) thing to write in python. Also I am no threading expert, but I would imagine it would be very hard to write a task scheduler in Python given that it has the whole GIL thing. (As I said that isn't my domain of expertise but I'm sure someone here could expound on that.) From pdemb at illx.org Sun Jan 2 16:39:51 2005 From: pdemb at illx.org (Peter Dembinski) Date: Sun, 02 Jan 2005 22:39:51 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <87hdlza4t4.fsf@hector.domek> Bulba! writes: [...] > The point is obviously "cover your ass" attitude of managers: Managers get paid for taking risk :) From apardon at forel.vub.ac.be Thu Jan 20 03:12:40 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Jan 2005 08:12:40 GMT Subject: Zen of Python References: Message-ID: Op 2005-01-19, Steve Holden schreef : > Peter Hansen wrote: > >> Timothy Fitz wrote: >> >>> While I agree that the Zen of Python is an amazingly concise list of >>> truisms, I do not see any meaning in: >>> >>> Flat is better than nested. >>> > [incrdeibly secret PSU facts blurted out] >> >> And with that out of the way, one is left with "there's a balance >> along the flat/nested dimension which is appropriate to any >> given situation, so nest with moderation and only when necessary". >> > They'd probably been talking to Antoon Pardon :-) Just what I thought: They'll be accusing me of this :-) -- Antoon Pardon From P.Schnizer at nospam.gsi.de Mon Jan 24 03:07:46 2005 From: P.Schnizer at nospam.gsi.de (Pierre Schnizer) Date: 24 Jan 2005 09:07:46 +0100 Subject: pygsl-0.3.1 released Message-ID: <87k6q35jxp.fsf@smtp.gsi.de> pyGSL is a wrapper for the GNU Scientific Library. Get it from http://sourceforge.net/projects/pygsl. Up to now it provides the following modules: Blas, Chebyshev, Combination, Const Diff, Deriv, Eigen, Fit, FFT, Ieee, Integrate Interpolation, Linalg, Math Minimize, Multifit, Multifit_nlin, Multimin, Multiroots, Odeiv, Permutation Poly, Qrng, Rng, Roots, Siman (Simulated Annealing) Special Functions, Spline GSL >= 1.3 and numerical python are required. It requires either Numeric or numarray. Please send all bug reports, requests, patches to pygsl-discuss at lists.sf.net Yours sincerely Pierre Schnizer -- Please remove the nospam for direct reply From rmemmons at member.fsf.org Sat Jan 1 14:28:16 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Sat, 01 Jan 2005 13:28:16 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: > For managers of companies it's worse: the company makes > VERY substantial investments into any technology it "marries", > and that means big losses if it goes. Long-term stability > of this technology in terms of "we're not going to be left out > in cold alone with this technology to feed it" means a lot > to them. Even a poor technology with external backing > of big, stable vendor is better than the excellent technology > without ...... There is the stability issue you mention... but also probably the fear issue. If you choose a solution from a major company -- then it fails for some reason or they drop the product -- it's their fault -- you've got an automatic fall guy. On the other hand, an open source solution or otherwise less accepted solution ... it will probably be consider your fault by the organization. It's a rational decision to avoid personal risk when you don't get much reward for choosing something different. Rob From grante at visi.com Sat Jan 1 21:31:07 2005 From: grante at visi.com (Grant Edwards) Date: 02 Jan 2005 02:31:07 GMT Subject: Approximating scattered data References: <41d72377$0$31717$a1866201@visi.com> <1104624125.552423.63000@z14g2000cwz.googlegroups.com> Message-ID: <41d75ceb$0$31682$a1866201@visi.com> On 2005-01-02, beliavsky at aol.com wrote: >>However, I can't find anything usable from Python, and my >>Fortram skills are pretty rusty. I tried SciPy, but it's spline >>fitting module doesn't work at all for my data. I've found >>mentions of a Python port NURBS toolbox, but all the links I >>can find are broken. > > NURBS is available in Matlab and Scilab at > http://www.aria.uklinux.net/nurbs.php3 , and translating to > Python with Numeric/Numarray should not be too hard. Right. It says there's a Python module for the NURBS toolkit, but there's nothing about NURBS on the page to which the link points. Googling for Python and NURBS toolkit doesn't find anything else. > If you are trying to fit z = f(x,y) without having a particular > functional form in mind, you can apply a nonparametric regression > technique. One of the easiest approaches to code is Nadaraya-Watson > kernel regression -- see for example > http://www.quantlet.com/mdstat/scripts/spm/html/spmhtmlnode24.html , > equation 4.68, Well, I can see it, but that's about it... :) > where a Gaussian kernel can be used for K. PyML at > http://pyml.sourceforge.net/doc/tutorial/tutorial.html may > implement this (I have not tried it). Thanks, I'll take a look. > LIBSVM at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ has a > Python interface for Support Vector Machines, a fairly popular > and recent flexible regression method. I'll give that a look also. One of the important considerations is the efficiency of evaluating the approximating function (calculating z given x and y). That code is going to be running on a rather slow processor w/o floating point HW, and if the evaluation takes more than about 40ms, I'm going to have problems. The evaluating the spline surface produced by scipy's FITPACK wrapper was fast enough, but I had to force the scattered data onto a grid (which introduced errors), and then the spline surfaces generated were wildly unstable between the grid points. -- Grant Edwards grante Yow! The Korean War must at have been fun. visi.com From ahaas at airmail.net Wed Jan 12 12:50:07 2005 From: ahaas at airmail.net (Art Haas) Date: Wed, 12 Jan 2005 11:50:07 -0600 Subject: [ANNOUNCE] Twenty-first release of PythonCAD now available Message-ID: <20050112175007.GC22649@artsapartment.org> I'm pleased to announce the twenty-first development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2 or newer. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. Addition of other PythonCAD interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The twenty-first release of PythonCAD adds the ability to save the visibility and locked status of entities when saving a drawing. This release also includes improved code for handling the undo/redo operations by simplifying various routines as well as making similiar routines in various modules consistent. Like all previous releases, numerous bug fixes and code improvements have been applied. A mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From jtr at ofb.net Thu Jan 20 19:19:03 2005 From: jtr at ofb.net (John Reese) Date: Fri, 21 Jan 2005 00:19:03 +0000 (UTC) Subject: Is there a library to parse Mozilla "mork" documents? Message-ID: Mozilla, Firefox, Thunderbird, and so forth use this awful format called MORK to store all kinds of things: which messages you've read in a newsgroup, headers and indexes into the mbox file of messages in a mail folder, and address books. It's documented to some extent here: http://www.mozilla.org/mailnews/arch/mork/primer.txt Does anyone know of a Python library for parsing these files? A single file basically just stores the equivalent of a nested dictionary with text that can be declared separately and interpolated. jwz has an over-specific perl version at http://www.jwz.org/hacks/marginal.html, which I might have to try to translate if there's nothing already available in Python. From noway at sorry.com Mon Jan 31 20:58:15 2005 From: noway at sorry.com (Giovanni Bajo) Date: Tue, 01 Feb 2005 01:58:15 GMT Subject: set, dict and other structures References: <1107214762.198058.55680@f14g2000cwb.googlegroups.com> Message-ID: Raymond Hettinger wrote: > If set-ifying a dictionary turns out to be an essential and > time-critical operation, it is possible to add some special case code > for this. The question is whether it is worth it. If you find the > need is pressing, file a feature request explaining why it is > essential. Then, I'll implement it for you. On the other hand, if > this is a theoretical nice-to-have, then why clutter up the code > (with pre-sizing and forcing all values to True). Just today I was writing some code where I wanted to use sets for the abstraction (intersection, etc.), but also carry some values with them to process. So, yes, I believe that having set-like abstraction for dictionaries would be great. In fact, for a moment I wondered if dict.keys() was already of type set in 2.4, because it could have made sense. My concrete situation was a routine that was updating a current snapshot of data (stored in a dictionary) with a new snapshot of data (another dictionary). With 'updating' I mean some kind of algorithm where you have to do different things for: - items that were present in the current snapshot but not in the new snapshot anymore (obsolete items) - items that were not present in the current snapshot but are presente in the new snapshot (new items) - items that were present in both the current and the new snapshot (possibly modified items) So, this was a perfect suit for sets. Given my dictionaries d1 and d2, I would have liked to be able to do: for k,v in (d1 - d2).iteritems(): ... for k,v in (d2 - d1).iteritems(): ... for k,v in (d1 & d2).iteritems(): # uhm, not fully correct ... Of course, there are some nitpicks. For instance, in the last case the dictionary at the intersection should probably hold a tuple of two values, one coming from each dictionary (since the intersection finds the items whose key is present in both dictionaries, but the value can obviously be different). So you'd probably need something: for k,(v1,v2) in (d1 & d2).iteritems(): ... Another solution would be to say that set-like operations, like (d1 & d2), return an iterator to a sequence of keys *only*, in this case the sequence of keys available in both dictionaries. I also tried a different approach, that is putting my data in some structure that was suitable for a set (with __hash__ and __key__ methods that were caring of the key part only): class FakeForSet: def __init__(self, k, v): self.key = key self.value = value def __hash__(self): return hash(self.key) def __cmp__(self, other): return cmp(self.key, other.key) but this looked immediatly weird because I was lying to Python somehow. It then became clear that it's not going to work, because when you go through (s1 & s2) you do not know if the items you get are coming from s1 or s2, and that is important because the value member is going to be different (even if you're lying to Python saying that those items are equal anyway). I know of course there are other ways of doing the same thing, like: # intersection for k in d1: if k not in d2: continue v1, v2 = d1[k], d2[k] ... But I don't think there is anything wrong in providing an abstraction for this, especially since we already decided that set-like abstractions are useful. So, FWIW, I would find set-like operations on dictionaries an useful addition to Python. Besides, I guess they can be easily experimented and studied by subclassing dict. -- Giovanni Bajo From dalke at dalkescientific.com Thu Jan 6 14:24:52 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 06 Jan 2005 19:24:52 GMT Subject: Other notes References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> <41DD40F1.5030301@holdenweb.com> Message-ID: Me >>>> (BTW, it needs to be 1 .. 12 not 1..12 because 1. will be interpreted >>>> as the floating point value "1.0".)< Steve Holden: > Indeed, but if ".." is defined as an acceptable token then there's > nothing to stop a strict LL(1) parser from disambiguating the cases in > question. "Token" is not the same thing as "character". Python's tokenizer is greedy and doesn't take part in the lookahead. When it sees 1..12 the longest match is for "1." which is a float. What remains is ".2". That also gets tokenized as a float. is not allowed in Python so the parser raises an compile time SyntaxError exception >>> 1..12 File "", line 1 1..12 ^ SyntaxError: invalid syntax >>> Consider the alternative of "1..a". Again "1." is tokenized as a float. What remains is ".a". The longest match is "." with "a" remaining. Then the next token is "a". The token stream looks like which gets converted to the same thing as getattr(1.0, "a") That is legal syntax but floats don't have the "a" property so Python raises an AttributeError at run-time. >>> 1..a Traceback (most recent call last): File "", line 1, in ? AttributeError: 'float' object has no attribute 'a' >>> Here's a property that does exist >>> 1..__abs__ >>> Because of the greedy lexing it isn't possible to do "1.__abs__" to get the __abs__ method of an integer. That's because the token stream is which is a syntax error. >>> 1.__abs__ File "", line 1 1.__abs__ ^ SyntaxError: invalid syntax >>> One way to avoid that is to use "1 .__abs__". See the space after the "1"? The tokenizer for this case creates which create code equivalent to getattr(1, "__abs__") and is valid syntax >>> 1 .__abs__ >>> Another option is to use parentheses: (1).__abs__ I prefer this latter option because the () is easier to see than a space. But I prefer using getattr even more. Andrew dalke at dalkescientific.com From chrisdewinN0SPAM at yahoo.com.au Sat Jan 29 13:05:53 2005 From: chrisdewinN0SPAM at yahoo.com.au (Dfenestr8) Date: Sun, 30 Jan 2005 04:05:53 +1000 Subject: An mysql-python tutorial? References: Message-ID: On Sat, 29 Jan 2005 06:41:37 +0000, Kartic wrote: [snip] > And here is one more site, good stuff here too:- > http://www.kitebird.com/articles/pydbapi.html > Hi. I followed the instructions there, tried out the test script they recommend. Can you tell me why this command, in the python interpreter: >>>conn = MySQLdb.connect (host = "localhost", user = "flipper", passwd = "[hidden]", db = "mydb") produces this error: Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/site-packages/MySQLdb/__init__.py", line 63, in Connect return apply(Connection, args, kwargs) File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line 115, in __init__ self._make_connection(args, kwargs2) File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line 41, in _make_connection apply(super(ConnectionBase, self).__init__, args, kwargs) _mysql_exceptions.OperationalError: (1045, "Access denied for user: 'flipper at localhost' (Using password: YES)") I also have MySQL installed, and tried setting up the user flipper with the mysql client, as per the instructions here: http://vsbabu.org/mt/archives/2003/04/17/mysql_in_mandrake_91.html From gandalf at geochemsource.com Mon Jan 31 09:44:38 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Mon, 31 Jan 2005 15:44:38 +0100 Subject: re module - cannot make expression Message-ID: <41FE4456.5050504@geochemsource.com> Hi All! I would like to match strings not beginning with '/webalizer'. How can I do this? The only one negation command is ^ inside [] but it cannot be used here. I looked over "re" examples on the net but I could not find an example about how to match "not beginning with" type expressions. Thanks, Laci 2.0 From flupke at nonexistingdomain.com Thu Jan 6 09:27:10 2005 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 06 Jan 2005 14:27:10 GMT Subject: logging from severl classes In-Reply-To: <1104193858.640852.120730@z14g2000cwz.googlegroups.com> References: <1104193858.640852.120730@z14g2000cwz.googlegroups.com> Message-ID: <2VbDd.21742$Nv5.1294471@phobos.telenet-ops.be> Vinay Sajip wrote: > It works for me: > > #file3.py > import file1 > import file2 > > a = file1.A() > b = file2.B() > b.otherfunction() > > gives > > 2004-12-28 00:18:34,805 DEBUG file2 6 creating class B > 2004-12-28 00:18:34,805 DEBUG file2 9 in otherfunction > yeah, the classes where a simplification of the classes i'm using and used these to just show what i wanted to do without testing them. they indeed work. strange. Thanks for your answer benedict From luv2luv_u at comcast.net Tue Jan 18 02:55:44 2005 From: luv2luv_u at comcast.net (collegebabe2004) Date: 17 Jan 2005 23:55:44 -0800 Subject: Advice to a Junior in High School? In-Reply-To: References: Message-ID: <1106034944.793262.19950@z14g2000cwz.googlegroups.com> wow! Aren't we getting ahead of ourselves? Well, I'm glad you are beefing up your college knowledge but let's just sit back for a minute and breathe..........there, feel better? Now, listen. When I was a freshman and sophomore in high school I was so sure I wanted to be an artist and attend one of the most highly recognized and expensive art schools in the country. I wanted to go to college back east away from my parents. Now I'm a psychology major in community college and I want to attend UCLA! First of all, NEVER SETTLE FOR LESS when it comes to your major. Do what it is true to your heart and never let people say you can't! You can double major if you want to be on the safe side. Compsci isn't an easy thing to do as you know and it's a highly regarded profffession! By the time you graduate college, the world could be a completely different place. But let's just worry about here and now. If you think too much about the future IT WILL DRIVE YOU CRAZY! Trust me, you are doing everything right so far. I applaud your effort but relax and everything will fall into place eventually! I would suggest taking Japanese because you will have to work with them eventually if you do decide to choose compsci as your proffesion. Margaux From fortepianissimo at gmail.com Fri Jan 21 00:55:28 2005 From: fortepianissimo at gmail.com (fortepianissimo at gmail.com) Date: 20 Jan 2005 21:55:28 -0800 Subject: Example of resolving an alias using Carbon.File module? Message-ID: <1106286928.806519.67720@c13g2000cwb.googlegroups.com> This is a question only relevant to Mac OS X. Could someone offer a simple example how to use Carbon.File module (perhaps Alias.FSResolveAlias()?) to resolve an alias? Basically I'd like to load in an alias file and find out which file/directory the alias points to. Thanks a lot! From tjreedy at udel.edu Thu Jan 27 00:44:49 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Jan 2005 00:44:49 -0500 Subject: Which is faster? References: <1106793602.782397.61260@z14g2000cwz.googlegroups.com> Message-ID: "Aggelos I. Orfanakos" wrote in message news:1106793602.782397.61260 at z14g2000cwz.googlegroups.com... > Any idea which of the following is faster? > > 'a/b/c/'[:-1] > 'a/b/c/'.rstrip('/') I find the first easier to read and mentally process. Others may have a different answer. But perhaps you meant with the CPython 2.x implementation ;-) > P.S. I could time it but I thought of trying my luck here first, in > case someone knows already, and of course the reason. For more on the CPython (2.2) reason, consider >>> def f1(s): return s[:-1] ... >>> def f2(s): return s.rstrip('/') ... >>> import dis >>> dis.dis(f1) 0 SET_LINENO 1 3 SET_LINENO 1 6 LOAD_FAST 0 (s) 9 LOAD_CONST 1 (-1) 12 SLICE+2 13 RETURN_VALUE 14 LOAD_CONST 0 (None) 17 RETURN_VALUE >>> dis.dis(f2) 0 SET_LINENO 1 3 SET_LINENO 1 6 LOAD_FAST 0 (s) 9 LOAD_ATTR 1 (rstrip) 12 LOAD_CONST 1 ('/') 15 CALL_FUNCTION 1 18 RETURN_VALUE 19 LOAD_CONST 0 (None) The second has a load attribute (via dict lookup) that the first does not. More important, the second has a generic function call versus a specific byte-coded slice call. The rstrip will also do a slice after it determines the endpoint of the slice. Terry J. Reedy From richardjones at optushome.com.au Sat Jan 29 16:34:39 2005 From: richardjones at optushome.com.au (richard) Date: Sun, 30 Jan 2005 08:34:39 +1100 Subject: Marketing reST (was Re: What YAML engine do you use?) References: <35a6tpF4gmat2U1@individual.net> Message-ID: <41fc016f$0$29490$afc38c87@news.optusnet.com.au> Aahz wrote: > While I can see how you'd get that impression of reST, it's not true: > like Python, reST is intended to be simpl*er* and readable, but not > simple.??The?joy?of?reST?is?that?I?can?concentrate?on?writing?instead?of > formatting, just as I do when writing Usenet posts.??;-)??Even?after > using reST for a long time, I'm still constantly looking up features that > I use rarely (such as correct formatting of URLs). > But reST is great because it's relatively unobtrusive. Those of us > who've used reST to document code for a long time have gotten into the > habit of using some reST-isms even when not writing reST: have you > noticed the number of Pythonistas who use constructs like ``foo()``? > Even if you didn't know it was from reST, the meaning is obvious. And this is the core of it for me too (if you want simple, use Word). Roundup's documentation__ (in particular the `Customisation Doc`__ which is now huge) is entirely written in reST. It uses a fraction of the total pool of reST constructs, but I believe the end result is perfectly legible. I also tend to write in reST style when composing emails (a biggie for me is starting examples with "::"). Anyway, some sample Roundup docs: __ http://roundup.sourceforge.net/doc-0.8/index.html __ http://roundup.sourceforge.net/doc-0.8/customizing.html > As you say, reST can/does get messy when you're doing complicated things, > but it stays more readable than XML/DocBook. Indeed - I chose to use reST for Roundup's documentation for two very important reasons: 1. lower the barrier for me to write the docs - and I am *really* happy with how current the Roundup docs stay, because I don't feel like actually writing them is a pain, as opposed to any sort of Markup Language format, and 2. the first contributor of docs suggested it, and I've had several contributors since. It's easier for contributors to write for Roundup's documentation - even if they don't get the reST markup correct, it's trivial to fix. This is less the case with a Markup Language. Richard From kartic.krishnamurthy at gmail.com Mon Jan 10 14:30:51 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 10 Jan 2005 11:30:51 -0800 Subject: Importing Problem on Windows In-Reply-To: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> Message-ID: <1105385451.560381.57650@c13g2000cwb.googlegroups.com> It is quite possible that in linux, you launched the python interpreter shell from the same directory you stored your parser.py and parse.py files. On windows, you probably saved the parser*.py files to some place like "my documents" and launched the python interpreter or IDLE. So, you could probably try this: 1. Launch command shell. 2. CD to the directory where you saved the parser*.py files. 3. Start python.exe from the command prompt (not from the Program Files shortcut) 4. Try importing. Easier...copy the parser*.py files into the Libs folder of your python installation in your windows machine. Thanks, --Kartic From ruses at users.ch Wed Jan 12 11:42:28 2005 From: ruses at users.ch (more i squawed) Date: Wed, 12 Jan 2005 17:42:28 +0100 Subject: java 5 could like python? In-Reply-To: References: Message-ID: <34l1saF4c17ifU1@individual.net> vegetax wrote : > I was a java developer one year ago ,before i moved to python i realy liked > it at the beggining, but i got very disapointed lately since my > previus two python proyects where relatively big,and python didnt feel > well suited for the task. > > The reasons are mainly due to the standard library,the language > performance was aceptable, but the library, in my opinion has several grave > issues: > > -No naming convention. The speech of "it fits in my head" is no longer valid > when i use a lot of functionality,modules,classes in a large proyect. > > For example if i remember a function i want ie:get attribute, i dont > remember if the module implementer coded it as > getAttribute,GetAttribute,get_attribute, then i have to go and check the > doc, every time,which is a waste of time. I believe this is a rather ill-suited example. People will react. > > -library Organization,we have modules that can have 20 classes(I imagine > that is because of the commodity of having all in one file) I challenge you to comparative statistics with Java. > which makes > reading the doc horribly painfull and is very hard to find the stuff > coupled with the "pool" of modules that is the python installation > directory,all throwed away at the installation directory without a > categorization. Well, for the soothing it can provide, I often feel nostalgic of the python documentation when I use javadoc. > > -Is python library half object oriented? half functional oriented? I can > understand that python allows some functional programing components when > they are necesary,but there are libraries that totaly ignore object > orientation which makes them problematic to use.for example,Whats with the > os.path module and files? why do i have to say os.path.getfilesize(f.name) > all the time? why cant i say f.size? Why does urlparse returns a tuple of 7 > items instead of an URL object? why there isnt an URL object? and so on.. > > I havent figured out a way to overcome those factors,the delaying and lost > of focus that is having to check the docs all the time,every 5 seconds and > having to make object oriented wrapers for several libraries or having to > go and read the source code to know what the heck a function returns or > what are its arguments makes coding unpleasant an very slow , i often have > 15 pydocs windows open at the same time. What should i do? First, you should believe the newsgroup when you get told that reading the source code "to know what the heck a function returns" is a not a need the python documentation leaves most pythoneers with. > -Realying on ides is imposible due to python dinamic nature,very litle(next > to nothing) assistance can be espected from them. > > -Memorazing all the function names,parameters,return values,conventions of > the modules i use doesnt look like a good solution. > > Join it with poor and outdated documention and we have a very unpleasant > standard library. You would be much closer to the mark, imho, by admitting that the main issue with "knowing a programming language" is knowing its standard library while feeling at home with the documentation thereof; *and* then admitting that changing languages generally implies the unpleasant experience of loosing touch with the content and style of one's beloved standard library and docs. > > In the other hand, with the recent changes in java 5 i can pythonize > java,And take advantage of a well designed library that coupled with the > "apache commons" libraries has no match,not even .Net. > > for example with the static import feature i can say: > > import static mylib.Toolbox.print; > import static mylib.Console.run; > // or import static mylib.Toolbox.*; > > class C{ > public void func(){ > print("hello world"); // instead of System.out.println("hello world"); > print(run("ls /tmp")); > } > } Well you should provide the complete python equivalent, and I anticipate that you will be hard pressed to find someone on clp who will share your feeling that this java version is evidently better. Regards. From ncoghlan at iinet.net.au Thu Jan 6 05:38:15 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 06 Jan 2005 20:38:15 +1000 Subject: [Python-Dev] Let's get rid of unbound methods In-Reply-To: <001d01c4f34c$a02f8770$6402a8c0@arkdesktop> References: <001d01c4f34c$a02f8770$6402a8c0@arkdesktop> Message-ID: <41DD1517.8080903@iinet.net.au> Andrew Koenig wrote: >>duck typing? > > > That's the Australian pronunciation of "duct taping". More Kiwi, I'm thinking ;) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From rnd at onego.ru Tue Jan 4 16:44:33 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 5 Jan 2005 00:44:33 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: <41DAFF93.7030502@pythonapocrypha.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> Message-ID: On Tue, 4 Jan 2005, Dave Brueck wrote: >Roman Suzi wrote: >>>>It may be optional in the sense that the language will >>>>accept missing declarations but as soon as the feature >>>>is available it will become "mandatory" to use it >>>>(peer pressure, workplace practices). >> >> >> What about generic programming coming into fashion anytime soon? > >Roman, I think I've read every single thread in the past year or three wherein >you've brought up generic programming, and I think you'd do well to choose a new >term for the idea you're trying to convey. IIRC, I did it only once: at fall 2004. >The term "generic programming" is too... er... generic. :) Nope. It is not generic. It has it's definition made by the co-author of STL - A.Stepanov. And the Boost C++ library (many of us know it as Boost Python) standardise on the approach, AFAIK. >As you know, Python >already includes a _lot_ of support for generic programming (a function that >iterates over a sequence can easily process a list, or a string, or a tuple as >input; a function that takes a file-like object can often work just as will with >a true file object or a cStringIO object; etc.). So when you bring up "generic >programming", it's too easy to dismiss the comment because (1) it's too vague >and (2) Python already does a lot of it. > >So, what is your term for the type of generic programming that Python doesn't >yet support? Interfaces? Protocols? Adapters? Metatype hierarchies? Python could have honest support of concepts. Everything else will be available with them. That is the whole point that Python supports GP. It is only one step to do concepts right (and GvR it seems want type-checking into Python 3.0 anyway), so support for concepts/concept checking is very logical, isn't it? Right now concepts in Python are things which experienced Python programmers know from practise. Sometimes, they feel them unconsciously. Concepts could be veryfied and this, for example, could prevent errors like DB-API-complient module doesn't have some small, but necessary to comply, attributes. Standard concepts could be part of standard concept "metalibrary", along with verification mechanisms (this could be done even on C++, why not in a candy like Python?). So every programmer could verify that his/her class, created to satisfy concept XYZ is (formally) such. Your example - cStringIO - does it really satisfy concept of STRING? It does. Partially. Those "partially" here and there could lead to madness. Unit testing will be simplified too, because structural tests will be built into concept-checking mechanism. And BTW, are we really disputing? What do you propose instead? Old-fashioned Pascal-like type definitions? Java-like interface/implementaion ...? IMHO it could be a big mistake to play catch-up. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From steve at holdenweb.com Fri Jan 7 06:36:31 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 07 Jan 2005 06:36:31 -0500 Subject: Other notes In-Reply-To: References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> <41DD40F1.5030301@holdenweb.com> <41dda7c5.167823026@news.oz.net> Message-ID: Andrew Dalke wrote: > Bengt Richter: > >>But it does look ahead to recognize += (i.e., it doesn't generate two >>successive also-legal tokens of '+' and '=') >>so it seems it should be a simple fix. > > > But that works precisely because of the greedy nature of tokenization. > Given "a+=2" the longest token it finds first is "a" because "a+" > is not a valid token. The next token is "+=". It isn't just "+" > because "+=" is valid. And the last token is "2". > [...] You're absolutely right, of course, Andrew, and personally I don't think that this is worth trying to fix. But the original post I responded to was suggesting that an LL(1) grammar couldn't disambiguate "1." and "1..3", which assertion relied on a slight fuzzing of the lines between lexical and syntactical analysis that I didn't want to leave unsharpened. The fact that Python's existing tokenizer doesn't allow multi-character tokens beginning with a dot after a digit (roughly speaking) is what makes the whole syntax proposal infeasibly hard to adapt to. 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 ncoghlan at iinet.net.au Tue Jan 18 03:46:03 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 18 Jan 2005 18:46:03 +1000 Subject: [Python-Dev] Getting rid of unbound methods: patch available In-Reply-To: References: Message-ID: <41ECCCCB.6070606@iinet.net.au> Guido van Rossum wrote: > What do people think? (My main motivation for this, as stated before, > is that it adds complexity without much benefit.) Something important that came up in my response to Marc-Andre: What about C method implementations which are relying on this typecheck and assuming that 'self' is (nearly) guaranteed to be of the correct type? The string object implementation is where I noticed this assumption being made, but I suspect it would be fairly widespread. Obviously, use of im_func can break such code already, but that's a far cry from having C.f skip the type check. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From markfanty at yahoo.com Sun Jan 23 11:05:26 2005 From: markfanty at yahoo.com (Mark Fanty) Date: Sun, 23 Jan 2005 16:05:26 GMT Subject: best way to do a series of regexp checks with groups Message-ID: In perl, I might do (made up example just to illustrate the point): if(/add (\d+) (\d+)/) { do_add($1, $2); } elsif (/mult (\d+) (\d+)/) { do_mult($1,$2); } elsif(/help (\w+)/) { show_help($1); } or even do_add($1,$2) if /add (\d+) (\d+)/; do_mult($1,$2) if /mult (\d+) (\d+)/; show_help($1) if /help (\w+)/; How can I best do this in pyhon? Attempt 1: m = re.search(r'add (\d+) (\d+)', $line) if m: do_add(m.group(1), m.group(2)) else: m = re.search(r'mult (\d+) (\d+)', $line) if m: do_mult(m.group(1), m.group(2)) else: m = re.search(r'help (\w+)', $line) show_help(m.group(1)) The increasing nesting is a problem. I could put them in a while loop just so I can use break while 1: m = re.search(r'add (\d+) (\d+)', $line) if m: do_add(m.group(1), m.group(2)) break m = re.search(r'mult (\d+) (\d+)', $line) if m: do_mult(m.group(1), m.group(2)) break m = re.search(r'help (\w+)', $line) if m: show_help(m.group(1)) break No nesting, but the while is misleading since I'm not looping and this is a bit awkward. I don't mind a few more key strokes, but I'd like clarity. I wish I could do if m = re.search(r'add (\d+) (\d+)', $line): do_add(m.group(1), m.group(2)) elif m = re.search(r'mult (\d+) (\d+)', $line): do_mult(m.group(1), m.group(2)) else m = re.search(r'help (\w+)', $line): show_help(m.group(1)) Now that's what I'm looking for, but I can't put the assignment in an expression. Any recommendations? Less "tricky" is better. Not having to import some personal module with a def to help would be better (e.g. for sharing).. Thanks From xun.ling at gmx.de Fri Jan 7 13:22:45 2005 From: xun.ling at gmx.de (xunling) Date: 7 Jan 2005 10:22:45 -0800 Subject: "Re: Probleme mit der Installation der openSource Bittorrent.... python vs JAVA" Message-ID: OK, no win english ;D I want to build my own bittorrent client to add some usefull features as "special download directory" and "save as rar-file passwordprotected" Does anyone know if the azureus project has an opensource version? I want to write it in JAVA because java is what i like ;) If no "open-source-bittorrent-client" could be find in java, i would write it in python. Anyone who could tell me what the best developmentkit is to write network app in python?, and maybe a good book that i could eat while im sleeping? thanks for your time - xunling --------------------------------------------------------------------- ] God is the father of my doughter ;]] O_o Hu?! [ From knguyen at megisto.com Sat Jan 8 19:03:59 2005 From: knguyen at megisto.com (knguyen at megisto.com) Date: 8 Jan 2005 16:03:59 -0800 Subject: pyparsing: how to negate a grammar Message-ID: <1105229039.136595.180640@c13g2000cwb.googlegroups.com> Hi, I want to define a rule for a line that does NOT start with a given Literal. How do I do that? I try the following and my program just hang there: BodyLine = ~Literal("HTTP/1.1") + restOfLine Thanks, Khoa From jdhunter at ace.bsd.uchicago.edu Wed Jan 26 10:32:31 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 26 Jan 2005 09:32:31 -0600 Subject: detect tk mainloop Message-ID: In matplotlib using the tkagg backend, the tk mainloop is started at the end of a python script by issuing a call to a "show" function, which realizes all the created figure windows and the calls Tkinter.mainloop(). This can cause problems if the mainloop was started by another module (eg idle). Is there a way to query tkinter to detect whether the mainloop has already been called? Thanks, JDH From bob_smith_17280 at hotmail.com Sat Jan 8 18:26:16 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sat, 08 Jan 2005 18:26:16 -0500 Subject: windows mem leak In-Reply-To: <41XDd.70234$Jk5.40626@lakeread01> References: <41XDd.70234$Jk5.40626@lakeread01> Message-ID: <41E06C18.6050407@hotmail.com> Steve Holden wrote: > Bob Smith wrote: > >> Does the Win32 port of Python have a memory leak? I have some code >> that runs flawlessly on Linux, but bombs after a few hours on Windows. >> It's threaded and uses a lot of memory. >> >> Thanks! > > > Yes, that's a well-known problem. Code that runs with a few errors will > port without any trouble at all to Windows, but once it runs flawlessly > on Linux it starts to leak memory on Windows. The PSU suspects a plot in > Redmond, the basic details of which ar Oh, the humor of it all ;) Attached is the code. Run it yourself and see. You too Peter. Be gentle with me, this was my first attempt with threads. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: web_scan.py URL: From ialbert at mailblocks.com Mon Jan 24 09:49:43 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 24 Jan 2005 09:49:43 -0500 Subject: What YAML engine do you use? In-Reply-To: <35i2qpF4nd7g0U1@individual.net> References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <35i2qpF4nd7g0U1@individual.net> Message-ID: rm wrote: > http://www.theinquirer.net/?article=20868 :-) There's a lot of nonsense out there propagated by people who do not understand XML. You can't possibly blame that on XML... For me XSLT transformations are the main reason for using XML. If I have an XML document I can turn it into other formats with a few lines of code. Most importantly these are much safer to run than a program. I think of an XML document as a "mini-database" where one can easily and efficiently access content via XPath. So there is a lot more to XML than just markup and that's why YAML vs XML comparisons make very little sense. Istvan. From tjv at hotmail.com Mon Jan 31 01:41:00 2005 From: tjv at hotmail.com (tjv at hotmail.com) Date: 30 Jan 2005 22:41:00 -0800 Subject: Image stats - going from Matlab to Python Message-ID: <1107153660.431217.145160@f14g2000cwb.googlegroups.com> Hi all, I am working with images in python using PIL. I come from a MATLAB background so I am finding it to be sometimes frustrating to do things correctly and quickly. All I need to do is load an image and store a list of pixel coordinates at which the alpha channel is set to 1. In Matlab this would be easy...Lets say we have a 2x2x4 array that represents the image. I would just type something like: indices = find(im(:,:,3)==1); then work with indices to get xy coords. Is there a similar way to accomplish the same thing in python and PIL without having a nested for loop and checking every pixel? I would appreciate advice. Thanks very much for your attention! -Tim From vincent at visualtrans.de Sat Jan 29 14:42:39 2005 From: vincent at visualtrans.de (vincent wehren) Date: Sat, 29 Jan 2005 20:42:39 +0100 Subject: tk global bindings In-Reply-To: References: Message-ID: vincent wehren wrote: > Gabriel B. wrote: > >> I'm starting to write a POS application UI's module. > In Tk here are three levels of binding: instance binding, class binding, > and application binding represented by the bind, bind_class, and > bind_all methods. You're probably looking for the the bind_all method, > as in self.bind_all("", self.onSomeKey) > > HTH, > -- > Vincent Wehren Oh and you of course __must__ look at the (recently updated!) New Mexico Tech tkinter document at: http://infohost.nmt.edu/tcc/help/pubs/tkinter.pdf See page 75 and follwing for more info on keyboard bindings... -- Vincent Wehren >> Thanks, >> Gabriel From python-url at phaseit.net Sun Jan 23 12:08:15 2005 From: python-url at phaseit.net (Josiah Carlson) Date: Sun, 23 Jan 2005 17:08:15 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 23) Message-ID: QOTW: "XML with elementtree is what makes me never have [to] think about XML again." -- Istvan Albert "'Plays well with others' was a strong motivator for Python's design, and that often means playing by others' rules." -- Tim Peters Type mutability, and why some types are immutable. This has been discussed before, and should be a FAQ topic (if it isn't already): http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f05c9cbb7e58db9b http://www.python.org/tim_one/000195.html Caching instances of classes for reuse: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9178beed046956d2 Storing data in a persistant fashion. One link discussing concurrency, the other discussing data storage mechanisms. A link to PyTables as a way of storing and indexing large amounts of data, and the announcement for Dejavu 1.3, which also stores persistant data: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/072e6da39a4e8760 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/7f2849d3099abfdc http://pytables.sourceforge.net/html/WelcomePage.html http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/01a77dc70a55fc94 So, you want to use SFTP in Python? Paramiko is the answer (or so I read): http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e95e8482c023fe25 http://www.lag.net/paramiko/ Circular iteration, or any strange iteration tasks? Try itertools! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/42bd800632199d2a What do PyChecker and Pylint have to do with each other? Are they configurable? And do *you* know a half-dozen distinct formats for printing a multi-line text? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2ff633d4474e52e7/ Jeremy Bowers and Dan Stromberg know that some applications should do the right thing, whether they happen to have a bit-mapped user interface at run time or not: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9ff27f0e5fea2045/ The Bangalore Python Meetup first convened on 22 January 2005: http://python.meetup.com/158/events/?eventId=3974233&action=pastdetail Why generator expressions sometimes don't beat list comprehensions, and fitting Python to requirements. Let not the anti-functional fashion obscure that filter() still sometimes makes for better coding than the comparable list comprehension: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/0155347dab27026d http://groups-beta.google.com/group/comp.lang.python/msg/b15bab678ad9b2dc Security is hard. Even the narrow aspect of cryptography is hard, if only for the complication state politics makes of the mathematics and engineering involved. Paul Rubin, Nick Craig- Wood, and others present a few details: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/fcf8b0764d369cfa No, really--Python does *that*, too. Although many people regard hardware interfacing, and its associated bit-twiddling, as outside Python's purview, they're ... wrong. See for yourself how Python makes for *clearer* codings than C or Java or Assembler or ...: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ea293235bef39473/ ======================================================================== 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 bokr at oz.net Tue Jan 18 22:00:05 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 19 Jan 2005 03:00:05 GMT Subject: generator expressions: performance anomaly? References: <377Hd.77904$Jk5.30235@lakeread01> <41ED1C0F.4030800@holdenweb.com> <41eda453.1215517842@news.oz.net> Message-ID: <41edcc68.1225778626@news.oz.net> On Tue, 18 Jan 2005 17:38:20 -0700, Steven Bethard wrote: >Bengt Richter wrote: >> Which make me wonder what plans there are for providing a better >> mechanism than default arguments as a way of initializing local function >> variables. Nested def's to create a closure with initialized values is >> pretty crufty for that, IMO. > >What about using a class? Associating functions with data is pretty >much what they're for... > >> Maybe extending the default argument space >> with whatever comes after e.g. a triple star delimiter in the argument list, >> but which wouldn't be counted as part of the normal arguments? E.g., >> >> def foo(x, y=123, *args, **kw, *** i=1, deftime=time.ctime()): >> return x*y, kw.get('which_time')=='now' and time.ctime() or deftime > >If what you want is to have i=1 and deftime=time.ctime() available >within foo, you could do something like (untested): > >class foo(object): > def __init__(self): > self.i = 1 > self.deftime = time.ctime() > def __call__(self, x, y=123, *args, **kwds): > return x*y, (kw.get('which_time') == 'now' > and time.ctime() or self.deftime) >foo = foo() Total: 8 lines, much irrelevant cruft. > >Or if you don't like 'foo = foo()', you could probably abuse the __new__ >method (also untested): > >class foo(object): > i = 1 > deftime = time.ctime() > def __new__(cls, x, y=123, *args, **kwds): > return x*y, (kw.get('which_time') == 'now' > and time.ctime() or self.deftime) Total: 6 lines, newbie-unfriendly abuse of __new__ ;-) > >I guess my point is that if you want attribute associated with the >function, it's often easy enough to write a class instead... vs. 2 easy lines with minimal irrelevant cruft ;-) Regards, Bengt Richter From ncoghlan at iinet.net.au Sun Jan 2 00:43:30 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 02 Jan 2005 15:43:30 +1000 Subject: Frameworks for "Non-Content Oriented Web Apps" In-Reply-To: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <41D78A02.10804@iinet.net.au> mirnazim at gmail.com wrote: > But is there some sort of framework or something that is actually meant > for such web apps,application that make heavy use of forms, have very > high amount of user interaction etc. Hmm, PJE's PEAK might be worth having a look at: http://peak.telecommunity.com/ However, I'm not sure if that will provide enough of the 'web' side of things. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jeff at ccvcorp.com Wed Jan 12 12:30:00 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 12 Jan 2005 09:30:00 -0800 Subject: a new Perl/Python a day In-Reply-To: <34k2q9F4bitrcU1@individual.net> References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> <87r7ku3pwq.fsf@mithril.chromatico.net> <34ism6F4athpcU1@individual.net> <34k2q9F4bitrcU1@individual.net> Message-ID: <10uanam1c9f7i36@corp.supernews.com> Jon Perez wrote: > ... or why 'Perl monkey' is an oft-heard term whereas 'Python > monkey' just doesn't seem to be appropriate? That's just because pythons are more likely to *eat* a monkey than to be one.... :) Jeff Shannon Technician/Programmer Credit International From sjmachin at lexicon.net Mon Jan 24 19:37:39 2005 From: sjmachin at lexicon.net (John Machin) Date: 24 Jan 2005 16:37:39 -0800 Subject: Looking for Form Feeds In-Reply-To: References: Message-ID: <1106613459.770572.44200@z14g2000cwz.googlegroups.com> Greg Lindstrom wrote: > Hello- > I have a file generated by an HP-9000 running Unix containing form feeds > signified by ^M^L. I am trying to scan for the linefeed to signal > certain processing to be performed but can not get the regex to "see" > it. Suppose I read my input line into a variable named "input" > > The following does not seem to work... > input = input_file.readline() You are shadowing a builtin. > if re.match('\f', input): print 'Found a formfeed!' > else: print 'No linefeed!' formfeed == not not linefeed???? > > I also tried to create a ^M^L (typed in as Q M L) but that > gives me a syntax error when I try to run the program (re does not like > the control characters, I guess). Is it possible for me to pull out the > formfeeds in a straightforward manner? > For a start, resolve your confusion between formfeed and linefeed. Formfeed makes your printer skip to the top of a new page (form), without changing the column position. FF, '\f', ctrl-L, 0x0C. Linefeed makes the printer skip to a new line, without changing the column position. LF, '\n', ctrl-J, 0x0D. There is also carriage return, which makes your typewriter return to column 1, without moving to the next line. CR, '\r', ctrl-M, 0x0A. Now you can probably guess why the writer of your report file is emitting "\r\f". What we can't guess for you is where in your file these "\r\f" occurrences are in relation to the newlines (i.e. '\n') which Python is interpreting as line breaks. As others have pointed out, (1) re.match works on the start of the string and (2) you probably don't need to use re anyway. The solution may be as simple as: if input_line[:2] == "\r\f": BTW, have you checked that there are no other control characters embedded in the file, e.g. ESC (introducing an escape sequence), SI/SO (change character set), BEL * 100 (Hey, Fred, the printout's finished), HT, VT, BS (yeah, probably lots of that, but I mean BackSpace)? HTH, John From claird at lairds.us Sat Jan 1 11:08:07 2005 From: claird at lairds.us (Cameron Laird) Date: Sat, 01 Jan 2005 16:08:07 GMT Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <1104511661.928284.10200@z14g2000cwz.googlegroups.com> Message-ID: In article <1104511661.928284.10200 at z14g2000cwz.googlegroups.com>, wrote: >Bulba wrote: >>OK, so what projects and why would you consider >>Python: >>1. "clearly unsuitable" > >Large-scale scientific computing projects, such as numerical weather >prediction, where performance is critical. Python could be used as the >"glue" but not the "guts", where Fortran 95 and C++ are more >appropriate. In my tests, some posted here, there has been a . . . I feel like growling that it's clearly a mistake for large-scale scientific computing projects not to leverage dynamic languages, at least in part. Yes, I've seen projects that would have been disasters if done entirely in Python. I've also seen many, many large-scale scientific projects that soaked up far more resources than they should have because they limited themselves to C++ or Fortran. I argue that it's a false opposition to categorize projects in terms of use of single languages. Many projects are MUCH better off with a mix of Python and Fortran, say (and probably SQL and JavaScript and ...), and it's pernicious to accomodate the managerial conceit that One Language will suffice. From http Sat Jan 29 23:02:42 2005 From: http (Paul Rubin) Date: 29 Jan 2005 20:02:42 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f1a70b$0$25959$9b622d9e@news.freenet.de> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> Message-ID: <7xy8ebzhr1.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > >> * Quixote > > Paul> Don't know what this is. > > Web app framework. I think Python should add a web app framework to its core, again since it otherwise can't seriously begin to compete with PHP. However, there are lots of approaches so this is an example of where your suggested process of letting a bunch of different implementations circulate before choosing something is a good idea. > >> * PyInline > > Paul> Not sure what this is. > > A module for inlining C code within a Python module. Also see Weave from > the scipy.org folks. It was inspired by the Perl Inline::C module. Hmm, sounds like it has the same issues as Pyrex. I'm also not sure why you'd want both PyInline and Pyrex. > >> * PyGTK > > Paul> wxPython might be a better choice. > > Doesn't matter. At work they decreed GTK as the GUI platform long before I > came along (they also use gtkmm for C++ apps). Can't wxPython use GTK? > It's still an example of a broadly useful package available outside > the core distribution. I'd say if access to GTK is widely important functionality, then the core should provide it in some way (e.g. through wxPython) and that's enough. If your company wants some different (i.e. nonstandard, if wxPython becomes the standard) form of access, then it can deal with the consequences of not following standards. > Paul> 2. Isn't xmlrpclib written in Python? > Yes. The implementation language is just a detail. I think it's more than a detail. If an external module is written in Python, I can download it from wherever and include it with my own app that I send to an end user. I do the work so the end user doesn't have to. If it's written in C, then the end user has to deal with it. > Paul> See, as Python improved, those things went into the core. > > Sure, than that's what Martin has been trying to tell you about your AES > proposal. Put it out there, refine it, and get it into the core when it's > mature. What kind of refinements are you envisioning? This isn't a web application framework we're talking about. It's more like the sha module. > Paul> Could you use sigalarm instead? > > I suppose. That's not the point though. I'm not married to the concept as > you seem to be that something has to be in the core distribution to be of > use to me. I'm perfectly happy incorporating solutions other people > provide. So aren't you happier when the other person provides you with a solution that installs with one command, instead of a solution that requires you to download N different modules from who knows where, and install them separately, all while hoping that they haven't been tampered with? If I'm trying to provide someone else with a solution, I'd rather use sigalarm than make the end-user download an extra module, because I think they'll be happier that way. > Paul> What happens if you send your Python program to a > Paul> nonprogrammer friend who has just a vanilla Python installation? > > I figure out some other packaging solution. In my world most of the > software I write is for my employer, so this is not a problem I face very > often. People use freeze, py2exe, py2app or other packaging solutions to > solve most/all of these problems. Only those people who think that a cross-platform application is one that works on both XP Home and XP Pro. That does simplify some things. Life in a cult is often indeed simpler than life in the real world . > Actually, there were at least two fairly mature implementations of > CSV modules out there before the PEP was a twinkle in anyone's eye. > The authors of those modules got together and wrote the current PEP > and module from scratch based upon their collective experience. Yes, CSV is complicated and benefits from that process just like web app frameworks do. Let's pick another example, the hmac module that appeared in Python 2.2. It implements the RFC 2104 HMAC algorithm. Where are the two mature implementations that circulated before the hmac module was added? Where were the authors pooling their collective wisdom? Where was the year of user feedback? The answer is, nothing like that was needed. HMAC is simple enough for a module author to read RFC 2104 and implement what it says, run some tests, and declare the module good to go. > I think the effort of having a couple versions out in the field > followed by joint effort to produce something worthy of inclusion in > the core is an excellent demonstration of what Martin has been > saying all along. Martin is saying the opposite: that he doesn't understand the point of writing a new module that synthesizes from experiences with old modules, instead of just using one of the old modules. I don't think there's a one-size-fits-all answer to any of these questions. You have to have your hands in the details of a specific problem, to arrive at the best way to deal with that problem. From python-url at phaseit.net Sun Jan 23 11:28:30 2005 From: python-url at phaseit.net (Josiah Carlson) Date: Sun, 23 Jan 2005 16:28:30 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 23) Message-ID: QOTW: "XML with elementtree is what makes me never have [to] think about XML again." -- Istvan Albert "'Plays well with others' was a strong motivator for Python's design, and that often means playing by others' rules." -- Tim Peters Type mutability, and why some types are immutable. This has been discussed before, and should be a FAQ topic (if it isn't already): http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f05c9cbb7e58db9b http://www.python.org/tim_one/000195.html Caching instances of classes for reuse: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9178beed046956d2 Storing data in a persistant fashion. One link discussing concurrency, the other discussing data storage mechanisms. A link to PyTables as a way of storing and indexing large amounts of data, and the announcement for Dejavu 1.3, which also stores persistant data: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/072e6da39a4e8760 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/7f2849d3099abfdc http://pytables.sourceforge.net/html/WelcomePage.html http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/01a77dc70a55fc94 So, you want to use SFTP in Python? Paramiko is the answer (or so I read): http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e95e8482c023fe25 http://www.lag.net/paramiko/ Circular iteration, or any strange iteration tasks? Try itertools! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/42bd800632199d2a What do PyChecker and Pylint have to do with each other? Are they configurable? And do *you* know a half-dozen distinct formats for printing a multi-line text? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2ff633d4474e52e7/ Jeremy Bowers and Dan Stromberg know that some applications should do the right thing, whether they happen to have a bit-mapped user interface at run time or not: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9ff27f0e5fea2045/ The Bangalore Python Meetup first convened on 22 January 2005: http://python.meetup.com/158/events/?eventId=3974233&action=pastdetail Why generator expressions sometimes don't beat list comprehensions, and fitting Python to requirements. Let not the anti-functional fashion obscure that filter() still sometimes makes for better coding than the comparable list comprehension: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/0155347dab27026d http://groups-beta.google.com/group/comp.lang.python/msg/b15bab678ad9b2dc Security is hard. Even the narrow aspect of cryptography is hard, if only for the complication state politics makes of the mathematics and engineering involved. Paul Rubin, Nick Craig- Wood, and others present a few details: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/fcf8b0764d369cfa No, really--Python does *that*, too. Although many people regard hardware interfacing, and its associated bit-twiddling, as outside Python's purview, they're ... wrong. See for yourself how Python makes for *clearer* codings than C or Java or Assembler or ...: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ea293235bef39473/ ======================================================================== 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 Wed Jan 26 11:30:23 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 09:30:23 -0700 Subject: Help With Python In-Reply-To: References: Message-ID: <7dWdnbKpQs8_WGrcRVn-pw@comcast.com> Thomas Guettler wrote: > Am Wed, 26 Jan 2005 15:55:28 +0000 schrieb Judi Keplar: > > >>I am currently taking a course to learn Python and was looking for >>some help. I need to write a Python statement to print a comma- >>separated repetition of the word, "Spam", written 511 times ("Spam, >>Spam, ? Spam"). >> >>Can anybody help me get started? I am completely new to programming! > > > Hi, > > # This way, there is a comma after the last: > import sys > for i in range(511): > sys.stdout.write("Spam, ") > > # No comma at the end: > mylist=[] > for i in range(511): > mylist.append("Spam") > print ", ".join(mylist) # also no comma at the end, using a list comprehension print ", ".join(["Spam" for _ in xrange(511)]) # also no comma at the end, using a generator expresssion (Python 2.4) print ", ".join("Spam" for _ in xrange(511)) Steve From phil at freehackers.org Mon Jan 31 23:18:12 2005 From: phil at freehackers.org (Philippe Fremy) Date: Tue, 01 Feb 2005 05:18:12 +0100 Subject: Next step after pychecker Message-ID: <41ff0308$0$6503$636a15ce@news.free.fr> 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. 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. For a simple pattern of what I want to do: def f1( a ): return a+1 def f2(): f1( [] ) Obviously, this won't work, but neither pychecker nor the python interpreter will catch it. But a program analysis can catch it in this simple example. regards, Philippe From aahz at pythoncraft.com Sun Jan 2 12:03:50 2005 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2005 12:03:50 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <41d6ee45$1_2@127.0.0.1> Message-ID: In article <41d6ee45$1_2 at 127.0.0.1>, Donn Cave wrote: > >I can only believe that if you think the benefit of static typing is >psychological, either something is very different between the way you >and I write programs, or you're not doing it right. > >For me, the effect is striking. I pound out a little program, couple >hundred lines maybe, and think "hm, guess that's it" and save it to >disk. Run the compiler, it says "no, that's not it - look at line 49, >where this expression has type string but context requires list string." >OK, fix that, iterate. Most of this goes about as fast as I can edit, >sometimes longer, but it's always about structural flaws in my program, >that got there usually because I changed my mind about something in >midstream, or maybe I just mistyped something or forgot what I was doing. >Then, when the compiler is happy -- the program works. Not always, but >so much more often than when I write them in Python. That's just not true for me. Take my recent Java experience (please!). I spent much effort trying to resolve stupid type dependencies that made no sense. Python's duck-typing just works -- if it looks like you should be able to use an object for a particular operation, you probably can. Python programs that I write mostly just work; instead of pounding out two hundred lines of code straight, I keep adding stubs and filling them in, testing operation as I go. This isn't even unit-testing -- I haven't drunk that Kool-Aid yet. This is easy because running a Python program is faster than invoking the Java compiler -- and you still haven't tested the actual operation of your Java program. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From simon.brunning at gmail.com Fri Jan 7 11:21:02 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 7 Jan 2005 16:21:02 +0000 Subject: Getting rid of "self." In-Reply-To: <1105114214.359029.152240@f14g2000cwb.googlegroups.com> References: <740c3aec05010705393048a374@mail.gmail.com> <1105114214.359029.152240@f14g2000cwb.googlegroups.com> Message-ID: <8c7f10c6050107082174ef1f7f@mail.gmail.com> On 7 Jan 2005 08:10:14 -0800, Luis M. Gonzalez wrote: > The word "self" is not mandatory. You can type anything you want > instead of self, as long as you supply a keyword in its place (it can > be "self", "s" or whatever you want). You *can*, yes, but please don't, not if there's any chance that anyone other than you are going to have to look at your code. 'self.whatever' is clearly an instance attribute. 's.whatever' isn't clearly anything - the reader will have to go off and work out what the 's' object is. The self prefix is a perfectly good convention. Let's stick to it. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From claird at lairds.us Tue Jan 25 11:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 25 Jan 2005 16:08:04 GMT Subject: Another scripting language implemented into Python itself? References: <10vb8cve125v0b0@corp.supernews.com> Message-ID: In article , Orlando Vazquez wrote: >Jeff Shannon wrote: > >snip > >> Because you cannot make Python secure against a malicious (or ignorant) >> user -- there's too much flexibility to be able to guard against every >> possible way in which user-code could harm the system. Parsing your own >> (limited) scripting language allows much better control over what >> user-code is capable of doing, and therefore allows (at least some >> measure of) security against malicious code. > >I don't see how that would equate to something that the original >programmer should be concerned about. You could include a bit in your >licensing scheme that voids all support on code that has been modified >in any way. You shouldn't be obligated and no one expects you to support >something the end-user has mucked with. > >You could trivially enforce this by keeping checksums of all the system >files. > >In any case, there's nothing you can really do to "secure" your code. >This is true of any language, C, C++, and especially scripting languages >like Python. Anyone who has the determination get at and modify the code >probably will. > >The only time where I can see someone using another language in place of >Python for a scripting language is just domain-specific factors, e.g. if >you need the extension language to be easily used non-programmers. . . . I think there's a bit of "talking past" each other. There's a serious issue here that I suspect Mr. Vazquez misunderstood. I'll try to illustrate: The original poster wants to work in Python. That's fine. Several of us have suggested he further expose Python itself to his end-users as an extension language. That certainly is feasible. He needn't explain all of Python to those end-users--probably only a bit about "assignments", control structures, and maybe lists. That approach creates a sort of fragility, though. Python includes, along with much else, os.unlink(). Suppose our original poster doesn't want end-users to be able to delete files (or directories ...). That particular design decision is NOT particularly apt for a licensing specification, much as I generally favor trust in the latter; don't-delete-filesystem- entries is simply too low-level to admit good expression in legal language. More broadly, the model of "end-users mucking around" captures the range of concerns only poorly. This is a serious issue. It's also one that brings Tcl, mentioned several times in this thread, back into focus. Tcl presents the notion of "safe interpreter", that is, a sub- ordinate virtual machine which can interpret only specific commands. It's a thrillingly powerful and correct solution to the main problem Jeff and others have described. From caseyhHAMMER_TIME at istar.ca Sun Jan 2 03:19:40 2005 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Sun, 02 Jan 2005 08:19:40 GMT Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> Message-ID: Aren't games using full screen mode to address only 320 by 240 resolution for faster screen painting? If one used only 320 by 240 in a window, then that would be 1/4 of the screen or less! -- Regards, Casey From tchur at optushome.com.au Tue Jan 11 23:18:51 2005 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 12 Jan 2005 15:18:51 +1100 Subject: Python.org, Website of Satan Message-ID: <200501120418.j0C4IpkA021269@mail08.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From tim.peters at gmail.com Fri Jan 7 20:09:27 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 7 Jan 2005 20:09:27 -0500 Subject: Returning same type as self for arithmetic in subclasses In-Reply-To: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> References: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> Message-ID: <1f7befae05010717095902528a@mail.gmail.com> [Max M] > """ > I subclass datetime and timedelta > > >>> dt = myDatetime(1970,1,1) > >>> type(dt) > > > >>> td = myTimedelta(hours=1) > >>> type(td) > > > But when I do arithmetic with these classes, they return datetime and > timedelta, ... > >>> new_time = dt + td > >>> new_time > datetime.datetime(1970, 1, 1, 1, 0) > > >>> type(new_time) > Yes, and all builtin Python types work that way. For example, int.__add__ or float.__add__ applied to a subclass of int or float will return an int or float; similarly for a subclass of str. This was Guido's decision, based on that an implementation of any method in a base class has no idea what requirements may exist for invoking a subclass's constructor. For example, a subclass may restrict the values of constructor arguments, or require more arguments than a base class constructor; it may permute the order of positional arguments in the base class constructor; it may even be "a feature" that a subclass constructor gives a different meaning to an argument it shares with the base class constructor. Since there isn't a way to guess, Python does a safe thing instead. > where I want them to return myDatetime and myTimedelta > > So I wondered if there was a simlpler way to coerce the result into my > desired types rather than overwriting the __add__, __sub__ etc. methods? Generally speaking, no. But I'm sure someone will torture you with a framework that purports to make it easy . From tadmc at augustmail.com Wed Jan 26 21:13:36 2005 From: tadmc at augustmail.com (Tad McClellan) Date: Wed, 26 Jan 2005 20:13:36 -0600 Subject: 20050126 find replace strings in file References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> <1106776836.679242.167880@c13g2000cwb.googlegroups.com> Message-ID: [ Followup set ] Dan Perl wrote: > I can't imagine why or how, but there are > actually 26 members in the perl-python Yahoo! group who have registered to > get these bogus lessons sent to them daily! There is one born every minute. -- Tad McClellan SGML consulting tadmc at augustmail.com Perl programming Fort Worth, Texas From harold.fellermann at upf.edu Thu Jan 13 07:45:36 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 13 Jan 2005 13:45:36 +0100 Subject: Unclear On Class Variables In-Reply-To: References: Message-ID: <0574006A-6561-11D9-B3E0-003065FB7B26@upf.edu> Hi Tim, If you have class Foo(object) : x = 0 y = 1 foo = Foo() foo.x # reads either instance or class attribute (class in this case) foo.x = val # sets an instance attribute (because foo is instance not class) Foo.x = val # sets a class attribute foo.__class.__x = val # does the same this might be sometimes confusing. IMHO, the following is especially nasty: >>> foo = Foo() >>> foo.x += 1 >>> >>> print foo.x 1 >>> print Foo.x 0 although the += operator looks like an inplace add it isn't. it is just syntactic sugar for foo.x = foo.x + 1. - harold - On 13.01.2005, at 07:18, Tim Daneliuk wrote: > I am a bit confused. I was under the impression that: > > class foo(object): > x = 0 > y = 1 > > means that x and y are variables shared by all instances of a class. > But when I run this against two instances of foo, and set the values > of x and y, they are indeed unique to the *instance* rather than the > class. > > It is late and I am probably missing the obvious. Enlightenment > appreciated ... > -- > ----------------------------------------------------------------------- > ----- > Tim Daneliuk tundra at tundraware.com > PGP Key: http://www.tundraware.com/PGP/ > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Everyone is a genius. It's just that some people are too stupid to realize it. From webmaster at smallco.com Wed Jan 19 11:40:43 2005 From: webmaster at smallco.com (Webmaster) Date: Wed, 19 Jan 2005 11:40:43 -0500 (EST) Subject: Automatic response to your mail (Error) Message-ID: The automatic reply to this e-mail which you should have received in response to your e-mail to webmaster at smallco.com has not been defined. Please contact postmaster at smallco.com for assistance. From jacek.generowicz at cern.ch Fri Jan 7 08:38:01 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Jan 2005 14:38:01 +0100 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Message-ID: "Anna" writes: > Having taken some calculus (derivatives, limits, some integrals) but > never even heard of lambda calculus, to me, lambda means absolutely > NOTHING. Less than nothing. And before you took calculus, the chances are that derivatives, limits and integrals meant less than nothing to you. But now, I am quite sure, you know that in Python lambda is a keyword which creates anonymous functions. Now that you know what lambda does, what's the problem with it? (It certainly doesn't mean "Less than nothing" to you now.) > So, I guess I don't like the word itself Fair enough. I guess there are people out there who might have a distaste for the word "class" or "def" or any of the other words which are keywords in Python. > Every other word in Python has an obvious meaning. lambda doesn't. Obvious to whom? The meaning of every word is obvious, once you have been taught it; and a complete mystery if you have not. What do you make of "seq[2:-2]"? It means "less than nothing" to the uninitiated. Just like lambda. Getting students in my Python courses to understand "seq[2:-2]" takes about as much (maybe even a bit more) effort as getting them to understand lambda[*]. But once they have been taught these features, they can handle them just fine. [*] Funnily enough, getting them to understand that "lambda x: fn(x)" is just a very silly way of writing "fn", can be quite a struggle at times ... but that's probably a consequence of the context in which lambda is introduced. From ajsiegel at optonline.net Mon Jan 31 12:11:09 2005 From: ajsiegel at optonline.net (ajsiegel at optonline.net) Date: Mon, 31 Jan 2005 12:11:09 -0500 Subject: variable declaration Message-ID: <180af5f180c303.180c303180af5f@optonline.net> MT writes - >In summary, again with all due respect and gratitude for the >spectacularly excellent product that Python is today, I wonder *why* >this strong aversion to declarative statements, and *whether* decorator >syntax constitutes a violation of it. I'd appreciate any responses or >links First be warned that I fit fairly well the profile Robert paints in the previous post on this thread - my life and livelihood do not depend on being a Python programmer. Though I would claim that my efforts to wrap my mind around it have enhanced both. Personal growth kind of thing. And I clutter this news group from time to time with observations which I admit are light on technical savy. I *can* tell you that some very bright, respected and technical members of the community argued *for* decorators on the exact grounds that Python needed to break away from its aversion to declarative statements. Someone like myself without a full grasp of the technical terminology and little grasp of the underlying structures, cannot tell you whether decorators are or are not declarative. I can observe that folks tend to get to where they want to get in these kinds of discussions by playing with the ambiguities in these kinds of words. >From an outside observer point of view, I seem to notice that in the world of programming, there seems to be more ambiguity in technical words than one would expect (or ideally like to see) in words that purport to be technical words. In short, I suspect there is a lot of semantics to be played with in answering your question. My own sense is that decorators do break a dam in Python, for better or for worse, and that it is OK to let folks provoke you into concluding for yourself what words best describe the specifics. But don't let the old hands convince you they represent business as usual. Though the authorative tone of your post indicates, I suspect, that this post was quite unnecessary. Art From c00lways at gmail.com Thu Jan 27 18:21:35 2005 From: c00lways at gmail.com (James) Date: Fri, 28 Jan 2005 07:21:35 +0800 Subject: threading and internet explorer com Message-ID: <41f9777f_2@news.tm.net.my> hi, i'm using python 2.4 with pywin32... I've tried to use internet explorer control with a class. it was fine until i decided to inherit thread for the class... class domain01(threading.Thread): def __init__(self): #blabla threading.Thread.__init__(self) def run(self): self.ie = win32com.client.Dispatch('InternetExplorer.Application.1') #this line gives error if i use .start(), but if i use .run.. no error... self.ie.Visibble = 1 print "running" xyz = domain() xyz.start() =========== this is what i get: Exception in thread Thread-23: Traceback (most recent call last): File "C:\Python24\lib\threading.py", line 442, in __bootstrap self.run() File "C:\python2exe\domain01.py", line 41, in run self.dologin() File "C:\python2exe\domain01.py", line 56, in dologin self.ie=win32com.client.Dispatch('InternetExplorer.Application.1') File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 79, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147221008, 'CoInitialize has not been called.', None, None) ===== but if i run: xyz = domain() xyz.run() ##no error! it's weird.... anyone know how to solve this problem? thank you :) best regards, James From harold.fellermann at upf.edu Mon Jan 10 12:05:46 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Mon, 10 Jan 2005 18:05:46 +0100 Subject: syntax error in eval() In-Reply-To: References: Message-ID: Thank you, Duncan and Steven. I completely forgot about setattr. Of course that's the way ... as its name might suggest *g* > What you are doing wrong is attempting to use eval before exhausting > all > the simpler techniques. Why not just call 'setattr'? > >>>> setattr(X, 'attr', 5) > > BTW, the syntax error is because eval evaluates an expression and > an assignment statement is a statement not an expression. -- Abandon the search for Truth -- settle for a good fantasy. -- From steven.bethard at gmail.com Sun Jan 16 17:48:00 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 16 Jan 2005 15:48:00 -0700 Subject: Why would I get a TypeEror? In-Reply-To: References: <34ql1vF4dqd9pU1@individual.net> Message-ID: Stian Soiland wrote: > P? 14. jan 2005 kl. 22:58 skrev Steven Bethard: > > (Any mac users? How do I fix this to appear in Norwegian? =) > >> Note that if you're not comfortable with short-circuiting behavior, >> you can also code this using lazy evaluation: >> >> (lambda: 1/x, lambda: 1.0e99)[x==0]() > > > .. and people wonder why so many Python people want to get rid of Lambda =) > Heh heh. No I don't. ;) In fact, I don't ever use lambdas in any of my own "real" code. But I don't mind being a little dirty when I post to c.l.py. ;) I guess I could have written this as: def inverse(): return 1/x def largenum(): return 1.0e99 b = (inverse, largenum)[x==0]() but I'm usually too lazy, and it's an ugly solution anyway, compared to the simple one which the OP was apparently trying to avoid: if x != 0: b = 1/x else: b = 1.0e99 =) Steve From eeykay at gmail.com Mon Jan 3 06:00:17 2005 From: eeykay at gmail.com (eeykay at gmail.com) Date: 3 Jan 2005 03:00:17 -0800 Subject: Developing Commercial Applications in Python Message-ID: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Hello All, I am trying to convince my client to use Python in his new product. He is worried about the license issues. Can somebody there to point me any good commercial applications developed using python ?. The licence clearly says Python can be used for commercial applications. Is there any other implications like that of GPL to make the source open ? Thanks for any help. eeykay From craig at postnewspapers.com.au Sat Jan 8 02:10:11 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 08 Jan 2005 15:10:11 +0800 Subject: _tkinter problem In-Reply-To: <002f01c4f54b$933fc9c0$8301a8c0@sanjay> References: <002f01c4f54b$933fc9c0$8301a8c0@sanjay> Message-ID: <1105168211.29489.1.camel@bucket.localnet> On Sat, 2005-01-08 at 14:30, Jatinder Singh wrote: > Hi > I am running a script which is importing tkinter from "/usr/local/lib/python2.3/lib-tk/Tkinter.py" and generating an error > " import _tkinter > ImportError: No module named _tkinter " > > can anybody tell me what is it? and how to get away with it? I think your question is the same problem as another recent poster - that is, you didn't have the Tcl and Tk headers installed when you installed Python. Please see my answer to "Help uninstalling/installing Python 2.4" (Yes, I know yours isn't Python 2.4 - it doesn't matter). -- Craig Ringer From sp1d3rx at gmail.com Tue Jan 11 18:18:29 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 11 Jan 2005 15:18:29 -0800 Subject: Time script help sought! In-Reply-To: References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> <1105477084.525279.312970@f14g2000cwb.googlegroups.com> <1105479292.689762.155510@f14g2000cwb.googlegroups.com> <1105480151.431987.327080@c13g2000cwb.googlegroups.com> Message-ID: <1105485509.346577.292130@f14g2000cwb.googlegroups.com> man, now that is beautifully done. Paul, I wish I knew about pyparsing a while ago. I could have used it in a few projects. :) From danperl at rogers.com Mon Jan 24 15:36:17 2005 From: danperl at rogers.com (Dan Perl) Date: Mon, 24 Jan 2005 15:36:17 -0500 Subject: Python 2.1 - 2.4 differences References: Message-ID: I'm not sure whether it's worth learning python from a book on 2.1 because of the changes that were made especially in 2.2 (see http://www.python.org/doc/2.2.1/whatsnew/, http://www.python.org/2.2.1/descrintro.html). I don't know of a specific e-book on Python although there are several good on-line tutorials. But if getting published books is difficult in your country, then I would heartily recommend Safari Books Online (http://www.safaribooksonline.com/). I have been using it for a few months and I find it to be very useful. Dan "BOOGIEMAN" wrote in message news:tcedpqix23lw$.v3p06vutw05p$.dlg at 40tude.net... >I found some e-book about Python 2.1, I want to print it but just to check > first if sintax of Python 2.1 is same as 2.4 ? Also does anybody know > where > can I download any newer Python related e-book, because there isn't any > published yet in my country. From peter at engcorp.com Sun Jan 16 21:13:12 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 16 Jan 2005 21:13:12 -0500 Subject: [perl-python] 20050115, for statement In-Reply-To: References: <1105783084.748174.307680@f14g2000cwb.googlegroups.com> Message-ID: <41EB1F38.70008@engcorp.com> Jeremy Bowers wrote: > (Hell, five days into Python and some people are already producing working > Backgammon games (I think that was the post last week), and Xah Lee here > is still on for loops! Woo! Go Xah!) Mah Jongg, actually (if we're thinking of the same post), which name is often applied in the world of computer games to a what amounts to the old game of "Concentration" (rather than the real Mah Jongg which bears no more resemblance to the computerized version than Bridge bears to Go Fish). The player merely turns over cards/tiles two at a time and any identical pairs are removed. A backgammon game, with the computer actually playing against a human and all the logic that entails, would be much more sophisticated, and rather more work. ...not to diminish the impressiveness of someone new to Python building a visually attractive GUI application in only a few days and delivering it to the web which in several ways is far more than I've contributed in over five years. ;-) (Doffs hat to the former newbie who achieved this.) -Peter From claird at lairds.us Sat Jan 15 10:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Sat, 15 Jan 2005 15:08:04 GMT Subject: reusing Tkinter Canvases References: Message-ID: In article , Sean McIlroy wrote: >I'd like to save one Tkinter Canvas in order to use it on another >Canvas later. The problem is that it gets saved as EPS but it needs to >be GIF to be reuseable. How can I convert that format? . . . There's probably a snappy answer to this, but I don't know it. There certainly are EPS -> GIF converters, if you truly want to go that way. In the Tk tradition, there are two main approaches to this need: 1. Use the Img extension, which knows how to render Canvases as .gif (and much else); 2. "Serialize" the canvas, and re-render it. Img is a venerable Tk extension, with a long, distinguished, history. It's not in the core only because of administrative issues not of interest here. It ought to work fine with Tkinter--but I know of no one who's succeeded in the attempt. From mike at hobbshouse.org Tue Jan 4 11:02:07 2005 From: mike at hobbshouse.org (Michael Hobbs) Date: Tue, 04 Jan 2005 16:02:07 -0000 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> Message-ID: <10tlffven8m3jdf@corp.supernews.com> Ville Vainio wrote: > What form of extreme dynamic behaviour have you been using lately? One real-world example: in my new coverage analysis tool (to be released any month now), I need to trace threads without changing any code. To do so, I redefine the thread.start_new_thread() function from outside the thread module, like so: orig_start_new_thread = thread.start_new_thread def traced_start_new_thread(func, args, kwargs={}): return orig_start_new_thread(traced_func_call, (func, args, kwargs)) def traced_func_call(func, args, kwargs): sys.settrace(my_trace_func) func(*args, **kwargs) thread.start_new_thread = traced_start_new_thread Granted, doing something like this on a regular basis is really bad coding style, but the ability to do something like this when I really need it is what I love about Python. From aaronwmail-usenet at yahoo.com Thu Jan 27 13:34:50 2005 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 27 Jan 2005 10:34:50 -0800 Subject: On benchmarks, heaps, priority queues In-Reply-To: References: <1106835562.598569.211370@c13g2000cwb.googlegroups.com> <1106842754.010427.74630@c13g2000cwb.googlegroups.com> <1106843673.755688.244160@f14g2000cwb.googlegroups.com> Message-ID: <1106850890.521046.11090@c13g2000cwb.googlegroups.com> re http://xsdb.sourceforge.net/bench/pq3.py Tim Peters: > If you repair that, and > instrument mixBench() to keep track of queue size statistics, you'll > find that even at 1000000, the queue at the top of the loop never > exceeds 30 entries, and has a mean size less than 3. Aha. Now that is embarrassing :(. If I fix it then I do see greater differences at sizes of 100000+. Below that, PQ0 still looks better on my machine, which I still consider weird. Thanks! -- Aaron Watters ==== War dims hope for peace -- a "real life headline" From jerf at jerf.org Sun Jan 30 22:58:36 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 30 Jan 2005 22:58:36 -0500 Subject: next line, new line References: <1107142942.626773.131980@c13g2000cwb.googlegroups.com> Message-ID: On Sun, 30 Jan 2005 19:42:22 -0800, rasdj wrote: > I have a lot of SQL to convert to postgres from oracle. I have most of the > problems worked out except for this last bit. Many of my tables need the > last comma replaced with a close parenthesis - they look like this: > > create table schema.table ( > FLD000 NUMERIC(10,0) NOT NULL, > FLD001 CHAR(3) NOT NULL, > FLD002 DATE NOT NULL, > ; > > when the syntax requires: > > FLD002 DATE NOT NULL) > ; > > I output the text in reverse thinking I could find the semicolon, go to > the next line and replace the 'comma newline' with 'closeparen newline' > and then go on to find the next semicolon. You don't give a heck of a lot of details here, but the first thing that leaps to mind is, * Suck it all into a string, let's call it "s". * s = s.replace(",\n;", ")\n;") * Dump out s. Failing that, regex can be used to allow for any whitespace, but worry about that if this isn't enough. We can also discuss trying to stream this operation if your SQL won't fit into memory all at once, but on modern machines that would be a breathtaking number of table definitions that would make me think you have other, larger problems :-) From matternc at comcast.net Thu Jan 27 15:01:12 2005 From: matternc at comcast.net (Chris Mattern) Date: Thu, 27 Jan 2005 15:01:12 -0500 Subject: [perl-python] 20050127 traverse a dir References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> Message-ID: Xah Lee wrote: > > # the above showcases a quick hack. > # File::Find is one of the worst module > # there is in Perl. One cannot use it > # with a recursive (so-called) "filter" > # function. And because the way it is > # written, one cannot make the filter > # function purely functional. (it relies > # on the $_) And the filter function > # must come in certain order. (for > # example, the above program won't work > # if g is moved to the bottom.) ... > > # the quality of modules in Perl are > # all like that. Is it just me, or is the disappointing lack of flamewars slowly ratcheting up the level of vitriol in his posts? -- Christopher Mattern "Which one you figure tracked us?" "The ugly one, sir." "...Could you be more specific?" From nelson at monkey.org Tue Jan 11 19:09:58 2005 From: nelson at monkey.org (Nelson Minar) Date: Wed, 12 Jan 2005 00:09:58 GMT Subject: XPath and XQuery in Python? Message-ID: Could someone help me get started using XPath or XQuery in Python? I'm overwhelmed by all the various options and am lacking guidance on what the simplest way to go is. What library do I need to enable three line Python programs to extract data with XPath expressions? I have this problem a lot with Python and XML. Even with Uche's excellent yearly roundups I have a hard time finding how to do fancy things with XML in Python. I think it's a bit like web server frameworks in Python - too many choices. http://www.xml.com/pub/a/2004/10/13/py-xml.html From hans at zephyrfalcon.org Sat Jan 1 16:48:20 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sat, 01 Jan 2005 16:48:20 -0500 Subject: UserDict deprecated In-Reply-To: References: Message-ID: Uwe Mayer wrote: > Why is the UserDict module is deprecated after Python 2.2. The application > of it I have in mind is, i.e. multiple inheritance from "file" and "dic" - > which is not possible. I am curious, what would you do with a class that derives from both file and dict? -- Hans Nowak http://zephyrfalcon.org/ From luisXX_lupe2XX at netvisaoXX.pt Wed Jan 19 15:02:18 2005 From: luisXX_lupe2XX at netvisaoXX.pt (Luis P. Mendes) Date: Wed, 19 Jan 2005 20:02:18 +0000 Subject: xml parsing escape characters Message-ID: <357s61F4iossjU1@individual.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I only know a little bit of xml and I'm trying to parse a xml document in order to save its elements in a file (dictionaries inside a list). When I access a url from python 2.3.3 running in Linux with the following lines: resposta = urllib.urlopen(url) xmldoc = minidom.parse(resposta) resposta.close() I get the following result: <DataSet> ~ <Order> ~ <Customer>439</Customer> (... others ...) ~ </Order> </DataSet> _____________________________________________________________ In the lines below, I try to get all the child nodes from string, first by counting them, and then ignoring the /n ones: stringNode = xmldoc.childNodes[0] print stringNode.toxml() dataSetNode = stringNode.childNodes[0] numNos = len(dataSetNode.childNodes) todosNos={} for no in range(numNos): todosNos[no] = dataSetNode.childNodes[no].toxml() posicaoXml = [no for no in todosNos.keys() if len(todosNos[no])>4] print posicaoXml (I'm almost sure there's a simpler way to do this...) _____________________________________________________________ I don't get any elements. But, if I access the same url via a browser, the result in the browser window is something like: ~ ~ ~ 439 (... others ...) ~ ~ and the lines I posted work as intended. I already browsed the web, I know it's about the escape characters, but I didn't find a simple solution for this. I tried to use LL2XML.py and unescape function with a simple replace text = text.replace("<", "<") but I had to convert the xml document to string and then I could not (or don't know) how to convert it back to xml object. How can I solve this? Please, explain it having in mind that I'm just beggining with Xml and I'm not very experienced in Python, too. Luis -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFB7rzKHn4UHCY8rB8RAhnlAKCYA6t0gd8rRDhIvZ5sdmNJlEPSeQCgteB3 XUtZ0JoHeTavBOCYi6YYnNo= =VORM -----END PGP SIGNATURE----- From asda at sdarta.com Sat Jan 8 08:00:27 2005 From: asda at sdarta.com (worzel) Date: Sat, 8 Jan 2005 21:00:27 +0800 Subject: tuples vs lists Message-ID: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> I get what the difference is between a tuple and a list, but why would I ever care about the tuple's immuutability? Also, do you say 'too-ple' or 'chu-ple' - if you get my drift. (tomato or tomato kind of thing) TIA From tzot at sil-tec.gr Fri Jan 14 08:57:48 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 14 Jan 2005 15:57:48 +0200 Subject: newbie q References: <34mgq0F4dq4buU1@individual.net> <34mku4F4c8bdkU1@individual.net> <41e7098e.782680124@news.oz.net> Message-ID: On Fri, 14 Jan 2005 00:08:09 GMT, rumours say that bokr at oz.net (Bengt Richter) might have written: >As I'm sure you know, with 2.4's generator expressions you >don't have to build the temporary list. >Which could be important if 'something' >is (or generates) a huge sequence. > > for i in (x[0] for x in something): and for some functional fun: from itertools import imap from operator import itemgetter for i in imap(itemgetter(0), something): -- 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 BOOGIEMANPN at YAHOO.COM Tue Jan 4 10:02:24 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Tue, 4 Jan 2005 16:02:24 +0100 Subject: How do I make Windows Application with Python ? References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> Message-ID: <1r9ydq5jsele7.1c45eb2jskpli.dlg@40tude.net> On Mon, 03 Jan 2005 19:56:10 -0600, Rob Emmons wrote: > I believe also if you want to use MS Visual Studio -- Active State sells > python programming tools that plug into MS Visual Studio if you want to do > that. I've not tried these so I don't know how they work or if they are > any good. Thanks all for very detailed answers. BTW I tried this one but it seems that it doesn't use VS'es visual designer. Also it doesn't have "build" option so it is basicly only usefull to higlight Python syntax. Active Sate Komodo looks like much better choice From gdamjan at gmail.com Mon Jan 24 09:43:05 2005 From: gdamjan at gmail.com (Damjan) Date: Mon, 24 Jan 2005 15:43:05 +0100 Subject: Python curses wizard Message-ID: <35kfrpF4n2odiU1@individual.net> Is there some tool that can help me design a simple curses wizards, preferably one that uses Python, but if there's some other sollution I'd be happy to hear. The important requirement is that its curses based (or similar text based UI). -- damjan From FBatista at uniFON.com.ar Tue Jan 18 10:20:59 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 18 Jan 2005 12:20:59 -0300 Subject: bind error!!!!! Message-ID: [Perrin Aybara] #- my code was working pretty well until yesterday.suddenly it started #- giving me bind error: address already in use. #- but i have logged out and again logged in, but still the #- problem is not solved #- can somebody give me solution for this Do you really think that somebody could help you with the information that you're giving? You should read this: http://www.catb.org/~esr/faqs/smart-questions.html Regards, . 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 phr at localhost.localdomain Mon Jan 24 16:27:51 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Mon, 24 Jan 2005 21:27:51 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> Message-ID: [Note: this is a 2nd attempt at posting reply to Martin's message, since the first one didn't reach the server. It's a rewrite from memory but says about the same thing as the other attempt. --Paul] "Martin v. L?wis" writes: > Paul Rubin wrote: > > If he understood how Python is actually used, he'd understand that any > > C module is a lot more useful in the core than out of it. > > This is non-sense. I have been distributing C modules outside the > core for quite some time now, and I found that the modules are quite > useful. distutils makes it really easy for anybody to use them. Maybe we're not thinking about the same problems. Say I'm an app writer and I want to use one of your modules. My development environment is GNU/Linux, and I want to ship a self-contained app that anyone can run without having to download additional components. That includes people wanting to run my app on Windows, Macintosh, Amiga, and various other Python target platforms that I don't have compilers for. How do I do it? I'm sure your modules are excellent but as an app writer, I feel I must try to avoid needing them, in favor of modules that are already in the core, even if it means more work for me or worse functionality in my app, just for the sake of reducing installation headaches for my target audience. So, if your modules are generally useful, I hope you will try to get them into the core. > > There are already tons of 3rd party crypto modules outside the > > core, and the module I was writing wouldn't add anything useful to those. > > Why do you think these are not part of the core? It's not because > they contain crypto code, or because they had been rejected. They > are primarily not included in Python because they have not been > contributed to Python, yet. I can't speak for the authors but I'd personally say that none of those old modules are really suitable for the core on technical grounds. They're too fancy and specialized, or they depend on external libraries like OpenSSL, or they're written mostly to support some specific application and don't present a simple, general-purpose interface like a core module should have. Maybe the authors felt the same way and chose not to submit them. Or maybe the authors had other reasons, such as licensing priorities that conflict with the Python license. The module I'm discussing would simply implement the FIPS standard block ciphers (AES and DES) and the FIPS operating modes. These are the basic building blocks that I feel are missing from the core. They should be enough to fill the crypto needs of most applications. > If they were contributed, a number of things still would need to > be considered, e.g. what is the size of the code, including libraries, > is the contributor really the author, is the code likely going > to be maintained, and so on. However, it never got that far. The module we're talking about wouldn't have had any of those problems. > I know that *I* am very opposed to any contribution of a larger > module that has not seen any real users, yet. We're not talking about a "larger module", we're talking about a module that implements the basic AES and DES block ciphers (similar to how the sha module implements the basic SHA-1 hash algorithm) and wraps them with some well-defined FIPS operating modes (similar to how the hmac module wraps the sha module to compute RFC 2104 hmac authentication codes). This stuff isn't rocket science. It's just straightforward implementation of modes and algorithms that go back to the 1970's, are the subject of national and international standards, and are already in use in thousands of non-Python applications all over the world. Also, I've already released a pure-Python implementation of the interface, suitable for application testing but too slow for real use. I tried rather hard to design a convenient and general interface that I feel was an improvement over PEP 272. I don't know if anyone except me is using it, but several people including Andrew (author of PEP 272) have written favorably about it based on reading the specification. The spec was designed from the beginning to fill the needs of the core. If I were writing it as a non-core module I would have included more stuff. > So if the module was primarily written to be included in the core, I > would initially reject it for that very reason. After one year or so > in its life, and a recognizable user base, inclusion can be > considered. That makes no sense; improving the core is a perfectly valid reason to write something. If someone wrote a straightforward patch that made the Python interpreter 3x faster, would you still want to wait a year before thinking about including it? I certainly believe that every contribution needs code review and user testing before entering wide release, but that doesn't seem to be what you're getting at. > I fail to see the problem you seem to have with C modules. They are > very easy to use if written properly. Well again, maybe we're not talking about the same thing, or perhaps I just need more explanation of what you mean. Suppose I want to write an "application" that tells people the SHA-1 checksum of their name. I write 3 lines of Python using the built-in sha module: import sha name = raw_input('Enter your name: ') print 'Your hash is', sha.new(name).hexdigest() I release this "app" and presto, every Python user on every OS platform can run it with no fuss. That includes CGI authors who aren't allowed to install C modules at all, without getting their hosting service to do it. How do I do the same thing if there's no built-in sha module and all I have is sha.c? To me, the whole Python notion of "batteries included" expresses precisely the idea that I'm trying to describe. Commonly-used functions belong in the core, because making people download or install them separately is a pain in the neck. From amk at amk.ca Fri Jan 21 13:04:10 2005 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 21 Jan 2005 12:04:10 -0600 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> Message-ID: On Fri, 21 Jan 2005 18:30:47 +0100, rm wrote: > Nowadays, people are trying to create binary XML, XML databases, > graphics in XML (btw, I'm quite impressed by SVG), you have XSLT, you > have XSL-FO, ... . Which is an argument in favor of XML -- it's where the activity is, so it's quite likely you'll encounter the need to know XML. Few projects use YAML, so the chance of having to know its syntactic details is small. --amk From brent.hughes at comcast.net Thu Jan 13 15:45:36 2005 From: brent.hughes at comcast.net (Brent W. Hughes) Date: Thu, 13 Jan 2005 13:45:36 -0700 Subject: Newbie: Pythonwin References: Message-ID: Thanks guys! That helps a lot. Brent From roy at panix.com Fri Jan 7 23:08:08 2005 From: roy at panix.com (Roy Smith) Date: Fri, 07 Jan 2005 23:08:08 -0500 Subject: Securing a future for anonymous functions in Python References: <7xvfa90w6g.fsf@ruckus.brouhaha.com> Message-ID: In article , James Stroud wrote: > On Friday 07 January 2005 01:24 pm, Paul Rubin wrote: > > Nick Coghlan writes: > > > Add in the fact that there are many, many Python programmers with > > > non-CS backgrounds, and the term 'lambda' sticks out like a sore thumb > > > from amongst Python's other English-based keywords. > > > > Richard Feynman told a story about being on a review committee for > > some grade-school science textbooks. One of these book said something > > about "counting numbers" and it took him a while to figure out that > > this was a new term for what he'd been used to calling "integers". > > > I think we should not try too hard to make everything "English" like. Its a > crappy language anyway (though its the only one I speak good). Matt Neuberg, > in _AppleScript: The Definitive Guide_, refers to "the English-likeness > monster". His example is that instead of > > x = 4 > > you have to say > > copy 4 to x The syntax was taken directly from HyperCard. From fuzzyman at gmail.com Thu Jan 6 19:16:34 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 6 Jan 2005 16:16:34 -0800 Subject: Python Operating System??? In-Reply-To: <10trb0mgiflcj4f@corp.supernews.com> References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <1105056994.107116.216480@f14g2000cwb.googlegroups.com> The bootloader would have to be a 'python-core'. Ideally a fast implementation of just the python syntax and language features. Now *that* would be an excellent basis for a restricted mode python interpreter - which could make 'python applets' closer to a reality. It would also make python for embedded systems and embedding python in larger programs easier as well. A purely 'core language' implementation with no libraries..... Obviously you'd need file systems, drivers, and something to create the functionality of the os and sys libraries. Basing it on the existing Linux kernel would seem like a much more sensible idea.... There is/was a project (Peter Hansen ?) to produce a pure python file system. that could be an interesting component. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml David Brown wrote: > Hello. I recently came across a free operating system called Unununium (or > something like that) and it was developed in Python and Assembly. > > Now, I have been looking for a way to make an operating system for a long > long time and the only possibilities I could find were C++ and assembly. I > don't mind assembly so much if I don't have to use it very often. But C++ is > so complicated and errors are pretty much impossible to find in the code for > me. > > So, I was wondering if it would be possible to find a bootloader that loads > a python file at startup or something... > > Is there an example somewhere of a Python OS? > > Thanks! From mfinder at digipen.edu Fri Jan 21 11:44:37 2005 From: mfinder at digipen.edu (M Jared Finder) Date: Fri, 21 Jan 2005 08:44:37 -0800 Subject: how to write a tutorial In-Reply-To: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: <35cprlF4hhav6U1@individual.net> Xah Lee wrote: > i've started to read python tutorial recently. > http://python.org/doc/2.3.4/tut/tut.html What does this have to do with Perl, Lisp, Scheme, or C? -- MJF From belred at gmail.com Mon Jan 31 01:53:40 2005 From: belred at gmail.com (Bryan) Date: Sun, 30 Jan 2005 22:53:40 -0800 Subject: Regarding exception handling In-Reply-To: References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> Message-ID: <41FDD5F4.8030507@gmail.com> Dan Perl wrote: > "Bryan" wrote in message > news:mailman.1614.1107137827.22381.python-list at python.org... > >>IMO, that is not the reason for the try/finally statement and it is not >>redundant. the try/finally statement guarantees the resource is closed >>and the try/finally statement only gets executed if and only if the >>opening of the resource doesn't raise an exception. it has nothing to do >>with exception handling. > > > But IMO, try-finally is meant to be used only if the block in the try clause > may raise exceptions. Here is an example that shows what I meant: > s = ... # socket opens > try: > a = 1 > finally: > s.close() > > works perfectly the same as: > s = ... # socket opens > a = 1 > s.close() > the above is not the same. make the a = ... raise an exception and you'll see the difference. s = ... # a = 1/0 s.close() as you can see, s.close() will never be called. also, in this example, i intentionally didn't put the extra try/except around the try/finally statement. usually i let an exception caused by s = ... to bubble up to some level that knows how to handle that error. we are talking about a resource here and in my experience, these low level functions (below the UI or management layer) don't know how to or shouldn't handle resources that can't be opened. bryan > The try-finally statement does not "handle" the exception, but it makes > sense only if exceptions are possible. There is no point in enclosing "a = > 1" in any kind of try statement. > > According to a following posting from Angelos he did expect some other > exceptions than socket.error and hence the nested try's. To my defence > though, I put in a disclaimer for that case in my initial posting. > > >>in the previous 2 examples s = ... was placed inside the try/finally, but >>if an exception occures and s doesn't get bound to an object, then >>s.close() in both examples will raise a NameError on s. > > > That is a very good point. I missed it. > > Dan > > From davorss at gmail.com Wed Jan 26 21:55:49 2005 From: davorss at gmail.com (Davor) Date: Wed, 26 Jan 2005 21:55:49 -0500 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> Message-ID: Timo Virkkala wrote: > This guy has got to be a troll. No other way to understand. not really - it was not my intention at all - but it seems people get upset whenever this OO stuff is mentioned - and what I did not expect at all at this forum as I believed Python people should not be so OO hardcore (seems not all as quite a few have indicated in their replies)... Nevertheless, I think the discussion has several quite good points! From sbryce at scottbryce.com Mon Jan 10 00:11:58 2005 From: sbryce at scottbryce.com (Scott Bryce) Date: Sun, 09 Jan 2005 22:11:58 -0700 Subject: a new Perl/Python a day In-Reply-To: References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: Bob Smith wrote: > Scott Bryce wrote: > >> Xah Lee wrote: >> >>> frustrated constantly by its inanities and incompetences.) >> >> >> I don't see what this has to do with Perl. > > > You're joking, right? No. Perl may have some interesting idiosyncrasies, especially for a programmer with little or no Unix experience, but I find it neither frustrating, inane nor incompetent. The more I use it, the more I like it. From steve at holdenweb.com Sun Jan 9 10:59:59 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 10:59:59 -0500 Subject: Python3: on removing map, reduce, filter In-Reply-To: <34csn1F4a46hqU1@individual.net> References: <34csn1F4a46hqU1@individual.net> Message-ID: <5CcEd.70344$Jk5.19962@lakeread01> Andrey Tatarinov wrote: > Hi. > > How does GvR suggestions on removing map(), reduce(), filter() correlate > with the following that he wrote himself (afaik): > > http://www.python.org/doc/essays/list2str.html > > ? It promotes the sensible realization that when optimization is the goal code may well tend to get ugly, sometimes uglier than necessary. Note that the first version is completely straightforward and comprehensible. And note that the summary in the conclusiogn BEGINS with "Rule number one: only optimize when there is a proven speed bottleneck", which seems to adequately imply that straightforward code is to be preferred unless speed requirements override that. 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 fredrik at pythonware.com Mon Jan 31 11:05:54 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 17:05:54 +0100 Subject: import doesn't work as i want References: <41fe5438$0$18865$8fcfb975@news.wanadoo.fr> Message-ID: Olivier Noblanc wrote: > In the botom of this post you will see my source code. > > The problem is when i launch main.py that doesn't make anything why ? the "if __name__" statement checks the name of the module. if you run Python file as a script, by passing a filename to the python interpreter, the __name__ variable is set to "__main__". if you import a file as a module, the __name__ is the name of the module, not "__main__". if you want main.py to do something, move that code to main.py (or move it into a function, and call it from main.py) From ncoghlan at iinet.net.au Mon Jan 10 05:16:43 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 10 Jan 2005 20:16:43 +1000 Subject: static compiled python modules In-Reply-To: <87u0pqn5pz.fsf@dev.null.daemon.de> References: <87u0pqn5pz.fsf@dev.null.daemon.de> Message-ID: <41E2560B.2040908@iinet.net.au> Thomas Linden wrote: > How can I tell python to use the compiled in modules and not try to > load them from outside? http://www.python.org/dev/doc/devel/api/importing.html Take a look at the last three entries about registering builtin modules. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jbperez808 at wahoo.com Sat Jan 15 04:21:29 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Sat, 15 Jan 2005 17:21:29 +0800 Subject: Integration with java (Jpype vs. JPE) In-Reply-To: References: Message-ID: <34s5krF4c85d5U1@individual.net> Can someone summarize in a nutshell what is the difference between JPype and JPE? From jonasgalvez at gmail.com Thu Jan 20 12:24:32 2005 From: jonasgalvez at gmail.com (Jonas Galvez) Date: Thu, 20 Jan 2005 15:24:32 -0200 Subject: What YAML engine do you use? In-Reply-To: <35a7grF4jjrcsU1@individual.net> References: <35a6tpF4gmat2U1@individual.net> <35a7grF4jjrcsU1@individual.net> Message-ID: <7c60b60505012009243f72944@mail.gmail.com> Diez B. Roggisch wrote: > I first used yaml, tried to migrate to syck. What I like about > syck is that it is faster and doesn't try to create objects but > only dicts - but it crashed if the number of yaml objects grew > larger. So I still use yaml. Hmm.. I've never had any problems with syck. In fact, I'm using it in a small project now where I store a helluva of data in yaml files... Strange. From cepl at surfbest.net Sat Jan 1 14:58:09 2005 From: cepl at surfbest.net (cepl at surfbest.net) Date: 1 Jan 2005 11:58:09 -0800 Subject: Python equivalent of script(1) In-Reply-To: <87d5wprla1.fsf@thomas.local> References: <1104607982.132310.181560@c13g2000cwb.googlegroups.com> <87d5wprla1.fsf@thomas.local> Message-ID: <1104609489.059828.296610@c13g2000cwb.googlegroups.com> Thanks a lot. From invalidemail at aerojockey.com Tue Jan 4 19:52:41 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 4 Jan 2005 16:52:41 -0800 Subject: Optional Static Typing: Part II In-Reply-To: <10tluavnqqufg07@news.supernews.com> References: <10tluavnqqufg07@news.supernews.com> Message-ID: <1104886361.160069.315210@z14g2000cwz.googlegroups.com> John Roth wrote: > http://www.artima.com/weblogs/viewpost.jsp?thread=86641 Nitpicking: I don't think he's necessarily in good company w.r.t. types vs classes. Take Ada, for example. In Ada, a class is a set of types (in particular, the type and all its subtypes), which is kind of the opposite way Guido claims to see it. Not the Ada is relevant, and not that there is ever any agreement on terminology in computer science, but still. Based on their English language meanings, I would tend to agree with Ada's terminology. But, based on how the terminology developed for computer languages (especially under the influence of C++), it seems that most people would regard class as more of an implementation. Another question: can anyone think of something an interface statement could syntactically that an interface metaclass couldn't? I couldn't think of anything, based on the description, and it's not like th BDFL to throw out keywords for things that current syntax can handle. It leads me to suspect that maybe he has something up his sleeve. Hmm. -- CARL BANKS From dmerrillq at usaq.netq Sat Jan 8 15:23:52 2005 From: dmerrillq at usaq.netq (Dave Merrill) Date: Sat, 8 Jan 2005 15:23:52 -0500 Subject: Installing IPython on win2k References: <1105213017.820231.67050@c13g2000cwb.googlegroups.com> Message-ID: "Tim G" wrote in message news:1105213017.820231.67050 at c13g2000cwb.googlegroups.com... > Dave Merrill wrote: > > Hi, I'm new to python, and ipython, but not to programming, having > trouble > > getting ipython installed on windows 2000, python 233. Any help would > be > > much appreciated; I'm sure I'm being some basic flavor of dense... > > First of all, rest assured that it does work (and quite > easily) so welcome to Python and iPython and I hope > the going's a bit smoother as you go along. I'm having fun with python itself, but feeling a little constrained in the IDE and debugger departments. (Not to mention the clues I haven't got...). > > Then downloaded ipython-0.6.6.zip and unzipped it. When I > double-click > > setup.py, I get only a brief wait cursor; nothing else happens, and > > importing ipython as a test fails. > > First of all, ipython isn't really an import into python; you run > it and it runs python (if you understand me). So when you've > installed it, I think it puts an item on your start menu. On > linux, it puts an executable ipython onto your path. > > I've just downloaded and run the setup.py, and it does > create a Start Menu item which will start iPython. Look > out for that and see if it does the business. Removed the files I'd unzipped and started over, putting a fresh unzip in Program Files. Ran setup.py while watching the windows task list, and pythonw ran for just a second, then disappeared. I saw no other signs of anything running, and there's no shortcut for ipython in my start menu. > > Both files in the scripts dir, ipython and pycolor, have no filename > > extension, which seems odd to my newbie eye. I tried renaming them to > .py, > > still no difference. > > This is a unixism. Some unix types decry the use of file extensions > because the information the extension gives -- which executable > program to use -- is already embedded in the first line of a file. So what do I do to try ipython directly, bypassing the shortcut (since I can make my own later)? I tried right-click on scripts/ipython, Open With, and chose python, but got only a quick DOS window. Now what? Thanks, Dave Merrill From rasdj at frontiernet.net Sun Jan 30 22:42:22 2005 From: rasdj at frontiernet.net (rasdj at frontiernet.net) Date: 30 Jan 2005 19:42:22 -0800 Subject: next line, new line Message-ID: <1107142942.626773.131980@c13g2000cwb.googlegroups.com> I have a lot of SQL to convert to postgres from oracle. I have most of the problems worked out except for this last bit. Many of my tables need the last comma replaced with a close parenthesis - they look like this: create table schema.table ( FLD000 NUMERIC(10,0) NOT NULL, FLD001 CHAR(3) NOT NULL, FLD002 DATE NOT NULL, ; when the syntax requires: FLD002 DATE NOT NULL) ; I output the text in reverse thinking I could find the semicolon, go to the next line and replace the 'comma newline' with 'closeparen newline' and then go on to find the next semicolon. ; FLD002 DATE NOT NULL, FLD001 CHAR(3) NOT NULL, FLD000 NUMERIC(10,0) NOT NULL, create table schema.table ( ; FLD002 DATE NOT NULL, FLD001 CHAR(3) NOT NULL, FLD000 NUMERIC(10,0) NOT NULL, create table schema.table2 ( I don't seem to be making any progress altho I have had some interesting output. Throw me a bone? Thank you, RasDJ From newsgroups at jhrothjr.com Tue Jan 4 15:15:06 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 4 Jan 2005 14:15:06 -0600 Subject: Optional Static Typing: Part II Message-ID: <10tluavnqqufg07@news.supernews.com> Guido has posted a second blog entry on the optional static typing initiative. I like this a lot better than the first. http://www.artima.com/weblogs/viewpost.jsp?thread=86641 Now, the base objective seems to be to incorporate PyChecker functionality into the root. This in turn requires type inference, which in turn strongly suggests type annotations to help the inferencer out over rough spots. I like this approach a lot. There's also an explicit recognition that there are a lot of use cases for being able to access type information at run time. I also like this. I'm kind of neutral to the idea of using it for actual type checking: I don't think that it catches that many errors if the developer is doing a decent job of testing. However, since it's going to be supplemental to type inference, it will be a lot less intrusive. There's a new approach to interfaces that looks intriguing. One nice part is the ability to include Design By Contract type preconditions with the interface. It will be even better if they can be checked at compile time, or by the PyChecker functionality. I have to say this turned my attitude around on the subject: I'm quite in favor of the direction Guido seems to be going. John Roth From http Wed Jan 5 06:53:29 2005 From: http (Paul Rubin) Date: 05 Jan 2005 03:53:29 -0800 Subject: Python evolution: Unease References: Message-ID: <7xvfac6qiu.fsf@ruckus.brouhaha.com> "EP" writes: > Python: it tastes so good it makes you hungrier. QOTW From philippe at philippecmartin.com Tue Jan 18 16:19:52 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 18 Jan 2005 21:19:52 GMT Subject: Tkinter in thread hangs on windows but not on Linux References: <1106080941.235008.296640@c13g2000cwb.googlegroups.com> Message-ID: Well this is what is on the top of my script: from Tkinter import * import threading from ScrolledText import * I still hang under XP .... wish I had 2K to test. I almost sounds like tkinter does not get refresh events anymore. I'll keep at it On Tue, 18 Jan 2005 12:42:21 -0800, Kamilche wrote: > This example worked for me on Windows 2000, after inserting > > import threading > from Tkinter import * > import ScrolledText > > > at the top. From tadmc at augustmail.com Mon Jan 17 23:53:14 2005 From: tadmc at augustmail.com (Tad McClellan) Date: Mon, 17 Jan 2005 22:53:14 -0600 Subject: [perl-python] 20050117, filter, map References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: Erik Max Francis wrote: > Steven Bethard wrote: > >> Is there any chance you could post these all as part of the same thread? >> That would be really nice for those of us who aren't interested -- >> then we could just ignore the thread... > > Or, better yet, not posting it at all. He's got his mailing list, what > does he need to post it here for? There isn't much point in trolling if you don't have an audience. -- Tad McClellan SGML consulting tadmc at augustmail.com Perl programming Fort Worth, Texas From martin at v.loewis.de Thu Jan 20 15:57:52 2005 From: martin at v.loewis.de (=?ISO-8859-2?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 20 Jan 2005 21:57:52 +0100 Subject: ElementTree cannot parse UTF-8 Unicode? In-Reply-To: References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106230846.455765.7310@c13g2000cwb.googlegroups.com> <1106233137.588111.216480@z14g2000cwz.googlegroups.com> Message-ID: <41F01B50.8030107@v.loewis.de> Jarek Zgoda wrote: >> So why are there non-UNICODE versions of wxPython??? To save memory or >> something??? > > > Win95, Win98, WinME have problems with unicode. This problem can be solved - on W9x, wxPython would have to pass all Unicode strings to WideCharToMultiByte, using CP_ACP, and then pass the result to the API function. Regards, Martin From tzot at sil-tec.gr Tue Jan 25 17:14:08 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 26 Jan 2005 00:14:08 +0200 Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: On Sun, 23 Jan 2005 12:28:12 -0500, rumours say that Hans Nowak might have written: >Xah Lee wrote: >> the first paragraph of 9.1 "A Word About Terminology" is epitome of >> masturbation. The entire 9.1 is not necessary. >> >> Large part of 9.2 "Python Scopes and Name Spaces" is again >> masturbatory. > >So I can just take a copy of the tutorial to the bathroom next time. >Thanks for the tip, man! The first day I (got) laid my eyes on the Python tutorial, I knew the days of "Pyboy", "Pythouse" and "Python 10" were over. I'm glad that finally others, too, really grok the "joy of Python programming". PS I just *love* the Classes chapter centerfold. All-time classic. -- 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 claird at lairds.us Tue Jan 25 18:08:06 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 25 Jan 2005 23:08:06 GMT Subject: Another scripting language implemented into Python itself? References: Message-ID: <0juic2-68k.ln1@lairds.us> In article , Terry Reedy wrote: . . . >worrying about Python security seems superfluous. Why worry, for instance, >about os.unlink when the user can just do the same much easier in a text or >gui shell? . . . It's an apt question--and one with several answers. I'll hint at the range by observing that part of security has to do with prevention not of malicious acts, but of common mistakes. I entirely agree with you that it's crucial to think of wider context, and whether a particular choice's costs are worth its benefits. From http Thu Jan 6 17:21:28 2005 From: http (Paul Rubin) Date: 06 Jan 2005 14:21:28 -0800 Subject: Embedding a restricted python interpreter References: <345mkrF46jc4cU1@individual.net> Message-ID: <7xvfaaurkn.fsf@ruckus.brouhaha.com> Peter Maas writes: > I think PHP has a safe mode which solves the probem of isolating > scripts of different users on application level. This is not optimal > but better than nothing. Best solution would probably be to create > a thread for each request that can operate only with the id of an > authenticated user. But this seems to be a problem with Apache or > with Linux? Threads wouldn't do it--you'd need separate processes. For example, multiple threads in the same process can access each other's file descriptors. From http Tue Jan 11 21:18:53 2005 From: http (Paul Rubin) Date: 11 Jan 2005 18:18:53 -0800 Subject: Help Optimizing Word Search References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: <7xacrfl78y.fsf@ruckus.brouhaha.com> "Case Nelson" writes: > Basically, the program needs to take in a random list of no more than > 10 letters, and find all possible mutations that match a word in my > dictionary (80k words). However a wildcard letter '?' is also an > acceptable character which increases the worst case time significantly. For that size pattern and dictionary, simply compiling the pattern to a regexp, joining the dictionary together into one big string ("abc def ghijk..."), and matching the regexp against the big string, may well be faster than using some fancy algorithm coded completely in python. From jeff at ccvcorp.com Thu Jan 27 14:34:31 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 27 Jan 2005 11:34:31 -0800 Subject: String Fomat Conversion In-Reply-To: References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Message-ID: <10vig6ss9gigc60@corp.supernews.com> Stephen Thorne wrote: > On Thu, 27 Jan 2005 00:02:45 -0700, Steven Bethard > wrote: > >>By using the iterator instead of readlines, I read only one line from >>the file into memory at once, instead of all of them. This may or may >>not matter depending on the size of your files, but using iterators is >>generally more scalable, though of course it's not always possible. > > I just did a teensy test. All three options used exactly the same > amount of total memory. I would presume that, for a small file, the entire contents of the file will be sucked into the read buffer implemented by the underlying C file library. An iterator will only really save memory consumption when the file size is greater than that buffer's size. Actually, now that I think of it, there's probably another copy of the data at Python level. For readlines(), that copy is the list object itself. For iter and iter.next(), it's in the iterator's read-ahead buffer. So perhaps memory savings will occur when *that* buffer size is exceeded. It's also quite possible that both buffers are the same size... Anyhow, I'm sure that the fact that they use the same size for your test is a reflection of buffering. The next question is, which provides the most *conceptual* simplicity? (The answer to that one, I think, depends on how your brain happens to see things...) Jeff Shannon Technician/Programmer Credit International From ncoghlan at iinet.net.au Mon Jan 31 05:15:42 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 31 Jan 2005 20:15:42 +1000 Subject: Nested scopes and class variables In-Reply-To: References: Message-ID: <41FE054E.5000907@iinet.net.au> Dave Benjamin wrote: > I ran into an odd little edge case while experimenting with functions that > create classes on the fly (don't ask me why): It gets even kookier: Py> x = 5 Py> def f(y): ... class C(object): ... x = x ... print C.x ... Py> f(5) # OK with x bound at global 5 Py> def f(x): ... class C(object): ... x = x ... print C.x ... Py> f(6) # Oops, ignores the argument! 5 Py> def f(y): ... class C(object): ... x = y ... print C.x ... Py> f(6) # OK with a different name 6 Py> y = 5 Py> def f(y): ... class C(object): ... x = y ... print C.x ... Py> f(6) # Correctly use the nearest scope 6 That second case is the disturbing one - the class definition has silently picked up the *global* binding of x, whereas the programmer presumably meant the function argument. With a nested function definition (instead of a class definition), notice that *both* of the first two cases will generate an UnboundLocalError. Anyway, the Python builtin disassembler is very handy when looking at behaviour like this (I've truncated the dis output below after the interesting section): Py> import dis Py> def f1(x): ... class C(object): ... x = x ... print C.x ... Py> def f2(y): ... class C(object): ... x = y ... print C.x ... Py> dis.dis(f1) 2 0 LOAD_CONST 1 ('C') 3 LOAD_GLOBAL 0 (object) 6 BUILD_TUPLE 1 9 LOAD_CONST 2 (", line 2>) [...] Py> dis.dis(f2) 2 0 LOAD_CONST 1 ('C') 3 LOAD_GLOBAL 0 (object) 6 BUILD_TUPLE 1 9 LOAD_CLOSURE 0 (y) 12 LOAD_CONST 2 (", line 2>) [...] Notice the extra LOAD_CLOSURE call in the second version of the code. What if we define a function instead of a class?: Py> def f3(x): ... def f(): ... x = x ... print x ... f() ... Py> def f4(y): ... def f(): ... x = y ... print x ... f() ... Py> dis.dis(f3) 2 0 LOAD_CONST 1 (", line 2>) [...] Py> dis.dis(f4) 2 0 LOAD_CLOSURE 0 (y) 3 LOAD_CONST 1 (", line 2>) [...] Again, we have the extra load closure call. So why does the function version give us an unbound local error, while the class version doesn't?. Again, we look at the bytecode - this time of the corresponding internal code objects: Py> dis.dis(f1.func_code.co_consts[2]) 2 0 LOAD_GLOBAL 0 (__name__) 3 STORE_NAME 1 (__module__) 3 6 LOAD_NAME 2 (x) 9 STORE_NAME 2 (x) 12 LOAD_LOCALS 13 RETURN_VALUE Py> dis.dis(f3.func_code.co_consts[1]) 3 0 LOAD_FAST 0 (x) 3 STORE_FAST 0 (x) 4 6 LOAD_FAST 0 (x) 9 PRINT_ITEM 10 PRINT_NEWLINE 11 LOAD_CONST 0 (None) 14 RETURN_VALUE In this case, it's the LOAD_FAST opcode that blows up, while the LOAD_NAME falls back on the globals and then the builtins. Looking at the class based version that works also lets us see why: Py> dis.dis(f2.func_code.co_consts[2]) 2 0 LOAD_GLOBAL 0 (__name__) 3 STORE_NAME 1 (__module__) 3 6 LOAD_DEREF 0 (y) 9 STORE_NAME 3 (x) 12 LOAD_LOCALS 13 RETURN_VALUE Here we can see the "LOAD_DEREF" instead of the "LOAD_NAME" that was present in the version where the same name is reused. The dereference presumably picks up the closure noted earlier. I vote bug. If the assignment is going to be allowed, it should respect the nested scopes. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From bill.mill at gmail.com Wed Jan 19 16:16:40 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 19 Jan 2005 16:16:40 -0500 Subject: a question In-Reply-To: References: <797fe3d405011912511a609c1c@mail.gmail.com> Message-ID: <797fe3d405011913161812785@mail.gmail.com> You are correct, sir. Didn't know you could do that. Neato. Peace Bill Mill bill.mill at gmail.com On Wed, 19 Jan 2005 22:10:05 +0100, Fredrik Lundh wrote: > Bill Mill wrote: > > > You've got a couple problems. First, you need to end the string before > > putting a continuation in. > > >>> "no\ > ... pe" > 'nope' > > >>> "however\ > File "", line 1 > "however\ > ^ > SyntaxError: EOL while scanning single-quoted string > > (in the second case, the ^ is trying to point out that I added > some whitespace after the backslash) > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From aleaxit at yahoo.com Thu Jan 27 08:39:57 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Jan 2005 14:39:57 +0100 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <10vdt2bpr0m84db@corp.supernews.com> <200501262039.23260.francis.girard@free.fr> <1993411a01509c62cae1715b62fe16f5@gmail.com> <200501262135.30872.francis.girard@free.fr> Message-ID: <1gr1xu0.nco4on13ibk3dN%aleaxit@yahoo.com> PA wrote: > Yes. But even with the "best" tool and the "best" intents, projects > still fail. In fact, most IT projects are considered failures: > > http://www.economist.com/business/PrinterFriendly.cfm?Story_ID=3423238 The main thesis of the article you quote (although it acknowledges that other think differently) is that better tools (including iterative, NOT waterfall, development; and, agile programming approaches, more generally) are the way to mitigate that horrid track record. Alex From bokr at oz.net Thu Jan 13 19:55:08 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 14 Jan 2005 00:55:08 GMT Subject: finding/replacing a long binary pattern in a .bin file References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> <41e6293f.725257715@news.oz.net> <10udjc3fmnhro9d@corp.supernews.com> Message-ID: <41e70dbd.783751855@news.oz.net> On Thu, 13 Jan 2005 11:40:52 -0800, Jeff Shannon wrote: >Bengt Richter wrote: > >> BTW, I'm sure you could write a generator that would take a file name >> and oldbinstring and newbinstring as arguments, and read and yield nice >> os-file-system-friendly disk-sector-multiple chunks, so you could write >> >> fout = open('mynewbinfile', 'wb') >> for buf in updated_file_stream('myoldbinfile','rb', oldbinstring, newbinstring): >> fout.write(buf) >> fout.close() > >What happens when the bytes to be replaced are broken across a block >boundary? ISTM that neither half would be recognized.... That was part of the exercise ;-) (Hint: use str.find to find unbroken oldbinstrings in current inputbuffer and buffer out safe changes, then when find fails, delete the safely used front of the input buffer, and append another chunk from the input file. Repeat until last chunk has been appended and find finds no more. Then buffer out the tail of the input buffer (if any) that then won't have an oldbinstring to change). > >I believe that this requires either reading the entire file into >memory, to scan all at once, or else conditionally matching an >arbitrary fragment of the end of a block against the beginning of the >oldbinstring... Given that the file in question is only a few tens of >kbytes, I'd think that doing it in one gulp is simpler. (For a large >file, chunking it might be necessary, though...) It's certainly simpler to do it in one gulp, but it's not really hard to do it in chunks. You just have to make sure your input buffer/chunksize is/are larger than oldbinstring ;-) Regards, Bengt Richter From dave at pythonapocrypha.com Tue Jan 4 15:41:55 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 04 Jan 2005 13:41:55 -0700 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> Message-ID: <41DAFF93.7030502@pythonapocrypha.com> Roman Suzi wrote: > On Tue, 4 Jan 2005, Dave Brueck wrote: > > >>>It may be optional in the sense that the language will >>>accept missing declarations but as soon as the feature >>>is available it will become "mandatory" to use it >>>(peer pressure, workplace practices). > > > What about generic programming coming into fashion anytime soon? Roman, I think I've read every single thread in the past year or three wherein you've brought up generic programming, and I think you'd do well to choose a new term for the idea you're trying to convey. The term "generic programming" is too... er... generic. :) As you know, Python already includes a _lot_ of support for generic programming (a function that iterates over a sequence can easily process a list, or a string, or a tuple as input; a function that takes a file-like object can often work just as will with a true file object or a cStringIO object; etc.). So when you bring up "generic programming", it's too easy to dismiss the comment because (1) it's too vague and (2) Python already does a lot of it. So, what is your term for the type of generic programming that Python doesn't yet support? Interfaces? Protocols? Adapters? Metatype hierarchies? -Dave From rkern at ucsd.edu Thu Jan 13 15:43:36 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 13 Jan 2005 12:43:36 -0800 Subject: News Reader In-Reply-To: References: Message-ID: Robert Kern wrote: > Daniel Bowett wrote: > >> Is anyone reading this list through thunderbird as news? If so - how >> did you set it up? > > > I subscribed to comp.lang.python under my USENET news server account. I guess I should add that that's all I did. There's nothing special to set up. -- 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 shoot at the.moon Sat Jan 8 09:36:09 2005 From: shoot at the.moon (Steve Horsley) Date: Sat, 08 Jan 2005 14:36:09 +0000 Subject: tuples vs lists In-Reply-To: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: worzel wrote: > I get what the difference is between a tuple and a list, but why would I > ever care about the tuple's immuutability? Mainly for security and speed. Many library functions return info by returning a reference to an internally held tuple, and could be damaged / compromised / corrupted if that internal data was modified by malicious code. If tuples were mutable (lists) then it would be necessary to return a copy instead. > Also, do you say 'too-ple' or 'chu-ple' - if you get my drift. (tomato or > tomato kind of thing) Try 'Two-pull'. Steve From exarkun at divmod.com Sat Jan 1 22:36:22 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 02 Jan 2005 03:36:22 GMT Subject: PEP 288 ponderings In-Reply-To: Message-ID: <20050102033622.26823.987540620.divmod.quotient.806@ohm> On Sun, 02 Jan 2005 01:04:06 GMT, Steven Bethard wrote: >PEP 288 was mentioned in one of the lambda threads and so I ended up > reading it for the first time recently. I definitely don't like the > idea of a magical __self__ variable that isn't declared anywhere. It > also seemed to me like generator attributes don't really solve the > problem very cleanly. An example from the PEP[1]: > > [snip] You may be interested in greenlets. They solve this problem in a way which is conceptually much simpler and cleaner. They are available as a third party extension, and unfortunately are not terribly well documented yet (but luckily they are quite simple). http://codespeak.net/svn/user/arigo/greenlet/ Jp From rbt at athop1.ath.vt.edu Mon Jan 10 15:49:54 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 10 Jan 2005 15:49:54 -0500 Subject: exceptions and items in a list Message-ID: If I have a Python list that I'm iterating over and one of the objects in the list raises an exception and I have code like this: try: do something to object in list except Exception: pass Does the code just skip the bad object and continue with the other objects in the list, or does it stop? Thanks From dbickett at gmail.com Sun Jan 2 23:19:57 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 2 Jan 2005 23:19:57 -0500 Subject: Problem remotely shutting down a windows computer with python In-Reply-To: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> References: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> Message-ID: <1d6cdae305010220191567dc84@mail.gmail.com> While I have no solution for the recipe you cited, it seems like alot of trouble could be avoided by simply importing the os module and running the following command using os.system: shutdown -s Daniel Bickett On 2 Jan 2005 20:13:35 -0800, EW wrote: > I have a problem when using the python script found here: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/360649 > > It is a script to remotely shutdown a windows computer. When I use it, > the computer shuts down, but doesn't power off like with a regular > shutdown. It stays on the "Safe to power off" screen and I have to push > the power button to actually power off. Anyone know why this happens > with this script? Thanks for any help. > > Eric > > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at holdenweb.com Mon Jan 10 05:35:27 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Jan 2005 05:35:27 -0500 Subject: 20050119: quoting strings In-Reply-To: <1105346247.031739.36550@c13g2000cwb.googlegroups.com> References: <1105346247.031739.36550@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > #strings are enclosed in double quotes quotes. e.g. > a="this and that" > print a > > #multiple lines must have an escape backslash at the end: > b="this\n\ > and that" > print b > > #One can use r"" for raw string. > c=r"this\n\ > and that" > print c > > #To avoid the backslash escape, one can use triple double quotes to > print as it is: > d="""this > and > that""" > print d > > --------------- > # in Perl, strings in double quotes acts as Python's triple """. > # String is single quote is like Python's raw r"". > # Alternatively, they can be done as qq() or q() respectively, > #and the bracket can be just about any character, > # matching or not. (so that escapes can be easy avoided) > > $a=q(here, everthing is literal, $what or \n or what not.); > $b=qq[this is > what ever including variables $a that will be > evaluated, and "quotes" needn't be quoted.]; > print "$a\n$b"; > > #to see more about perl strings, do on shell prompt > #perldoc -tf qq > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html > Well, that gets that sorted out, then. Tomorrow: using single quotes. Using single quotes. The larch. 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 http Fri Jan 28 23:16:35 2005 From: http (Paul Rubin) Date: 28 Jan 2005 20:16:35 -0800 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Message-ID: <7xu0p0yin0.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > After my original flippant reply, I've been thinking some more about > this, and whether CPython can really benefit from initial notification > of a security flaw going privately to the developers first. > > And, due to CPython's release model, I really don't think it can. > > Upgrading your Python interpreter (even to a new maintenance branch > release) in a production environment is usually a fairly involved > exercise requiring a significant amount of testing, and the fact of That's true of any production environment, and yet if there's a serious flaw, you absolutely have to do it. > So, for CPython, the window of vulnerability is driven mainly by the > time to when application developers, system administrators and end > users get around to upgrading, not by the time to when a patched > version is released. No. If you're running a production system you have to stay on top of security patches and install them ASAP. If a vulnerability is bad enough, you have to close down your service until you're done installing the fix. If it takes 72 hours for the developers to make a patch, and 8 hours for you to install the patch once it's announced, then your exposure to attackers who learn of the bug from the announcement is 10 times smaller if the bug and patch are announced simultaneously than if the bug is announced immediately and the patch is released 72 hours later. > More significantly, any security problem is likely to be with a > specific function or object that has been implemented in C. False; the Cookie module example we talked about was caused by an unforeseen interaction between pure Python modules (Cookie and pickle). > So the most appropriate response to security issues in the CPython > interpreter and standard library is to notify application developers > as to what the issue is, and exactly which features it affects. It helps a lot if when the application developers are notified, a patch is already available, since once there's a lot of notification, the bug is public. > Sending a private notification to the *interpreter* developers does > nothing to assist in this. Um, it lets them get a patch ready before they notify the app developers. > If the problem is significant, then it should also be brought directly > to the attention of python-dev. It's a sure bet that attackers are monitoring python-dev and one should generally assume that they're monitoring the email of any developer for projects with serious security footprints. Notifying python-dev isn't much different than broadcasting the info on "Attack TV". Security bug reports should be made through SSL-encrypted web pages, not unencrypted email. Bugzilla already has this feature. I think it should also be added to Sourceforge, if it's not already there. If it's available in Sourceforge, then Python's Sourceforge project should enable it. Meanwhile, the OP can always open a CERT notification (www.cert.org), though it usually takes a very long time for anything to happen with those. From jtr at ofb.net Sun Jan 2 20:19:17 2005 From: jtr at ofb.net (John Reese) Date: Mon, 3 Jan 2005 01:19:17 +0000 (UTC) Subject: using HTTP Digest auth with arbitrary HTTP methods? Message-ID: Hello there. I've run into some missing functionality with HTTP Digest authentication in the 2.3 library and I was wondering if I'm just missing something. Missing functionality the first: urllib2 1a. You can add "handlers" to your opener indicating that you want to use HTTP Digest auth. This is nice way to handle it, but I don't see any way to use a custom verb in your URLOpener -- it always uses either GET or POST depending on whether you provided data. Is there any way to specify an arbitrary method? This would allow urllib2 to be used to write WebDAV clients. 1b. HTTPDigestAuthHandler is initialized with an HTTPPasswordMgr object, which unfortunately deals in cleartext passwords. Digest authentication can be computed using only a hash of username, password, and realm; it would be nice if there was an alternate version of HTTPPasswordMgr that let you deal in hashes instead of or in addition to plaintext passwords. Missing functionality the second: httplib. 2a. httplib.HTTPConnection lets you execute arbitrary HTTP methods with arbitrary headers and data; this is the missing functionality in 1a above. However, you have to deal with following redirects and authentication and so forth yourself. Is there any way to use the flexibility of HTTPConnection.request(method, url[, body[, headers]]) with the convenience of the chains of urllib2 handlers? The upshot is what I'm trying to do is write a WebDAV-using DAV client library, and I almost have everything I need to do it; the problem is I can't find an easy way to do digest authentication for arbitrary HTTP methods. WebDAV (RFC 2518), for those not familiar, is an extension to HTTP that defines some new methods and settles the semantics of some existing but rarely implemented HTTP methods (PUT and DELETE, for example) to define something similar to a file system. It's intended for things like letting a group of people author a web site. From danb_83 at yahoo.com Sun Jan 9 17:04:40 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 9 Jan 2005 14:04:40 -0800 Subject: else condition in list comprehension References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: <1105305000.052714.188980@c13g2000cwb.googlegroups.com> Luis M. Gonzalez wrote: > Hi there, > > I'd like to know if there is a way to add and else condition into a > list comprehension. I'm sure that I read somewhere an easy way to do > it, but I forgot it and now I can't find it... > > for example: > z=[i+2 for i in range(10) if i%2==0] > what if I want i [sic] to be "i-2" if i%2 is not equal to 0? z = [i + (2, -2)[i % 2] for i in range(10)] In general, the expression "T if C is true, or F if C is false" can be written as (F, T)[bool(C)]. (If you know that C will always be either 0 or 1, as is the case here, the "bool" is redundant.) Unless, of course, either F or T has side effects. For a side-effect free expression, you can use (C and [T] or [F])[0] or one of the many other ternary operator substitutes. (Search for PEP 308.) From jeff at ccvcorp.com Tue Jan 11 20:50:09 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 11 Jan 2005 17:50:09 -0800 Subject: python guy ide In-Reply-To: <1105491287.384930.167400@z14g2000cwz.googlegroups.com> References: <41e46d24@usenet01.boi.hp.com> <1105491287.384930.167400@z14g2000cwz.googlegroups.com> Message-ID: <10u908d5llrj528@corp.supernews.com> Kartic wrote: > SPE is great, > but it stops responding when I try to run my wxPython apps (probably > something I am doing!). I don't know about SPE specifically, but this is a common issue with a lot of lower-end IDEs. The IDE is a GUI application, which operates using an event loop. If the IDE runs user code in the same process that it runs in itself, and if that user code also contains some sort of event loop, then the two loops will interfere with each other (or rather, the first loop won't run until the inner loop quits, which tends to make Windows unhappy...) Most commercial IDEs, I believe, run user code in a separate process and thus avoid this problem. I *think* that IDLE now runs user code out-of-process as well, but I'm not sure about that. I can't afford to pay for an IDE for hobby purposes, so when I'm writing GUI apps, I also keep a command shell open. Edit, save, alt-tab to command shell, uparrow-enter to run program... not as convenient as a toolbar button or hotkey, but it works. Jeff Shannon Technician/Programmer Credit International From Scott.Daniels at Acm.Org Fri Jan 14 17:18:54 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 14 Jan 2005 14:18:54 -0800 Subject: query python env In-Reply-To: References: Message-ID: <41e841bb$1@nntp0.pdx.net> David Bear wrote: > How does one query the python environment, ie pythonhome, pythonpath, > etc. > > also, are there any HOWTO's on keeping multiple versions of python > happy? In general, (and in this case) the answer is system-specific. You need to explain (A) what operating system, and (B) what you mean by multiple Python versions. For example, for Windows 2K/XP, As long as you try for only distinct major versions (2.2.x, 2.3.x, 2.4.x). There should not be a problem. The primary issues are where (and how) does your system get to the python files. --Scott David Daniels Scott.Daniels at Acm.Org From bokr at oz.net Wed Jan 12 20:24:29 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 01:24:29 GMT Subject: Refactoring; arbitrary expression in lists References: Message-ID: <41e5cb07.701137402@news.oz.net> On Wed, 12 Jan 2005 18:16:23 +0000, Frans Englich wrote: > >As continuation to a previous thread, "PyChecker messages", I have a question >regarding code refactoring which the following snippet leads to: > >> > runner.py:200: Function (detectMimeType) has too many returns (11) >> > >> > The function is simply a long "else-if" clause, branching out to >> > different return statements. What's wrong? It's simply a "probably ugly >> > code" advice? >> >> That is also advice. Generally you use a dict of functions, or some other >> structure to lookup what you want to do. > >More specifically, my function looks like this: > >#-------------------------------------------------------------- >def detectMimeType( filename ): > > extension = filename[-3:] > basename = os.path.basename(filename) > > if extension == "php": > return "application/x-php" > > elif extension == "cpp" or extension.endswith("cc"): > return "text/x-c++-src" ># etcetera > elif extension == "xsl": > return "text/xsl" > > elif basename.find( "Makefile" ) != -1: > return "text/x-makefile" > else: > raise NoMimeError >#-------------------------------------------------------------- >(don't bother if the MIME detection looks like stone age, it's temporary until >PyXDG gets support for the XDG mime type spec..) > >I'm now wondering if it's possible to write this in a more compact way, such >that the if-clause isn't necessary? Of course, the current code works, but >perhaps it could be prettier. > >I'm thinking along the lines of nested lists, but what is the obstacle for me >is that both the test and return statement are simple expressions; not >functions or a particular data type. Any ideas? > I think I would refactor along these lines: (untested) extensiondict = dict( php = 'application/x-php', cpp = 'text/x-c-src', # etcetera xsl = 'test/xsl' ) def detectMimeType(filename): extension = os.path.splitext(filename)[1].replace('.', '') try: return extensiondict[extension] except KeyError: basename = os.path.basename(filename) if "Makefile" in basename: return 'text/x-makefile' # XXX case sensitivity? raise NoMimeError Regards, Bengt Richter From harold.fellermann at upf.edu Tue Jan 11 13:36:53 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 11 Jan 2005 19:36:53 +0100 Subject: exporting from Tkinter Canvas object in PNG In-Reply-To: <41E4178F.4050804@free.fr> References: <41E4178F.4050804@free.fr> Message-ID: On 11.01.2005, at 19:14, Nicolas Pourcelot wrote: > Hello, > I'm new to this mailing list and quite to Pyhon too. > I would like to know how to export the contain of the Canvas object > (Tkinter) in a PNG file ? > Thanks :) > Nicolas Pourcelot > -- > http://mail.python.org/mailman/listinfo/python-list you can make a postscript dump using >>> canvas = Tkinter.Canvas(master) >>> canvas.postscript(file="your_file_name.ps") If you have ImageMagick, you can later use % convert your_file_name.ps your_file_name.png on the comand line, if you want to have png. - harold - -- Science is to see what everybody else has seen, and think what nobody else has thought. -- From fredrik at pythonware.com Mon Jan 31 02:02:11 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 08:02:11 +0100 Subject: a Python bug in processing __del__ method ?? References: <1107154011.859866.23480@z14g2000cwz.googlegroups.com> Message-ID: Baoqiu Cui wrote: > The error returned is this: > > $ python bug.py > Exception exceptions.AttributeError: "'NoneType' object has no > attribute 'population'" in <__main__.Person instance at 0xa0c9fec>> ignored > > However, if I rename variable name 'peter' to something like 'peter1' > or 'david', the error is gone. Looks to me the > error only happens to variable name 'peter'. > > Does anyone know what is wrong? Is this a bug only on Cygwin? it is not a bug, and the documentation has the answer: language reference -> index -> __del__ http://docs.python.org/ref/customization.html#l2h-175 Warning: Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted. For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants. if you absolutely need to have reliable access to globals, you need to make sure they're available as instance variables, or are bound in some other way. From kumar.rakesh at gmail.com Sat Jan 29 08:40:26 2005 From: kumar.rakesh at gmail.com (Rakesh Kumar) Date: 29 Jan 2005 05:40:26 -0800 Subject: Coding style article with interesting section on white space References: Message-ID: <1107006026.348724.80080@z14g2000cwz.googlegroups.com> Thanx Nick From fredrik at pythonware.com Mon Jan 17 04:54:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Jan 2005 10:54:38 +0100 Subject: [perl-python] 20050116 defining a function References: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> Message-ID: Ala Qumsieh wrote: > > ? my $n= @_[0]; > > Do you ever test your code before making fun of yourself in front of millions? this perl usability study is getting more and more interesting. who needs television? From duncan.booth at invalid.invalid Mon Jan 10 11:50:16 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Jan 2005 16:50:16 GMT Subject: syntax error in eval() References: Message-ID: harold fellermann wrote: > Python 2.4 (#1, Dec 30 2004, 08:00:10) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> class X : pass > ... > >>> attrname = "attr" > >>> eval("X.%s = val" % attrname , {"X":X, "val":5}) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1 > X.attr = val > ^ > SyntaxError: invalid syntax > > > Does anyone have a clue what might be wrong? Thanks in advance. What you are doing wrong is attempting to use eval before exhausting all the simpler techniques. Why not just call 'setattr'? >>> setattr(X, 'attr', 5) BTW, the syntax error is because eval evaluates an expression and an assignment statement is a statement not an expression. From marklists at mceahern.com Thu Jan 20 20:07:24 2005 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 20 Jan 2005 19:07:24 -0600 Subject: Print a string in binary format In-Reply-To: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> Message-ID: <41F055CC.90800@mceahern.com> neutrino wrote: >Greetings to the Python gurus, > >I have a binary file and wish to see the "raw" content of it. So I open >it in binary mode, and read one byte at a time to a variable, which >will be of the string type. Now the problem is how to print the binary >format of that charater to the standard output. It seems a common task >but I just cannot find the appropriate method from the documentation. >Thanks a lot. > How is this *not* what you want: import sys f = open(filename, 'rb') data = f.read(1) while data: sys.stdout.write(data) data = f.read(1) Of course, that's the long version of: print open(filename, 'rb').read() // m From stian at soiland.no Sun Jan 23 16:36:56 2005 From: stian at soiland.no (Stian Soiland) Date: Sun, 23 Jan 2005 22:36:56 +0100 Subject: Keyboard problems with Python shell over SSH In-Reply-To: <8h38v0h322qokr7cgmen17805kbldhi87o@4ax.com> References: <8h38v0h322qokr7cgmen17805kbldhi87o@4ax.com> Message-ID: P? 23. jan 2005 kl. 21:55 skrev Nils Emil P.Larsen: > > I connect to my server using SSH and then run 'python' to enter the > shell. I can't use the arrow buttons (up, down, left and right). > Instead I get this ^[[A , ^[[B, ^[[C or ^[[D. Your Python installation is probably compiled without readline support. It is the readline library that enables arrow keys and Ctrl-R and stuff to work. Try "import readline" - you will probably get an error. I won't go into detail on how to install readline on your OS. In Linuxes, it might be apt-get install readline-dev. In other OSes, different licensing and packaging issues might have prevented readline's precense. -- -- Stian S?iland You can't say civilization don't Trondheim, Norway advance, however, for in every war http://www.soiland.no/ they kill you in a new way. [Rogers] =/\= From bob_smith_17280 at hotmail.com Sun Jan 16 20:57:27 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sun, 16 Jan 2005 20:57:27 -0500 Subject: python mode indentation problem In-Reply-To: <1105842678.044409.270450@z14g2000cwz.googlegroups.com> References: <1105802644.939051.229990@f14g2000cwb.googlegroups.com> <1105842678.044409.270450@z14g2000cwz.googlegroups.com> Message-ID: Xah Lee wrote: > ? ok, here's the ordeal. > ? > ? for i in range(5): > ? print i > ? for i in range(2): > ? print i, 'tt' > ? for i in [3]: > ? print i > ? for i in [32]: > ? print i > ? > ? # 1 level, 4 space > ? # 2 level, 1 tab > ? # 3 level, 1 tab, 4 spaces > ? # 4 level, 2 tabs. > ? > ? who the fuck coded the python mode in emacs? fuckhead please peruse: > ? http://xahlee.org/UnixResource_dir/writ/responsible_license.html I hope you never need a favor or interview for a job with someone who reads news groups. You're committing eSuicide by posting insulting rants such as this. All you accomplish is to isolate yourself. Try to be friendly. Ideas are only half the battle... presentation is the other half. You have some good and valid ideas, but your presentation is offensive and condescending. Your ideas are like golden coins wrapped in horse shit. Personally, I've had enough of your horse shit... perhaps I speak for others as well. From ptmcg at austin.rr._bogus_.com Wed Jan 12 13:10:14 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 12 Jan 2005 18:10:14 GMT Subject: counting items References: Message-ID: "It's me" wrote in message news:ukdFd.10645$5R.2000 at newssvr21.news.prodigy.com... > Okay, I give up. > > What's the best way to count number of items in a list? > > For instance, > > a=[[1,2,4],4,5,[2,3]] > > I want to know how many items are there in a (answer should be 7 - I don't > want it to be 4) > I've sure seen a lot of questions about the flattening of lists. I found this version of flatten somewhere, I thought I got it from the Python Cookbook but I can't find it now. Perhaps it was posted here on c.l.py. I *don't* claim authorship, I'm merely an admirer of such a clean-looking solution. def flatten(a): if not isinstance(a, (tuple,list)): return [a] if len(a)==0: return [] return flatten(a[0])+flatten(a[1:]) a = [[1, 2, 4], 4, 5, [2, 3], 6, [6], [], 'askjdf'] print len(flatten(a)) gives the value 10. Considering how often this comes up, might there be a place for some sort of flatten() routine in the std dist, perhaps itertools? -- Paul From steven.bethard at gmail.com Sun Jan 30 17:52:43 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 30 Jan 2005 15:52:43 -0700 Subject: how do i create such a thing? In-Reply-To: References: Message-ID: <7vGdnTsopcKl-GDcRVn-rw@comcast.com> Pedro Werneck wrote: > If you need direct access to some atribute, use object.__getattribute__. > >>>>class DefaultAttr(object): > > ... def __init__(self, default): > ... self.default = default > ... def __getattribute__(self, name): > ... try: > ... value = object.__getattribute__(self, name) > ... except AttributeError: > ... value = self.default > ... return value > ... > >>>>x = DefaultAttr(99) >>>>print x.a > 99 > >>>>x.a = 10 >>>>print x.a > 10 Of if you only want to deal with the case where the attribute doesn't exist, you can use getattr, which gets called when the attribute can't be found anywhere else: py> class DefaultAttr(object): ... def __init__(self, default): ... self.default = default ... def __getattr__(self, name): ... return self.default ... py> x = DefaultAttr(99) py> x.a 99 py> x.a = 10 py> x.a 10 Steve From as006d4848 at blueyonder.co.uk Fri Jan 28 10:30:19 2005 From: as006d4848 at blueyonder.co.uk (Philip Smith) Date: Fri, 28 Jan 2005 15:30:19 GMT Subject: Elliptic Code References: Message-ID: thanks for the suggestion I understand the algorithm quite well but how to code the multiplication stage most efficiently in python eludes me. William Stein's code is obviously not high performance because in the region where ecm should do well (30-40 dec digits) my python implementation of the rho algorithm blows it away. In terms of factoring implementations generally (in python) I think nzmath's mpqs is brilliant - and it has such a small footprint I can run it in 10 threads at once. anyway - I'll have a look at MIRACL (I have the library but have never used it yet. Phil wrote in message news:m3acqtu6r1.fsf at localhost.localdomain... > "Philip Smith" writes: >> Does anyone have/know of a python implementation of the elliptic curve >> factoring algorithm (lenstra) which is both: >> >> simply and cleanly coded >> functional > > It's not in Python but take a look at Mike Scott's C++ implementation > in MIRACL, > > http://indigo.ie/~mscott/ > > It's the simplest and most direct implementation I know of, just the > bare essentials. It could probably be translated into Python pretty > straightforwardly. > >> I'm aware of William Stein's code (from elementary number theory >> book) but I don't understand his coding style and the algorithm >> doesn't seem to work efficiently. > > A high performance implementation means complicated code, e.g. Peter > Montgomery has done a few of those. If it's for instructional > purposes I think the MIRACL version is far more understandable even if > it's slower. > > If you mean you don't understand the algorithm, try Neal Koblitz's > book "A Course in Number Theory and Cryptography". It has no code but > it explains the algorithm in a pretty accessible way. From phr at localhost.localdomain Tue Jan 25 20:40:39 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Wed, 26 Jan 2005 01:40:39 GMT Subject: Help! Host is reluctant to install Python References: Message-ID: Daniel Bickett writes: > I've been trying to convince my host to install python/mod_python on > his server for a while now, however there are a number of reasons he > is reluctant to do so, which I will outline here: I'm surprised that you're getting such detailed answers from him. Usually, low-cost web hosts want to offer a one-size-fits-all package that requires minimal interaction with customers. If you're paying $10 a month for hosting and a host admin has to spend 1 hour sending you email, that probably wipes out at least 6 months of profits from you as a customer. If you want custom service you usually have to pay a lo tmore. > 1. His major reason is optimization. He uses Zend's optimization of > PHP as an example, and he has stated that python is rather resource > consuming. Maybe that's true, though if there's enough customer demand for Python anyway, the answer is to buy more equipment and pass the costs on. The real problem is there's not enough demand. > 2. Another one of his points is that he is unexperienced in installing > python, and he would not know how to do it securely. By 'securely', > I'm assuming he means disallowing a malicious (or ignorant) user from > harming the server That's a serious issue too, and "securely" means not just securing against the service's own customers, but also against outside attacks. I have no idea how carefully mod_python has been audited. I don't use it myself, though I do run some Python cgi's. > I have no experience with this sort of thing, so I'm asking a little > assistance in the direction of any documents or websites (or what have > you) I could show him in order to answer some of these questions, or > perhaps even some unspoken ones -- anything worth noting. (all I'm > really going to do is link him to this thread once it has accumulated > any answers) I think you should look into some type of virtual hosting that gives you more ability to install your own software. Typing "uml hosting" (UML is user-mode Linux) into Google finds a lot of such services. If you find one that you like, post it here, I'm interested in this myself. From wittempj at hotmail.com Sun Jan 23 11:29:16 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 23 Jan 2005 08:29:16 -0800 Subject: best way to do a series of regexp checks with groups In-Reply-To: References: Message-ID: <1106497756.578620.152920@z14g2000cwz.googlegroups.com> what about something like this? >>> import re >>> m = re.match(r"""(?Padd|mult) (?P\d+) (?P\d+)""", 'add 3 5') >>> from operator import add, mul >>> op = {'add': add, 'mult: mul} >>> op[m.groupdict()['operator']](int(m.groupdict()['int_1']), int(m.groupdict()['int_2'])) 8 From philippecmartin at sbcglobal.net Fri Jan 7 10:18:05 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Fri, 07 Jan 2005 16:18:05 +0100 Subject: Tkinter: passing parameters to menu commands (looping through a list) Message-ID: <1105111085.9221.28.camel@localhost> >>l_dec.add_command(label=i, command=lambda x=i: self.__Dec(x)) Woof! I'd better do my homework on lambda ! Thanks, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From andybak at gmail.com Fri Jan 14 12:53:39 2005 From: andybak at gmail.com (andybak at gmail.com) Date: 14 Jan 2005 09:53:39 -0800 Subject: Integration with java In-Reply-To: <1105723092.315634.181590@z14g2000cwz.googlegroups.com> References: <1105723092.315634.181590@z14g2000cwz.googlegroups.com> Message-ID: <1105725219.247286.312590@f14g2000cwb.googlegroups.com> How about this? http://jpype.sourceforge.net/ (I haven't used it myself) From kenneth.m.mcdonald at sbcglobal.net Mon Jan 31 16:04:36 2005 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Mon, 31 Jan 2005 21:04:36 GMT Subject: Request for Feedback; a module making it easier to use regular expressions. Message-ID: <310120051504352505%kenneth.m.mcdonald@sbcglobal.net> I'm working on the 0.8 release of my 'rex' module, and would appreciate feedback, suggestions, and criticism as I work towards finalizing the API and feature sets. rex is a module intended to make regular expressions easier to create and use (and in my experience as a regular expression user, it makes them MUCH easier to create and use.) I'm still working on formal documentation, and in any case, such documentation isn't necessarily the easiest way to learn rex. So, I've appended below a rex interactive session which was then annotated with explanations of the features being used. I believe it presents a reasonably good view of what rex can do. If you have time, please read it, and then send your feedback via email. Unfortunately, I do not currently have time to keep track of everything on comp.lang.python. Thanks, Ken McDonald ============================================= What follows is an illustration by example of how the 'rex' module works, for those already knowledgable of regular expressions as used in Python's 're' (or similar) regular expressions package. It consists of a quick explanation of a rex feature, followed by an interactive demo of that feature. You need to understand a couple of quick points to understand rex and the demo. 1) To distinguish between standard regular expressions as constructed by hand and used with the 're' package, and regular expressions constructed by and used in 'rex', I'll call the former 'regexps', and the latter 'rexps'. 2) The Rexp class, of which every rexp is an instance, is simply a subclass of Python's regular string class, with some modified functionality (for example, the __add__ method has been changed to modify the action of the '+' operation), and many more operators and methods. I'm not sure this was the wisest thing to do, but it sure helps when trying to relate rexps to regexps; just construct a rexp interactively or in a program and print it, and in either case you'll see the underlying string that is passed to the 're' module functions and methods. On to the tutorial. 'rex' is designed have few public names, so the easiest way to use it is to import all the names: >>> from rex import * The most basic rex function is PATTERN, which simply takes a string or strings, and produces a rexp which will match exactly the argument strings when used to match or search text. As mentioned above, what you see printed as the result of executing PATTERN is the string that will be (invisibly) passed to 're' as a regexp string. >>> PATTERN("abc") 'abc' If given more than one argument, PATTERN will concatenate them into a single rexp. >>> PATTERN("abc", "d") 'abcd' The other rex function which converts standard strings to rexps is CHARSET, which produces patterns which match a single character in searched text if that character is in a set of characters defined by the CHARSET operation. This is the equivalent of the regexp [...] notation. Every character in a string passed to CHARSET will end up in the resulting set of characters. >>> CHARSET("ab") '[ab]' If CHARSET is passed more than one string, all characters in all arguments are included in the result rexp. >>> CHARSET("ab", "cd") '[abcd]' If an argument to CHARSET is a two-tuple of characters, it is taken as indicating the range of characters between and including those two characters. This is the same as the regexp [a-z] type notation. For example, this defines a rexp matching any single consonant. >>> CHARSET('bcd', 'fgh', ('j', 'n'), ('p', 't'), 'vwxz') '[bcdfghj-np-tvwxz]' When using CHARSET (or any other rexp operation), you do _not_ need to worry about escaping any characters which have special meanings in regexps; that is handled automatically. For example, in the follwing character set containing square brackets, a - sign, and a backslash, we have to escape the backslash only because it has a special meaning in normal Python strings. This could be avoided by using raw strings. The other three characters, which have special meaning in regexps, would have to be escaped if building this character set by hand. >>> CHARSET('[]-\\') '[\\[\\]\\-\\\\]' The result above is what you'd need to type using re and regexps to directly define this character set. Think you can get it right the first time? CHARSET provides a number of useful attributes defining commonly used character sets. Some of these are defined using special sequences defined in regexp syntax, others are defined as standard character sets. In all cases, the common factor is that CHARSET attributes all define patterns matching a _single_ character. Here are a few examples: >>> CHARSET.digit '\\d' >>> CHARSET.alphanum '\\w' >>> CHARSET.uspunctuation '[~`!@#$%\\^&*()_\\-+={\\[}\\]|\\\\:;"\'<,>.?/]' Character sets can be negated using the '~' operator. Here is a rexp which matches anything _except_ a digit. >>> ~CHARSET(('0','9')) '[^0-9]' Remember from above that PATTERN constructs rexps out of literals, and also concatenates multiple arguments to form a rexp which matches if all of those arguments match in sequence. However, the arguments to PATTERN don't have to be just strings; they can be other rexps, which are concatenated correctly to produce a new rexp. The following expression produces a rexp which matches the string 'abc' followed by any of 'd', 'e', or 'f'. >>> PATTERN("abc", CHARSET("def")) 'abc[def]' Instead of passing multiple arguments to PATTERN to obtain concatenation, you can simple use the '+' operator, which has exactly the same effect, but in many circumstances may produce easier-to-read code. However, if '+' is used in this way, its left operand _must_ be a rexp; a plain string won't work. >>> PATTERN("abc") + CHARSET("def") 'abc[def]' To obtain an alternation rexp--one which matches if any one of several other rexps match--we use the ANYONEOF function. This is equivalent to the "|" character in regexp notation. >>> ANYONEOF("a", "b", "c") 'a|b|c' As with PATTERN and '+', the '|' operator may be used in place of ANYONEOF to obtain alternation. As usual, the left-hand operand must be a rexp: >>> PATTERN("a") | "b" | "c" 'a|b|c' Note in the above that only the _first_ operand needs to be a rexp; this is because the first and second operands combine to form a rexp, and that rexp then becomes the left operand for the second '|' operator. Now we come to a very significant difference between regexps and rexps; the ability to combine smaller expressions into larger expressions. Below are two regexps, the first matching any one of 'a' or 'b' or 'c', the second matching 'd', 'e', or 'f'. It would be nice if there were an easy way to combine them to match strings of the form ('a' or 'b' or 'c') followed by ('d' or 'e' or 'f') using simple string addition: >>> "a|b|c" + "d|e|f" 'a|b|cd|e|f' Unfortunately, this produces a regexp which matches any one of 'a', 'b', 'cd', 'e', or 'f'. The simplest way I know of to achieve the desired result in this case is something like "("+"a|b|c"+")("+"d|e|f"+")". This is not exactly pretty, or easy to type. Something like this isn't necessary when dealing with all string literals as above, but what if the two operands were other regexps? Then you would have to type something like "("+X+")("+Y+")". This is much clearer useing rexps: >>> PATTERN(ANYONEOF("a","b", "c"), ANYONEOF("d", "e", "f")) '(?:a|b|c)(?:d|e|f)' or, shortening the expression using the '+' operator: >>> ANYONEOF("a", "b", "c") + ANYONEOF("d", "e", "f") '(?:a|b|c)(?:d|e|f)' Note that when rexps are put together like this, the parentheses used for grouping are 'numberless' parentheses--they will not be considered when extracting match subresults using numbered groups. Since the insertion of these parentheses in the produced regexp are invisible to the rex user, this is exactly what is desired. Precedence works as you might expect, with '+' having higher precedence than '|' (though the example below is rather simple as an illustration of this.) >>> PATTERN("a") + "b" | "e" + "f" 'ab|ef' To match a pattern 0 or more times, use the ZEROORMORE function. This is analogous to the regexp '*' character. Note that parentheses are inserted to ensure the function applies to all of what you pass in. >>> ZEROORMORE("a") '(?:a)*' >>> ZEROORMORE("abc") '(?:abc)*' ONEORMORE matches a sequence of one or more rexps, and is like the "+" regexp operator. >>> ONEORMORE("abc") '(?:abc)+' The short way of obtaining repetition, and of matching more limited repetitions of a pattern, is to use the "*" operator. This expression is the same as ZEROORMORE("abc"): >>> PATTERN("abc")*0 '(?:abc)*' ...and this is the same as ONEORMORE("abc"): >>> PATTERN("abc")*1 '(?:abc)+' If a negative sign precedes the match number, it indicates the resulting rexp should match _no more_ than that many repetitions of the (positive) number. This matches anywhere from 0 to 3 repetitions of "abc": >>> PATTERN("abc")*-3 '(?:abc){0,3}' Use a two-tuple to specify both an upper and lower bound. Match anywhere from 2 to five repetitions of "abc". >>> PATTERN("abc")*(2,5) '(?:abc){2,5}' The OPTIONAL function indicates that the argument rexp is optional (the containing pattern will match whether or not the rexp produced by OPTIONAL matches.) >>> OPTIONAL("-") '(?:\\-)?' There is no shorthand form for OPTIONAL. However, the following is semantically identical, though it produces a different regexp: >>> PATTERN("-")*(0,1) '(?:\\-){0,1}' Let's look a bit more at how easy it is to combine rexps into more complex rexps. PATTERN provides an attribute defining a rexp which matches floating-point numbers (without exponent): >>> PATTERN.float '(?:\\+|\\-)?\\d+(?:\\.\\d*)?' Using this to build a complex number matcher (assuming no whitespace) is trivial: >>> PATTERN.float + ANYONEOF("+", "-") + PATTERN.float + "i" '(?:\\+|\\-)?\\d+(?:\\.\\d*)?(?:\\+|\\-)(?:\\+|\\-)?\\d+(?:\\.\\d*)?i' I think the rexp construct is a little easier to understand and modify than the produced regexp :-) What if we want to extract the real and imaginary parts of any complex number we happen to match? To do this, we name the rexp subpatterns which match the numeric portions of the complex number, by indexing them with the desired name. This corresponds to re's named groups facility for regexps, using the (?P...) notation. >>> complexrexp = PATTERN.float['re'] + ANYONEOF("+", "-") + PATTERN.float['im'] + "i" >>> complexresult = complexrexp.match("-3.14+2.17i") By the way, here's the regexp resulting from the above rexp. >>> complexrexp '(?P(?:\\+|\\-)?\\d+(?:\\.\\d*)?)(?:\\+|\\-)(?P(?:\\+|\\-)?\\d+(?:\\.\\d*)?)i' Would you really like to write it out by hand? To extract the what matched the named group, we simply index the match result: >>> complexresult['re'] '-3.14' I highly recommend using named groups when constructing rexps; it makes code more readable and less error-prone. However, if you do want to use a numbered group for some reason, use the group() method on an existing rexp: >>> PATTERN.float.group() + ANYONEOF("+", "-") + PATTERN.float.group() + "i" '((?:\\+|\\-)?\\d+(?:\\.\\d*)?)(?:\\+|\\-)((?:\\+|\\-)?\\d+(?:\\.\\d*)?)i' If a match fails, we get a MatchResult which evaluates to False when used as a boolean: >>> complexresult = complexrexp.match("-3.14*2.17i") >>> complexresult >>> bool(complexresult) False Attempting to extract a subgroup from a failed match raises a KeyError and prints an appropriate error message. >>> complexresult['re'] Traceback (most recent call last): File "", line 1, in ? File "/local/python/packages/rex/__init__.py", line 508, in __getitem__ return self.get(key) File "/local/python/packages/rex/__init__.py", line 518, in get else: raise KeyError, "Invalid group index: "+ `key` + " (a failed match result only has one group, indexed by 0)." KeyError: "Invalid group index: 're' (a failed match result only has one group, indexed by 0)." However, extracting group 0 (which in a successful match always represents the entirety of the matched text) of a failed MatchResult still results in the entire string against which the match was attempted. This may seem pointless now, but will be very useful when we get into iterative searches using rexps. >>> complexresult[0] '-3.14*2.17i' We can do some nice things with named groups which cannot be accomplished with standard regexps. The keys() method returns the names of all named subgroups which participated in a match (but does not return the names of subgroups which did _not_ participate in the match, such as a subgroup contained in a failed OPTIONAL rexp): >>> complexresult.keys() ['re', 'im'] In addition, if a named group matches the _entire_ matched string, then the name of that group can be obtained with the 'getname' method. This is useful for determining which of a number top-level alternative rexps matched. >>> altrexp = PATTERN.float['number'] | PATTERN.word['symbol'] >>> altrexp.match("3.14").getname() 'number' >>> altrexp.match("abc").getname() 'symbol' Note that if more than one named group matches the entire matched substring, then getname() will return one of the appropriate names, but which one is not predictable. Lesser-used pattern matching facilities have not been neglected. Non-greedy reptition can be expressed in the same way as standard (greedy) repetition, by using the ** operator in place of *: >>> PATTERN("a")**0 '(?:a)*?' >>> PATTERN("a")**1 '(?:a)+?' In this next example, the big number in the resulting regexp is sys.MAXINT. This is the closest I know how to express "three to infinity" in a regexp pattern. >>> PATTERN("a")**3 '(?:a){3,2147483647}?' Lookahead and lookback assertions are supported with the '+' and '-' unary operators: >>> +PATTERN("a") '(?=a)' >>> -PATTERN("a") '(?<=a)' Both types of assertions can be negated by prepending with a tilde, as can be done with CHARSET rexps: >>> ~-PATTERN("a") '(?>> ~+PATTERN("a") '(?!a)' Any regular expression can be considered as denoting the set of all strings which it matches. (Or, for those who've taken a formal class on RE's and finite automate, the set of strings which it "generates".) So, matching a piece of text against a regular expression is really the same thing as asking if that text is in the set of strings "generated" by the regular expression. Rexps provide a nice way of doing this using Python's "in" operator. The examples below ask if a couple of strings are in the set of strings consisting of a sequence of one or more 'a' characters: >>> "aa" in PATTERN("a")*1 True >>> "ab" in PATTERN("a")*1 False Searching text is done using a rexp's search() method. Let's find the string "cd" in the text "abcdef": >>> searchresult = PATTERN("cd").search("abcdef") We know the search succeeded by evaluating the MatchResult as a boolean... >>> bool(searchresult) True ...and can easily extract the start and end positions of the matched string, and the string itself (which might be useful if the search rexp was not a literal): >>> searchresult.start(0) 2 >>> searchresult.end(0) 4 >>> searchresult[0] 'cd' Iterative searching--that is, searching for _all_ instances in a piece of text matched by a regular expression--can be a bit awkward when using regexps. It is very easy when using rexps. The example below uses the fact that __str__ in a MatchResult object is defined so that str(matchresult) returns the entire substring matched by the MatchResult; str() is mapped over the sequence of MatchResult instances generated by itersearch() to get a list of the matched substrings. >>> map(str, CHARSET.digit.itersearch("ab0c9de7")) ['0', '9', '7'] 'itersearch' is a generator function, which means that it only computes and returns MatchResult instances as they are requested by the enclosing loop. So, itersearch() can be used in a memory-efficient manner even on very large pieces of text. 'itersearch' can also be used more flexibly. If defines an optional paramater named 'matched' which defaults to True and indicates that only successful MatchResults should be returned. If we perform a search with this parameter set to False, then only _failing_ MatchResults will be returned... >>> map(str, CHARSET.digit.itersearch("ab0c9de7", matched=False)) ['ab', 'c', 'de'] ...and if None is passed as the value of 'matched', then both successful and failed MatchResults will be returned: >>> map(str, CHARSET.digit.itersearch("ab0c9de7", matched=None)) ['ab', '0', 'c', '9', 'de', '7'] We can still determine which of these results are failures and which are successes by using the MatchResults as a boolean: >>> map(bool, CHARSET.digit.itersearch("ab0c9de7", matched=None)) [False, True, False, True, False, True] This leads to a great little idiom for going through _all_ the text of a string, and processing each part as appropriate (the bit of Python code below is not part of the interactive session): for result in myRexp.itersearch(myText, matched=None): if result: ...process the successful match... else: ...process the failed match... Rexps also have a 'replace' method, to replace found text with other text. Let's replace all digits in a string with the word "DIGIT": >>> CHARSET.digit.replace("DIGIT", "ab0c9de7") 'abDIGITcDIGITdeDIGIT' More specific replacements can be achieved by passing in a dictionary as the replace argument. Any matched substring must have a key defined in the dictionary (else a KeyError will be thrown), and is replaced with the value associated with that key: >>> CHARSET.digit.replace({"9":"NINE", "0":"ZERO", "7":"SEVEN"}, "ab0c9de7") 'abZEROcNINEdeSEVEN' For the ultimate in flexibility, we can pass in a function as the replace argument. Whenever a match is found, its MatchResult will be passed as an argument to the function, and the result of the function will be used as the replacement value. Here's an example which increments the integer interpretation of each digit in some text by 1. >>> def incr(matchresult): ... return str(1+int(matchresult[0])) ... >>> CHARSET.digit.replace(incr, "ab0c9de7") 'ab1c10de8' From fuzzyman at gmail.com Mon Jan 24 06:06:39 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Jan 2005 03:06:39 -0800 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> Message-ID: <1106564799.011057.181280@c13g2000cwb.googlegroups.com> I also feel the lack of a standard cryptography module in the core... even a *basic* one. At least rotor provided that, before it was deprecated. I (along with many other python users) write CGIs where the only extension modules that I can use are either pure python, or ones my web hoster is willing to install. Luckily my hoster will install modules without too much fuss - others aren't so lucky. Cryptography is a pretty 'standard' requirement these days.. and IMHO ought to be in the 'standard library'. Without commenting (or reading properly) on this exchange... it does seem that many of ''s contributions have been very bad tempered recently. Hmmm..... Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From reinhold-birkenfeld-nospam at wolke7.net Fri Jan 14 14:13:48 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 14 Jan 2005 20:13:48 +0100 Subject: Octal notation: severe deprecation In-Reply-To: <41e6f606.777680996@news.oz.net> References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> <39ednWfqlrgB6HvcRVn-iA@powergate.ca> <41e6f606.777680996@news.oz.net> Message-ID: <34qjvcF4dkctuU2@individual.net> Bengt Richter wrote: > On Thu, 13 Jan 2005 08:18:25 -0500, Peter Hansen wrote: > >>and-google at doxdesk.com wrote: >>> In Mythical Future Python I would like to be able to use any base in >>> integer literals, which would be better. Example random syntax: >>> >>> flags= 2x00011010101001 >>> umask= 8x664 >>> answer= 10x42 >>> addr= 16x0E800004 # 16x == 0x >>> gunk= 36x8H6Z9A0X >> >>I think I kinda like this idea. Allowing arbitrary values, >>however, would probably be pointless, as there are very >>few bases in common enough use that a language should make >>it easy to write literals in any of them. So I think "36x" >>is silly, and would suggest limiting this to 2, 8, 10, and >>16. At the very least, a range of 2-16 should be used. >>(It would be cute but pointless to allow 1x000000000. :-) >> > My concern is negative numbers when you are interested in the > bits of a typical twos-complement number. (BTW, please don't tell me > that's platform-specific hardware oriented stuff: Two's complement is > a fine abstraction for interpreting a bit vector, which is another > fine abstraction ;-) > > One way to do it consistently is to have a sign digit as the first > digit after the x, which is either 0 or base-1 -- e.g., +3 and -3 would be > > 2x011 2x101 > 8x03 8x75 > 16x03 16xfd > 10x03 10x97 Why not just -2x11? IMHO, Py2.4 does not produce negative values out of hex or oct literals any longer, so your proposal would be inconsistent. Reinhold From rbt at athop1.ath.vt.edu Sat Jan 29 12:53:37 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sat, 29 Jan 2005 12:53:37 -0500 Subject: Description Field in WinXP Services Message-ID: How does one associate a "Description" with a Windows service written in Python? I've just started experimenting with Python services. Here's my code... copied straight from Mr. Hammond's "Python Programming on Win32": import win32serviceutil import win32service import win32event class test_py_service(win32serviceutil.ServiceFramework): _svc_name_ = "test_py_service" ## Tried the following to no avail. _svc_description_ = "Test written by Brad" _svc_display_name_ = "Test Python Service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) if __name__ == '__main__': win32serviceutil.HandleCommandLine(test_py_service) From richie at entrian.com Fri Jan 21 09:41:01 2005 From: richie at entrian.com (Richie Hindle) Date: Fri, 21 Jan 2005 14:41:01 +0000 Subject: ElementTree.findtext() Message-ID: Hi, I can't get ElementTree.findtext() to work with anything other than a single-level path: >>> from elementtree import ElementTree >>> tree = ElementTree.fromstring("""\ ... ... ... ... The title ... ... ... """) >>> print tree.findtext("*/title") The title >>> print tree.findtext("html/head/title") None >>> What am I missing? I'm using elementtree-1.2.4-20041228 on Windows with Python 2.3. -- Richie Hindle From aleaxit at yahoo.com Sat Jan 29 17:23:10 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 29 Jan 2005 23:23:10 +0100 Subject: limited python virtual machine References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> <16891.41849.882856.527798@montanaro.dyndns.org> <1gr5th5.13asce21fjmj8tN%aleaxit@yahoo.com> Message-ID: <1gr6ber.i8gzs6l2o8yiN%aleaxit@yahoo.com> Skip Montanaro wrote: > Alex> I dunno, maybe I'm just being pessimistic, I guess... > > No, I think you are being realistic. I thought one of the basic tenets of > computer security was "that which is not expressly allowed is forbidden". > Any attempt at security that attempts to find and plug the security holes > while leaving the basic insecure system intact is almost certainly going to > miss something. I guess security is drastically different from all other programming spheres because you DO have an adversary, who you should presume to be at least as clever as you are. In most tasks, good enough is good enough and paranoia doesn't pay; when an adversary IS there, only the paranoid survive...;-) Alex From apardon at forel.vub.ac.be Tue Jan 11 10:04:44 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 11 Jan 2005 15:04:44 GMT Subject: Python 2.4 and os.open question? References: <41e3e670$0$20038$39db0f71@news.song.fi> Message-ID: Op 2005-01-11, Eino M?kitalo schreef : > I just test in Windows XP with Python 2.4 > > I'd like to create a file with exclusive flag. Why? What is it about the exclusive flag that makes you like to use it? > If file exist I try to use it, if not I'd like to create it. If you want that, you cant use the exclusive flag. > Python (and underlying library) works differently with/without O_EXCL > flag. Well if the absence and presence of this flag wouldn't make a difference, it would hardly be usefull to have such a flag, wouldn't it? > Is this okay. How I should use this. > > Has somebody manual :-) ? > > Eino M?kitalo > > see scenarios (1 without flag ) (2 with flag) > > Scenario 1: > > To create file if it's not available this works ok > > >>> aa=os.open("c:\\temp\\a.txt",os.O_RDWR|os.O_CREAT) > >>> os.close(aa) > >>> aa=os.open("c:\\temp\\a.txt",os.O_RDWR|os.O_CREAT) > >>> os.close(aa) > > > Scenario 2: > But if you try to do same with O_EXCL then it does not use same logic??? That is what flags are for: to change the logic. O_EXCL, makes sure you are the one that creats the file. If the file exists it fails. This is to make sure that if two programs can create the same file but shouldn't work on it the same time, the file isn't opened multiple times. > >>> aa=os.open("c:\\temp\\a.txt",os.O_RDWR|os.O_EXCL|os.O_CREAT) > >>> os.close(aa) > >>> aa=os.open("c:\\temp\\a.txt",os.O_RDWR|os.O_CREAT) I suppose this should again be the instrcution two lines above; this actually works. (At least on my linux box, if it didn't on your XP box, that is a bug) > Traceback (most recent call last): > File "", line 1, in > OSError: [Errno 17] File exists: 'c:\\temp\\a.txt' Which is exactly as it should, provided you actually used the os.O_EXCL flag twice. -- Antoon Pardon From claird at lairds.us Tue Jan 25 12:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 25 Jan 2005 17:08:03 GMT Subject: Another scripting language implemented into Python itself? References: <1106624803.825442.73870@f14g2000cwb.googlegroups.com> Message-ID: In article <1106624803.825442.73870 at f14g2000cwb.googlegroups.com>, Carl Banks wrote: . . . >> Python, or Perl, or TCL, or Ruby, or PHP, > >Not PHP. PHP is one of the better (meaning less terrible) examples of >what happens when you do this sort of thing, which is not saying a lot. >PHP was originally not much more than a template engine with some >crude operations and decision-making ability. Only its restricted >problem domain has saved it from the junkheap where it belongs. > >TCL isn't that great in this regard, either, as it makes a lot of >common operations that ought to be very simple terribly unweildy. . . . I've lost track of the antecedent by the time of our arrival at "this regard". I want to make it clear that, while Tcl certainly is different from C and its imitators, and, in particular, insists that arithmetic be expressed more verbosely than in most languages, the cause is quite distinct from the imperfections perceived in PHP. PHP is certainly an instance of "scope creep" in its semantics. Tcl was designed from the beginning, though, and has budged little in over a decade in its fundamentals; Tcl simply doesn't bother to "make a lot of common operations ..." concise. From danperl at rogers.com Mon Jan 31 00:06:23 2005 From: danperl at rogers.com (Dan Perl) Date: Mon, 31 Jan 2005 00:06:23 -0500 Subject: Regarding exception handling References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> Message-ID: "Bryan" wrote in message news:mailman.1614.1107137827.22381.python-list at python.org... > IMO, that is not the reason for the try/finally statement and it is not > redundant. the try/finally statement guarantees the resource is closed > and the try/finally statement only gets executed if and only if the > opening of the resource doesn't raise an exception. it has nothing to do > with exception handling. But IMO, try-finally is meant to be used only if the block in the try clause may raise exceptions. Here is an example that shows what I meant: s = ... # socket opens try: a = 1 finally: s.close() works perfectly the same as: s = ... # socket opens a = 1 s.close() The try-finally statement does not "handle" the exception, but it makes sense only if exceptions are possible. There is no point in enclosing "a = 1" in any kind of try statement. According to a following posting from Angelos he did expect some other exceptions than socket.error and hence the nested try's. To my defence though, I put in a disclaimer for that case in my initial posting. > in the previous 2 examples s = ... was placed inside the try/finally, but > if an exception occures and s doesn't get bound to an object, then > s.close() in both examples will raise a NameError on s. That is a very good point. I missed it. Dan From fredrik at pythonware.com Tue Jan 18 05:53:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Jan 2005 11:53:57 +0100 Subject: Problem parsing namespaces with xml.dom.minidom References: <41eca38d@clear.net.nz> <41ece45f@clear.net.nz> Message-ID: Mike McGavin wrote: >> is the DOM API an absolute requirement? > > It wouldn't need to conform to the official specifications of the DOM API, but I guess I'm after > some comparable functionality. > > In particular, I need to be able to parse a namespace-using XML document into some kind of node > tree, and then being able to query the tree to select elements based on their namespace and local > tag names, and so on. I don't mind if the methods provided don't conform exactly to DOM > specifications. sounds like this might be exactly what you need: http://effbot.org/zone/element-index.htm (it's also the fastest and most memory-efficient Python-only parser you can get, but I suppose that's not a problem ;-) From xah at xahlee.org Wed Jan 19 00:12:26 2005 From: xah at xahlee.org (Xah Lee) Date: 18 Jan 2005 21:12:26 -0800 Subject: [perl-python] 20050119 writing modules Message-ID: <1106111546.794861.148010@c13g2000cwb.googlegroups.com> ? # -*- coding: utf-8 -*- ? # Python ? ? # one can write functions, ? # save it in a file ? # and later on load the file ? # and use these functions. ? ? # For example, save the following line in ? # a file and name it module1.py ? # def f1(n): returns range(n) ? ? # to load the file, use import ? import mymodule ? ? # to use the function, use ? # fileName.functionName. ? print mymodule.f1(5) ? ? # the file name without the .py suffix ? # is the module's name, and is available ? # as the variable fileName.__name__ ? print mymodule.__name__ ? ? # for more on modules, see ? # http://python.org/doc/2.3.4/tut/node8.html ? ? -------------------- ? # the perl analogue is like this: ? # save the following 3 lines in a file ? # and name it mymodule.pm ? ? # package mymodule; ? # sub f1($){(1..$_[0])} ? # 1 ? ? # then, call it like the following way ? use mymodule; ? use Data::Dumper; ? print Dumper [&mymodule::f1(7)]; ? ? # this is about the simplest way ? # to write a modlue in perl and ? # calling its function. ? # for an inscrutable treatment, ? # see "perldoc perlmod" ? ? Xah ? xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html From generate at gmail.com Tue Jan 4 15:55:54 2005 From: generate at gmail.com (generate at gmail.com) Date: 4 Jan 2005 12:55:54 -0800 Subject: Working with flat files [LDIF]. In-Reply-To: <33A3E2B3.7F5CF6F0@whoi.edu> References: <33A3E2B3.7F5CF6F0@whoi.edu> Message-ID: <1104872154.907906.213620@z14g2000cwz.googlegroups.com> Scott A. McIntyre wrote: > > I looked around but didn't see any LDIF tools for perl or python... > > Any assistance or advice is appreciated!! > > Scott Hello Scott, Did you ever get this issue resolved? I have a similar need to merge two LDIF files. I did find a program called mmldif, but I believe it is proprietary to Sun. Cheers, Charles From a at b.c Sun Jan 23 12:49:09 2005 From: a at b.c (Doug Holton) Date: Sun, 23 Jan 2005 11:49:09 -0600 Subject: compile python to binary In-Reply-To: References: <1d6cdae3050123080242bf8994@mail.gmail.com> Message-ID: <_YCdnROs58UKfm7cRVn-vA@comcast.com> Fredrik Lundh wrote: > Daniel Bickett wrote: > > >>I believe Sam was talking about "frozen" python scripts using tools >>such as py2exe: > > > oh, you mean that "python compiler" didn't mean "the python compiler". > I wouldn't assume a novice uses terms the same way you would. It was quite clear from his message that py2exe and the like were what he was referring to, if you had read his first sentence: "I have seen some software written in python and delivered as binary form." From ewanon at gmail.com Sun Jan 2 23:13:35 2005 From: ewanon at gmail.com (EW) Date: 2 Jan 2005 20:13:35 -0800 Subject: Problem remotely shutting down a windows computer with python Message-ID: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> I have a problem when using the python script found here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/360649 It is a script to remotely shutdown a windows computer. When I use it, the computer shuts down, but doesn't power off like with a regular shutdown. It stays on the "Safe to power off" screen and I have to push the power button to actually power off. Anyone know why this happens with this script? Thanks for any help. Eric From usenet_spam at janc.invalid Wed Jan 5 17:57:33 2005 From: usenet_spam at janc.invalid (JanC) Date: Wed, 05 Jan 2005 22:57:33 GMT Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> Message-ID: Peter Hansen schreef: >> You mean to say that your editor does not have rectangle operations ? >> :-) > > I wouldn't know.** I try quite hard to limit the features > that I have to learn and remember to a very, very small > list. Why the heck would I ever have to do "rectangle > operations" on a regular basis? ;-) > ** I'm using Scite; it probably has it. It has quite a few > features -- far more than I'll ever use. Remarkable how > simple an editor could be and still be effective... for > some people. Rectangular selection only works with the mouse in SciTE/Scintilla: alt-click-drag. Most of SciTE's (editor-)features are also available in other Scintilla based editors. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From b_b at net.hr Fri Jan 14 12:26:04 2005 From: b_b at net.hr (Brane) Date: Fri, 14 Jan 2005 18:26:04 +0100 Subject: python to mssql Message-ID: <1lmwxbtst8x8x$.10hwcoinem3cs.dlg@40tude.net> can someone please give me some info regarding subject please advice regards brane From cjbottaro at alumni.cs.utexas.edu Sat Jan 8 02:17:06 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Sat, 08 Jan 2005 01:17:06 -0600 Subject: How to read/write blobs with mysqldb? Message-ID: First off, writing the blob. From what I gather on the internet, I'm suppose to read the entire file into memory (a Python string), then create a dbiRaw object with that string and use the dbiRaw object in an insert statement? That doesn't sound very efficient to me. What if my computer only has 64 MB of memory and the data I want to insert is 128 MB? It seems like there should be a way to read part of the data, insert that part into the DB, then get the next part, append, etc. Also, what if you are inserting a huge piece of data, like a GB, and you want to have a progress bar in your UI? How would you do that if you couldn't split up the insert statements? Thanks for the help. From douardda at free.fr Sat Jan 29 13:44:26 2005 From: douardda at free.fr (David Douard) Date: Sat, 29 Jan 2005 19:44:26 +0100 Subject: Redirecting stdout/err under win32 platform Message-ID: <41fbd6b5$0$6098$626a14ce@news.free.fr> Hi everybody, let me explain by problem: I am working on an application which consists in a C++ dll (numeric computations) and a Python IHM (Python/Tk), which must run under Linux and win32. My problem is the C++ lib does write stuffs on its stdout, and I would like to print those messages in a Tk frame. When I run the computation, it has it's own thread. So my question is : how van I redirect the dll's stdout to something I can retrieve in Python (pipe, socket,...)? I can do it easily under Linux. I made tests with a socket which just works fine. In the threaded function (that will do the heavy computation), I write: import os, sys from socket import * s=socket(AF_UNIX, SOCK_STREAM) s.connect(...) os.dup2(sys.__stdout__.fileno(), s.fileno()) very_intensive_function(many_parameters) s.close() That's OK under Linux, but does not work under win32 (even if I use an INET localhost socket), cause I cannot do the os.dup2 trick (Windows does not want to consider a socket as a file! What a shity system!). So my question is : is there a simple solution ? I have tested different solutions. I am trying hacks with pipes created with the win32api. But I have not yet managed this simple operation. Note that I have no access to the dll source code, so I cannot modify it so it uses a named pipe (for example) as message output pipe instead os stdout... Thanks, David From SSchukat at dspace.de Fri Jan 28 07:45:06 2005 From: SSchukat at dspace.de (Stefan Schukat) Date: Fri, 28 Jan 2005 13:45:06 +0100 Subject: threading and internet explorer com Message-ID: ... and pythoncom.CoUninitialize() My preferred way is: def run(): pythoncom.CoInitialize() try: ie = win32com.client.Dispatch('InternetExplorer.Application.1') finally: # Trigger the release of the object since after CoUninitialize # it could not be reached ie = None pythoncom.CoUninitialize() Stefan > -----Original Message----- > From: python-list-bounces+sschukat=dspace.de at python.org > [mailto:python-list-bounces+sschukat=dspace.de at python.org]On Behalf Of > Roger Upole > Sent: Friday, January 28, 2005 7:29 AM > To: python-list at python.org > Subject: Re: threading and internet explorer com > > > You'll need to call pythoncom.CoInitialize() in each thread. > > Roger > > "James" wrote in message > news:41f9777f_2 at news.tm.net.my... > > hi, > > > > i'm using python 2.4 with pywin32... > > I've tried to use internet explorer control with a class. > > it was fine until i decided to inherit thread for the class... > > > > class domain01(threading.Thread): > > def __init__(self): > > #blabla > > threading.Thread.__init__(self) > > > > def run(self): > > self.ie = > win32com.client.Dispatch('InternetExplorer.Application.1') #this > > line gives error if i use .start(), but if i use .run.. no error... > > self.ie.Visibble = 1 > > print "running" > > > > > > > > xyz = domain() > > xyz.start() > > > > =========== > > this is what i get: > > Exception in thread Thread-23: > > Traceback (most recent call last): > > File "C:\Python24\lib\threading.py", line 442, in __bootstrap > > self.run() > > File "C:\python2exe\domain01.py", line 41, in run > > self.dologin() > > File "C:\python2exe\domain01.py", line 56, in dologin > > > self.ie=win32com.client.Dispatch('InternetExplorer.Application.1') > > File > "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line > > 95, in Dispatch > > dispatch, userName = > > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > > File > "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line > > 91, in _GetGoodDispatchAndUserName > > return (_GetGoodDispatch(IDispatch, clsctx), userName) > > File > "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line > > 79, in _GetGoodDispatch > > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > > pythoncom.IID_IDispatch) > > com_error: (-2147221008, 'CoInitialize has not been > called.', None, None) > > > > > > > > ===== > > but if i run: > > xyz = domain() > > xyz.run() > > > > ##no error! it's weird.... > > > > anyone know how to solve this problem? > > > > thank you :) > > > > best regards, > > > > James > > > > > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure > Usenet News==---- > http://www.newsfeeds.com The #1 Newsgroup Service in the > World! >100,000 Newsgroups > ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- > -- > http://mail.python.org/mailman/listinfo/python-list > From tim.peters at gmail.com Tue Jan 4 19:46:17 2005 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 4 Jan 2005 19:46:17 -0500 Subject: Restore a unified diff In-Reply-To: References: Message-ID: <1f7befae050104164661991e58@mail.gmail.com> [Nick Allen] > After using ndiff from difflib, the function restore > would return the sequence that generated the delta. It can actually reproduce either sequence from which the delta was generated. But this is really trivial: ndiff was intended to produce diff output for humans to read, and includes the full text of both input sequences in "the diff" it generates. > Unfortunately, restore does not do the same for unified_diff. I do > not see any similar function that is intended for unified_diff. Does > anyone know how to "restore" from a unified diff generated delta? That's in general impossible, since unified diffs generally omit most lines that compared equal to begin with. Unified and context diffs are, in part, compression gimmicks, showing only what changed plus a bit of context. ndiff shows everything, so can restore everything too. From jeremy+plusnews at jeremysanders.net Wed Jan 26 04:50:19 2005 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Wed, 26 Jan 2005 09:50:19 +0000 Subject: Python with no significant whitespace References: <35oh4gF4nvvfoU1@individual.net> Message-ID: On Wed, 26 Jan 2005 11:31:18 +0800, mep wrote: > Hi,all > Is there anybody trying to release a modification version to current > python source code with no significant whitespace, say replacing whitespace > by {} > like C or java. I do *NOT* mean whitespace is good or bad, just > want to know. It probably would be easy to convert source in the form using brackets to indented form on the fly, and use exec to interpret the converted form. You need to do something like convert XXXX { to XXXX: foo Of course this isn't a good idea. Jeremy From aahz at pythoncraft.com Thu Jan 27 20:48:13 2005 From: aahz at pythoncraft.com (Aahz) Date: 27 Jan 2005 20:48:13 -0500 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Message-ID: In article <1106863164.745581.11920 at f14g2000cwb.googlegroups.com>, wrote: > >Who are the appropriate people to report security problems to in >respect of a module included with the Python distribution? I don't >feel it appropriate to be reporting it on general mailing lists. There is no generally appropriate non-public mechanism for reporting security issues. If you really think this needs to be handled privately, do some research to find out which core developer is most likely to be familiar with it. Even before you do that, check SourceForge to find out whether anyone else has reported it as a bug. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From roccomoretti at hotpop.com Mon Jan 24 20:20:40 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Mon, 24 Jan 2005 19:20:40 -0600 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: Message-ID: Roy Smith wrote: > In article , > Quest Master wrote: > >>So, my question is simply this: is there an implementation of another >>scripting language into Python? > > Python *is* a scripting language. Why not just let your users write > Python modules which you them import and execute via some defined API? I can think of a couple of reasons off the top of my head: The OP doesn't mention his application, but there is something to be said about domain specific scripting languages. A well designed domain-specific scripting language(*) with the appropriate high level constructs can make script writing simpler. There's also an audience factor. Python is easy to learn, but it's still a programming language. A well designed domain-specific scripting language(*) can make it very easy to get work done in a particular case without having to learn the Python mind frame. (How assignments work, mutable/immutable, Python's call passing system, etc.) Python's also dangerous. Every time you do an "import module", you put your system at risk of crashing, having the hard-drive wiped, sending incorrect signal codes to peripherals, etc. A well-designed specialty language(*) minimizes those risks - don't need disk access? Don't allow it in your language. There's also the valuable learning experience of designing and implementing a scripting language. (*) Note that I keep saying "well-designed". A poorly designed scripting language is very bad - you can feel shackled by the restrictions it imposes, and find yourself unable to do what you want without laborious contortions, if at all. I also say "domain specific" because, at this time, there are enough general purpose scripting languages that you are likely to find what you need already existing, unless you are experimeting with a completely new programing paradigm. To answer the OP's question: Yes - sort of. Currently work is underway to implement the Python scripting language in Python. Cleverly called "PyPy", the website is "http://www.codespeak.net/pypy". From tonino.greco at gmail.com Fri Jan 21 09:54:30 2005 From: tonino.greco at gmail.com (Tonino) Date: 21 Jan 2005 06:54:30 -0800 Subject: tkinter socket client ? In-Reply-To: <1106318469.311179.126140@c13g2000cwb.googlegroups.com> References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> <1106318469.311179.126140@c13g2000cwb.googlegroups.com> Message-ID: <1106319270.932204.180590@c13g2000cwb.googlegroups.com> hi there , yeah - had a look at createfilehandler() - was a bit confusing - but your example helps ;) Thanks Tonino From fuzzyman at voidspace.org.uk Wed Jan 12 05:25:29 2005 From: fuzzyman at voidspace.org.uk (Fuzzyman) Date: Wed, 12 Jan 2005 10:25:29 +0000 Subject: [Ann] PyName and downman Message-ID: <41E4FB19.8010707@voidspace.org.uk> A couple of new 'modules' available from Voidspace Pythonutils. PyName http://www.voidspace.org.uk/python/modules.shtml#pyname Slightly tongue in cheek, this isn't really a python module. It's three lists of English words containing 'py' - intended to be helpful to those choosing names for python projects. The word lists were produced from an initial file of about 8mb. Words selected all contain 'py', single words or hyphenated words, but no compound words. * pywordlist.txt All words contain 'py' 23kb - 1946 words * pywordlist2.txt All words starting or ending in 'py' 16kb - 1406 words * pywordlist3.txt All words as pywordlist2, but only words less than 10 chars long 5kb - 658 words. downman.py Version 0.2.1 14th December 2004 Simple Download Manager http://www.voidspace.org.uk/python/cgi.shtml#downman This is a simple download manager tool. It may be egotistical, but I like to know which of my projects are being downloaded (and which aren't). Simply make your files available in a single directory and have the links point to downman (see the download link for downman itself for an example) and downman will track the downloads. At the moment it only presents simple data - but all the raw data is collected to do per week/last month (or whatever) analysis. It will also manage links as well. See the example output at http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py Regards, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From aahz at pythoncraft.com Sat Jan 8 11:07:43 2005 From: aahz at pythoncraft.com (Aahz) Date: 8 Jan 2005 11:07:43 -0500 Subject: "A Fundamental Turn Toward Concurrency in Software" References: <1105171949.823433.72860@f14g2000cwb.googlegroups.com> Message-ID: In article <1105171949.823433.72860 at f14g2000cwb.googlegroups.com>, wrote: >Michele deleted an attribution: >> >> So I've always had it in >> the back of my mind that languages that can easily support massive >> (especially automatic) parallelization will have their day in the sun, >> at least someday. > >and the language of the future will be called ... FORTRAN! > >:-) > >(joking, but it is the only language I know supporting massive >parallelization ...) Less of a joke than you think, perhaps. Back in the early 1980s, a family friend said something like, "In the year 2000, there will be a programming language. I don't know what it will look like, and I don't know what it will do. But I do know one thing: it will be called FORTRAN." After all, FORTRAN 2003 contains OOP support.... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From info at frengky.no Fri Jan 7 09:58:06 2005 From: info at frengky.no (Øystein Western) Date: Fri, 7 Jan 2005 15:58:06 +0100 Subject: countint words from an input string Message-ID: Hello! Try to write som code that will get an input string from the user. Futher more, I'd like to have the program to count all the word the user has written. Startet out like this: /------------- s = raw_input("Write a text line") print s.split() /---------------- How can I count the words in the split function. Do I have to use the split function to count the words in the S variable? Regards Frengky -- Organisation nr: 983063349 Frengky, Olsokveien 65,1727 Sarpsborg, Norway Tel: +47 92611725 Fax: +47 69152017 Email: oystein.western at frengky.no Web: www.frengky.no From steve at holdenweb.com Thu Jan 6 10:40:59 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 10:40:59 -0500 Subject: Embedding a restricted python interpreter In-Reply-To: References: Message-ID: <41DD5C0B.3030007@holdenweb.com> Jp Calderone wrote: [...] > > > A Python sandbox would be useful, but the hosting provider's excuse > for not allowing you to use mod_python is completely bogus. All the > necessary security tools for that situation are provided by the > platform in the form of process and user separation. Not sure this is strictly true: mod_python gets loaded into the server's address space and gives the ability to add any type of handler. While Apache might well be able to respawn failed subprocesses, it's not something that most hosting providers would like to have to do all the time for many hosted sites. 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 jeff at ccvcorp.com Thu Jan 6 17:27:55 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jan 2005 14:27:55 -0800 Subject: The Industry choice In-Reply-To: References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: <10trej2fl8dip65@corp.supernews.com> Bulba! wrote: > On Thu, 06 Jan 2005 08:39:11 GMT, Roel Schroeven > wrote: > >>That's generally the goal of the Free Software Foundation: they think >>all users should have the freedom to modify and/or distribute your code. > > You have the freedom of having to wash my car then. ;-) A more accurate analogy would be, "You're free to borrow my car, but if you do, you must wash it and refill the gas tank before you return it." Note that the so-called 'viral' nature of GPL code only applies to *modifications you make* to the GPL software. The *only* way in which your code can be 'infected' by the GPL is if you copy GPL source. Given the standard usage of closed-source software, you never even have access to the source. If you use GPL software in the same way that you use closed-source software, then the GPL cannot 'infect' anything you do. The 'infective' nature of the GPL *only* comes when you make use of the *extra* privelidges that open source grants. So yes, those extra privelidges come with a price (which is that you share what you've done); but if you don't want to pay that price, you have the choice of not using those privelidges. This does not, in any way, prevent you from using GPL'ed software as a user. (Problems may come if someone licenses a library under the GPL; that's what the LGPL was invented for. But the issue here is not that the GPL is bad, it's that the author used the wrong form of it.) Personally, I'm not a big fan of the GPL. I'm much more likely to use BSD-ish licenses than [L]GPL. But it still bugs me to see the GPL misrepresented as some plot to steal the effort of hardworking programmers -- it is, instead, an attempt to *encourage* hardworking programmers to share in a public commons, by ensuring that what's donated to the commons remains in the commons. Jeff Shannon Technician/Programmer Credit International From davorss at gmail.com Tue Jan 25 16:49:48 2005 From: davorss at gmail.com (Davor) Date: 25 Jan 2005 13:49:48 -0800 Subject: python without OO Message-ID: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Is it possible to write purely procedural code in Python, or the OO constructs in both language and supporting libraries have got so embedded that it's impossible to avoid them? Also, is anyone aware of any scripting language that could be considered as "Python minus OO stuff"? (As you can see I'm completely new to Python and initially believed it's a nice&simple scripting language before seeing all this OO stuff that was added in over time) Thanks, Davor From lbolognini at gmail.com Thu Jan 6 06:26:10 2005 From: lbolognini at gmail.com (lbolognini at gmail.com) Date: 6 Jan 2005 03:26:10 -0800 Subject: wxPython clipboard Message-ID: <1105010770.911397.278520@c13g2000cwb.googlegroups.com> Hi all, I'm thinking about coding a free version of this software: http://www.pitrinec.com/pkindex.htm I would use wxPython and wx.Clipboard class (hoping to be able to make it cross-platform) The software above detects macros you code in any Windows active window and replaces them with a text: something like you write "/ff" and he pastes "Feel free to call us back for whatever questions you might have". This kind of softwares are very usefull in a call-centre environment (where I'm currently working). The thing is I'm thinking about the best approach (in terms of CPU resources) to detect the macro. Not sure how keyloggers work but I suspect I could run a service that compares everything beign written in the active window with the macros I saved in the software configuration. Could you please give me some advice on the best approach to solve this problem? Thanks a lot, Lorenzo -- http://www.bolognini.net/ From aleaxit at yahoo.com Wed Jan 5 13:05:37 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 5 Jan 2005 19:05:37 +0100 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> <1gpx56v.yb9ubn188tj2yN%aleaxit@yahoo.com> Message-ID: <1gpxj3q.1uqc3s6sy7m08N%aleaxit@yahoo.com> Roman Suzi wrote: > Alex, I think you are +10 for adding interfaces into Python. "Concept" > is more compact word and I am sure it is not used as a name in existing > projects, unlike other words. Actually, I want protocols -- semantics (and pragmatics), too, not just syntax (method names and signatures). Eby's PyProtocols comes closest to my desiderata (though it possibly exceeds them). But if you start coding a PyConcepts alternative to PyProtocols I'll be delighted to try it out, contribute, &c -- I won't be a stickler for the name. Indeed, "protocol" is no doubt more overloaded, since it's an established name in networking, and if you google for "protocol adaptation" you get a mix mostly related to networking with a few examples of the way PEP 246 uses the phrase thrown in;-). Alex From peter at engcorp.com Fri Jan 14 23:32:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 14 Jan 2005 23:32:50 -0500 Subject: porting C code In-Reply-To: References: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> <0NidnetRONZTgHrcRVn-oQ@powergate.ca> Message-ID: Lucas Raab wrote: > Sorry, the third "byte" is what I meant. Fair enough. Note, however, that as someone pointed out, it's actually the *fourth* of something, and it would not necessarily be a byte. In fact, in your case, it's not: > typedef unsigned long int word32 ; > void mu(word32 *a) > { > int i ; > word32 b[3] ; This defines an array of *3* long (32-bit) integers. > b[0] = b[1] = b[2] = 0 ; Each of these is just indexing into that array, starting as Python does with an index origin of zero. > The "a[#]" and "b[#]" are the parts that are giving me trouble. Between the clarifications you've got and Duncan's post, you shouldn't have much more trouble now. :-) -Peter From peter at engcorp.com Sun Jan 9 09:45:33 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 09:45:33 -0500 Subject: Python Installation In-Reply-To: <1105232505.142279.85810@c13g2000cwb.googlegroups.com> References: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> <1105232505.142279.85810@c13g2000cwb.googlegroups.com> Message-ID: Simon John wrote: > I would say install on one machine, then just copy the C:\Python24 > directory, but then you'd have to deal with the missing Registry > entries.... That part is pretty trivial to automate as well. Fredrik Lundh has a useful utility on his web site that will do much of what is required. Google for his name and "python registry" to find out more. -Peter From ncoghlan at iinet.net.au Mon Jan 17 06:18:15 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 17 Jan 2005 21:18:15 +1000 Subject: getting a class attribute using a keyword argument In-Reply-To: References: Message-ID: <41EB9EF7.60203@iinet.net.au> Guy Robinson wrote: > Hello, > > I have a list of class instances. I wish to get the appropriate class > attribute in each class instance depending on a SINGLE keyword in the > calling class. Py> help(getattr) Help on built-in function getattr in module __builtin__: getattr(...) getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From theller at python.net Thu Jan 6 07:39:35 2005 From: theller at python.net (Thomas Heller) Date: Thu, 06 Jan 2005 13:39:35 +0100 Subject: Is there any way/where to subscribe for automated PEP status emails? References: <41dc24f8.68802652@news.oz.net> Message-ID: Nick Coghlan writes: > Thomas Heller wrote: >> You could probably subscribe to python-checkins, and filter it. >> Or read it via gmane. > > Hmm - can SF be used to setup a mailing list just for checkins to a > single directory in the source tree? Yes. You should suggest this on python-dev. > If so, that would seem to be an easy way to provide a > python-pep-updates mailing list. > > Cheers, > Nick. Thomas From skullw at sina.com.cn Sat Jan 15 21:07:27 2005 From: skullw at sina.com.cn (skull) Date: Sat, 15 Jan 2005 21:07:27 -0500 Subject: How to del item of a list in loop? References: <34rvjqF4f6l70U1@individual.net> <34s7omF4emdsaU1@individual.net> Message-ID: Reinhold Birkenfeld writes: >> Quick solution: >> >> for i in lst[:] >> >> iterates over a copy. > > Addition: In Py2.4, I can't find a problem with > > for i in reversed(lst) > > Any objections? > > Reinhold I just downloaded py2.4, and made a test using reversed. it sure be no problem, I thought maybe the reversed holded a copy of list, and eventually iterated through the copy. but the truth is not as I thought so: import sys class Test: pass lst = [Test(),Test(),Test()] E1: for i in lst[:]: E2: for i in reversed(lst): print sys.getrefcount(i) ################### E1 outputs: 4 4 4 E2 outputs: 3 3 3 It looks that the reversed does not make a copy of list in contrast with lst[:]. so should we regard: reversed is faster than lst[:]? I do not have any idea about why it is. - skull From fccoelho at gmail.com Tue Jan 11 10:51:35 2005 From: fccoelho at gmail.com (Flavio codeco coelho) Date: 11 Jan 2005 07:51:35 -0800 Subject: Python serial data aquisition References: <41e384d0.552090624@news.oz.net> Message-ID: bokr at oz.net (Bengt Richter) wrote in message news:<41e384d0.552090624 at news.oz.net>... > On 9 Jan 2005 14:13:28 -0800, fccoelho at gmail.com (Flavio codeco coelho) wrote: > > >Hi, > > > >I am using pyserial to acquire data from an A/D converter plugged to > >my serial port. > > > >my hardware represents analog voltages as 12bit numbers. So, according > >to the manufacturer, this number will be stored in two bytes like > >this; > > |-------------bits(1-8)-----------| > >Byte1: x x x n1 n2 n3 n4 n5 > >Byte2: x n6 n7 n8 n9 n10 n11 n12 > > > >where x is some other information, and nx are the digits of my number. > > > >My problem is to how to recover my reading from these bytes, since > >pyserial gives me a character (string) from each byte... I dont know > >how to throw away the unneeded bits and concatenate the remaining > >bits to form a number... > > > The others have shown how to recover a 12 bit positive value 0 through 4095, > but if the number is signed, and you want the signed value, you'll have to > find out how signed numbers are represented. An offset is common, in which > case you would subtract 2048 (2**11). If it's two's complement by some chance, > you'll want (I think -- untested ;-) to do num -= 2*(num&2048) instead of always num -= 2048 > If you need speed in converting large strings of byte pairs, you could > convert pairs of bytes with the array module ('H' for unsigned 2-byte numbers) > and use the resulting 16-bit numbers as indices into another array of final values > prepared beforehand with redundant information that will accomplish the effect > of masking and shifting and adjusting sign. > If you need this speed, volunteers will magically appear. Maybe even if you don't ;-) > Regards, > Bengt Richter Hi Bengt, The Idea of using Array is realy cool Though I have to think about it since I would to plot the values as they are sampled... Anyway, how would you set up this array to do the shifting and masking? BTW, since this thread is generating quite a bit of attention let me post a complete description of my problem so that it may serve as reference to others: Hardware: DI-151RS from Dataq (2 analog channels, 2 digital input, single ended/differential recording, max sampling rate 240Hz) connects to the serial pro through a standard db9 plug. Encryption table: B7 B6 B5 B4 B3 B2 B1 B0 Byte1 A4 A3 A2 A1 A0 1 Din 0 Byte2 A11 A10 A9 A8 A7 A6 A5 1 Byte3 B4 B3 B2 B1 B0 1 Din 1 Byte4 B11 B10 B9 B8 B7 B6 B5 1 first two bytes are for analog ch 1 and remaining two are for ch 2. Din stands for digital in. AXX and BXX are the nth bits of each reading. A0 and B0 are the least significant bits. The latest and preferred solution on how to convert these bytes is, according to the suggestion of Chris Liechti (author of pyserial) is: (this is for the first channel only, repeat for the second) import struct l, h = struct.unpack(">BB", ser.read(2)) n = (l >> 3) + ((h >> 1)<<5) struct.unpack returns a tuple of values represented by a string(the output of the read command) packed according to the format specified by ">BB" In this forma string, ">" stands for big Endian representation and "B" stands for unsigned char. If anyone has a better suggestion, speack up! oof! I started this thread knowing next to nothing about this stuff, It seem that I am finally getting the idea! :)) cheers, Fl?vio From steve at holdenweb.com Sun Jan 2 09:17:47 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Jan 2005 09:17:47 -0500 Subject: The Industry choice In-Reply-To: <7xekh423b6.fsf@ruckus.brouhaha.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xfz1lal5d.fsf@ruckus.brouhaha.com> <7xekh423b6.fsf@ruckus.brouhaha.com> Message-ID: <_rTBd.66275$Jk5.46@lakeread01> Paul Rubin wrote: > Steve Holden writes: > >>>It seems to me >>>that IDLE and a lot of the rest of Python are examples of someone >>>having a cool idea and writing a demo, then releasing it with a lot of >>>missing components and rough edges, without realizing that it can't >>>reasonably be called complete without a lot more work. >> >>^Python^open source^ > > > I wouldn't say so. I'd say the Linux kernel, GCC, Emacs, Apache, > Mozilla, etc. are all developed with a much more serious attitude than > Python is. Of course there are lots of other FOSS programs that > someone wrote for their own use and released, that are less polished > than Python, but that are also the subject of less advocacy than Python. Well clearly there's a spectrum. However, I have previously written that the number of open source projects that appear to get stuck somewhere between release 0.1 and release 0.9 is amazingly large, and does imply some dissipation of effort. Give that there's no overall coordination this is of course inevitable, but some open source projects are doomed from the start to be incomplete because the original authors have never been involved in producing software with a reasonably large user base, and so their production goals and quite often their original specifications (where there are any) are unrealistic. These projects meander towards a half-assed initial implementation and then become moribund. This is not to tar respectable projects like Linux, many (but not all) of the Gnu projects, and Python with that same brush, and personally I think the Python *core* is pretty solid and quite well-documented, but I don;t regard IDLE as part of the core myself. Since I'm not an active developer, this may not be in line with python-dev's opinions on the matter. 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 sbryce at scottbryce.com Sun Jan 9 20:31:44 2005 From: sbryce at scottbryce.com (Scott Bryce) Date: Sun, 09 Jan 2005 18:31:44 -0700 Subject: a new Perl/Python a day In-Reply-To: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > frustrated constantly by its inanities and incompetences.) I don't see what this has to do with Perl. From bj_666 at gmx.net Wed Jan 12 15:24:42 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 12 Jan 2005 21:24:42 +0100 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <41e41633$1@nntp0.pdx.net> <41e458a9$0$7090$8fcfb975@news.wanadoo.fr> Message-ID: In <41e458a9$0$7090$8fcfb975 at news.wanadoo.fr>, Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: > I understand, but I have a feeling of attempt at hegemony. Is english > language really least-common-denominator for a russian who writes into > cyrillic, or not anglophone chinese? > > And, did you think of klingons? Klingons don't do Python, they hack ('n slash) in var'aq: http://www.geocities.com/connorbd/varaq/ SCNR, Marc 'BlackJack' Rintsch From flamesrock at gmail.com Thu Jan 27 19:58:24 2005 From: flamesrock at gmail.com (flamesrock) Date: 27 Jan 2005 16:58:24 -0800 Subject: Question about 'None' In-Reply-To: <2fCdnYr1l-CZwmTcRVn-ig@comcast.com> References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> <2fCdnYr1l-CZwmTcRVn-ig@comcast.com> Message-ID: <1106873904.761513.153710@z14g2000cwz.googlegroups.com> Wow! Thanks for all the replies. I'll have to reread everything to absorb it. The test code is pretty simple: if 2 > None: print 'true' else: print 'false' It prints false every time. I should also mention that I'm using version 2.0.1 (schools retro solaris machines :( ) At home (version 2.3.4) it prints out 'True' for the above code block. From ptmcg at austin.rr._bogus_.com Mon Jan 17 14:13:34 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 17 Jan 2005 19:13:34 GMT Subject: Assigning to self References: <200501171845.46766.frans.englich@telia.com> <1105988333.379592.327600@z14g2000cwz.googlegroups.com> Message-ID: wrote in message news:1105988333.379592.327600 at z14g2000cwz.googlegroups.com... > An implementation of what you want can be found here: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558 > I think this recipe pre-dates the introduction of __new__ in Python. How about something like this (requires the name to be the first constructor argument): ------------------------------------------- class RegisteredObject(object): registry = {} def __new__(cls,name,*args,**kwargs): if name not in cls.registry: cls.registry[name] = object.__new__(cls) return cls.registry[name] class foo (RegisteredObject): def __init__(self,name): self.myName = name def yo(self): return self.myName def main(): a = foo( "test" ) print "ATTR:", a.yo() print id(a) b = foo( "test" ) print "ATTR:", b.yo() print id(b) c = foo( "test2" ) print "ATTR:", c.yo() print id(c) if __name__ == "__main__": main() ---------------------------------------------- gives: ATTR: test 7886256 ATTR: test 7886256 ATTR: test2 7887984 -- Paul From stephen.thorne at gmail.com Sun Jan 30 20:14:21 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Mon, 31 Jan 2005 11:14:21 +1000 Subject: Problem with loading textfiles into dictionaries. In-Reply-To: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> References: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> Message-ID: <3e8ca5c805013017145017e17f@mail.gmail.com> On 30 Jan 2005 16:43:26 -0800, mercuryprey at gmail.com wrote: > Hello, > I want to do the following: > > def do_load(self, arg): > sitefile = file('sitelist', 'r+', 1) > while True: > siteline = sitefile.readline() > site_rawlist = siteline.split() > sitelist[site_rawlist[0]] = site_rawlist[1:] > if len(siteline) == 0: > break maybe you would be better off doing something slightly simpler, and in such a way that you see the input which is causing problems. sitelist = {} for line in file('sitelist'): elems = line.split() if len(elems) == 1: raise ValueError, "Invalid line in file %r" % line sitelist[elem[0]] = elem[1:] :) Stephen From engsolnorm at peak.org Wed Jan 12 21:02:49 2005 From: engsolnorm at peak.org (engsol) Date: Wed, 12 Jan 2005 18:02:49 -0800 Subject: pyserial and com port interrupts References: Message-ID: <24lbu0htudrc9ir4b0na3r1m6g09qlbck4@4ax.com> On Wed, 12 Jan 2005 17:45:48 -0500, Peter Hansen wrote: >engsol wrote: >> Has anyone done a script that will rspond to the serial com port(s) >> receive buffer interrupt, as opposed to polling and timeouts? >> Win2000 is the main interest right now. > >What problem do you hope to avoid by not using "polling >and timeouts"? (Note that if you specify a sizable >read timeout, you're closer to being interrupt-driven >than you are to what is traditionally called "polling".) > >-Peter Peter, Thanks for the reply. I'm working on a s/w test program using python code. Com1 and com2 play a part. The problem is that the python code has a lot of work to do...and the results from the hardware under test can come from either com1 or com2...at any time. It may be a few milliseconds, or several seconds, sometimes minutes, before a response is expected. I'm not sure what timeout value I'd use. Using threads, and re-loading the timeout values on the fly may be a solution, but I'm not experienced with threads....and was hoping to avoid them. Norm B From aleaxit at yahoo.com Mon Jan 10 04:51:01 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 10 Jan 2005 10:51:01 +0100 Subject: Getting rid of "self." References: <1gq4ery.1v79c2t9lsfinN%aleaxit@yahoo.com> <10u2dlj4p45psf0@news.supernews.com> Message-ID: <1gq64d2.1iwvg0313tohejN%aleaxit@yahoo.com> BJ?rn Lindqvist wrote: ... > > http://starship.python.net/crew/mwh/hacks/selfless.py > > That's excellent! There is one small problem with the code though: It shows the fundamentals of how to rewrite the bytecode, yes. > .class Hi(Selfless): > . __attrs__ = ["x"] > . def __init__(x): > . self.x = x > > In this case, I think the Python interpreter should realise that the > parameter x shadows the attribute x. But the selfless code has > problems with that. I want it to work exactly like how the situation > is handled in Java and C++. I believe you're referring to the test in rewrite_method: if op.arg < code.co_argcount: raise ValueError, "parameter also instance member!" If you think that parameters that are also instance members should "shadow" instance members, just skip the op.arg cases which are less than code.co_argcount -- those are the parameters. > > Alex Martelli: > > A decorator can entirely rewrite the bytecode (and more) of the method > > it's munging, so it can do essentially anything that is doable on the > > basis of information available at the time the decorator executes. > > Which I believe means that the instance variables have to be declared > in the class? I am content with declaring them like the selfless > approach does: It means the information about which names are names of instance attributes must be available somewhere, be that "declared", "inferred", or whatever. For example, many C++ shops have an ironclad rule that instance attributes, and ONLY instance attributes, are always and invariably named m_. If that's the rule you want to enforce, then you don't necessarily need other declarations or inferences, but rather can choose to infer the status of a name from looking at the name itself, if you wish. "Declarations" or other complications yet such as: > alternative would be not to declare the variables in an __attr__ list, > and instead let them be "declared" by having them initialised in the > __init__. I.e: > > .def __init__(hi, foo): > . self.hi = hi > . self.foo = foo > > When the metaclass then does it magic, it would go through the code of > the __init__ method, see the assignments to "self.hi" and "self.foo", > decide that "hi" and "foo" are attributes of the object and replace > "hi" and "foo" in all other methods with "self.hi" and "self.foo". The OK, but this approach is not compatible with your stated desire, which I re-quote...: > I want it to work exactly like how the situation > is handled in Java and C++. ...because for example it does not deal with any attributes which may be initialized in a *superclass*'s __init__. However, I guess it could be extended at the cost of some further lack of transparency, to obtain just as horrid a mess as you require, where it's impossible for any human reader to guess whether, say, hi = 33 is setting a local variable, or an instance variable, without chasing down and studying the sources of an unbounded number of superclasses. I do not think there is any _good_ solution (which is why many C++ shops have that rule about spelling this m_hi if it's an instance variable, keeping the spelling 'hi' for non-instance variables -- an attempt to get SOME human readability back; a smaller but non-null number of such shops even achieve the same purpose by mandating the use of 'this->hi' -- just the Python rule you want to work around, essentially). The least bad might be to rely on __attrs__, enriching whatever is in the current class's __attr__ with any __attrs__ that may be found in base classes PLUS any member variables specifically set in __init__ -- if you focus on convenience in writing the code, to the detriment of ability to read and understand it; or else, for more readability, demand that __attrs__ list everything (including explicitly attributes coming from subclasses and ones set in any method by explicit "self.whatever = ...") and diagnose the problem, with at least a warning, if it doesn't. Yes, there's redundancy in the second choice, but that's what declarations are all about: if you want to introduce the equivalent of declarations, don't be surprised if redundancy comes with them. > downside is that it probably could never be foolproof against code > like this: > > .def __init__(hi, foo): > . if hi: > . self.hi = hi > . else: > . self.foo = foo > > But AFAIK, that example is a corner case and you shouldn't write such > code anyway. :) I don't see any problem with this code. A static analysis will show that both hi and foo are local variables. Either may be not initialized, of course, but having to deal with variables which are not initialized IS a common problem of C++: you said you want to do things like in C++, so you should be happy to have this problem, too. > > Alex Martelli: > > You do, however, need to nail down the specs. What your 'magic' does > > is roughly the equivalent of a "from ... import *" (except it > > ... > > Then, you must decide whether this applies to all names the method > > accesses (which aren't already local). For example, if the method > > has a statement such as: > > x = len(y) > > All names should be checked like this: > 1. Is the name in the parameter list? If so, do not rebind it. > 2. Is the name in the objects attribute list? If so, prepend "self." > 3. Do stuff like normal. That's basically what the already-mentioned "selfless" does, then, with the small change to consider name conflicts (parameter vs instance attribute) to be OK rather than errors, as above mentioned; and possibly larger changes to determine the attribute names, depending on what strategy you want to pursue for that. > > Alex Martelli: > > If you can give totally complete specifications, I can tell you > > whether your specs are doable (by a decorator, or other means), how, > > and at what cost. Without knowing your specs, I can't tell; I can > > _guess_ that the answer is "probably doable" (as long as you're not > > demanding the code in the decorator to be an oracle for the future, > > This is promising, I'm content with whatever slowdowns necessary as > long as I can prove those who say "you can't do it" wrong. :) It seems Nobody (that I saw) said you can't do it, as long as you're willing to pay the price in terms of some mixture of extra stuff to write (__attrs__ or whatever), more difficulty in human reading (not being able to tell locally what's a local variable and what isn't), new and interesting kinds of errors such as "uninitialized member variables", and time to execute the class statement or its methods, depending on the exact mix and strategies you choose. > to me that it should be doable by having the metaclass that modifies > the class go through the class and bytecode-rewrite all its methods. > So there has to be a big slowdown when the class is created, but after > that, it should execute at pure Python speed? That doesn't seem to > hard, and pretty robust too since bytecode doesn't change so often. Starting with "selfless" and the few extra pointers I've given, I agree it should not be too hard. Not sure what you mean by bytecode not changing often: the bytecode rewrite will happen every time you execute the 'class' statement, and only then. > And THEN I'll rewrite python-mode so that it syntax highlights member > attributes! It will be cool. This part might well be pretty hard, given the possibility of inheritance from classes that might be anywhere at all -- sys.path can change dynamically, so to know exactly what classes from other modules your class is inheriting from (and that is crucial to determine which names are those of instance attributes) basically requires executing all the program up to the 'class' statement. If you're keen on this part I suggest you use one of the approaches that also facilitate human reading: for exactly the same reasons they'll facilitate the highlighting. Either use something like m_ as the name for instance attributes, or have all instance attributes listed in __attrs__, considering it an error (worth at least a warning... and a lack of highlighting!) to use other instance attributes (from superclasses or whatever) that _aren't_ listed in __attrs__. Alex From aleaxit at yahoo.com Sat Jan 22 08:10:35 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 14:10:35 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <1gqsayh.th49i518ixczeN%aleaxit@yahoo.com> <7xpszxljra.fsf@ruckus.brouhaha.com> Message-ID: <1gqsmuk.n2y4senmpr3fN%aleaxit@yahoo.com> Paul Rubin wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > > If it changed the semantics of for-loops in general, that would be quite > > inconvenient to me -- once in a while I do rely on Python's semantics > > (maintaining the loop control variable after a break; I don't recall if > > I ever used the fact that the variable is also maintained upon normal > > termination). > > Some languages let you say things like: > for (var x = 0; x < 10; x++) > do_something(x); > and that limits the scope of x to the for loop. That seems like a > reasonable way to offer for-loops that don't leak. Yes, that's how C++ introduced it, for example. But note that, after waffling quite a bit in various betas of VC++, Microsoft ended up having this form *not* limit the scope, for years, in two major releases; I'm not privy to their reasons for accepting the syntax but rejecting its key semantic point, and I think they've finally broken with that in the current VC++ (don't know for sure, haven't used MS products for a while). But it sure made for quite a long transition period. It's far from clear to me that it's worth complicating Python by introducing a third form of loop, next to normal while and for ones, to mean "a for loop whose control variables are hyperlocalized" (plural, in general, of course -- ``for n, v in d.iteritems():'' etc). > > (musing...): I think the reason there's no real use case for using a > > listcomp's control variable afterwards is connected to this distinction: > > listcomps have no `break'... > > Of course you can still break out of listcomps: You can abort them by having an exception raised -- that's quite a different issue. > class oops: pass > def f(x): > if x*x % 11 == 3: raise oops > return x*x > try: > lcomp = [f(x) for x in range(10)] > except oops: pass > print x > > prints "5" This way, you don't get anything assigned to lcomp. break is quite different from raise, which aborts the whole caboodle up to the handler. Alex From merkosh at hadiko.de Sat Jan 1 17:15:55 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Sat, 01 Jan 2005 23:15:55 +0100 Subject: UserDict deprecated References: Message-ID: Saturday 01 January 2005 22:48 pm Hans Nowak wrote: > Uwe Mayer wrote: > >> Why is the UserDict module is deprecated after Python 2.2. The >> application of it I have in mind is, i.e. multiple inheritance from >> "file" and "dic" - which is not possible. > I am curious, what would you do with a class that derives from both file > and dict? I was writing a class that read /writes some binary file format. I implemented the functions from the file interface such that they are refering to records. However, the file format has some header fields and I'd wanted to grant access to those via the dict-interface. Another example: working with PyQt I have an instance of a QListView and wanted to use the list-interface to get and set individual records. Ciao Uwe From kartic.krishnamurthy at gmail.com Sun Jan 9 11:16:58 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 9 Jan 2005 08:16:58 -0800 Subject: use a file as a database, access rights In-Reply-To: References: Message-ID: <1105287418.765236.250270@c13g2000cwb.googlegroups.com> Steve Holden wrote: > Sounds to me like you need to add a rights layer to gadfly. Aha...I did not consider that possibility. I have not gone indepth into Gadfly...is that a straigtforward thing to implement? From jeff at ccvcorp.com Thu Jan 6 15:43:18 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jan 2005 12:43:18 -0800 Subject: What could 'f(this:that=other):' mean? In-Reply-To: <41DCE28B.70806@pytex.org> References: <41DC52CA.5070104@pytex.org> <10toomjdjcs5v21@corp.supernews.com> <41DCE28B.70806@pytex.org> Message-ID: <10tr8eo5skqo2a3@corp.supernews.com> Jonathan Fine wrote: > Jeff Shannon wrote: > >> Jonathan Fine wrote: >> >>> Giudo has suggested adding optional static typing to Python. >>> (I hope suggested is the correct word.) >>> http://www.artima.com/weblogs/viewpost.jsp?thread=85551 >>> >>> An example of the syntax he proposes is: >>> > def f(this:that=other): >>> > print this > > > > >>> I'm going to suggest a different use for a similar syntax. >>> >>> In XML the syntax >>> > >>> is used for name spaces. >>> >>> Name spaces allow independent attributes to be applied to an >>> element. For example, 'fo' attributes for fonts and layout. >>> XSLT is of course a big user of namespaces in XML. >>> >>> Namespaces seems to be a key idea in allow independent >>> applications to apply attributes to the same element. >>> [...] >>> Here's an example of how it might work. With f as above: >>> > f(this:that='value') >>> {'that': 'value'} >> >> >> >> I fail to see how this is a significant advantage over simply using >> **kwargs. It allows you to have multiple dictionaries instead of just >> one, that's all. And as you point out, it's trivial to construct your >> own nested dicts. > > > This argument could be applied to **kwargs (and to *args). In other > words, **kwargs can be avoided using a trivial construction. The use of *args and **kwargs allows functions to take a variable number of arguments. The addition of ***nsargs does not add significantly. Note that *args and **kwargs should always be used together, because to do otherwise would require the function caller to know details of the function's implementation (i.e. which arguments are expected to be positional and which must be keywords). Since we *want* the caller to not need to know this, then ***nsargs would always need to be used together with *args and **kwargs. (A function defined 'def f(***nsargs): ...' could not be called with 'f(1)'. This means that all you're gaining is an extra bag to put variable numbers of arguments in. The value here is that it maintains a parallel with *args and **kwargs when one allows 'namespaced' arguments -- if one allows that, then ***nsargs is required for consistency's sake, but it does not simplify anything by itself. So really, we need to look at what gains we'd get from having 'namespaced' arguments. What's the real advantage here? When using 'namespace' arguments, instead of standard keyword arguments, the function body would be given a dictionary instead of a set of local variables, right? 'def f1(arg1, arg2, arg3, arg4)' creates four names in locals(), where 'def f2(ns1:arg1, ns1:arg2, ns1:arg3, ns1:arg4) creates a single dict named ns1 in locals(), which contains four items (keyed on 'arg1', 'arg2', etc.), and 'def f3(ns1:arg1, ns1:arg2, ns2:arg3, ns2:arg4)' creates two dicts (ns1 and ns2) with two entries each. Okay, now, let's take a look at how these functions will be used. f1(1, 2, 3, 4) f1(arg1=1, arg2=2, arg3=3, arg4=4) Note that f1 doesn't care which of these methods of calling is employed -- both result in the same situation inside of f1(). So what's the intended way of calling f2()? I'd presume that it shouldn't care whether keywords or namespaces are specified, so that the following should all be equivalent: f2(1, 2, 3, 4) f2(1, 2, arg3=3, arg4=4) f2(1, 2, arg3=3, ns1:arg4=4) Note that this doesn't *add* any utility. The function caller hasn't gained anything. Since arg4 is unambiguous regardless of whether it's referred to as arg4 or ns1:arg4, the only time that the caller has any reason to specify the namespace is if argnames within different namespaces clash -- that is, if we allow something like 'def f4(ns1:arg1, ns1:arg2, ns2:arg1, ns2:arg2)'. Now, though, we've lost the ability to specify *only* the argname and not the namespace as well -- that is, you *cannot* call f4 with keywords but not namespaces. From the caller's vantage point, this means that they need to know the full namespace spec of the function, which makes it no different than simply using longer (but unique) keyword names. So, we can see that allowing namespaces and ***nsargs doesn't add any utility from the caller's perspective. How much does the callee gain from it? Well, the following functions would be equivalent: def g1(arg1, arg2, arg3, arg4): ns1 = {'arg1':arg1, 'arg2':arg2, 'arg3':arg3, 'arg4':arg4} return ns1 def g2(ns1:arg1, ns1:arg2, ns1:arg3, ns1:arg4): return ns1 You might say "Wow, look at all that repetetive typing I'm saving!" But that *only* applies if you need to stuff all of your arguments into dictionaries. I suspect that this is a rather small subset of functions. In most cases, it will be more convenient to use your arguments as local variables than as dictionary entries. def gcd1(a, b): while a: a, b = b%a, a return b def gcd2(ns1:a, ns1:b): while ns1['a']: ns1['a'], ns1['b'] = ns1['b']%ns1['a'], ns1['a'] return ns1['b'] Speaking of repetetive typing.... :P Besides, another function equivalent to the above two would be: def g3(arg1, arg2, arg3, arg4): ns1 = locals() return ns1 ...which is quite a bit less repetetive typing than the 'namespace' version. So, you're looking at making the function-calling protocol significantly more complex, both for caller and callee, for the rather marginal gain of being able to get arguments prepackaged in a dictionary or two, when there already exist easy ways of packaging function arguments into a dict. Given the deliberate bias against adding lots of new features to Python, one needs a *much* better cost/benefit ratio for a feature to be considered worthwhile. >> Besides, Python already uses the concept of namespaces by mapping them >> to object attributes. [...] > > Here, I don't understand. Could you give an example of two obvious ways > of doing the same thing, should my suggestion be adopted? My main point here is that 'namespace' is a term/concept that is already in use in Python, in different circumstances and using a completely different mechanism. Functions already *have* namespaces, whose contents can be inspected with locals() and modules have namespaces that can be accessed through globals(). I'd note also that the usage you're drawing from, in XML/XSLT, isn't really comparable to function parameters. It's a much closer parallel to object attributes. Python *does* have this concept, but it's spelled differently, using a '.' instead of a ':'. In other words, the XML fragment you give, ... would be more appropriate to render in Python as e = Element() e.this.that = 'other' It's quite reasonable to suppose that some object of type Element may have a set of font attributes and a set of image attributes, and that some of these may have the same name. Python would use font objects and image objects instead of 'namespaces' -- e.font.size = '14pt' e.image.size = (640, 480) So while these namespaces are probably a great thing for XML, XSLT, they're not very useful in Python. Which, given the rather different goals and design philosophies behind the languages, shouldn't really be much of a surprise. Jeff Shannon Technician/Programmer Credit International From fuzzyman at gmail.com Fri Jan 28 10:09:44 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 28 Jan 2005 07:09:44 -0800 Subject: Help with web dashboard In-Reply-To: References: Message-ID: <1106924984.507889.265070@c13g2000cwb.googlegroups.com> Ifd you want to use standard CGI I've written a CGI user authentication/management module called logintools. See http://www.voidspace.org.uk/python/logintools.html Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From http Fri Jan 7 16:28:33 2005 From: http (Paul Rubin) Date: 07 Jan 2005 13:28:33 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> Message-ID: <7xmzvl0vzy.fsf@ruckus.brouhaha.com> Donn Cave writes: > I don't by any means agree that this notation is worth adopting, and > in general I think this kind of readability issue is more or less a lost > cause for a language with Python's scoping rules, but the motive makes > sense to me. But we're talking about the mythical/hypothetical Python 3, so maybe there's a chance of fixing the scoping rules, which it seems to me are currently pretty badly broken. From rogerb at rogerbinns.com Tue Jan 11 02:28:42 2005 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 10 Jan 2005 23:28:42 -0800 Subject: PyChecker messages References: Message-ID: > runner.py:878: Function (main) has too many lines (201) > > What does this mean? Cannot functions be large? Or is it simply an advice that > functions should be small and simple? It is advice. > runner.py:200: Function (detectMimeType) has too many returns (11) > > The function is simply a long "else-if" clause, branching out to different > return statements. What's wrong? It's simply a "probably ugly code" advice? That is also advice. Generally you use a dict of functions, or some other structure to lookup what you want to do. > _must_ take two arguments; is there any way that I can make 'frame' go away? Yes, you can name it just _ (underscore). There are a few other names like that that are ignored. (Check the doc). > Also, another newbie question: How does one make a string stretch over several > lines in the source code? Is this the proper way? > > print "asda asda asda asda asda asda " \ > "asda asda asda asda asda asda " \ > "asda asda asda asda asda asda" Depends what you are trying to achieve. Look at triple quoting as well. Roger From Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org Sun Jan 30 23:40:38 2005 From: Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org (Alexander) Date: Mon, 31 Jan 2005 07:40:38 +0300 Subject: variable declaration Message-ID: 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! Even Visual Basic have 'Option Explicit' keyword! May be, python also have such a feature, I just don't know about it? Alexander, zatv at bk.ru From fredrik at pythonware.com Sun Jan 16 05:41:51 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 16 Jan 2005 11:41:51 +0100 Subject: How to del item of a list in loop? References: <1105835640.771989.163400@f14g2000cwb.googlegroups.com> Message-ID: John Machin wrote: >> (if you have 2.4, try replacing [] with () and see what happens) > > The result is a generator with a name ("lst") that's rather misleading > in the context. according to my dictionary, the word "list" means "A series of names, words, or other items written, printed, or imagined one after the other". I'd say that matches both list objects and iterators pretty well. but alright, you can change the name to "seq" if you want. > Achieving the same result as the list comprehension, by doing lst = list(i for ... etc etc), appears to be slower. the original post didn't contain a complete use case; a generator is a perfect replacement for a list in many cases. I'm sure most comp.lang.python readers are smart enough to understand when and why. From fumanchu at amor.org Fri Jan 14 12:36:05 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 14 Jan 2005 09:36:05 -0800 Subject: python to mssql Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33981C0@exchange.hqamor.amorhq.net> Brane wrote: > can someone please give me some info regarding subject http://sourceforge.net/projects/mysql-python Ask a broad question... Robert Brewer MIS Amor Ministries fumanchu at amor.org From brion at pobox.com Tue Jan 11 00:49:24 2005 From: brion at pobox.com (Brion Vibber) Date: Mon, 10 Jan 2005 21:49:24 -0800 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: <7x6524d6pv.fsf@ruckus.brouhaha.com> References: <7x6524d6pv.fsf@ruckus.brouhaha.com> Message-ID: <34h7m9F43vomsU1@individual.net> Paul Rubin wrote: > Mediawiki is written in PHP and > is far more complex than MoinMoin, plus it's database backed, meaning > you have to run an SQL server as well as the wiki software itself > (MoinMoin just uses the file system). Plus, I'll guess that it really > needs mod_php, while MoinMoin runs tolerably as a set of cgi's, at > least when traffic is low. MediaWiki should run with PHP configured in CGI handler mode, but these days mod_php has got its claws just about everywhere anyway. If you control your own server and don't have multi-user security worries, mod_php is simple enough to install and will probably perform better. For performance I also highly recommend using Turck MMCache or equivalent PHP bytecode cache extension. Unlike Python, saving compiled bytecode is not the default behavior of PHP, and for non-trivial scripts compilation eats up a lot of runtime. > I'll say that I haven't actually looked at > the Mediawiki code, though I guess I should do so. Cover your eyes...! it _is_ PHP after all. ;) > What I'm getting at is I might like to install MoinMoin now and > migrate to Mediawiki sometime later. Anyone have any thoughts about > whether that's a crazy plan? Should I just bite the bullet and run > Mediawiki from the beginning? Is anyone here actually running > Mediawiki who can say just how big a hassle it is? I would generally recommend you just start with MediaWiki if you intend to use it. To migrate a non-tiny site later you'll need to work out a migration script to import your data in some way (some people have asked about this in the past, I don't know if anyone's ever completed one or made it public). On the other hand if you _do_ write a MoinMoin-to-MediaWiki conversion script (or vice-versa!) we'd love to include it in the MediaWiki distribution. -- brion vibber (brion @ pobox.com) From http Fri Jan 14 15:30:57 2005 From: http (Paul Rubin) Date: 14 Jan 2005 12:30:57 -0800 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <1105734450.961150.32980@z14g2000cwz.googlegroups.com> Message-ID: <7xfz13zrb2.fsf@ruckus.brouhaha.com> "Chris Lasher" writes: > Forgive my ignorance, but what does using mmap do for the script? My > guess is that it improves performance, but I'm not sure how. I read the > module documentation and the module appears to be a way to read out > information from memory (RAM maybe?). Mmap lets you treat a disk file as an array, so you can randomly access the bytes in the file without having to do seek operations. Just say a[234]='x' and you've changed byte 234 of the file to the letter x. It works through the OS's virtual memory system and the computer's MMU hardware, and so it has lower overhead than doing system calls for every access. From deetsNOSPAM at web.de Wed Jan 26 09:33:01 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 26 Jan 2005 15:33:01 +0100 Subject: 4suite XSLT thread safe ? References: <6lkkc2-fbd.ln1@pluto.i.infosense.no> Message-ID: <35pntaF4os76kU1@individual.net> Ola Natvig wrote: > Anybody out there who knows if the 4suite implementation of XSLT are a > threadsafe one? What do you mean by that? You can of course transform xml using xslt in as many threads as you like - but what do you want with two or more threads in _one_ transformation? You start it, and some time later the result is there. -- Regards, Diez B. Roggisch From roy at panix.com Tue Jan 4 20:06:56 2005 From: roy at panix.com (Roy Smith) Date: Tue, 04 Jan 2005 20:06:56 -0500 Subject: coding conventions, PEP vs. practice References: Message-ID: Roman Roelofsen wrote: > These frameworks are using "mixedCase" but PEP8 suggests > "lower_case_with_underscores" except "in contexts where that's already the > prevailing style" which is not the case here IMHO. > > So, are there any specific reasons for breaking the rules here? I think > consistent conventions are very important. Being a Java developer in the last > couple of years, i learned how practical it can be to have only one naming > style. My personal preference is camelCase over words_with_underscores, but fundamentally, this is a bit of a religious issue. Pick a style, and go with it. If you're working on existing code, go with the prevailing style. If you're working in a group, pick a common style and go with the group decision. Of all the software engineering issues to worry about, this is pretty low on the list. From martin at v.loewis.de Mon Jan 17 17:24:51 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 17 Jan 2005 23:24:51 +0100 Subject: Static executable with shared modules In-Reply-To: References: <41e80078$0$1518$9b622d9e@news.freenet.de> Message-ID: <41ec3b31$0$3328$9b622d9e@news.freenet.de> Rickard Lind wrote: > I'll be more specific: when I build python 2.3.4 on FreeBSD 4.9, > the interpreter binary is linked against three shared libraries: > libutil.so.3, libm.so.2 and libc_r.so.4. Now, these libraries are > not present on the TARGET system (which is distinct from the build > system, but based on the same version of FreeBSD) so I add "-static" > to LDFLAGS. This produces an interpreter that runs on the target > system (no dependency on shared libc etc) but it also cannot load > modules compiled as shared libraries. Man page for dlopen(3) says > it is located in libc (and consquently there seems to be no libdl), > and anyway I'd expect to get a link error if the dl* functions were > not present. What I DO get is an ImportError exception. Most likely, the static libc.a does not provide dlopen (contrary to what the man page says). Python's configure detects that you don't have dlopen (when linking with -static), and concludes that dynamic loading of modules is not supported on your system. Then, during import, it checks built-in modules, module.py, module.pyc, and finds neither - it then reports an import error. To confirm this theory, have a look at pyconfig.h, and check whether HAVE_DLOPEN and/or HAVE_DYNAMIC_LOADING are defined; I expect that neither is defined. > At present I see no other option than to link the modules into the > interpreter which is very inconvenient since I'll have to rebuild > the every time a module changes :-( The other option, clearly, is to move the shared libraries to the target system along with the interpreter binary (assuming the target system supports shared libraries). If the target system does not have a dlopen, and the static libc.a does not have dlopen, either, there is nothing you can do except to use a different operating system. Regards, Martin From steve at holdenweb.com Thu Jan 13 09:56:15 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 13 Jan 2005 09:56:15 -0500 Subject: Octal notation: severe deprecation In-Reply-To: <1105587098.932273.315230@c13g2000cwb.googlegroups.com> References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> Message-ID: <41E68C0F.4040205@holdenweb.com> and-google at doxdesk.com wrote: > John Machin wrote: > > >>I regard continued usage of octal as a pox and a pestilence. > > > Quite agree. I was disappointed that it ever made it into Python. > > Octal's only use is: > > a) umasks > b) confusing the hell out of normal non-programmers for whom a > leading zero is in no way magic > > (a) does not outweigh (b). > > In Mythical Future Python I would like to be able to use any base in > integer literals, which would be better. Example random syntax: > > flags= 2x00011010101001 > umask= 8x664 > answer= 10x42 > addr= 16x0E800004 # 16x == 0x > gunk= 36x8H6Z9A0X > > But either way, I want rid of 0->octal. > > >>Is it not regretted? > > > Maybe the problem just doesn't occur to people who have used C too > long. > :-) > OT: Also, if Google doesn't stop lstrip()ing my posts I may have to get > a proper news feed. What use is that on a Python newsgroup? Grr. I remember using a langauge (Icon?) in which arbitrary bases up to 36 could be used with numeric literals. IIRC, the literals had to begin with the base in decimnal, folowed by a "b" followed by the digits of the value using a through z for digits from ten to thirty-five. So gunk = 36b8H6Z9A0X would have been valid. nothing-new-under-the-sun-ly y'rs - 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 bill.mill at gmail.com Fri Jan 28 11:28:54 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 28 Jan 2005 11:28:54 -0500 Subject: Dynamic class methods misunderstanding In-Reply-To: <1106928492.114459.191320@c13g2000cwb.googlegroups.com> References: <1106928492.114459.191320@c13g2000cwb.googlegroups.com> Message-ID: <797fe3d405012808284aed5cf1@mail.gmail.com> Kamilche, On Fri, 28 Jan 2005 08:10:07 -0800 (PST), Kamilche wrote: > I see what you're attempting to do. However, your code, if it DID run, > would result in a method being added to the object, not the object's > class! Modify the class itself, not the object, as follows: > > |class Test: > | def __init__(self): > | self.method() > | > |def m(self): > | print self > | > |setattr(Test, 'method', m) > |Test() > beautiful; so this appears to be equivalent to the __class__ method that Hans suggested. Thanks a lot. Peace Bill Mill bill.mill at gmail.com > -- > http://mail.python.org/mailman/listinfo/python-list > From spam at nospam.org Tue Jan 25 17:19:56 2005 From: spam at nospam.org (Erik Johnson) Date: Tue, 25 Jan 2005 15:19:56 -0700 Subject: building Python: up arrow broken on SuSE Linux 8.2 Message-ID: <41f6c3f7$1@nntp.zianet.com> I am trying to upgrade my Python installation. After downloading sources and building Python 2.3.4, I am unable to use the command history editing feature in the interactive interpreter (where the up-arrow would previously give you the last command line to edit, it now just prints "^[[A".) This is a feature I use often, and it kinda nullifies that warm fuzzy feeling you get when things are otherwise working as expected. Python 2.2.2 was installed via YaST (standard SuSE distribution) and works fine. Unfortunately, several modules I need are not part of that installation and there doesn't seem to be a newer installation via that route (that I know of). I downloaded source and built Python 2.3.4 in my local directory. There were a lot of warnings like this: Objects/intobject.c:1125: warning: comparison between signed and unsigned Objects/intobject.c:1135: warning: comparison between signed and unsigned I don't know exactly what "normal" output is, but things seem to have gone pretty well, as this is the output after 'make test': ... test_zlib 226 tests OK. 29 tests skipped: test_aepack test_al test_bsddb test_bsddb185 test_bsddb3 test_cd test_cl test_curses test_dbm test_email_codecs test_gdbm test_gl test_imgfile test_linuxaudiodev test_macfs test_macostools test_nis test_normalization test_ossaudiodev test_pep277 test_plistlib test_scriptpackages test_socket_ssl test_socketserver test_sunaudiodev test_timeout test_urllibnet test_winreg test_winsound 3 skips unexpected on linux2: test_dbm test_gdbm test_bsddb (I'm not doing anything with DBM stuff, so I don't think I care about the three skipped tests.) I thought the problem may have had something to do with the curses module, which is apparently not enabled by default. In the Modules/Setup file, I changed this: # First, look at Setup.config; configure may have set this for you. #_curses _cursesmodule.c -lcurses -ltermcap # Wrapper for the panel library that's part of ncurses and SYSV curses. #_curses_panel _curses_panel.c -lpanel -lncurses to this (my system has /usr/lib/libncurses.so.5.3): # First, look at Setup.config; configure may have set this for you. #_curses _cursesmodule.c -lcurses -ltermcap _curses _cursesmodule.c -lncurses # Wrapper for the panel library that's part of ncurses and SYSV curses. #_curses_panel _curses_panel.c -lpanel -lncurses I got a clean compile and the test_curses.py file executes silently: sand:~/Python-2.3.4/Lib/test> ../../python ./test_curses.py sand:~/Python-2.3.4/Lib/test> Unfortunately, that didn't solve the problem. Has anyone else seen this problem? Or, more importantly, can someone tell me how to fix this? Thanks for taking the time to read my post. -ej From elephantum at dezcom.mephi.ru Tue Jan 11 08:50:38 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Tue, 11 Jan 2005 16:50:38 +0300 Subject: embedded scripts debugging In-Reply-To: References: <347dpqF45nskbU1@individual.net> Message-ID: <34i3teF4auq8gU1@individual.net> Miki Tebeka wrote: >>So the question is: Is there suitable library for simple python gui >>debugger, or may be there are some other techniques for debugging >>embedded scripts? > > What I usually do is add > from pdb import set_trace > in the embedded module somewhere and then add a call to set_trace > (breakpoint) whenever I with. > When the code reaches the call to set_trace, you'll have pdb prompt and you > can debug as you like. > > Note that you can't add breakpoint dynamically this way. Thanks, I gathered pros and cons of embedding and decided to use python extending (i.e. creating python modules) instead of embedding. Happily I have an option to choose From maxm at mxm.dk Sat Jan 8 11:30:19 2005 From: maxm at mxm.dk (Max M) Date: Sat, 08 Jan 2005 17:30:19 +0100 Subject: Returning same type as self for arithmetic in subclasses In-Reply-To: References: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> Message-ID: <41e00a3b$0$265$edfadb0f@dread12.news.tele.dk> Tim Peters wrote: > Yes, and all builtin Python types work that way. For example, > int.__add__ or float.__add__ applied to a subclass of int or float > will return an int or float; similarly for a subclass of str. This > was Guido's decision... I will not discuss it with him. He is usually right :-s > Generally speaking, no. But I'm sure someone will torture you with a > framework that purports to make it easy . Apparently not... But here is my solution. If anybody is interrested. It should also be obvious what I am working on. Btw. I really love doctests ... Unittests are a nice idea. But doctest is a really practical solution. ############################### class vDatetime(datetime): """ A subclass of datetime, that renders itself in the iCalendar datetime format. >>> dt = vDatetime(1970, 1,1, 12, 30, 0) >>> str(dt) '19700101T123000' >>> dt2 = vDatetime(1970, 1,1, 0, 0, 0) >>> str(dt - dt2) 'PT12H30M' Adding is not allowed >>> dt + dt2 Traceback (most recent call last): ... AttributeError: 'NotImplementedType' object has no attribute 'days' """ def __init__(self, *args, **kwargs): datetime.__init__(self, *args, **kwargs) self.params = Params() def __add__(self, other): return self._to_vdatetime(datetime.__add__(self, other)) def __sub__(self, other): return self._to_vdatetime(datetime.__sub__(self, other)) def _to_vdatetime(self, result): if hasattr(result, 'timetuple'): return vDatetime(*result.timetuple()[:6]) return vDuration(result.days, result.seconds) def fromstring(st): "Class method that parses" try: timetuple = map(int, (( st[:4], # year st[4:6], # month st[6:8], # day st[9:11], # hour st[11:13], # minute st[13:15], # second ))) except: raise ValueError, 'Wrong format' return vDatetime(*timetuple) fromstring = staticmethod(fromstring) def __str__(self): return self.strftime("%Y%m%dT%H%M%S") -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From baza at localhost.localdomain Wed Jan 12 17:50:34 2005 From: baza at localhost.localdomain (baza) Date: Wed, 12 Jan 2005 22:50:34 +0000 Subject: Game programming in Python References: Message-ID: On Wed, 12 Jan 2005 09:49:50 +0800, Simon Wittber wrote: >> I'm looking for any books or on-line resources on game programming >> using Python. Does anyone have any advice? > > Hi Baza, > > If I you are as I assume, a programmer just starting out with game > programming, the best suggestion I can give is head over to > pygame.org, and after downloading and installing the library (also > install PyOpenGL if you can), go through the tutorials listed at > http://www.pygame.org/docs/ . > > You will also find the pygame mailing list very helpfu, and, if you > are so inclined, the IRC #pygame channel on freenode.net > > Sw. Thanks for these. I'm sorted now. pygame looks very interesting. Baz From __peter__ at web.de Thu Jan 27 03:35:21 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Jan 2005 09:35:21 +0100 Subject: string.atoi and string.atol broken? [OT] References: <1106700417.482871.45140@z14g2000cwz.googlegroups.com> Message-ID: Christos TZOTZIOY Georgiou wrote: >>> In current Greek hexadecimal is "????????????" ("dekaexadikon"). I borrowed Guido's time machine to fix the above (hopefully) :-) >>The Latin part escaped me. > > By Latin I suppose you jokingly mean the Greek parts... :) I thought it was a well-known fact that speakers of the awful German language have absolutely no humour. My first assumption was that hexadecimal is Greek and then I modified that to a Greek/Latin combo "???decimal". > Just in case it didn't show up correctly in your ng/mail client, it does > on groups.google.com (the post was in UTF-8, dammit! --excuse my romance > language) It did show up correctly, but was garbled in the response through technical incompetence of the poster. Peter From deetsNOSPAM at web.de Wed Jan 12 11:00:08 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 12 Jan 2005 17:00:08 +0100 Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> Message-ID: <34kvs0F4bqiviU1@individual.net> zip or izip is your friend: import itertools a = [1,2,3] b = ['a', 'b', 'c'] for a,b in itertools.izip(a, b): print a, b -- Regards, Diez B. Roggisch From ark at acm.org Wed Jan 12 13:07:47 2005 From: ark at acm.org (Andrew Koenig) Date: Wed, 12 Jan 2005 18:07:47 GMT Subject: counting items References: Message-ID: "It's me" wrote in message news:ukdFd.10645$5R.2000 at newssvr21.news.prodigy.com... > What's the best way to count number of items in a list? > > For instance, > > a=[[1,2,4],4,5,[2,3]] > > I want to know how many items are there in a (answer should be 7 - I don't > want it to be 4) How about this? def totallen(x): if isinstance(x, (list, tuple, dict)): return sum(map(totallen, x)) return 1 From fperez.net at gmail.com Sat Jan 29 04:58:43 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Sat, 29 Jan 2005 02:58:43 -0700 Subject: Installing Numeric with ATLAS and LAPACK References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> <1106940704.164253.134630@c13g2000cwb.googlegroups.com> <1106971706.986114.26420@c13g2000cwb.googlegroups.com> Message-ID: drife wrote: > Could you clarify this please? > > Let's say that I want to make a call to the LAPACK > routine sspevd, and pass it a matrix, and get the result. How do I > accomplish this? I just had a quick look, and it seems that sspevd is NOT one of the already wrapped LAPACK functions. Try dir(scipy.linalg.flapack) and dir(scipy.linalg.clapack) to see what's been already wrapped. From what I understand, wrapping more of lapack is rather easy, it's just that nobody has committed the time to 100% coverage. But this question is much better posed on the scipy list, where the people who wrote the lapack wrapping code can give you a better answer (I didn't). Cheers, f From weblord at gmail.com Sat Jan 1 23:08:48 2005 From: weblord at gmail.com (weblord at gmail.com) Date: 1 Jan 2005 20:08:48 -0800 Subject: Mailing list hosting? In-Reply-To: <87d67lwxv6.fsf@pobox.com> References: <8765dhd2dr.fsf@pobox.com> <878yibccyz.fsf@pobox.com> <87d67lwxv6.fsf@pobox.com> Message-ID: <1104638928.465176.206870@z14g2000cwz.googlegroups.com> free mailing list offer - limited time http://nabaza.com/autoresponders.htm From anno4000 at lublin.zrz.tu-berlin.de Tue Jan 11 12:59:17 2005 From: anno4000 at lublin.zrz.tu-berlin.de (Anno Siegel) Date: 11 Jan 2005 17:59:17 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: It's me wrote in comp.lang.perl.misc: [reply moved to bottom into context] > "J?rgen Exner" wrote in message > news:Fm6Ed.3556$u47.321 at trnddc09... > > xah at xahlee.org wrote: > > > #python supports complex numbers. > > [...] > > > > So? > > > > The world would come to a halt if all of a sudden nobody understands complex > numbers anymore. :-) > > > > # Perl doesn't support complex numbers. But there are packages that > > > supports it. > > > > The Math::Complex module is part of the standard installation already, no > > need for any "packages" (whatever that might be). > > Did you check "perldoc Math::Complex" > > > > NAME > > Math::Complex - complex numbers and associated mathematical functions > > [...] > For those of us that works with complex numbers, having complex number as a > natively supported data type is a big advantage. Non-native add-ons are not > sufficient and lead to very awkward program code. Like this? use Math::Complex; my $z = sqrt( -1); print 1 + $z, "\n"; # prints "1+i" Operator overloading makes it possible to work with complex numbers as if they were a native data type. Anno From phr at localhost.localdomain Fri Jan 28 06:35:59 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Fri, 28 Jan 2005 11:35:59 GMT Subject: Elliptic Code References: Message-ID: "Philip Smith" writes: > Does anyone have/know of a python implementation of the elliptic curve > factoring algorithm (lenstra) which is both: > > simply and cleanly coded > functional It's not in Python but take a look at Mike Scott's C++ implementation in MIRACL, http://indigo.ie/~mscott/ It's the simplest and most direct implementation I know of, just the bare essentials. It could probably be translated into Python pretty straightforwardly. > I'm aware of William Stein's code (from elementary number theory > book) but I don't understand his coding style and the algorithm > doesn't seem to work efficiently. A high performance implementation means complicated code, e.g. Peter Montgomery has done a few of those. If it's for instructional purposes I think the MIRACL version is far more understandable even if it's slower. If you mean you don't understand the algorithm, try Neal Koblitz's book "A Course in Number Theory and Cryptography". It has no code but it explains the algorithm in a pretty accessible way. From steve at holdenweb.com Thu Jan 6 09:42:42 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 09:42:42 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> Message-ID: <41DD4E62.1020404@holdenweb.com> Bulba! wrote: > On Wed, 5 Jan 2005 11:19:56 +0100, aleaxit at yahoo.com (Alex Martelli) > wrote: [...] > You see, I'm not disagreeing with you that your model applies > _where it applies_. I only disagree that it applies in face of > stronger forces. Now what kind of forces is dominant in > most frequent scenarios would have to be worked out in tedious > empirical research I think. Which I haven't done, because > learning some economics is just a hobby to me. > Yes, by all means let's just spout our opinions without any of that inconvenient tedious empirical research which might invalidate them. > [...] >>Italian, at most German and French, and not Polish or Russian, closeness >>to good international airports and other good transportation, closeness >>to partner firms and potential customers' decision-makers, all appeared >>to point to Warsaw, if I recall correctly. Mechanical engineers with >>some programming experience or viceversa, good translators, and good >>salespeople with connections in the mechanical industry, are not as >>ultra-specialized as all that, after all. > > > Most sales offices in Warsaw do not employ esp. educated people in > my impression. OTOH, the carmaking facilities nowadays require > more much more know-how and specialized workforce than a sales > office does. Or at least that was my impression when I worked at > the construction machine manufacturer in Berlin. > Again you are forming impressions form rather limited evidence: I might agree with you about the relative intelligence and education of engineers over sales people, but that might be *my* bias showing. > Capital investments per worker in auto industries are reportedly > very high. Simple physical tasks are done largely by machines, > like this 100 million Deutschmark costing laser-cutting installation > that I've seen there, where a pile of iron bars is pulled in at one > end and the pile of ready components is spitted out of the other end > (unlike typical thermal cutting, laser has the advantage of not > destroying the metal structure adjacent to the cut, so the parts > of the machines subject to high-stress are oft produced this way). > The same is true of plasma-arc cutting for thicker steels, and I believe it's still not possible to cut 3-inch stainless with a laser. But what's your point? > Oh, and by the way that installation doesn't get used much. > Somebody at the office didn't check carefully enough the > energy prices before ordering it and later someone discovered > that off-site specialized cutting firms that take advantage of > energy available at low prices at special times in other countries > can get it produced cheaper. Moving it elsewhere or selling > is not an option, since it is a specially constructed, low, 50-meters > long hall that stands inside the huge manufacturing hall of the > company. > And you are using this example to try and argue that engineers are better-educated than sales people? Who sold this installation? Who bought it? How much, therefore, is education worth? > 100 million DM (when 1 DM was worth some half of Euro > back then) down the drain. When the company was in rather > bad financial situation (later I've learned it was finally bought > out by Americans). Oh well. No big deal. > > I was utterly shocked. Having grown up in Soviet times I have > been used to seeing precious resources wasted by organizations > as if resources were growing on trees, but smth like this?! In a > shining ideal country of Germany?! Unthinkable. > Indeed not. Quite often the brown paper bag is a factor in purchases like this. I wouldn't be at all surprised if somebody with a major input to the decision-making process retired to a nice place in the country shortly afterwards. You appear to be making the mistake of believing that people will act in the larger interest, when sadly most individuals tend to put their own interests first (some would go as far as to define self-interest as the determinant of behavior). > >>The firm I was working for had a consensus decision-making process (even >>I was involved) and managers (and other employees) and stockholders were >>mostly the same people -- it wasn't all that large a firm at the time. >>Nobody needed to practice risk avoidance. > > > Again, you may have had good luck. Where I worked (including > some places in Germany and UK) it was almost the only factor > that seemed to matter to people - they'd do ANYTHING not to > take a risky decision, to "pass the buck", not to stick their necks > out, not to declare doing some work that involved challenges. > Some people are like that. I chose a long time ago to try not to work with them whenever I could avoid it and, while that may have had negative economic consequences I an convinced it has improved my quality of life immensely. Of course, I have no proof for such an assertion. > [and on, and on, and on ...] 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 ariza at flexatone.com Thu Jan 13 05:53:15 2005 From: ariza at flexatone.com (ariza) Date: 13 Jan 2005 02:53:15 -0800 Subject: site.here on python 2.4 References: <1105609399.915874.71150@z14g2000cwz.googlegroups.com> Message-ID: <1105613595.725326.9950@z14g2000cwz.googlegroups.com> i am not sure where i found site.here documented as used prior to 2.4. the issue is that i do not need sys.path, as in the list of all paths that python searches. sys.prefix is close to what i need: >>> sys.prefix '/System/Library/Frameworks/Python.framework/Versions/2.3' but the old site.here gave sys.prefix, plus the additional directories to get into the actual python library: >>> site.here '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3' can we assume that, on all platforms, the old site.here is the same as: >>> os.path.join(sys.prefix, 'lib', 'python%s' % sys.version[:3]) '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3' or is it better to use, as you suggest, >>> import os >>> os.path.dirname(os.__file__) '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3' this is useful for a few reasons. the first was i needed a cross platform way to find the complete path to the idle directory; the second was the complete path to the 'site-packages' directory. thanks! From macrocosm at fastmail.fm Thu Jan 13 14:09:46 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Thu, 13 Jan 2005 14:09:46 -0500 Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <41E6C77A.40803@fastmail.fm> Jane wrote: >"Lucas Raab" wrote in message >news:UsuFd.5434$KJ2.1253 at newsread3.news.atl.earthlink.net... > > >>Jane wrote: >> >> >>> wrote in message >>>news:1105495569.479185.166340 at z14g2000cwz.googlegroups.com... >>> >>> >>> >>>>python.org = 194.109.137.226 >>>> >>>>194 + 109 + 137 + 226 = 666 >>>> >>>>What is this website with such a demonic name and IP address? What >>>>evils are the programmers who use this language up to? >>>> >>>> >>>> >>>Some people have too much time on their hands... >>> >>>Jane >>> >>> >>> >>> >>Better get some ointment for that burn!! >> >> > >Huh??? > >Jane > > > > You said that people have too much "time" on their "hands", so he suggested ointment to prevent the irritation etc... He was probably also getting at the topic of this thread (hint: Satan = Hell = Fire), so the ointment puts out the burn. Have fun folks! - Arich From jacek.generowicz at cern.ch Mon Jan 17 03:26:53 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Jan 2005 09:26:53 +0100 Subject: from __future__ import decorators References: Message-ID: Tim Roberts writes: > Jacek Generowicz wrote: > > > >I have some code, which makes copious use of the @decorator syntax > > I'm very curious to know what kind of application you are writing in which > "copious use of the @decorator syntax" actually solved a problem > productively. An application in which, before python2.4, I used to have lots of code that looked like def somefun(...): ... somefun = somedecorator(somefun) :-) It's not interesting to discuss what "somedecorator" actually represents. But being able to see that the function is decorated right next to the "def", as opposed to having to look beyond the end of the definition certianly makes a significant difference to me. From carribeiro at gmail.com Sat Jan 8 14:25:40 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 8 Jan 2005 17:25:40 -0200 Subject: Recent infoworld column In-Reply-To: References: <41DEEF0F.5000300@nospamyahoo.com> Message-ID: <864d3709050108112538052455@mail.gmail.com> On Sat, 08 Jan 2005 13:14:17 -0500, Peter Hansen wrote: > Dwarf Electrician wrote: > > from a long time listener... > > > > http://www.infoworld.com/article/04/12/30/01OPstrategic_1.html > > Kudos for Roger Binns! >From Mr. Udell himself: """ When people talk about the heroes of open source, you tend to hear such familiar names as Linus Torvalds, Larry Wall, Brendan Eich, Guido van Rossum, Monty Widenius, Miguel de Icaza, and Rasmus Lerdorf. No question about it: These people are my heroes. But so is Roger Binns, and so are the countless other unsung heroes of open source. For solving a host of vexing problems with quiet competence, and for doing it in ways that invite others to stand on their shoulders, I salute them all. """ That's recognition. Wow. -- 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 Scott.Daniels at Acm.Org Mon Jan 17 12:15:34 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 17 Jan 2005 09:15:34 -0800 Subject: platform independent kbhit() In-Reply-To: References: Message-ID: <41ebef6e$1@nntp0.pdx.net> Hans Georg Krauthaeuser wrote: > I use msvcrt.kbhit() to check for a user keyboard event on windows. But > now, I would prefer to make the module independent from the platform > used. This is not in general possible; many machines do not have keyboards. You can, perhaps, build one for yourself from a pair of implementations or more. Portable software seldom comes from adding one platform at a time that the software works on. Portable software comes from working using only features common (or in rare circumstances available) on all machines in your target set, and then adding enough tests to believe the portability. CPython starts with the C89-supported environment as its base. It tries hard to stick to that abstract machine. I assume Jython does a similar thing using Java VM semantics that it trusts will be common across implementations. > I already know that I can use curses (on linux/unix) or Tkinter. > Also, I found this http://my.execpc.com/~geezer/software/kbhit.c C > source that has a kbhit() and a getch() for linux/unix that I can SWIG > to python. Either of these might be a good basis for your personal "all machines I care about" semantics. If you use curses, make sure it doesn't impose an extra constraint on all terminal access. --Scott David Daniels Scott.Daniels at Acm.Org From golux at comcast.net Sun Jan 23 03:52:14 2005 From: golux at comcast.net (Stephen Waterbury) Date: Sun, 23 Jan 2005 03:52:14 -0500 Subject: [OT] XML design intent ... further musings In-Reply-To: <7xhdl8pz1j.fsf@ruckus.brouhaha.com> References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> <41F2C840.2050304@comcast.net> <7xhdl8pz1j.fsf@ruckus.brouhaha.com> Message-ID: <41F365BE.20102@comcast.net> Paul Rubin wrote: > Stephen Waterbury writes: >>I should note that I have to deal with XML a lot, but always >>kicking and screaming (though much less now because of Fredrik's >>Elementtree package ;). Thanks, Fredrik and Peter, for the >>references. ;) > > I love this old rant about XML: > > http://groups-beta.google.com/group/comp.lang.lisp/msg/9a30c508201627ee Yep, Erik Naggum is one of my heroes for that! :) From tchur at optushome.com.au Mon Jan 10 16:44:35 2005 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 11 Jan 2005 08:44:35 +1100 Subject: Python and Tsunami Warning Systems Message-ID: <41E2F743.90807@optushome.com.au> Boc Cringely's column on the need for a grassroots (seaweed roots?) tsunami warning system for the Indian Ocean (and elsewhere) makes some very good points - see http://www.pbs.org/cringely/pulpit/pulpit20041230.html In his following column ( http://www.pbs.org/cringely/pulpit/pulpit20050107.html ), he notes: "Now to last week's column about tsunamis and tsunami warning systems. While my idea may have set many people to work, only a couple of them have been telling me about it. Developer Charles R. Martin and Canadian earth scientist Darren Griffith met through this column, and are in the initial stages of building an Open Tsunami Alerting System (OTAS). Although work has just started, they've established a few basic principles: OTAS will be very lightweight; will use openly available geophysical or seismic data sources; will be highly distributed and decentralized; and will be built to run on very low-powered commodity hardware. They currently foresee using Python and Java, but aren't religious about it. Anyone who wants to help out is welcome and their OTAS blog can be found in this week's links." See http://otasblog.blogspot.com/ It seems to me that this would be a valuable and feasible type of project for the Python community to get involved in (or perhaps take the lead on). Something the PSF might even consider resourcing to some degree? Tim C From rkern at ucsd.edu Tue Jan 4 20:16:30 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 04 Jan 2005 17:16:30 -0800 Subject: coding conventions, PEP vs. practice In-Reply-To: References: Message-ID: Roman Roelofsen wrote: > Dear python-list, > > while looking for some coding conventions for python programs, i found the > PEP8 at http://www.python.org/peps/pep-0008.html. It defines the rules very > well and leaves no space for interpretations. I guess thats a good thing :-) > But when i started playing a bit with python and frameworks like Zope, > Webworks, etc., i noticed, that a lot frameworks are using a different > convention for methodnames. Note the first sentence of the PEP: "This document gives coding conventions for the Python code comprising the standard library for the main Python distribution." It is not intended to be a style guide for all Python code although many groups do adopt all or part of it for their own style guides. -- 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 moshebg at shamaut.co.il Mon Jan 17 00:57:46 2005 From: moshebg at shamaut.co.il (moshebg at shamaut.co.il) Date: 16 Jan 2005 21:57:46 -0800 Subject: fefinining % of c'm'y and k Message-ID: <1105941466.596034.166370@f14g2000cwb.googlegroups.com> hello i need a program (and pleas shoe me the modol in the softwar) that : if i have a scaned photo i want to define out of each poligon color ,as it seems in the photo, the cmyk in % (percets) of the color/ 4 exampl from poligon color orang defin the cmyk in % like that: (example) c: 30% m:56% y:78% k: 10% moshe thanks From belred at gmail.com Thu Jan 20 20:58:27 2005 From: belred at gmail.com (Bryan) Date: Thu, 20 Jan 2005 17:58:27 -0800 Subject: PyCon Preliminary Program Announced! In-Reply-To: <20050121000607.DE1261E4010@bag.python.org> References: <20050121000607.DE1261E4010@bag.python.org> Message-ID: <41F061C3.3000802@gmail.com> can anyone tell me how the talks work? there are between 9 and 12 talks for each time slot. do all talks start at the same time? or are there just four talks at a time and the columns show what talks are in a given room? is it easy to go to the talks you want? thanks, bryan From tim.peters at gmail.com Mon Jan 24 11:13:01 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 24 Jan 2005 11:13:01 -0500 Subject: Memory Usage In-Reply-To: References: Message-ID: <1f7befae050124081327f0c5bd@mail.gmail.com> [] > Would a Python process consume more memory on a PC with lots of > memory? > > For example, say I have the same Python script running on two WinXP > computers that both have Python 2.4.0. One computer has 256 MB of Ram > while the other has 2 GB of Ram. On the machine with less Ram, the > process takes about 1 MB of Ram. On the machine with more Ram, it uses > 9 MB of Ram. > > Is this normal and expected behavior? [and later confirms he's looking at Mem Usage in Task Manager] 256MB is on the low end for an XP system, and will generally cause lots of swap space (virtual memory residing on disk -- kinda) to get used. Mem Usage doesn't count swap space, just RAM currently in use. Under Task Manager it's better to look at the VM Size column, which tells roughly how much virtual address space is assigned to the process, and regardless of how it's currently split between RAM and disk. You may need to use View -> Select Columns to get this statistic displayed. If your process is in fact using a fixed amount of address space, the VM Size column will stay steady but Mem Usage may jump all over the place as time goes on. In general, I would expect VM Size to be about the same on your two boxes; I would not expect Mem Usage to be the same. From abigail at abigail.nl Wed Jan 12 03:22:04 2005 From: abigail at abigail.nl (Abigail) Date: 12 Jan 2005 08:22:04 GMT Subject: 20050111: list basics References: <1105512773.543336.29930@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee (xah at xahlee.org) wrote on MMMMCLII September MCMXCIII in : :: :: # in perl, list is done with paren (). Wrong. Except in a few cases, parens don't make lists. Parens are used from precedence. *Context* makes lists. :: # the at sign in front of variable is necessary. The at sign in front of a variable means the variable is an array. Arrays are *NOT* lists. :: # it tells perl that it is a list. :: @a = (0,1,2,'three',4,5,6,7,8,9); :: :: # perl can't print lists. To show a list content, :: # load the package Data::Dumper, e.g. :: use Data::Dumper; :: print '@a is:', Dumper(\@a); Utter bullshit. Perl's print statement has no problem accepting a list. In fact, YOUR EXAMPLE PASSES A LIST to print. But this works fine too: @a = ('Xah ', 'Lee ', 'does ', 'not ', 'know ', 'Perl'); print @a; __END__ Xah Lee does not know Perl :: # the backslash in front of @a is to tell Perl :: # that "get the "address" of the "array" @a". Wrong. Perl is not C. You get a reference, not a pointer. :: # it is necessary in Dumper because Dumper is :: # a function that takes a memory address. Wrong. Perl functions don't take memory addresses. Perl doesn't allow the programmer to do direct memory access. :: # see perldoc -t Data::Dumper for the intricacies :: # of the module. Please do so yourself. :: # to join two lists, just enclose them with () :: @b = (3,4); :: @c = (@a, at b); :: print '\@c is', Dumper \@c; :: # note: this does not create nested list. There is no such thing as "nested lists". :: # to extrat list element, append with [index] :: # the index can be multiple for multiple elements :: @b = @a[3,1,5]; :: print Dumper \@b; Why are you printing to the Dumper filehandle? :: # to replace parts, do :: $a[3]= 333; :: print ' is', Dumper \@a; :: # note the dollar sign. :: # this tells Perl that this data is a scalar :: # as opposed to a multiple. :: # in perl, variable of scalars such as numbers and strings :: # starts with a dollar sign, while arrays (lists) starts with Again, arrays are NOT lists. :: # a at @ sign. (and harshes/dictionaries starts with %) :: # all perl variables must start with one of $,@,%. Or *, or &. And some variables don't have a sigil in front of them. :: # one creates nested list by :: # embedding the memory address into the parent list :: @a=(1,2,3); :: @b = (4,5, \@a, 7); :: print 'nested list is', Dumper \@b; Rubbish. That's not a nested list. @b is an *ARRAY*, whose third element is a *REFERENCE* to another *ARRAY*. :: # to extrat element from nested list, :: $c = $b[2]->[1]; :: print '$b[2]=>[1] is', $c; :: :: # the syntax of nested lists in perl is quite arty, see :: # perldoc -t perldata :: Xah Please Xah, do the Perl and Python communities a favour, and stop posting bullshit. Abigail -- perl -e '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %; BEGIN {% % = ($ _ = " " => print "Just Another Perl Hacker\n")}' From mordaha at gmail.com Fri Jan 14 16:55:48 2005 From: mordaha at gmail.com (mr_little) Date: 14 Jan 2005 13:55:48 -0800 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <1105739748.306557.72120@z14g2000cwz.googlegroups.com> Brian Eable wrote: > perl -e '$a="194.109.137.226"; @a = reverse split /\./, $a; for $i (0..3) { $sum += $a[$i]*(256**$i) } print "sum = $sum\n"' > > 226 + 35072 + 7143424 + 3254779904 = 3261958626 > > http://3261958626/ > > Which is NOT 666. Comrade, why perl here? :) Are you afraid python? :) From wjiang at gmail.com Mon Jan 17 17:35:11 2005 From: wjiang at gmail.com (Wen Jiang) Date: 17 Jan 2005 14:35:11 -0800 Subject: pyMPI momory leak Message-ID: <1106001311.306343.53840@c13g2000cwb.googlegroups.com> Hi, I have been using pyMPI to parallelize my code and found that the function mpi.send() leaks memory a lot and thus is not really working for large amount fo data communication. It actually fails after the leak accumulates more than 2G. I wonder if others have the same experience or I did something wrong. I compiled python 2.4, mpich 1.2.6, pyMPI 2.1b4 on Opteron cluster running Rocks 3.3. Here is a small test script with 2 CPUs to demo the memory leak: import mpi n = 10000 i=0 data = [0]*40000 while i < n: if mpi.rank==1: mpi.send(data, 0) elif mpi.rank==0: msg, status = mpi.recv() n+=1 if one watchs the memory usage using 'top', one can see one process use little and constant amount of memory (recv for rank=0) and the other process uses more and more memory (send for rank=1). From tjreedy at udel.edu Wed Jan 5 00:38:45 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 5 Jan 2005 00:38:45 -0500 Subject: coding conventions, PEP vs. practice References: Message-ID: "Robert Kern" wrote in message news:crff5d$noi$1 at news1.ucsd.edu... > Note the first sentence of the PEP: "This document gives coding > conventions for the Python code comprising the standard library for the > main Python distribution." Even that should say "from now on". Some library code was written before PEP8. And Guido has so far discouraged purely stylistic patches to functioning code (because of the risk on introducing bugs where none exist). TJR From danperl at rogers.com Tue Jan 25 12:10:55 2005 From: danperl at rogers.com (Dan Perl) Date: Tue, 25 Jan 2005 12:10:55 -0500 Subject: [perl-python] 20050125 standard modules References: <1106669614.666772.17750@z14g2000cwz.googlegroups.com> Message-ID: I sent the following feedback message to Yahoo! Groups about this abusive use of their service. Feel free to also report this as an abuse of the Yahoo! Groups service until the problem is resolved. Dan ----------- As the owner of the perl-python group, p0lyglut (aka Xah Lee), has added two newsgroups to the mailing list of the group: comp.lang.perl.misc and comp.lang.python. First of all, I don't think anyone could have given Xah Lee an authorization on behalf of the newsgroups. I am not sure, but that is probably a violation of the Terms of Service in itself. I will leave this matter up to you to investigate. The daily messages of the perl-python group are unwanted by the two newsgroups. Just take a look at the follow-ups in the newsgroups that the perl-python postings have generated. I hope that not only the newsgroups will be removed from the perl-python group but that such an abuse will also be prevented in the future. Thanks, Dan Perl From rschroev_nospam_ml at fastmail.fm Sat Jan 8 04:40:07 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 08 Jan 2005 09:40:07 GMT Subject: Getting List Of All Filesystem Mounts In-Reply-To: References: Message-ID: Tim Daneliuk wrote: > Is there some pure Python/portable way to get a list > of all currently mounted filesystems? Check out MtPython: http://bebop.bigasterisk.com/python/docs/MtPython -- "Codito ergo sum" Roel Schroeven From http Wed Jan 19 12:45:10 2005 From: http (Paul Rubin) Date: 19 Jan 2005 09:45:10 -0800 Subject: [OT] Good C++ book for a Python programmer References: <1106136496.719185.87850@c13g2000cwb.googlegroups.com> Message-ID: <7x4qhdia8p.fsf@ruckus.brouhaha.com> "rick_muller at yahoo.com" writes: > I was wondering whether anyone could recommend a good C++ book, with > "good" being defined from the perspective of a Python programmer. I > realize that there isn't a book titled "C++ for Python Programmers", > but has anyone found one that they think goes particularly well with > the Python way? I think it's not possible to really grok C++ without having worked on large multi-person C projects and understood what problems C++ tried to solve. The only good book I know about C++ is by Stroustrup, "The C++ Programming Language" or something like that; it's not an easy book though. From news at guessmysurname.net Thu Jan 6 21:18:13 2005 From: news at guessmysurname.net (Lorenzo Bolognini) Date: Fri, 07 Jan 2005 02:18:13 +0000 Subject: wxPython clipboard In-Reply-To: <1105054966.693860.59270@f14g2000cwb.googlegroups.com> References: <1105010770.911397.278520@c13g2000cwb.googlegroups.com> <1105054966.693860.59270@f14g2000cwb.googlegroups.com> Message-ID: <3469sbF46es8jU1@individual.net> flaxeater at gmail.com wrote: > Ok well you should look at this module > http://www.rutherfurd.net/python/sendkeys/#id1 > I then you could take frequent snapshots and use and OCR to find your > stuff. Then use the above library to type to the window. > Ok the problem on Windows looks like solved but still I would have to check if Windows Scripting Host is enabled. Anyway I'll keep u updated Cheers Lorenzo -- Get my PGP Public Key @ http://www.bolognini.net/LBolognini.txt From jstroud at mbi.ucla.edu Mon Jan 24 20:19:22 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 24 Jan 2005 17:19:22 -0800 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <1106615822.2400.122.camel@lipscomb.mbi.ucla.edu> References: <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <1106615822.2400.122.camel@lipscomb.mbi.ucla.edu> Message-ID: <1106615961.2400.126.camel@lipscomb.mbi.ucla.edu> I was purposefully making an illogical statement to illustrate the lapse in reason of Martin's statement. Users have crypto needs, not applications. Applications are presumably not anthropomorphic enough to have needs--hence the lack of logic. However, I am not an application (as far as you or I know) and thus can not truly speak to the needs of applications in general, if indeed they have any. Applications that lack features force users to accept a limited feature set or they use an alternative program with other limitations. Putting the possibility for cryptographic storage increases the utility of any application that stores data, and it could be done without much work if it were properly included in the core distribution. I have found it amazing how few programs include encryption as an option. I believe this is because its hard for programmers to include it and/or they falsely reason that "if I don't need it, the user doesn't", which is up there with "if I can't see them, then they can't see me" in terms of bad logic. James On Mon, 2005-01-24 at 17:17, James Stroud wrote: > I was purposefully making an illogical statement to illustrate the lapse > in reason of Martin's statement. Users have crypto needs, not > applications. Applications are presumably not anthropomorphic enough to > have needs--hence the lack of logic. > > However, I am not an application (as far as you or I know) and thus can > not truly speak to the needs of applications in general, if indeed they > have any. > > Applications that lack features force users to accept a limited feature > set or they use an alternative program with other limitations. Putting > the possibility for cryptographic storage increases the utility of any > application that stores data, and it could be done without much work if > it were properly included in the core distribution. I have found it > amazing how few programs include encryption as an option. I believe this > is because its hard for programmers to include it and/or they falsely > reason that "if I don't need it, the user doesn't", which is up there > with "if I can't see them, then they can't see me" in terms of bad > logic. From http Sat Jan 29 04:57:27 2005 From: http (Paul Rubin) Date: 29 Jan 2005 01:57:27 -0800 Subject: Pystone benchmark: Win vs. Linux (again) References: <7xhdl0ll3t.fsf@ruckus.brouhaha.com> <1gr59wv.9tx8a21g2kdv9N%aleaxit@yahoo.com> Message-ID: <7xllac36d4.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > ...or (just as hypothetically) purchasing some commercial compiler might > help, under the assumption that the optimization and code generation of > the compiler are the issues here. I have nothing but hearsay to go on, > but IBM's compiler for PPC chips, and Intel's compiler for Intel chips, > appear to claim that they have excellent code generation, for example. Perhaps so. Actually that benchmark difference may have come from differing Python versions. I've heard that Intel cc typically beats gcc by 5% or so for integer code. There are various benchmarks floating around. But that Pystone measurement differed by considerably more. From ncoghlan at iinet.net.au Fri Jan 7 10:26:44 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 01:26:44 +1000 Subject: 2 versions of python on 1 machine In-Reply-To: References: <0fydnX5CmoCCwkDcRVn-2w@powergate.ca> Message-ID: <41DEAA34.8020800@iinet.net.au> flupke wrote: > Peter Hansen wrote: >> The content of each batch file is like this: >> @echo off >> c:\python23\python.exe %1 %2 %3 %4 %5 %6 %7 %8 %9 More recent versions of Windows should allow you to use %* for "all the arguments to the batch file". > Where did you find more info on PYTHONHOME and PYTHONPATH because > the docs don't seem to contain a whole lot of info. I think PYTHONPATH is discussed in the tutorial. PYTHONHOME, I'm not so sure on (PYTHONPATH and PYTHONSTARTUP are the only two you're likely to care about, though - and I think the Tutorial covers both of them). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From export at hope.cz Fri Jan 7 03:14:26 2005 From: export at hope.cz (export at hope.cz) Date: 7 Jan 2005 00:14:26 -0800 Subject: Asyncore Message-ID: <1105085666.634359.33640@z14g2000cwz.googlegroups.com> Is there any tutorial and docs with samples how to use asyncore module? Thanks Lad From aleaxit at yahoo.com Fri Jan 7 09:21:22 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 15:21:22 +0100 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> <1gq0odo.1x1uyr2kgdgiyN%aleaxit@yahoo.com> <7xu0ptjtv3.fsf@ruckus.brouhaha.com> Message-ID: <1gq0xda.12eqd291540i5tN%aleaxit@yahoo.com> Paul Rubin wrote: ... > > GUI/IDEs for Python, > > I remember there was a gud interface for Python but it didn't work > pretty well. There's also IDLE which is pretty crude and flaky. I > think I'll just wait for Pypy deployment before worrying about this > situation too much. Is there something else I can download? eric3 seems pretty good. > > Python add-ons such as numarray, > > gmpy, ctypes, ...) -- all of those you still have to download and > > install, just as you would for the satanware. > > That's unfortunate, that stuff should be included with Python. numarray aims to be, WHEN they will be sufficiently complete and stable. As for predictions of when that will be, I'm not qualified to offer one. I think ctypes would be a _great_ addition to the standard Python library in 2.5, if Thomas Heller agrees. gmpy is LGPL (because so is the GMP library that gmpy wraps and extends), so that including it with the standard Python library is very iffy/problematic. As gmpy's author I'd be delighted to do anything possible to help this happen, but it just doesn't seem likely. Besides, I wonder how large a fraction of Python's user base really needs something as specialized as gmpy -- unlimited-precision integers which are _slightly_ faster than Python 2.4's built-in longs and offer a few more highly specialized functions, etc. Even if all of these were included in Python 2.5, how long will it be before standard distributions and operating systems start including 2.5? I don't agree with your general stance that the standard Python distribution should be "sumo", including _everything_ that could possibly be of _some_ interest to _some_ Python users, or thereabouts. "Sumo distributions" have their place; enthought currently makes an excellent one for scientific use of Python on Windows, and, I hear, it is planning a similar one for Macintosh. But the vast majority of what's in it will be of no interest to somebody who doesn't care for scientific applications -- and it will STILL be missing something that some scientific users might like, such as gmpy. Moreover, it's important to distinguish between standard Python, and enriched distributions made of components that grow and change at different speeds and with different groups of maintainers -- just the same important distinction that must be drawn between Linux, and any of the many distributions based on and including Linux. Asking standard Python to include dozens of third-party modules is just as silly as asking the Linux kernel to be distributed with, say, gimp... anybody's free to make a distribution including several components, but it's best for the various components, including the core ones, to stay separate. Alex From ed at leafe.com Mon Jan 17 10:37:51 2005 From: ed at leafe.com (Ed Leafe) Date: Mon, 17 Jan 2005 10:37:51 -0500 Subject: Native widgets for Python In-Reply-To: References: <41EBC7F3.5050807@web.de> <87oefom7at.fsf@mrbun.watterson> Message-ID: On Jan 17, 2005, at 10:19 AM, Steve Holden wrote: >> It looks like dabo uses, not replaces, wxPython >> http://dabodev.com/about > > Actually I think it *layers* wxPython, with the intention of being > able to replace wxPython with other GUI kits at a later date. So, > there should be a simpler graphical API, but since I haven't yet done > more than dabble (dabole?) with dabo I can't be sure. That's correct. We are basing the UI on wxPython initially, but wrapping wx for two reasons: to make it simpler to code UIs, and to make it possible to use other UI toolkits instead of wx. The first reason is by far the more important of the two, but an eventual goal for Dabo post-1.0 release (we're at 0.3 now!) will be to allow TkInter and other toolkits to be used as well. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From tjreedy at udel.edu Wed Jan 12 15:44:19 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Jan 2005 15:44:19 -0500 Subject: Another look at language comparisons References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> <1105188426.955508.263030@c13g2000cwb.googlegroups.com><41e00ac1$0$265$edfadb0f@dread12.news.tele.dk> <34kaf5F4ag9k6U1@individual.net> Message-ID: >>> http://www.tbray.org/ongoing/When/200x/2004/12/08/-big/IMG_3061.jpg Here is the link giving the context for that picture http://tbray.org/ongoing/When/200x/2004/12/08/DynamicJava The other person is Larry Wall. Samuele Pedroni is in the next one. A rather interesting meeting. Terry J. Reedy From tim.peters at gmail.com Sun Jan 9 01:11:13 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 9 Jan 2005 01:11:13 -0500 Subject: time module precision In-Reply-To: References: Message-ID: <1f7befae05010822117f566baf@mail.gmail.com> [Jane Austine] > What is the precision (and accuracy) of time module on a Windows XP > machine? There are many functions in the time module. You shouldn't assume that any two have similar behavior (because, in fact, they may not). > threading module depends on time module so it's precision(and > accuracy) is up to time module's. > > | for i in xrange(1000): > | time.sleep(0.001) > > This sleeps for awhile, which means 0.001 sec is not ignored. On the > other hand, > > | for i in xrange(10000): > | time.sleep(0.0001) > > This returns right away. It may or may not, depending on what other threads are trying to do. > 0.0001 sec is ignored and lost in the air. > > So can I tell the time.sleep's precision is 1ms? Any other way to > increase the precision? (Using busy waiting -- spinning loop -- is not > a good option, it makes over 90% cpu usage) Python's time.sleep() calls the Win32 API Sleep() function on Windows. All behavior is inherited from the latter. See MS's docs: In particular, MS Sleep() takes an integer argument, giving the number of milliseconds to sleep. Your 0.0001 case falls under the special Sleep(0) case due to truncation in float->int conversion. Also Google on sleep thread deviation to find an interesting CodeProject article quantifying behavior on one particular tester's Windows box. Also see an article it references for approaches to the question "how do I handle small intervals?" (short course: you probably can't, unless we're willing to throw money at it). From http Fri Jan 21 23:44:39 2005 From: http (Paul Rubin) Date: 21 Jan 2005 20:44:39 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> Message-ID: <7xbrbiqdhk.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > > I'm going by newsgroup messages from around the time that I was > > proposing to put together a standard block cipher module for Python. > > Ah, newsgroup messages. Anybody could respond, whether they have insight > or not. Here's the message I had in mind: http://groups-beta.google.com/group/comp.lang.python/msg/adfbec9f4d7300cc It came from someone who follows Python crypto issues as closely as anyone, and refers to a consensus on python-dev. I'm not on python-dev myself but I feel that the author of that message is credible and is not just "anyone". From exarkun at divmod.com Tue Jan 4 11:43:34 2005 From: exarkun at divmod.com (Jp Calderone) Date: Tue, 04 Jan 2005 16:43:34 GMT Subject: Hlelp clean up clumpsy code In-Reply-To: <41dabf3d$1@nntp0.pdx.net> Message-ID: <20050104164334.25734.201508819.divmod.quotient.750@ohm> On Tue, 04 Jan 2005 08:18:58 -0800, Scott David Daniels wrote: >Nick Coghlan wrote: > > A custom generator will do nicely: > > > > Py> def flatten(seq): > > ... for x in seq: > > ... if hasattr(x, "__iter__"): > > ... for y in flatten(x): > > ... yield y > > ... else: > > ... yield x > > Avoiding LBYL gives you: > def flatten(seq): > for x in seq: > try: > for y in flatten(x): > yield y > except TypeError: > yield x But totally messes up on error handling. Instead: def flatten(seq): for x in seq: try: subseq = iter(x) except TypeError: yield x else: for subx in flatten(subseq): yield subx to avoid catching TypeErrors from .next(). Jp From aahz at pythoncraft.com Fri Jan 14 16:54:07 2005 From: aahz at pythoncraft.com (Aahz) Date: 14 Jan 2005 16:54:07 -0500 Subject: Threading Or Other Suggestions?!? References: Message-ID: In article , wrote: > > I have a wxPython application that does a lot of things. One of them, >in particular, I have doubts on how to implement it. Essentially, this part >of my application calls an external executable (an oil reservoir >simulator). What I would like to do, is to give the user the possibility to >run more than 1 simulation at the same time. This means: > >1) Writing the executable "data file" needed by the simulator >2) Run the executable file (and wait until completion) >3) Examine the simulation results > >For this, I was thinking about threads... does anyone have other/better >suggestion(s)? Does anyone see any difficulty/memory problems in using >threads? If you're not on Windows, this will be much easier with multiple processes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From deetsNOSPAM at web.de Wed Jan 26 07:04:00 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 26 Jan 2005 13:04:00 +0100 Subject: add indexes on the fly to lists References: <41f69f0b$0$6606$8fcfb975@news.wanadoo.fr> Message-ID: <35pf5tF4nmm25U1@individual.net> > If you want only "search and found" element, look dictionnary ; if you > want also to have the order, see the module set. Erg - no. Sets are mathematically defined as having no order. -- Regards, Diez B. Roggisch From mcturra2000 at yahoo.co.uk Sun Jan 2 13:46:23 2005 From: mcturra2000 at yahoo.co.uk (Mark Carter) Date: Sun, 02 Jan 2005 18:46:23 +0000 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <41d8417e$0$14596$ed2619ec@ptn-nntp-reader01.plus.net> Cameron Laird wrote: > In article <41d7def6$0$74273$ed2619ec at ptn-nntp-reader03.plus.net>, > Mark Carter wrote: > . > [tale of *very* > typical experience > with non-software > engineers] > . > . > Don't start me! Dammit, too late ... I've noticed that they have an overwhelming obsession with GUIs, too. They design wizards for everything. Damn pretty they are, too. Albeit a bit flakey. They seem to conflate pretty interfaces with good interfaces and good software. I used to joke that since our software wasn't particularly magical, it didn't need wizards. But I think I just ended up sounding bitter. We once had a bit of software that we thought we'd like to turn into a generic application. The focus on improvements was, predictably enough, that we should design a GUI that could do anything a client would likely to want to do. It was my opinion, though, having seen the very "special-cases" nature required in the original software, that it was almost impossible to predict exactly how a customer might want the product tailored. I suggested that what they really needed was a library (Python would have been good for this, Lisp might have been even better) that could be extended as required. GUIs second, functionality first. But hey, what would I know. Fortunately, the whole thing's been put on the back burner. And trying to get through to them why source control makes sense, that when more than one person works on a project, some form of coordination is required, that copying and pasting code is evil, and that Excel probably isn't the hammer for every nail. Honestly, I thought (real) engineers were supposed to be clever. From bdesth.quelquechose at free.quelquepart.fr Fri Jan 7 09:22:00 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 07 Jan 2005 15:22:00 +0100 Subject: Getting rid of "self." In-Reply-To: References: Message-ID: <41de998e$0$10263$626a14ce@news.free.fr> BJ?rn Lindqvist a ?crit : > I think it would be cool if you could refer to instance variables > without prefixing with "self." I know noone else thinks like me so > Python will never be changed, but maybe you can already do it with > Python today? > (snip code) > > It works! exec(magic()) does the needed hi = self.hi. Not so > impressive in this case but much cooler when there is more instance > variables around. But the solution is very ugly because you have to > write exec(magic()) in every method. So I'm asking here if someone > knows a better way, maybe using decorators or metaclasses or other > black magic? > The better way is definitively to forget about black magic and understand why mandatory 'self' is Good Thing (tm). (Tip : even when [this|self|@|whatsoever] is not mandatory, using it makes for much more readable code.) Bruno From MAILsweeper at hibernian.ie Fri Jan 28 18:33:51 2005 From: MAILsweeper at hibernian.ie (MAILsweeper at hibernian.ie) Date: Fri, 28 Jan 2005 23:33:51 +0000 (GMT) Subject: Mail sent to Hibernian has a virus !!! Message-ID: <20050128233253.BB6441E5328@bag.python.org> Mail sent to Hibernian was received with a computer virus infected attachment. The mail has been intercepted and did not reach the intended recipient. Sender please remove the virus from the message and resend the mail. From: python-list at python.org To: mailsweeper at hibernian.ie Subject: Mail Delivery (failure mailsweeper at hibernian.ie) Virus: Scenarios/Incoming/Content Scanner: Threat: 'W32/Netsky-P' detected by 'Sophos AV Interface for MIMEsweeper'. Scenarios/Incoming/Blocking .SCR file types incoming: A filename matching the file mask was detected: 'message.scr'. Scenarios/Incoming/Restrict Attachments In: 'ItemLength.GE.0'. was blocked at Fri, 28 Jan 2005 23:30:42 +0000 From kent3737 at yahoo.com Wed Jan 26 10:08:23 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Wed, 26 Jan 2005 10:08:23 -0500 Subject: fast list lookup In-Reply-To: <3e96ebd7.0501260641.159e007f@posting.google.com> References: <3e96ebd7.0501260641.159e007f@posting.google.com> Message-ID: <41f7afd8_3@newspeer2.tds.net> Klaus Neuner wrote: > Hello, > > what is the fastest way to determine whether list l (with > len(l)>30000) contains a certain element? If you can use a set or dict instead of a list this test will be much faster. Kent From clpy at a-nugget.de Fri Jan 28 15:59:26 2005 From: clpy at a-nugget.de (Guido Goldstein) Date: Fri, 28 Jan 2005 21:59:26 +0100 Subject: handling xls with pyuno References: Message-ID: Hi! On Fri, 28 Jan 2005 12:59:11 -0600 John Hunter wrote: > Does anyone have any example scripts using the OpenOffince > python-bridge module pyuno to load xls, extract the data, and/or save > to another format such as xsc or csv. There is something called BlueDCS which can do that. See here: http://cvs.bluedynamics.org/viewcvs/BlueDCS/ HIH Guido -- Guido Goldstein PGP Key: http://www.a-nugget.de/public-key.txt From pdemb at illx.org Sun Jan 2 16:32:14 2005 From: pdemb at illx.org (Peter Dembinski) Date: Sun, 02 Jan 2005 22:32:14 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1> <7x8y7cjo57.fsf@ruckus.brouhaha.com> <87zmzsax12.fsf@hector.domek> <87pt0na5zf.fsf@hector.domek> Message-ID: <87llbba55t.fsf@hector.domek> Peter Dembinski writes: > Peter Dembinski writes: > > [...] > >> str = foo(x) > > (ick!) it should be: > > bar = foo(x) Besides, shouldn't str be a reserved word or something? From jerf at jerf.org Wed Jan 26 19:06:49 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 26 Jan 2005 19:06:49 -0500 Subject: What's so funny? WAS Re: rotor replacement References: <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: On Thu, 27 Jan 2005 04:04:38 +0000, phr wrote: > Skip Montanaro writes: >> Because good requirements specification is difficult and testing improves >> the breed. Better to have the major API changes and bugs taken care of, and >> to have its popularity demonstrated *before* it gets into the Python >> distribution. The best way to do something isn't always obvious at the >> outset. > > That is sometimes true, but not always. Sometimes the best way is > obvious. With all due respect, you aren't arguing very well. Your posts are, like this quote, more reactionary than thought-out. You need to stop arguing for the sake of argument, read more carefully, and think more about your global goals in this conversation than your local ones. I'm 99% certain that you've already gotten all the answers you're going to get and all the answers you need in this thread, but you're so busy arguing the local points like this, you haven't noticed. (Either that, or it's the "you haven't answered me because you haven't given the exact answer I want" bit, which I find quite tiresome; there's another list where there are these three teenagers that don't even realize they've defined "answer" that way and keep bitching that they aren't being "answered" when the "answer" is, basically, "it's nice that you feel that way." But I digress.) > I don't need your permission to do that. What I'm looking for is an > indication that it's worth my while, before I spend the effort. The policy has been laid out, multiple times, by multiple people now. The answer is, you are not going to get any such indication that will satisfy you. Note that I am not a Python contributor of any kind. Also note that I figured this out about two days ago. You can wheedle these guys all you want, but they are too experienced for you to extract a promise from them. From mahs at telcopartners.com Fri Jan 28 02:53:56 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 27 Jan 2005 23:53:56 -0800 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <7x3bwmggi3.fsf@ruckus.brouhaha.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> <6PKdnVpD-4f3CGvcRVn-gQ@comcast.com> <7x3bwmggi3.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Francis Girard writes: > >>Thank you Nick and Steven for the idea of a more generic imerge. > > > If you want to get fancy, the merge should use a priority queue (like > in the heapsort algorithm) instead of a linear scan through the > incoming iters, to find the next item to output. That lowers the > running time to O(n log k) instead of O(n*k), where k is the number of > iterators and n is the length. I looked at a heapq solution but didn't see any clean way of dealing with multiple iterators having equal values. The dict solution below deals cleanly with that, since one key can be shared by any number of iterators. Extracting the minimum, and the associated iterables is fast, but the overall solution is still slower than the brute force approach for the 3 hamming iterators. >>> def imerge(*iterables): ... cache = {} ... iterators = map(iter,iterables) ... number = len(iterables) ... exhausted = 0 ... while 1: # First time through, looked at all of them # Subsequently, update only the minimum iterators ... for it in iterators: ... try: # Key each iterator by its next() value # Multiple iterators may share the same key ... cache.setdefault(it.next(),[]).append(it) ... except StopIteration: ... exhausted += 1 ... if exhausted == number: ... raise StopIteration # Get the lowest value ... val = min(cache) # and all the iterators that have that value ... iterators = cache.pop(val) ... yield val >>> list(imerge([1, 2, 3, 6], [1, 2, 3, 7], [1, 2, 3, 4, 5])) [1, 2, 3, 4, 5, 6, 7] >>> Michael From fumanchu at amor.org Thu Jan 13 00:30:12 2005 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 12 Jan 2005 21:30:12 -0800 Subject: why are people still using classic classes? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33981A9@exchange.hqamor.amorhq.net> Simon Wittber wrote: > Is there a legitimate use for classic classes that I am not aware of? As was pointed out to me when I asked on this list just a short while ago ;) classic classes can be faster. Robert Brewer MIS Amor Ministries fumanchu at amor.org From tjreedy at udel.edu Wed Jan 26 13:55:16 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Jan 2005 13:55:16 -0500 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: "Peter Maas" wrote in message news:ct8517$m03$1 at swifty.westend.com... > Davor schrieb: >> so initially I was hoping this is all what Python is about, but when I >> started looking into it it has a huge amount of additional (mainly OO) >> stuff which makes it in my view quite bloated now. > > So you think f.write('Hello world') is bloated and file_write(f,'Hello > world') > is not? This is the minimum amount of OO you will see when using Python. Now that we have gently teased Davor for his OO fear, I think we should acknowledge that his fears, and specifically his bloat fear, are not baseless. In Python, one can *optionally* write a+b as a.__add__(b). That is bloat. I believe, in some strict OO languages, that bloat is mandatory. For one operation, the bloat is minor. For ever a relatively simple expression such as b**2-4*a*c, it becomes insanity. If we were to have to write sin(x) instead as x.sin(), there would not be syntax bloat. And it would be easier to write generic float-or-complex math functions, just as your print example shows how __str__ methods facilitate generic print operations. But if the class method syntax were manditory, there would be class and/or class hierarchy bloat due to the unlimited number of possible functions-of-a-float and large number of actual such functions that have been written. On the other hand... curryleft(list.append, somelist) is a bit more to type than somelist.append. > print "*** Davor's evolution towards an OO programmer ***" Your Four Steps to Python Object Oriented Programming - vars, lists, dicts, and finally classes is great. It makes this thread worthwhile. I saved it and perhaps will use it sometime (with credit to you) to explain same to others. Terry J. Reedy From jbperez808 at wahoo.com Wed Jan 12 17:08:43 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Thu, 13 Jan 2005 06:08:43 +0800 Subject: Another look at language comparisons In-Reply-To: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> Message-ID: <34llf5F4apou6U2@individual.net> Anyone know of a cached copy where the photos are present? The whole thing makes little sense with the photos gone. Pierre Quentel wrote: > http://khason.biz/blog/2004/12/why-microsoft-can-blow-off-with-c.html From francis.girard at free.fr Wed Jan 26 14:39:20 2005 From: francis.girard at free.fr (Francis Girard) Date: Wed, 26 Jan 2005 20:39:20 +0100 Subject: python without OO In-Reply-To: <10vdt2bpr0m84db@corp.supernews.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <10vdt2bpr0m84db@corp.supernews.com> Message-ID: <200501262039.23260.francis.girard@free.fr> Le mercredi 26 Janvier 2005 02:43, Jeff Shannon a ?crit?: > In statically typed languages like C++ and Java, inheritance trees are > necessary so that you can appropriately categorize objects by their > type. Since you must explicitly declare what type is to be used > where, you may need fine granularity of expressing what type a given > object is, which requires complex inheritance trees. In Python, an > object is whatever type it acts like -- behavior is more important > than declared type, so there's no value to having a huge assortment of > potential types. Deep inheritance trees only happen when people are > migrating from Java. ;) > > Jeff Shannon > Technician/Programmer > Credit International These lines precisely express my thoughts. Most of the difficulties in OO in Java/C++ comes from the all mighty goal of preserving type safety. Type safety is certainly a very desirable goal but it, sometimes, leads to very complex code only to achieve it. The prize is just too high. The design patterns that were supposed to save time through high code reuse oftenly becomes a maintenance nightmare. Something that no one in the company can understand except a few. Instead of trying to fix some domain specific code, you end up trying to fix a supposedly highly reusable code that, oh well, you have to adapt. This is espeacially true if the system had been designed by a big OO-design-patterns enthusiastic programmer geek. I am not saying that design patterns are bad. I think that they are an invaluable gift to OO. I'm only saying that they have indeed a perniciuous and pervert effect in the real world industry. People become religious about it and forget to think about a simple solution ... Being dynamically typed, these kind monster patterns are much less probable. And the Python philosophy and culture is the very contrary to that trend. I've been involved in C++/Java projects for the last 8 years. The first time I met Python, I've been frigthen by its lack of static type safety. But over the time, I've been convinced by seeing clean Python code over and over again. In the end, I could appreciate that being simple leads the way to less bugs, which type safety was supposed to prevent ... Coming from the C++ community, Python had been just like fresh air. It changed me from the nightmare derscribed in that discussion thread. When I think that comapnies pay big money for these kind of monsters after having seen a few ppt slides about it, it makes me shiver. Regards, Francis Girard FRANCE From ville at spammers.com Mon Jan 3 06:05:48 2005 From: ville at spammers.com (Ville Vainio) Date: 03 Jan 2005 13:05:48 +0200 Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: >>>>> "jfj" == jfj writes: jfj> There were functional and non-functional programming jfj> languages (the first being *much* simpler to jfj> implement). There is a *reason* people chose C over jfj> lisp. It's not that we were all blind and didn't see the jfj> amazingness of lisp. Procedural languages are simply better, jfj> and I'm not replying to this flamewar. You did already ;). Lisp is not a functional programming language, if that was the case it would be even less popular than it is now. Lisp had it's heyday, while pure FP languages didn't even have that much. Hey, it's 2005, I don't think we've used up our yearly Lisp flamewar quota yet. -- Ville Vainio http://tinyurl.com/2prnb From marklists at mceahern.com Sun Jan 2 15:43:34 2005 From: marklists at mceahern.com (Mark McEahern) Date: Sun, 02 Jan 2005 14:43:34 -0600 Subject: Rebinding stdout In-Reply-To: <41D85CAF.2090505@mceahern.com> References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <41D85CAF.2090505@mceahern.com> Message-ID: <41D85CF6.9070004@mceahern.com> Ron Garret wrote: > But this topic does bring up a legitimate question: I have a bunch of > code that generates HTML using PRINT statements. I need to convert > all this code to return strings rather than actually printing them (so > I can use the results to populate templates). In Lisp I could do this: > > (with-output-to-string (s) > (let ( (*standard-output* s) ) > (call-html-generating-code) > s)) > > Is there an equivalent Python trick to capture a function call's > output as a string? > > Just to make sure I understand, I'm going to restate your question: Is there a way to capture stdout? The answer: Sure, replace it with something file-like: >>> import sys, StringIO >>> default = sys.stdout >>> writer = StringIO.StringIO() >>> sys.stdout = writer >>> print 'Whatever' >>> sys.stdout = default >>> print writer.getvalue() Whatever >>> // m From aleaxit at yahoo.com Wed Jan 26 03:04:42 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 26 Jan 2005 09:04:42 +0100 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> Message-ID: <1gqznmh.8tvy67o59lppN%aleaxit@yahoo.com> Davor wrote: > no one ever had to document structured patterns - which definitely > exist - but seem to be obvious enough that there is no need to write a > book about them... You _gotta_ be kidding -- what do you think, e.g., Wirth's "Algorithms plus Data Structures Equals Programs" *IS* all about? Alex From bokr at oz.net Fri Jan 14 18:30:49 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 14 Jan 2005 23:30:49 GMT Subject: Class initialization from a dictionary, how best? References: <1105677379.632236.17020@z14g2000cwz.googlegroups.com> <41e7b80e.827352389@news.oz.net> <1105716725.996023.255800@c13g2000cwb.googlegroups.com> Message-ID: <41e84a4f.864793467@news.oz.net> On 14 Jan 2005 07:32:06 -0800, "brianobush at gmail.com" wrote: >Yes, my examle here is a tiny part of a larger more complex issue. My >application is an DOM XML parser that is reading attributes one at a you mean like blah blah and you are grabbing things of interest out of a stream of info you are getting from call-backs? Or the equivalent? >time. My class that I am creating is used elsewhere and must have >certain arguments for those uses to continue working. So, I seem to be >left with creating an intermediate object. Before, I was simply Unless the "intermediate object" accumulates information for multiple Test() instances, why couldn't t= Test() be its own "intermediate object"? If you are accumulating info for multiple instances before creating them it is not clear from your description. >creating an object: > >t = Test() >for attr_name in mapping.keys(): >setattr(t, attr_name, value_from_source) > >This I feel was ellegant, efficient and clear. However, what I have now >works but is not clear. >BTW, t1 is just for example and was just being printed What about giving Test some methods to do what you'd like? E.g., a micro-step in that direction from the above would let you write t = Test() ... t.load_info(infosource) Then the question becomes what infosource should be, or whether you really need it at all. IOW, if you are doing infosource.add_info(info_id, info_value) why couldn't you do t.add_info(info_id, info_value), unless you have to do t2.add_info(...) alternately with t.add_info(...), and if that's the case, what is the criterion for choosing t vs t2? Maybe that could be done by something that automatically manufactures t's as needed in a pool of partially complete t's. But your real requirements are not clear enough here, so you may get help crossing a stream, but no one will be able to say you are already on the side of the stream you want to be later, and there's an easy path without need of crossing twice ;-) Regards, Bengt Richter From jurgenex at hotmail.com Sun Jan 9 03:58:13 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sun, 09 Jan 2005 08:58:13 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: xah at xahlee.org wrote: > #python supports complex numbers. [...] So? > # Perl doesn't support complex numbers. But there are packages that > supports it. The Math::Complex module is part of the standard installation already, no need for any "packages" (whatever that might be). Did you check "perldoc Math::Complex" NAME Math::Complex - complex numbers and associated mathematical functions [...] jue From noone at nowhere.com Wed Jan 12 18:28:38 2005 From: noone at nowhere.com (Simon Foster) Date: Wed, 12 Jan 2005 23:28:38 -0000 Subject: Release date for 2nd edn. Cookbook Message-ID: <41e5b2b3$0$330$cc9e4d1f@news.dial.pipex.com> Does anyone have any idea on this date? Any chance of a signed copy for contributors? From rnd at onego.ru Mon Jan 10 03:28:54 2005 From: rnd at onego.ru (Roman Suzi) Date: Mon, 10 Jan 2005 11:28:54 +0300 (MSK) Subject: interpreter Py_Initialize/Py_Finalize mem leak? In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE0252027E@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE0252027E@au3010avexu1.global.avaya.com> Message-ID: On Mon, 10 Jan 2005, Delaney, Timothy C (Timothy) wrote: >Roman Suzi wrote: > >> In pure curiosity I tried to compile loop.c from Demo/embed >> and started it with 'print 2+2'. It seems, that both 2.3 and 2.4 >> pythons have memory leaks in Py_Initialize/Py_Finalize calls. >> (That is, interpreter doesn't clean up well after itself). > >What's your evidence for this (i.e. what are the symptoms)? - memory usage grows over time. >If you have a repeatable test case, please raise a bug report on >SourceForge. I tested only under Linux. And it is 100% repeatable. >Tim Delaney > Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From fumanchu at amor.org Fri Jan 7 16:23:26 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 7 Jan 2005 13:23:26 -0800 Subject: switching an instance variable between a property and a normal value Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398133@exchange.hqamor.amorhq.net> Steven Bethard wrote: > I'd like to be able to have an instance variable that can > sometimes be > accessed as a property, and sometimes as a regular value, > e.g. something > like: ... > py> c.x is c.x # I'd like this to be False You'd like 'c.x is c.x' to be FALSE? You can't be serious. Must be a typo. If you want C._x to return something other than the property descriptor, you can. Grab the sample code for Property from http://users.rcn.com/python/download/Descriptor.htm#properties and modify the __get__ method: def __get__(self, obj, objtype=None): if obj is None: return self # Return whatever you like here if self.fget is None: raise AttributeError, "unreadable attribute" return self.fget(obj) That might be one way to get what you want. Robert Brewer MIS Amor Ministries fumanchu at amor.org From FBatista at uniFON.com.ar Tue Jan 11 13:49:12 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 11 Jan 2005 15:49:12 -0300 Subject: Game programming in Python Message-ID: [Baza] #- I'm looking for any books or on-line resources on game #- programming using #- Python. Does anyone have any advice? Check PyGame: http://www.pygame.org/ . 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 carl.lowenstein at gmail.com Wed Jan 12 00:10:05 2005 From: carl.lowenstein at gmail.com (carl.lowenstein at gmail.com) Date: 11 Jan 2005 21:10:05 -0800 Subject: stopping the sound server in PySol code -- how? In-Reply-To: References: Message-ID: <1105506605.004416.314560@z14g2000cwz.googlegroups.com> # chmod 000 /usr/lib/python2.3/site-packages/pysolsoundserver.so crude but very effective. carl From iwcook58 at gmail.com Sun Jan 9 19:44:10 2005 From: iwcook58 at gmail.com (iwcook58 at gmail.com) Date: 9 Jan 2005 16:44:10 -0800 Subject: xml.sax._exceptions.SAXReaderNotAvailable Message-ID: <1105317850.406005.74980@c13g2000cwb.googlegroups.com> I am having a problem running py2exe on my computer. When running the exe that has been generated by py2exe the following error comes up. C:\MyPython\dist>kirbyutils.exe kirby350.xml Traceback (most recent call last): File "kirbyutils.py", line 292, in ? File "kirbyutils.py", line 261, in main File "xml\sax\sax2exts.pyc", line 37, in make_parser File "xml\sax\saxexts.pyc", line 77, in make_parser xml.sax._exceptions.SAXReaderNotAvailable: No parsers found I'm baffled. I have searched google. There are lots of threads about "xml.sax._exceptions.SAXReaderNotAvailable: No parsers found" but I do not understand what is wrong. There is thread http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/4cb60885adde0cf3/f47d9aeaa584b8c6?q=xml.sax._exceptions.SAXReaderNotAvailable&_done=%2Fgroup%2Fcomp.lang.python%2Fsearch%3Fq%3Dxml.sax._exceptions.SAXReaderNotAvailable%26start%3D0%26scoring%3Dd%26&_doneTitle=Back+to+Search&&d#f47d9aeaa584b8c6 that made a suggestion or two basically to check xml has been installed. Here are my results.. C:\MyPython>\Python23\python.exe 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 xml >>> print xml >>> import xml.dom >>> print xml.dom >>> import xml.dom.minidom >>> print xml.dom.minidom >> I have installed pyxml and everything I can think of.. Setup.cmd is... setup.py py2exe -i xml.sax.drivers2.drv_pyexpat -i win32com.gen_py.* Setup.py is... # setup.py from distutils.core import setup import py2exe setup(console=["kirbyutils.py"], options = {"py2exe": {"packages": ["encodings"], "dll_excludes":["mfc71.dll"]}} ) The imports in kirbyutils.py are.... import os import zipfileext import zipfile import sys import xml.sax as sax import xml.sax.handler import fnmatch import shutil import binascii import time import filecmp What am I missing?? Thanks in advance. Ian Cook (Freeware author of Kirby Alarm And Task Scheduler www.kirbyfooty.com) From steven.bethard at gmail.com Tue Jan 25 14:54:00 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 12:54:00 -0700 Subject: How to input one char at a time from stdin? In-Reply-To: References: Message-ID: <-qudnR5aSc1FPmvcRVn-sg@comcast.com> Swaroop C H wrote: > On Tue, 25 Jan 2005 12:38:13 -0700, Brent W. Hughes > wrote: > >>I'd like to get a character from stdin, perform some action, get another >>character, etc. If I just use stdin.read(1), it waits until I finish typing >>a whole line before I can get the first character. How do I deal with this? > > > This is exactly what you need: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 > Title: "getch()-like unbuffered character reading from stdin on both > Windows and Unix" > > This recipe was a lifesaver for me once :-) Thanks for the link! I've seen this question before a few times, but no one had pointed out the recipe. Steve From mike.kreiner at gmail.com Sun Jan 16 18:53:06 2005 From: mike.kreiner at gmail.com (mike kreiner) Date: 16 Jan 2005 15:53:06 -0800 Subject: import problems *newbie* In-Reply-To: References: <1105682316.601321.118820@f14g2000cwb.googlegroups.com> <41e7959b$0$385$636a15ce@news.free.fr> Message-ID: <1105919586.453157.42550@c13g2000cwb.googlegroups.com> Thanks for your help Steve and F. Petitjean. Sorry for taking so long to get back, I was away from my lab for a few days. The path to my directory was not included in the sys.path list. Adding a my.pth file to the site-packages directory fixed the import problem. F. Petitjean, I originally edited the PYTHONPATH because "Learning Python," the O'Reilly book, says to do so. I like your and Steve's solutions better--editing the PYTHONPATH seems a little unwieldy--but just to satisfy my curiosity, what are some of the reasons these methods are preferable? Steve, as far as finding out the cause of this problem, I muddled around python and the registry for a while, but nothing jumped out at me. The only thing I can think of is that I have both Python 2.3 and 2.4 installed, and I'm currently working in 2.3. I thought that PYTHONPATH was an environment variable, so having two different versions wouldn't affect it, but I was wondering...should I bother uninstalling 2.4 to see if the prob gets fixed? Other than that I'm still something of a newbie, but I'd love to actually help fix this bug if you can think of anything for me to try (oh joy, my first open source contribution!). Thanks. ~mike From bulba at bulba.com Fri Jan 7 07:40:14 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 13:40:14 +0100 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <7xsm5et0rb.fsf@ruckus.brouhaha.com> Message-ID: <370tt0deerdah8tm15rnv3q98ccerpsq3g@4ax.com> On 06 Jan 2005 18:46:00 -0800, Paul Rubin wrote: >"Terry Reedy" writes: >> Would it be possible, at least for Windows, to write a Python script >> implementing a 'virtual distribution'? IE, download Python, install it, >> download next package, install it, etc. -- prefereably table driven? >I just don't understand why you'd want to do that, instead of putting >all the files in the distro in the first place. Plus there would be maddening dependencies - "oh, in order to use this I need dl that". "oh, that package is missing", "why that doesn't work?" - and time gets wasted. On Linux, quite a lot of code had to be written to resolve dependencies like "a.rpm depends on b.rpm depends on c.rpm ...". Sure, apt is a wonderful tool for resolving such stuff - but I've seen even apt choking sometimes on dependencies it couldn't resolve, esp. when the package you attempt to dl is broken in some way. Reason - apt-get says "sorry, what this package depends on is broken and I can't find anything else in your /etc/apt/sources.list that would be appropriate". Result? Nobody gets to use Pine on this machine, unless I compile it myself (which I finally did). Sure it _can_ be done, but essentially it's a waste of time that this person could devote to doing smth else. It doesn't happen often, but it happens. Why get into resolving such complexity if you don't have to? There are good reasons to use tools like apt-get or yum or up2date on Linux: you can't fit the bugfixes on a CD that come every day, obviously, there's too much of it all to fit simply everything anybody could ever need on the media, etc, etc. However, with Python that's not a problem, because distro is smaller and it doesn't change _that_ often, as lots of packages on Linux are updated almost daily. One of the options for Python could be to have two distributions: one standard, basic distribution, and the "Stuffed Python" based on the standard, created simply by piling all the good stuff on top of standard distro. -- It's a man's life in a Python Programming Association. From fredrik at pythonware.com Thu Jan 13 10:26:08 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Jan 2005 16:26:08 +0100 Subject: python 2.3.4 for windows: float("NaN") throws exception References: <1105629033.442397.124820@c13g2000cwb.googlegroups.com> Message-ID: wrote: > my python 2.3.4 for windows refuse to execute line float("NaN"). It > says: > >>>> float("NaN") > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for float(): NaN > > The same line works as expected on Linux and Solaris with python 2.3.4. > Could anybody explain what is possibly wrong here? is it bug or > feature? feature, sort of. see http://www.python.org/peps/pep-0754.html : "Currently, the handling of IEEE 754 special values in Python depends on the underlying C library. Unfortunately, there is little consistency between C libraries in how or whether these values are handled. For instance, on some systems "float('Inf')" will properly return the IEEE 754 constant for positive infinity. On many systems, however, this expression will instead generate an error message." the PEP includes a pointer to a module that lets you replace that "float" with the fully portable: import fpconst def myfloat(x): if x == "NaN": return fpconst.NaN return float(x) From lcatalin at siadv.com Wed Jan 5 10:45:34 2005 From: lcatalin at siadv.com (Catalin Lungu) Date: Wed, 5 Jan 2005 16:45:34 +0100 Subject: Image capture References: <1104939479.011181.147650@f14g2000cwb.googlegroups.com> Message-ID: Hi, I want to capture a no visible area of a wxFrame of Python. This area contain a wxGrid object. In VB6 this code work very good. Thanks. "Kartic" escribi? en el mensaje news:1104939479.011181.147650 at f14g2000cwb.googlegroups.com... > Catalin, > > Some explanation about what you are tring to do will be of immense > help. > > Did you want to capture some other Windows object from Python or do you > want to capture a Python GUI application from Python? > > I might be able to help out, but please send more details. > Thank you, > --Kartic > From aleaxit at yahoo.com Sat Jan 1 17:46:29 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 1 Jan 2005 23:46:29 +0100 Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> Message-ID: <1gpqhbl.125l3evz09uefN%aleaxit@yahoo.com> BOOGIEMAN wrote: > Beginners question, but really what can you do with it ? You can write application programs, big or small, of just about any kind you may imagine, on just about any platform you may imagine (from mainframes and supercomputers down to powerful cellphones such as Nokia's S-60 series). > How hard is Python to learn compared with other languages > (let's say C#). Python is among the simplest languages to learn. > Can you make fullscreen game with it (for example) ? Sure! Have you thought of using google? The first 2 hits for python games are on www.pygame.org, "This allows you to create fully featured games and multimedia programs in the python language", as the google snippet says. The third hit is for the book "Game Programming With Python" on the amazon site. The 4th one is about Month Python, but the fifth is back to our subject -- a "Python Game Programming" page full of useful links. Then you get another link to the same book, a link to a different book, &c. > I've looked at http://www.python.org but nothing concrete there You _gotta_ be kidding, right...? The Beginner's Guide link takes you right to the BeginnersGuide page which starts with the reassurance that Python is easy to learn even if you're new to programming and continues with a zillion useful links. The Python Books link takes you to a huge list of books, and the FIRST subheading under "specific applications" is for game programming, leading you to the two books I already mentioned. There's a Search bar, enter Game there, and the FIRST hit is http://www.python.org/moin/GameProgramming which STARTS with the reassurance that, yes, you CAN "write whole games in Python", and besides PyGame also points you to PyKira, "a fast game development framework for Python" (which) "also supports MPEG video, sound (MP3, Ogg Vorbis, Wav and Multichannel module files), direct images reading and much more". Etc, etc, ...!!! How much more "concrete" could you expect *ANY* blessed website to BE, for Pete's sake?!??! Alex From simon.alexandre at cetic.be Tue Jan 11 07:19:11 2005 From: simon.alexandre at cetic.be (simon.alexandre) Date: Tue, 11 Jan 2005 13:19:11 +0100 Subject: [csv module] duplication of end of line character in output file generated Message-ID: Hi all, I use csv module included in python 2.3. I use the writer and encouter the following problem: in my output file (.csv) there is a duplication of the end of line character, so when I open the csv file in Ms-Excel a blank line is inserted between each data line. OS: W2k Someone has an idea ? thanks in advance the source code is the following: --------------------------------------------------> import csv class CsvDumper: def __init__(self): self.object = [['la','mb','mc','md'],['ma','mb','mc','md'],['ma','mb','mc','md']] self.writer = csv.writer(file("Test.csv", "w")) def DumpCsvFile(self): for row in self.object: self.writer.writerow(row) c = CsvDumper() c.DumpCsvFile() From daniel at bowettsolutions.com Wed Jan 12 15:39:56 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Wed, 12 Jan 2005 20:39:56 +0000 Subject: encryption/decryption help In-Reply-To: References: Message-ID: <41E58B1C.7030100@bowettsolutions.com> MD5 and SHA are by their very nature one way encryption. You cannot decrypt them. A quick google for other encrytion methods found this: http://www.amk.ca/python/code/crypto.html What you will need to do is find an encryption methos that uses a key which you use to encrypt and decrypt the data. You could get hold of something like GPG which has a command line interface and encrypt and decrypt that way.... drs wrote: >Hi, I need to send secure data over an insecure network. To that end, I am >needing to encrypt serialized data and then decrypt it. Is there a builtin >way to do this in Python? MD5, SHA, etc encrypt, but I am not seeing a way >to get back my data. Encryption is totally new to me, so any pointers of >what to read up on would be appreciated. > >As a side note, I understand that I could use https, but this would involve >changing things that I may not be at liberty to change -- though if this >turns out to be the best solution, then I'll find a way to use it. > >Thanks > > > > From steven.bethard at gmail.com Mon Jan 31 01:25:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 30 Jan 2005 23:25:17 -0700 Subject: Problem with loading textfiles into dictionaries. In-Reply-To: References: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> Message-ID: Kartic wrote: > mercuryprey at gmail.com said the following on 1/30/2005 7:43 PM: > >> Hello, >> I want to do the following: >> >> def do_load(self, arg): >> sitefile = file('sitelist', 'r+', 1) >> while True: >> siteline = sitefile.readline() >> site_rawlist = siteline.split() >> sitelist[site_rawlist[0]] = site_rawlist[1:] >> if len(siteline) == 0: >> break >> > You should move "if len(siteline) == 0" part right after your readline. > The way you have done it really does not help. Or better yet, don't use "if len(siteline) == 0" -- use "if siteline". See this an other examples of dubious Python: http://www.python.org/moin/DubiousPython Specifically, see the section on Overly Verbose Conditionals. Steve From tim.peters at gmail.com Mon Jan 10 14:12:29 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 10 Jan 2005 14:12:29 -0500 Subject: Writing huge Sets() to disk In-Reply-To: <41E2CE0E.5000704@ribosome.natur.cuni.cz> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> Message-ID: <1f7befae050110111239496b07@mail.gmail.com> [Martin MOKREJ?] > just imagine, you want to compare how many words are in English, German, > Czech, Polish disctionary. You collect words from every language and record > them in dict or Set, as you wish. Call the set of all English words E; G, C, and P similarly. > Once you have those Set's or dict's for those 4 languages, you ask > for common words This Python expression then gives the set of words common to all 4: E & G & C & P > and for those unique to Polish. P - E - G - C is a reasonably efficient way to compute that. > I have no estimates > of real-world numbers, but we might be in range of 1E6 or 1E8? > I believe in any case, huge. No matter how large, it's utterly tiny compared to the number of character strings that *aren't* words in any of these languages. English has a lot of words, but nobody estimates it at over 2 million (including scientific jargon, like names for chemical compounds): http://www.worldwidewords.org/articles/howmany.htm > My concern is actually purely scientific, not really related to analysis > of these 4 languages, but I believe it describes my intent quite well. > > I wanted to be able to get a list of words NOT found in say Polish, > and therefore wanted to have a list of all, theoretically existing words. > In principle, I can drop this idea of having ideal, theoretical lexicon. > But have to store those real-world dictionaries anyway to hard drive. Real-word dictionaries shouldn't be a problem. I recommend you store each as a plain text file, one word per line. Then, e.g., to convert that into a set of words, do f = open('EnglishWords.txt') set_of_English_words = set(f) f.close() You'll have a trailing newline character in each word, but that doesn't really matter. Note that if you sort the word-per-line text files first, the Unix `comm` utility can be used to perform intersection and difference on a pair at a time with virtually no memory burden (and regardless of file size). From newsgroups at jhrothjr.com Mon Jan 17 12:55:18 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 17 Jan 2005 11:55:18 -0600 Subject: PyChecker messages References: <1105983271.574296.37740@c13g2000cwb.googlegroups.com> Message-ID: <10unv167p6l9335@news.supernews.com> "Ben Sizer" wrote in message news:1105983271.574296.37740 at c13g2000cwb.googlegroups.com... > But you could use a dict of return values, or even just assigning a > different return value in each if clause. The end result is that you > have a single well-defined exit point from the function, which is > generally considered to be preferable. Preferable, but not any form of an absolute. "Single Exit" was one of the recommendations from the early structured program work back in the 70s, and the industry has long since sent it to the dustbin of history. The issue is a simple one of clarity, and woodenly applying the single exit rule where it doesn't belong frequently winds up creating nested if-elif-else structures and extranious flag variables. If an embedded return isn't clear, the method probably needs to be refactored with "extract method" a few times until it is clear. John Roth > From kp8 at mac.com Tue Jan 11 12:25:45 2005 From: kp8 at mac.com (kpp9c) Date: 11 Jan 2005 09:25:45 -0800 Subject: Time script help sought! Message-ID: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> I am kind of in a bit of a jam (okay a big jam) and i was hoping that someone here could give me a quick hand. I had a few pages of time calculations to do. So, i just started in on them typing them in my time calculator and writing them in by hand. Now i realize, that i really need a script to do this because: 1. It turns out there are hundreds of pages of this stuff. 2. I have to do something similar in again soon. 3. By doing it by hand i am introducing wonderful new errors! 4. It all has to be typed up anyway (which means weeks of work and even more typos!) The input would like so: Item_1 TAPE_1 1 00:23 8:23 Item_2 TAPE_1 2 8:23 9:41 Item_3 TAPE_1 3 9:41 10:41 Item_3 TAPE_1 4 10:47 11:19 Item_3 TAPE_1 5 11:21 11:55 Item_3 TAPE_1 6 11:58 12:10 Item_3 TAPE_1 7 12:15 12:45 Defect in analog tape sound. Item_3 TAPE_1 8 12:58 24:20 Defect in analog tape sound. Item_4 TAPE_1 9 24:33 Item_4 TAPE_1 10 25:48 Item_4 TAPE_1 11 29:48 Item_4 TAPE_1 12 31:46 Item_4 TAPE_1 13 34:17 Electronic sounds. Item_4 TAPE_1 14 35:21 Item_4 TAPE_1 15 36:06 Item_4 TAPE_1 16 37:01 37:38 These are analog tapes that were digitized (on to CD or a digital tape) that have now been exported as individual files that are meant to be part of an on-line audio archive. The timings refer to the time display on the CD or digital tape. The now all have to adjusted so that each item starts at 0.00 since they have all been edited out of their context and are now all individual items that start at 00:00. So Item_1 which was started at 00:23 on the tape and ended at 8:23 needs to have 23 seconds subtracted to it so that it says: Item_1 TAPE_1 1 00:00 08:00 Item_2 TAPE_1 2 08:23 09:41 would change to: Item_2 TAPE_1 2 00:00 01:18 etc. but as always you may notice a wrinkle.... some items have many times (here 6) indicated: Item_3 TAPE_1 3 9:41 10:41 Item_3 TAPE_1 4 10:47 11:19 Item_3 TAPE_1 5 11:21 11:55 Item_3 TAPE_1 6 11:58 12:10 Item_3 TAPE_1 7 12:15 12:45 Defect in analog tape sound. Item_3 TAPE_1 8 12:58 24:20 Defect in analog tape sound. This is all a single sound file and these separate times mark where there was a break, defect, or edit in the individual item. These have to be adjusted as well to show where these events would appear in the new sound file which now starts at 00:00. Item_3 TAPE_1 3 00:00 01:00 ---- Item_3 TAPE_1 4 01:00 01:38 ---- Item_3 TAPE_1 5 01:38 02:14 ---- Item_3 TAPE_1 6 02:14 02:29 ---- Item_3 TAPE_1 7 02:29 03:04 Defect in analog tape sound. Item_3 TAPE_1 8 03:04 14:39 Defect in analog tape sound. Further wrinkles: Some have start and end times indicated, some only start times. I suppose that the output would ideally have both.... some have comments and others don't ... and I need these comments echo-ed or since i probably need to make a database or table eventually non comments just have some place holder. I'd have a lot of similar type calculations to do... I was hoping and praying that some one here was feeling generous and show me the way and then, of course i could modify that to do other tasks... Usually i am happy to take the long road and all but i'll be honest, i am in a big jam here and this huge task was just dumped on me. I am frankly a little desperate for help on this and hoping someone is feeling up to spoon feeding me a clear modifiable example that works. Sorry..... cheers, kevin From kent3737 at yahoo.com Sun Jan 9 20:54:45 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Sun, 09 Jan 2005 20:54:45 -0500 Subject: Please Contribute Python Documentation! In-Reply-To: References: Message-ID: <41e1de2d$1_1@newspeer2.tds.net> Aahz wrote: > In article , > Tony Meyer wrote: > >>I don't think I've seen such a statement before - the stuff I've seen >>all indicates that one should be submitting proper LaTeX docs/patches. >>If plain-text contributions are welcome, could this be added to the doc >>about contributing to the docs? (I suppose I could submit a patch, but >>that seems overkill ). > > > It *is* in the docs now -- see the top of > http://www.python.org/doc/2.4/doc/doc.html It's also spelled out pretty clearly in the "About this document" document you get by clicking on the link at the bottom of every page. Kent > > (This has been the official policy for some time, but you're right that > it wasn't earlier documented. So I filed a bug report. ;-) If you > think this still isn't enough, file another.) From http Fri Jan 28 07:07:44 2005 From: http (Paul Rubin) Date: 28 Jan 2005 04:07:44 -0800 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> Message-ID: <7x3bwlsqnj.fsf@ruckus.brouhaha.com> Duncan Booth writes: > In other words, I'm intrigued how you managed to come up with something you > consider to be a security issue with Python since Python offers no > security. Perhaps, without revealing the actual issue in question, you > could give an example of some other situation which, if it came up in > Python you would consider to be a security issue? Until fairly recently, the pickle module was insufficiently documented as being unsafe to use with hostile data, so people used it that way. As a result, the Cookie module's default settings allowed remote attackers to take over Python web apps. See SF bug 467384. From dbickett at gmail.com Tue Jan 11 20:02:16 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Tue, 11 Jan 2005 20:02:16 -0500 Subject: shutil.move has a mind of its own In-Reply-To: <41e46e0d@usenet01.boi.hp.com> References: <41e46e0d@usenet01.boi.hp.com> Message-ID: <1d6cdae30501111702e71bdfc@mail.gmail.com> Don wrote: > I don't know if this is the problem or, not, but: > [snip] As I said, that was simply an error when typing the example, and it is not present in my code. See below. Neil Benn wrote: > >Oh, I'm sorry, that was my mistake. The example contained that error, > >but my code does not. > > > > [snip] > > > To be fair though - I would have expected the method to throw an error > rather than default to cwd. > > Neil > Which is why I found this so strange, and also why I provided my code. The paths are user-inputed, and only referenced as variables, so this is clearly not a matter of escape sequences. Daniel Bickett From bob_smith_17280 at hotmail.com Sun Jan 9 21:56:45 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sun, 09 Jan 2005 21:56:45 -0500 Subject: a new Perl/Python a day In-Reply-To: References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: Scott Bryce wrote: > Xah Lee wrote: > >> frustrated constantly by its inanities and incompetences.) > > I don't see what this has to do with Perl. You're joking, right? From gabriel.cooper at mediapulse.com Mon Jan 24 10:40:29 2005 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Mon, 24 Jan 2005 10:40:29 -0500 Subject: Finding a script's home directory? Message-ID: <41F516ED.3090503@mediapulse.com> In one of my python programs has a data file I need to load. My solution was to say: if os.path.exists(os.path.join(os.getcwd(), "config.xml")): self.cfgfile = os.path.join(os.getcwd(), "config.xml") Which works fine... as long as you're *in* the script's home directory when you run it (as in, run it as: ./startApp.py as opposed to ./myApp/startApp.py). If I run it from an alternate directory the program looks for the config.xml file in my current directory not the app's home directory. So how do I get the script's home directory? From a at b.c Thu Jan 6 22:02:46 2005 From: a at b.c (Doug Holton) Date: Thu, 06 Jan 2005 21:02:46 -0600 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: Message-ID: Alan Gauld wrote: >>GvR has commented that he want to get rid of the lambda keyword for Python 3.0. >>Getting rid of lambda seems like a worthy goal, > > > Can I ask what the objection to lambda is? > 1) Is it the syntax? > 2) Is it the limitation to a single expression? > 3) Is it the word itself? > > I can sympathise with 1 and 2 but the 3rd seems strange since a > lambda is a well defined name for an anonymous function used in > several programming languages and originating in lambda calculus > in math. Lambda therefore seems like a pefectly good name to > choose. I agree with keeping lambda functionality, and I don't care what name is used, but there are people who do not like "lambda": http://lambda-the-ultimate.org/node/view/419#comment-3069 The word "lambda" is meaningless to most people. Of course so is "def", which might be why Guido van Robot changed it to "define": http://gvr.sourceforge.net/screen_shots/ Even a simple word like "type" can be difficult to explain to beginners: http://lambda-the-ultimate.org/node/view/337 Python is easier for beginners to learn than other mainstream programming languages (like java or C++), but that's not to say it doesn't have some stumbling blocks for beginners of course: http://www.linuxjournal.com/article/5028 > So why not retain the name lambda but extend or change the syntax > to make it more capable rather than invent a wholly new syntax > for lambdas? Yes, I agree, and either keep the "lambda" keyword or else reuse the "def" keyword for anonymous methods. See this page Steven Bethard created: http://www.python.org/moin/AlternateLambdaSyntax I really don't think anyone should worry about lambda disappearing. By the way, you've done great work with your learning to program site and all the help you've given on the python-tutor list: > Alan G. > Author of the Learn to Program website > http://www.freenetpages.co.uk/hp/alan.gauld From mg.mailing-list at laposte.net Mon Jan 24 04:00:11 2005 From: mg.mailing-list at laposte.net (mg) Date: Mon, 24 Jan 2005 10:00:11 +0100 Subject: PyWin32 installation Message-ID: <41F4B91B.2060307@laposte.net> Hi all, I have reinstalled my Win32 computer last week and I did an update of the project PyWin32 to complete my Python installation. (I have to use sources from CVS for my project !) So, when I run 'python setup.py' in my PyWin32 directory, I have two problem : the version indacated in windows.h and some symbols who are not defined. See the trace : running install running build running build_py running build_ext Warning - can't find an installed platform SDK Found WINDOWS.H version 0x501 in C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\include building 'win32print' extension C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:C:\ext_projects\python\dist\src\libs /LIBPATH:C:\ext_projects\python\dist\src\PCBuild /LIBPATH:build\temp.win32-2.5\Release winspool.lib user32.lib /EXPORT:initwin32print build\temp.win32-2.5\Release\win32\src\win32print\win32print.obj /OUT:build\lib.win32-2.5\win32\win32print.pyd /IMPLIB:build\temp.win32-2.5\Release\win32\src\win32print\win32print.lib /MACHINE:ix86 Creating library build\temp.win32-2.5\Release\win32\src\win32print\win32print.lib and object build\temp.win32-2.5\Release\win32\src\win32print\win32print.exp win32print.obj : error LNK2019: unresolved external symbol __imp__StartDocA at 8 referenced in function "struct _object * __cdecl PyStartDoc(struct _object *,struct _object *)" (?PyStartDoc@@YAPAU_object@@PAU1 at 0@Z) win32print.obj : error LNK2019: unresolved external symbol __imp__EndDoc at 4 referenced in function "struct _object * __cdecl PyEndDoc(struct _object *,struct _object *)" (?PyEndDoc@@YAPAU_object@@PAU1 at 0@Z) Then, I don't kwnow how to solve theses problem ! Is there someone tho help me ? Thank, Mathieu G. From stephan.diehl at gmx.net Tue Jan 4 09:17:04 2005 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Tue, 04 Jan 2005 15:17:04 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> Message-ID: On Tue, 04 Jan 2005 05:43:32 -0800, michele.simionato wrote: > Holger: > >> FWIW, i added the recipe back to the online cookbook. It's not > perfectly >> formatted but still useful, i hope. > >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361742 > > Uhm... on my system I get: > >>>> german_ae = unicode('\xc3\xa4', 'utf8') >>>> print german_ae # dunno if it will appear right on Google groups > ? > >>>> german_ae.decode('latin1') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in > position 0: ordinal not in range(128) > ?? What's wrong? I'd rather use german_ae.encode('latin1') ^^^^^^ which returns '\xe4'. > > Michele Simionato From aleaxit at yahoo.com Thu Jan 6 09:45:09 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 6 Jan 2005 15:45:09 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> Roel Schroeven wrote: > Can you point to closed-source licenses that allow using the code *at > all*? As I recall, for example, Microsoft Visual C++ came with sources for various libraries; all that the (closed-source) license for those libraries forbade you from doing was to further distribute the _sources_ themselves. You could do modifications big or small to those libraries for whatever purposes, and redistribute the _compiled_ form of the code as a DLL, or statically linked into your own programs, etc, etc. Is this what you mean by "allow using the code *at all*"? I think it's a pretty common arrangement when the code being sold under closed-source terms is a set of libraries, or a development system part of whose value is a set of accompanying libraries. Alex From ruses at users.ch Mon Jan 17 15:28:43 2005 From: ruses at users.ch (more i squawed) Date: Mon, 17 Jan 2005 21:28:43 +0100 Subject: hash patent by AltNet; Python is prior art? In-Reply-To: References: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> Message-ID: <352l07F4cvej3U1@individual.net> Tim Churches a ?crit : > Provided other countries don't recognise software and business method > patents, the litigation will be confined within US borders, where > resources can be productivelt spent making television dramas about > attractive young patent attorneys and plodding, tram-riding patent > clerks who are really brilliant physicists if only someone would > recognise their potential. Nicely put. From http Thu Jan 13 11:29:07 2005 From: http (Paul Rubin) Date: 13 Jan 2005 08:29:07 -0800 Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> Message-ID: <7x7jmh1eek.fsf@ruckus.brouhaha.com> "hanz" writes: > > But wait if I do that, people will tell me how bad that it is, > > because it will keep a reference to the value which will prevent > > the garbage collector from harvesting this memory. > > Nobody will tell you that it's bad. Python was never about super > performance, but about readability. Besides, using such temporaries > won't consume much memory (relatively). That completely depends on the objects in question. Compare temp = all_posters[:] temp.sort() top_five_posters = temp[-5:] to: top_five_posters = all_posters.sorted()[-5:] which became possible only when .sorted() was added to Python 2.4. This is another reason it would be nice to be able to create very temporary scopes. From dderakon at hotmail.com Sun Jan 30 18:22:08 2005 From: dderakon at hotmail.com (Chris Weisiger) Date: Sun, 30 Jan 2005 23:22:08 -0000 Subject: PyGame not working(?) (was: trouble installing numeric) References: <20050129232540162-0800@news.claremont.edu> Message-ID: <20050130152208505-0800@news.claremont.edu> On 1/29/05 11:38 PM, Robert Kern wrote: > Chris Weisiger wrote: >> I'm trying to install numeric on my MacOS X box using Darwin, with >> the eventual goal of satisfying all of PyGame's dependencies so I >> can finally start working on my semester project. I would be using >> MacPython, except that I can't seem to get its Package Manager to >> work. > > This is fixed in CVS. > Thanks; I've now successfully installed Numeric, as well as all of the other dependencies listed for PyGame. However, PyGame appears to still not be working. When I try to run the program at the top of this page: http://www.pygame.org/docs/tut/tom/games2.html I get the following error: % python main.py Fatal Python error: Interpreter not initialized (version mismatch?) Abort Is this a problem with PyGame or with something else? I can run a simple Hello World program, so I'm assuming that Python itself is fine. Any ideas? -- "Don't take life so serious, son - it ain't nohow permanent." - Porkypine http://www.cs.hmc.edu/~cweisige From mcfletch at rogers.com Tue Jan 11 23:38:15 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 11 Jan 2005 23:38:15 -0500 Subject: Help Optimizing Word Search In-Reply-To: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: <41E4A9B7.7040201@rogers.com> To search for a word which is a jumble of a given set of characters in a (sizable) lexicon, see this posting: http://blog.vrplumber.com/427 your alterations would be to check for length == to length - number-of-wildcards (with the wildcards removed from the translation table, of course) and then some tweaks to the "expensive" loop to allow for up to wildcard-count ValueErrors. There's some (informal) analysis in the comments of that post regarding why its a fairly good mechanism for searching large sets of words. HTH, Mike Case Nelson wrote: ... >Basically, the program needs to take in a random list of no more than >10 letters, and find all possible mutations that match a word in my >dictionary (80k words). However a wildcard letter '?' is also an >acceptable character which increases the worst case time significantly. >So if the letters are ['a','b','c'] check a, b, c, ab, ac, ba, bc, ca, >cb, abc, acb, bac, bca, cab, cba where only a, ba and cab would be >added to the dict of words. If the letters are ['?','?'] check a-z, aa, >ab, ac, ad, ..., az, ba, bb, bc, bd, ..., zz > > ... ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From asda at sdarta.com Wed Jan 5 08:46:08 2005 From: asda at sdarta.com (worzel) Date: Wed, 5 Jan 2005 21:46:08 +0800 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au><41dbe722$0$23057$5a62ac22@per-qv1-newsreader-01.iinet.net.au><41dbec00$0$23064$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41dbefa2$0$23052$5a62ac22@per-qv1-newsreader-01.iinet.net.au> thanks, thats pretty much what I expected to hear. "Premshree Pillai" wrote in message news:mailman.195.1104932572.22381.python-list at python.org... > On Wed, 5 Jan 2005 21:30:40 +0800, worzel wrote: >> Wth respect to coldfusion, is there much doubt about the fact that Python >> is >> a more prominent and important technology? > > No doubt in my mind at least. > >> >> How is colfusion percieved by the Python community? Many people belive >> coldfusion is becomeing irrelavant and is on its death bed - do Python >> folk >> generally feel this way about it? > > I have no much idea about Coldfusion, but as far as its *use* is > concerned, it definitely isn't much. > >> >> Thanks for your input on this by the way. >> >> "Premshree Pillai" wrote in message >> news:mailman.192.1104931284.22381.python-list at python.org... >> > On Wed, 5 Jan 2005 21:09:54 +0800, worzel wrote: >> >> How seriuosly do folk take the TIOBE index? Is it a good way to ague >> >> what >> >> you should be keeping up to speed with or just a 'vague' guide? >> > >> > I use the TIOBE index -- sometimes -- when I give presentations on >> > Python (and Ruby) to people who haven't heard of the languages. >> > >> > The index is not something to be relied upon (take a look at the >> > calculation mechanism). However, more often than not, the indices >> > seems to reflect what *I* perceive the indices are in reality. So I >> > kinda use them. >> > >> > The thing about introducing a "new" language to a bunch of folks used >> > to their "favorite" language is that they wouldn't care much for a >> > language it isn't popular, or if it isn't "growing in popularity". >> > >> > Beyond these things, I don't think anybody uses the index. I mean I >> > wouldn't tell people to learn languages that hold the top position on >> > TIOBE ;). >> > >> >> >> >> "Premshree Pillai" wrote in message >> >> news:mailman.189.1104927428.22381.python-list at python.org... >> >> > On Wed, 5 Jan 2005 19:59:21 +0800, worzel wrote: >> >> >> >> >> >> >> >> >> >> >> >> is python more popular than coldfusion? >> >> > >> >> > I don't know if Coldfusion _was_ ever more "popular" than Python, >> >> > but >> >> > Python is definitely more "popular" _now_. >> >> > >> >> > This might be of some help: http://www.tiobe.com/tpci.htm >> >> > >> >> >> >> >> >> I realsie that is a very general question as one thing does not >> >> >> directly >> >> >> relate to the other. My issue is that I am ditching coldfusion due >> >> >> to >> >> >> there >> >> >> being next to no work for it, and I am thinking of taking on python >> >> >> as >> >> >> a >> >> >> second language to java in the hope of improving my resume. >> >> >> -- >> >> >> http://mail.python.org/mailman/listinfo/python-list >> >> >> >> >> >> >> >> > >> >> > >> >> > -- >> >> > Premshree Pillai >> >> > http://www.livejournal.com/~premshree >> >> >> >> -- >> >> http://mail.python.org/mailman/listinfo/python-list >> >> >> > >> > >> > -- >> > Premshree Pillai >> > http://www.livejournal.com/~premshree >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > -- > Premshree Pillai > http://www.livejournal.com/~premshree From claird at lairds.us Thu Jan 27 12:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 27 Jan 2005 17:08:04 GMT Subject: Please suggest on the book to follow References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> <1106829519.540737.164210@z14g2000cwz.googlegroups.com> <1106836611.862211.283470@c13g2000cwb.googlegroups.com> Message-ID: In article <1106836611.862211.283470 at c13g2000cwb.googlegroups.com>, santanu wrote: . . . >>From what you and Fyzzyman said, I guess when I am done with >Programming Python, graduating to the latest features would >be quite easy. Isn't it? . . . Yes. From luisXX_lupe2XX at netvisaoXX.pt Fri Jan 21 12:55:55 2005 From: luisXX_lupe2XX at netvisaoXX.pt (Luis P. Mendes) Date: Fri, 21 Jan 2005 17:55:55 +0000 Subject: xml parsing escape characters In-Reply-To: References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efedf2$0$11622$9b622d9e@news.freenet.de> <35adg4F4jgvpnU1@individual.net> <41F01A86.2040805@v.loewis.de> Message-ID: <35ctgpF4ktmgoU2@individual.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 ~From your experience, do you think that if this wrong XML code could be meant to be read only by somekind of Microsoft parser, the error will not occur? I'll try to explain: xml producer writes the code in Windows platform and 'thinks' that every client will read/parse the code with a specific Windows parser. Could that (wrong) XML code parse correctly in that kind of specific Windows client? Or in other words: Do you know any windows parser that could turn that erroneous encoding to a xml tree, with four or five inner levels of tags? I'd like to thank everyone for taking the time to answer me. Luis -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFB8UIOHn4UHCY8rB8RAgK4AKCiHjPdkCKnirX4gEIawT9hBp3HmQCdGoFK 3IEMLLXwMZKvNoqA4tISVnI= =jvOU -----END PGP SIGNATURE----- From ncoghlan at iinet.net.au Sun Jan 9 02:19:13 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 17:19:13 +1000 Subject: python3: accessing the result of 'if' In-Reply-To: <1105249487.644698.309100@c13g2000cwb.googlegroups.com> References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> <1105236383.521393.40680@c13g2000cwb.googlegroups.com> <1105249487.644698.309100@c13g2000cwb.googlegroups.com> Message-ID: <41E0DAF1.8080306@iinet.net.au> Carl Banks wrote: > I'm sorry, I really can't agree that this helper function "solves" it. > IMO, it's a workaround, not a solution. And, if I may be frank, it's a > pretty ugly one. Heck, I thought it was ugly and I wrote it :) So in reality, I'd continue to use the nested-if approach that works right now if I wanted access to part of the condition instead of the whole thing. However, being able to bind a name to the conditions would be handy for many cases. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tmohr at s.netic.de Tue Jan 11 01:34:41 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 11 Jan 2005 07:34:41 +0100 Subject: reference or pointer to some object? Message-ID: Hi, i'd like to pass a reference or a pointer to an object to a function. The function should then change the object and the changes should be visible in the calling function. In perl this would be something like: sub func { $ref = shift; $$ref += 123; # change } $a = 1; func(\$a); is something like this possible in python? The keyword "global" does NOT fit this purpose to my understanding as it only makes the variables of the UPPERMOST level visible, not the ones of ONE calling level above. Is this somehow possible with weakref? I don't want to pass the parameter to a function and then return a changed value. Is there some other mechanism in python available to achieve a behaviour like this? Thanks for any hints, Torsten. From fumanchu at amor.org Sat Jan 8 14:04:58 2005 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 8 Jan 2005 11:04:58 -0800 Subject: there's a socket.sendall(), so why no socket.recvall()? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398146@exchange.hqamor.amorhq.net> Irmen de Jong wrote: > Subject says it all; > there's a socket.sendall(), so why no socket.recvall()? Good question! Something like: # Receive reply. data = [] while True: try: chunk = conn.recv(8192) except Exception, x: if x.args[0] != 10035: raise x else: if chunk == '': break data.append(chunk) If you call .makefile() and then .read() the _fileobject, you get the same behavior (only better). Adding recvall would just duplicate that, I think. But that's desirable IMO. Robert Brewer MIS Amor Ministries fumanchu at amor.org From steve at holdenweb.com Wed Jan 12 18:36:46 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 12 Jan 2005 18:36:46 -0500 Subject: else condition in list comprehension In-Reply-To: References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: Nick Coghlan wrote: > Luis M. Gonzalez wrote: > >> Hi there, >> >> I'd like to know if there is a way to add and else condition into a >> list comprehension. I'm sure that I read somewhere an easy way to do >> it, but I forgot it and now I can't find it... >> >> for example: >> z=[i+2 for i in range(10) if i%2==0] >> what if I want i to be "i-2" if i%2 is not equal to 0? >> > > Hmm: > > z = [newval(i) for i in range(10)] using: > def newval(x): > if x % 2: > return x - 2 > else: > return x + 2 > > Just some more mental twiddling relating to the thread on statement > local namespaces. > I presume the point of this is to avoid polluting the local namespace with "newval". I further presume you also have plans to do something about "i"? ;-) 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 http Sat Jan 8 03:15:35 2005 From: http (Paul Rubin) Date: 08 Jan 2005 00:15:35 -0800 Subject: How to read/write blobs with mysqldb? References: Message-ID: <7xr7kwpc9k.fsf@ruckus.brouhaha.com> "Christopher J. Bottaro" writes: > That doesn't sound very efficient to me. What if my computer only has 64 MB > of memory and the data I want to insert is 128 MB? Don't use such large blobs. From pythongnome at hotmail.com Thu Jan 27 08:12:07 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Thu, 27 Jan 2005 13:12:07 GMT Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: > > As long as we are discussing cryptography, what's wrong with m2crypto? > > http://sandbox.rulemaker.net/ngps/m2/ > > Why not incorporate it into the standard distribution? > > Or, what about Andrew Kuchling's crypto toolkit? > > http://www.amk.ca/python/code/crypto.html > Umm, is it just me or did we just discuss the legal issues of that?? From simon.brunning at gmail.com Wed Jan 12 10:43:44 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 12 Jan 2005 15:43:44 +0000 Subject: Excel module for Python In-Reply-To: References: Message-ID: <8c7f10c605011207434ee6b078@mail.gmail.com> On Wed, 12 Jan 2005 23:19:44 +0800, sam wrote: > > No, I don't use MS windows. I need to generate Excel file by printing > data to it, just like Perl module Spreadsheet::WriteExcel. If it's just data that needs to go into your spreadsheet, then I'd just build a CSV file if I were you. Excel opens them perfectly happily. If you need to write out formulae, formratting, that kind of thing, then I think you'll need to write a 'real' Excel file. I don't have a clue how to do that - sorry. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From steve at holdenweb.com Wed Jan 5 15:01:03 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 05 Jan 2005 15:01:03 -0500 Subject: modpython, apache and windows In-Reply-To: References: Message-ID: Sam wrote: > Hi All, > > I am interested in learning python since I am hearing more and more > about python for use in web development > > I am starting out on python, with knowledge of PHP some perl > > my current hurdle is setting up either apache 1 or 2 with python 2.3.3 I > have installed modpython fine > > which informed me that I need to make some configuration changes to > httpd.conf > These changes are relatively easy, but of course making them requires access to the files, not always available unless you are managing your own server. Note, though, that it's easliy possible to use Python as a CGI language on most Apache installations. > I have not had it working yet, searches on the web give conflicting > suggestions and so far has confused me > Perhaps if you could explain what it is you are failing to do, you might eleicit some explicit help. > some forums mention spyce and serving .spy files > > so far I one explanation worked in that a .py file was parsed but I had > to set the name of the actual file within apache.conf > this seems strange > > thanks in advance >> SS > > Try creating a Python file (.py file, with world-executable permissions) in a cgi-bin directory: #!/usr/bin/env python print """Content-Type: text/plain Hello, world""" and see if you can call it from a web browser. 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 devries at idolstarastronomer.com Wed Jan 12 08:13:45 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: 12 Jan 2005 05:13:45 -0800 Subject: distutils linux script installation broken? References: Message-ID: <1105535625.443343.326560@z14g2000cwz.googlegroups.com> I just installed python2.4 and used it to install a set of scripts I had previously been using distutils with. It worked fine, and replaced the first line with: #!/usr/local/bin/python2.4 distutils should replace that first line with the location of the binary used to run setup.py. Are you running setup with the following command line? python setup.py install From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sun Jan 2 18:38:38 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Mon, 3 Jan 2005 00:38:38 +0100 Subject: ctypes NULL pointers; was: Python To Send Emails Via Outlook Express References: Message-ID: <41d8f228$0$2742$8fcfb975@news.wanadoo.fr> Ok ; thank you. From kylotan at gmail.com Mon Jan 3 20:13:50 2005 From: kylotan at gmail.com (Ben Sizer) Date: 3 Jan 2005 17:13:50 -0800 Subject: Integrating Python into a C++ app Message-ID: <1104801230.728736.83970@f14g2000cwb.googlegroups.com> I know the conventional wisdom is to write the whole app in Python and only extend with C++ where speed is an issue, but I already have a large C++ app that I'd like to add Python to. Ideally I'd rewrite the whole app in Python but I don't have time to do that and maintain the old system at the same time. So my next thought was to perhaps integrate the two and slowly migrate modules and classes across from C++ to Python. If it matters, the main reason I'm interested in doing this is because I appreciate the productivity of Python and would like to take advantage of that as I add features to the current code, to reduce bugs and cut development time. I've read a few good things in this group about Elmer (http://elmer.sourceforge.net), but I'm not sure how simply that accommodates calls in the reverse direction (from Python code back into C++). Are there any other options that would require a minimum of rewriting of code? Does anybody have any experience of such a project? -- Ben Sizer From ncoghlan at iinet.net.au Thu Jan 20 05:08:05 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 20 Jan 2005 20:08:05 +1000 Subject: Freezing a mutable (was Re: lambda) In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> <41ed8c13.1209309354@news.oz.net> Message-ID: <41EF8305.1070202@iinet.net.au> Antoon Pardon wrote: > Interesting idea. But I think you are wrong when you say that two lists > that compare equal at the time they are frozen, will get the same > dictionary entry. The problem is an object must compare equal to > the key in the dictionary to get at the same entry. So if you freeze > a list and its copy but then mutate them differently, they no longer > are equal and so wont get you at the same entry. The trick is that the result of the freezing operation is cached until such time as you explicitly unfreeze the object. Output: x: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Write via x, read via y: Hi there! x: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y: [0, 1, 2, 3, 4, 5, 6, 7, 8] Read via mutated x: Hi there! Read via mutated y: Hi there! x: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y: [0, 1, 2, 3, 4, 5, 6, 7, 8] Found unfrozen x: False Found unfrozen y: False Produced by: class mylist(list): def __init__(self, arg): super(mylist, self).__init__(arg) self._tuple = None def frozen(self): if self._tuple is None: self._tuple = tuple(self) return self._tuple def unfreeze(self): self._tuple = None x = mylist(range(10)) y = mylist(range(10)) dct = {} dct[x.frozen()] = "Hi there!" print "x:", x print "y:", y print "Write via x, read via y:", dct[y.frozen()] x.append(10) del y[-1] print "x:", x print "y:", y print "Read via mutated x:", dct[x.frozen()] print "Read via mutated y:", dct[y.frozen()] x.unfreeze() y.unfreeze() print "x:", x print "y:", y print "Found unfrozen x:", x.frozen() in dct print "Found unfrozen y:", y.frozen() in dct -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ialbert at mailblocks.com Mon Jan 17 13:12:47 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 17 Jan 2005 13:12:47 -0500 Subject: pychecker - sets.Set need to be overridden In-Reply-To: References: Message-ID: Peter Otten wrote: > The Set class has implementations for __cmp__() and __hash__() that > unconditionally raise an exception. pychecker assumes that these methods > are "abstract", i. e. meant to be overriden by a subclass, and warns that > you are instantiating an abstract base class, while the intention of the I see. Thanks! Istvan. From cjbottaro at alumni.cs.utexas.edu Sat Jan 1 23:06:14 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Sat, 01 Jan 2005 22:06:14 -0600 Subject: HTTP GET request with basic authorization? Message-ID: How do I do this using httplib.HTTPConnection and httplib.HTTPConnection.request()? The library reference only gives a simple GET example with no header stuff. I tried this, but it didn't work: conn.request("GET", "/somepage.html", None, {"AUTHORIZATION": "Basic username:password"}) Thanks for the help. P.S. I know nothing about HTTP, I'm just piecing this stuff together from examples on the internet, please be gentle with your responses. From fuzzyman at gmail.com Wed Jan 5 11:22:11 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2005 08:22:11 -0800 Subject: How to make executable file ? In-Reply-To: References: Message-ID: <1104942131.727332.76380@c13g2000cwb.googlegroups.com> An alternative way is to use Movable Python. It's a frozen distribution of python that can run without being 'installed'. See http://sourceforge.net/projects/movpy To display things in a 'window' you'll need to use a GUI toolkit like Tkinter or wxPython. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From fredrik at pythonware.com Thu Jan 20 02:46:05 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jan 2005 08:46:05 +0100 Subject: iteritems() and enumerate() References: <1106206068.867004.195010@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > Python has iteritems() and enumerate() to be used in for loops. > > can anyone tell me what these are by themselves, if anything? iteritems() is a dictionary method, which returns a lazily constructed sequence of all (key, value) pairs in the dictionary. enumerate(seq) is a function that returns a lazily constructed list of (index, value) pairs for all values in a sequence. check the relevant sections of the library reference for details. From tim.peters at gmail.com Fri Jan 21 14:54:28 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 21 Jan 2005 14:54:28 -0500 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> Message-ID: <1f7befae05012111543cc0b81c@mail.gmail.com> [Paul Rubin] >> You snipped out the examples I gave, like [x*x for x in range(5)] >> leaving unnecessary residue in the name space. Was it not >> obvious from the beginning that that was a kludge? If it was >> obviously a kludge, was it not obvious that there would be >> reason to want to fix it someday? I'm saying that if some new >> feature is going to need a fix later, it's better to fix it before >> releasing it in the first place. [Steve Holden] > Well no, I certainly have never thought the name droppings from > list comprehensions to be anything other than a wart. > > But my parting shot was simply to point out that you don't > always know where you're going until you're at least part of the > way there. Until the feature exists, how do you know it needs > fixing? > > The fact that a bright bunch like the Python developers didn't > realize that it would be sensible to have a local scope for the list > comprehension variable is a perfect demonstration of that point. Well, language design issues aren't really that mysterious. It was, for example, _always_ obvious that Scheme-heads would complain about the way listcomps got implemented (wrt the scope of the iteration vrbl). But at that time, Python didn't have lexical scoping, and it wasn't clear that it ever would. So what's the bigger wart? Making listcomps exactly equivalent to an easily-explained Python for-loop nest, or introducing a notion of lexical scope unique to listcomps, hard to explain in terms of the way the rest of the language worked? The former was thought to be the lesser evil at the time, and for truly obvious reasons. Except, perhaps, to those looking at Python as if it were a flawed approximation to some other language -- as Lispers and Schemers are notoriously prone to do, even wrt each others' favorite dialects. At the time, the right decision was made. From danb_83 at yahoo.com Sun Jan 2 21:10:15 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 2 Jan 2005 18:10:15 -0800 Subject: Calling Function Without Parentheses! References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> Message-ID: <1104718215.795501.83450@f14g2000cwb.googlegroups.com> Kamilche wrote: > What a debug nightmare! I just spent HOURS running my script through > the debugger, sprinkling in log statements, and the like, tracking down > my problem. > > I called a function without the ending parentheses. I sure do WISH > Python would trap it when I try to do the following: > MyFunc > > instead of: > > MyFunc() You're a former Pascal programmer, aren't you? ;-) In Python, it's not an error, because you can do things like: >>> def simpson(f, a, b): ... "Simpson's Rule approximation of the integral of f on [a, b]." ... return (b - a) * (f(a) + 4 * f((a + b) / 2.0) + f(b)) / 6.0 ... >>> simpson(math.sin, 0.0, math.pi) # Note that math.sin is a function 2.0943951023931953 From asda at sdarta.com Wed Jan 5 06:59:21 2005 From: asda at sdarta.com (worzel) Date: Wed, 5 Jan 2005 19:59:21 +0800 Subject: is python more popular than coldfusion? Message-ID: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> is python more popular than coldfusion? I realsie that is a very general question as one thing does not directly relate to the other. My issue is that I am ditching coldfusion due to there being next to no work for it, and I am thinking of taking on python as a second language to java in the hope of improving my resume. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at nospam.com Mon Jan 3 10:41:39 2005 From: nospam at nospam.com (3c273) Date: Mon, 3 Jan 2005 07:41:39 -0800 Subject: Tkinter (OOP?) help References: <863bxnry43.fsf@guru.mired.org> Message-ID: "Mike Meyer" wrote in message news:863bxnry43.fsf at guru.mired.org... > Every time you call newwindow, you rebind self.new to the window just > created. So any close button that works will close the last window opened. > > You need to create a separate class for new windows, each with it's > own self.new (or self.window) that it's self.closeme will call destroy > on. > > Message-ID: Pro Grammer writes: > Hello, all, > I am not sure if this is the right place to ask, but could you kindly tell me > how to "load" a shared object (like libx.so) into python, so that the methods in > the .so can be used? That too, given that the shared object was written in c++, > compiled with g++ ? > Thanks, > Pro Grammer Will the dl standard library module help you? From the Python docs at: http://docs.python.org/lib/module-dl.html Example: >>> import dl, time >>> a=dl.open('/lib/libc.so.6') >>> a.call('time'), time.time() (929723914, 929723914.498) I'm guessing that there might be some C++ issues, but maybe it's worth looking into. Rick From apardon at forel.vub.ac.be Fri Jan 14 03:12:29 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Jan 2005 08:12:29 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> Message-ID: Op 2005-01-13, hanz schreef : > > Antoon Pardon wrote: >> So if I have a call with an expression that takes more than >> one line, I should assign the expression to a variable and >> use the variable in the call? > > Yes, that's sometimes a good practice and can clarify > the call. > >> But wait if I do that, people will tell me how bad that it >> is, because it will keep a reference to the value which >> will prevent the garbage collector from harvesting this >> memory. > > Nobody will tell you that it's bad. Sorry, someone already did. If I recall correctly it was Alex Martelli. -- Antoon Pardon From fuzzyman at gmail.com Tue Jan 25 09:17:35 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2005 06:17:35 -0800 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <1106564799.011057.181280@c13g2000cwb.googlegroups.com> Message-ID: <1106662655.352239.151790@z14g2000cwz.googlegroups.com> I've already downloaded p3 - thanks :-) I wonder how long it took (in reality) an average hacker to break the algorithm used by rotor ? Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From mt at 3planes.com Mon Jan 31 11:19:19 2005 From: mt at 3planes.com (Michael Tobis) Date: 31 Jan 2005 08:19:19 -0800 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> Message-ID: <1107188359.375703.110590@f14g2000cwb.googlegroups.com> With all due respect, I think "so go away if you don't like it" is excessive, and "so go away if you don't like it and you obviously don't like it so definitely go away" is more so. The writer is obviously neither a native speaker of English nor an accomplished user of Python, so there are two language issues here. Try expressing your reply in Russian before deciding that "very ugly" means exactly what you think it does. I think just saying that "experienced Python users have not found the lack of declarations to be a major hindrance" would have been more appropriate. Also, the assertion that "Python has no declarations whatsoever" is no longer obviously true. In the 2.4 decorator syntax, a decorator line is not executable, but rather a modifier to a subsequent symbol binding. I call it a declaration. I found this disappointing in that it seems to me a violation of "Special cases aren't special enough to break the rules" but on further reflection it enables consideration of what a whole slew of declarative constructs could achieve. To begin with, now that the design constraint of "no declarations" has been shown to be less than absolute, why not allow for perl-style ('use strict') declarations? It actually is very useful in the small-script space (up to a few hundred lines) where the best Perl codes live. Let me add that I remain unconvinced that a language cannot combine the best features of Python with very high performance, which is ultimately what I want. It seems to me that such a language (possibly Python, possibly a Python fork, possibly something else) will need substantial programmer control over references as well as referents. It seems to me that Python has a weaker case for purity in this regard now that the dam has been breached with decorator syntax, which is, I think, a declaration. Let me conclude with the confession that I'm still on the steep part of the learning curve (if it ever flattens out at all...). Python has definitely significantly modified how I think about things, and I deeply appreciate all the efforts of you veterans. So I say this all with some trepidation, because I don't want to join Alexander in inadvertently offending you. And since I presumably missed some intense flame wars about decorators by only a couple of months, this may be a real hornet's nest I am poking. In summary, again with all due respect and gratitude for the spectacularly excellent product that Python is today, I wonder *why* this strong aversion to declarative statements, and *whether* decorator syntax constitutes a violation of it. I'd appreciate any responses or links. -- mt From cdieterich at geosci.uchicago.edu Thu Jan 27 13:53:37 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Thu, 27 Jan 2005 12:53:37 -0600 Subject: inherit without calling parent class constructor? In-Reply-To: Message-ID: On D? C?adaoin, Ean 26, 2005, at 17:02 America/Chicago, Steven Bethard wrote: > Just a note of clarification: > > The @deco syntax is called *decorator* syntax. > Classes with a __get__ method are called *descriptors*. Okay, I think I get the idea. I didn't know about the @deco syntax, but it seems to be straightforward. And I got myself updated a little bit on descriptors and static methods. On D? C?adaoin, Ean 26, 2005, at 17:09 America/Chicago, Jeff Shannon wrote: > You could try making D a container for B instead of a subclass: Thank you for the solution. I'll need to have a closer look at it. However it seems like the decision whether to do "some expensive calculation" or not is delegated to the exterior of class D. Different classes that instanciate D would need to know what has been going on elsewhere. That might complicate things. I'll go ahead and try with the descriptors first. Thanks for all the help, Christian From ville at spammers.com Wed Jan 5 02:05:54 2005 From: ville at spammers.com (Ville Vainio) Date: 05 Jan 2005 09:05:54 +0200 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "Paul" == Paul Rubin writes: Paul> inclusion in some bigger distro. E.g., I'm now running the Paul> Python Python into Fedora. So it's up to the Python Paul> maintainers, not the Fedora maintainers or the user, to make Paul> sure that the Python distro has everything that users need, Paul> without further downloading. To me, this seems to be the job for the Fedora maintainers, not Python maintainers. If something essential is not in the distro the distro maintainers have screwed up. Paul> And that was just about Tkinter, for which good docs exist Paul> but just don't happen to be in the distro. How about I think most people these days do a google search when they are learning how to use a feature to get the whole story. It's often also faster than finding the information in the bundled documentation - even if the first google hit often happens to refer to the page with the very documentation thu user would have looked up. Paul> The book is very good, but having to go buy a proprietary Paul> book is the opposite of what self-contained free software Paul> documentation is supposed to mean. I'm not sure the free software documentation is going to evolve to be more self-contained; the exact opposite is more likely. -- Ville Vainio http://tinyurl.com/2prnb From fredrik at pythonware.com Tue Jan 18 10:56:32 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Jan 2005 16:56:32 +0100 Subject: bind error!!!!! References: Message-ID: Perrin Aybara wrote: > my code was working pretty well until yesterday.suddenly it started > giving me bind error: address already in use. google has the details: http://hea-www.harvard.edu/~fine/Tech/addrinuse.html > but i have logged out and again logged in, but still the problem is not solved > can somebody give me solution for this and you're sure that nobody else on this computer is running a process that's using the same port? on most platforms, you can use "netstat" to list all active connections and ports. From craig at postnewspapers.com.au Fri Jan 21 10:06:54 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 21 Jan 2005 23:06:54 +0800 Subject: need help on generator... In-Reply-To: <1106318290.19065.11.camel@bucket.localnet> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> Message-ID: <1106320014.19065.14.camel@bucket.localnet> On Fri, 2005-01-21 at 22:38 +0800, Craig Ringer wrote: > consecutive_sets = ( x[offset:offset+subset_size] > for subset_size in xrange(2, len(x)) > for offset in xrange(0, len(x) + 1 - subset_size) ) Where 'x' is list to operate on, as I should've initially noted. Sorry for the reply-to-self. I did say "awful" for a reason ;-) -- Craig Ringer From chris.cavalaria at free.fr Tue Jan 25 15:00:30 2005 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Tue, 25 Jan 2005 21:00:30 +0100 Subject: Help on project, anyone? References: <35ienhF4lu88lU1@individual.net> <1106561458.167373.303270@c13g2000cwb.googlegroups.com> <1106640690.817073.248670@c13g2000cwb.googlegroups.com> Message-ID: <35nmr8F4lnbfvU1@individual.net> Fuzzyman wrote: > > Miki Tebeka wrote: >> Hello Fuzzyman, >> >> > 3) Simple Version Control program for single programmer. A very > simple >> > way of doing version control/releases for small projects with only > a >> > single programmer. [3] >> Subversion (and CVS) are dead simple to install and use. > > I've heard *lots* of people say exactly the opposite. Let's see : # First we prepare the local cvs storage : mkdir ~/cvsroot export CVSROOT=~/cvsroot cvs init # Now we import the existing source code in the cvs "server" cd path/to/project/to/import cvs import ModuleName VendorName START cd ~ cvs co ModuleName And voila, the folder ModuleName is ready for a local cvs usage : cvs update, commit etc... You only need to do once the mkdir ~/cvsroot and the cvs init but don't forget to specify the CVSROOT each time you need to do a cvs import or a cvs checkout. From fredrik at pythonware.com Sat Jan 22 17:13:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 23:13:50 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net><46ednYMe9-q4Om_cRVn-tQ@comcast.com><35fo4iF4maov2U1@individual.net><35fpq0F4mh1ffU1@individual.net> <7xoefhtavd.fsf@ruckus.brouhaha.com> <1gqtawv.omj416ues6jN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: >> [1, 2, 'Joe Smith', 8237972883334L, # comment >> {'Favorite fruits': ['apple', 'banana', 'pear']}, # another comment >> 'xyzzy', [3, 5, [3.14159, 2.71828, []]]] >> >> I don't see what YAML accomplishes that something like the above wouldn't. >> >> Note that all the values in the above have to be constant literals. >> Don't suggest using eval. That would be a huge security hole. > > I do like the idea of a parser that's restricted to "safe expressions" > in this way. Once the AST branch merge is done, it seems to me that > implementing it should be a reasonably simple exercise, at least at a > "toy level". for slightly more interop, you could plug in a modified tokenizer, and use JSON: http://www.crockford.com/JSON/xml.html > I wonder, however, if, as an even "toyer" exercise, one might not > already do it easily -- by first checking each token (as generated by > tokenize.generate_tokens) to ensure it's safe, and THEN eval _iff_ no > unsafe tokens were found in the check. Accepting just square brackets, > braces, commas, constant strings and numbers, and comments, should be > pretty safe -- we'd no doubt want to also accept minus (for unary > minus), plus (to make complex numbers), and specifically None, True, > False or you could use a RE to make sure the string only contains safe literals, and pass the result to eval. > but that, it appears to me, still leaves little margin for an attacker to prepare > an evil string that does bad things when eval'd... besides running out of parsing time or object memory, of course. unless you check the size before/during the parse. From ialbert at mailblocks.com Mon Jan 10 15:44:49 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 10 Jan 2005 15:44:49 -0500 Subject: Writing huge Sets() to disk In-Reply-To: References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> Message-ID: Martin MOKREJ? wrote: > Istvan Albert wrote: > So you say 1 million words is better to store in dictionary than > in a set and use your own function to get out those unique or common > words? I have said nothing even remotely like that. > Fine, that's what I wanted to hear. How do you improve the algorithm? > Do you delay indexing to the very latest moment or do you let your > computer index 999 999 times just for fun? I think that you need to first understand how dictionaries work. The time needed to insert a key is independent of the number of values in the dictionary. Istvan. From danperl at rogers.com Wed Jan 26 17:50:59 2005 From: danperl at rogers.com (Dan Perl) Date: Wed, 26 Jan 2005 17:50:59 -0500 Subject: 20050126 find replace strings in file References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> <1106776836.679242.167880@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1106776836.679242.167880 at c13g2000cwb.googlegroups.com... > I guess there is no way to check if the file opened fine? What if the > filesystem or file is locked for this user/session. Pretty puny > language if it cannot tell you that it cannot do what you tell it to. > .......... > Same for the close. Is there no way check a good close? An exception (IOError) is raised when a file operation fails. The open() and and close() statements should be enclosed in a try-except statement. Please, take Xah Lee's postings with more than just a grain of salt. As a matter of fact, you are better off ignoring them than trying to learn from them. He is an egomaniac who is learning python and who thinks that he can already teach others. Personally I doubt he will ever learn python well enough to teach others. Just look at his English. He has a similar list with a-word-a-day just like the perl-python a-lesson-a-day and he seems indeed to know a lot of words. But his grammar is horrendous (there's a word for you, Xah Lee!). And according to his own website he's been living in North America for more than 15 years! English is a second language for me too but you won't see me writing something like "this groups is for Perlers who wants to learn Python". It may be unfair to pick on his English, but it is the best way I can make the point to someone who does not know python that Xah Lee does not know what he's talking about. I find Xah Lee annoying and I could just ignore him, but I am concerned that some people may actually take his statements seriously and learn from them. I can't imagine why or how, but there are actually 26 members in the perl-python Yahoo! group who have registered to get these bogus lessons sent to them daily! Dan From len-1 at telus.net Wed Jan 26 17:27:02 2005 From: len-1 at telus.net (Lenard Lindstrom) Date: Wed, 26 Jan 2005 22:27:02 GMT Subject: Subclassed dict as globals References: Message-ID: Evan Simpson writes: > In Python 2.4 the following works: > > >>> class G(dict): > ... def __getitem__(self, k): > ... return 'K' + k > ... > >>> g = G() > >>> exec 'print x, y, z' in g > Kx Ky Kz > >>> > [snip] > [Is] there a way to do this (intercept global variable accesses) > in Python 2.3? > One can emulate it in a rather limited way in pre 2.4 releases: >>> cd = compile("print x, y, z", '', 'exec') >>> glbs = dict(globals()) >>> for id in cd.co_names: glbs[id] = 'K' + id >>> exec cd in glbs Kx Ky Kz Special names can be used only as constants. It is better suited for eval() than exec. Lenard Lindstrom From http Thu Jan 6 19:31:57 2005 From: http (Paul Rubin) Date: 06 Jan 2005 16:31:57 -0800 Subject: Securing a future for anonymous functions in Python References: <10trlbqnb86tbb0@corp.supernews.com> Message-ID: <7xvfaaaxky.fsf@ruckus.brouhaha.com> Jeff Shannon writes: > It seems to me that in other, less-dynamic languages, lambdas are > significantly different from functions in that lambdas can be created > at runtime. What languages are those, where you can create anonymous functions at runtime, but not named functions?! That notion is very surprising to me. From simon.brunning at gmail.com Fri Jan 21 07:42:31 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 21 Jan 2005 12:42:31 +0000 Subject: map in Python In-Reply-To: <8c7f10c605012104373199e615@mail.gmail.com> References: <1106310327.213874.305660@f14g2000cwb.googlegroups.com> <8c7f10c605012104373199e615@mail.gmail.com> Message-ID: <8c7f10c6050121044212f6fc3@mail.gmail.com> On Fri, 21 Jan 2005 12:37:46 +0000, Simon Brunning wrote: > This what you want? > > >>> import re > >>> test = ["a1", "a2", "a3"] > >>> test = [re.sub("[a-z]", "", item) for item in test] > >>> test > ['1', '2', '3'] Or, if you *must* use map, you can do: >>> test = map(lambda item: re.sub("[a-z]", "", item), test) >>> test ['1', '2', '3'] I much prefer the first list comprehension form myself, but reasonable men can differ... -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From claudio.grondi at freenet.de Mon Jan 24 10:12:32 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 24 Jan 2005 15:12:32 -0000 Subject: is there better 32 clock() timing? References: <7xbrbgxjxs.fsf@ruckus.brouhaha.com> Message-ID: <35ke4eF4mbj1fU1@individual.net> On my 2.8GHz P4, Windows 2000 SP4 with Python 2.3.4 I am getting totally different results compared to Ray. Does Python 2.3.4 already use the Pentium RTDSC instruction for clock()? Claudio # \> Claudio Grondi, 2.8GHz P4 Python 2.3.4 (2005-01-24 14:32) # time of taking time: # 0.000001396825574200073100 # 0.000001676190689040086400 # 0.000001396825574200074000 # 0.000001676190689040088100 # 0.000001955555803880100500 # 0.000001620317666072084300 (average) # statistics of 1.000.000 times of taking time in a while loop: # 0.000001396825573429794100 (min) # 0.002370692364532356300000 (max) # 0.000001598858514140937100 (avg) # >>> Ray Schumacher, 2.4GHz P4 Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 # 0.000321028401686 # 0.00030348379596 # 0.000297101358228 # 0.000295895991258 # 0.000342754564927 (average) Here my code: # Tests show, that the first call takes longer than subsequent calls, # so it makes sense to run t = clock() just one time before the next calls # are used: t = clock() t0 = clock() t1 = clock() t2 = clock() t3 = clock() t4 = clock() t5 = clock() print 'time of taking time: ' print ' %25.24f'%((t1-t0),) print ' %25.24f'%((t2-t1),) print ' %25.24f'%((t3-t2),) print ' %25.24f'%((t4-t3),) print ' %25.24f'%((t5-t4),) print ' %25.24f (average)'%( ((-t0+t5)/5.),) intCounter=1000000 fltTotTimeOfTakingTime = 0.0 fltMaxTimeOfTakingTime = 0.0 fltMinTimeOfTakingTime = 1.0 while(intCounter > 0): t1 = clock() t2 = clock() timeDiff = t2-t1 if(timeDiff < fltMinTimeOfTakingTime): fltMinTimeOfTakingTime = timeDiff if(timeDiff > fltMaxTimeOfTakingTime): fltMaxTimeOfTakingTime = timeDiff fltTotTimeOfTakingTime+=timeDiff intCounter-=1 #:while fltAvgTimeOfTakingTime = fltTotTimeOfTakingTime / 1000000.0 print 'statistics of 1.000.000 times of taking time in a while loop:' print ' %25.24f (min)'%(fltMinTimeOfTakingTime,) print ' %25.24f (max)'%(fltMaxTimeOfTakingTime,) print ' %25.24f (avg)'%(fltAvgTimeOfTakingTime,) "Ray Schumacher" schrieb im Newsbeitrag news:mailman.1120.1106491193.22381.python-list at python.org... > I have a need for a time.clock() with >0.000016 second (16us) accuracy. > The sleep() (on Python 2.3, Win32, at least) has a .001s limit. > > Are they lower/better on other's platforms? > > Test code, 2.4GHz P4 > Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 > > import time > t0 = time.clock() > t1 = time.clock() > t2 = time.clock() > t3 = time.clock() > t4 = time.clock() > t5 = time.clock() > print (-t0+t5)/5. > print t1-t0 > print t2-t1 > print t3-t2 > print t4-t3 > print t5-t4 > > >>> > ave 0.000342754564927 > 0.000321028401686 > 0.00030348379596 > 0.000297101358228 > 0.000295895991258 > > I had also considered forking a thread that would spin a loop checking time.clock() and firing the TTL pulse after the appropriate interval, but the real, ultimate resolution of time.clock() appears to be ~.00035s. If I increase process priority to real-time, it is ~.00028s > The alternative appears to be more C code... > > Ray > BCI/Congitive Vision > "Paul Rubin" schrieb im Newsbeitrag news:7xbrbgxjxs.fsf at ruckus.brouhaha.com... > Ray Schumacher writes: > > I have a need for a time.clock() with >0.000016 second (16us) accuracy. > > The sleep() (on Python 2.3, Win32, at least) has a .001s limit. > > > > Are they lower/better on other's platforms? > > > > The alternative appears to be more C code... > > C code is your best bet. The highest resolution timer on x86's these > days is the Pentium RTDSC instruction which counts the number of cpu > cycles since power-on. There's various C routines floating around > that let you access that instruction. From aleaxit at yahoo.com Sat Jan 29 09:34:27 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 29 Jan 2005 15:34:27 +0100 Subject: limited python virtual machine References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> Message-ID: <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> Aahz wrote: ... > >>>> object.__subclasses__() ... > One thing my company has done is written a ``safe_eval()`` that uses a > regex to disable double-underscore access. will the regex catch getattr(object, 'subclasses'.join(['_'*2]*2)...?-) Alex From fla.liu at gmail.com Thu Jan 20 13:51:04 2005 From: fla.liu at gmail.com (fla liu) Date: Fri, 21 Jan 2005 02:51:04 +0800 Subject: What's the best python web-developer's editor In-Reply-To: <41EFFCD9.7060302@wild-flower.co.uk> References: <41EFFCD9.7060302@wild-flower.co.uk> Message-ID: <7c157e36050120105127f58fdd@mail.gmail.com> Try to use Eclipse + pydev On Thu, 20 Jan 2005 18:47:53 +0000, andy wrote: > Anybody like to comment on which editor they use for python web app > development - for both discrete and mixed python and html code, and why? > > I'm comfortable with IDLE (used it for years) but of course it lacks ftp > or webDAV abilities, obviously because it's not intended for that type > of use. > > I've had a look at Screem - and that seems to do python syntax > highlighting, but it dosn't seem to be python syntax aware (unless > there's a hidden option somewhere). Although I can live without auto > indent, I'd rather not... > > I'm sure emacs, xemacs, vi, elvis and so on can do the same, but I have > no experience with them for heavy python or html coding, nor the time > to trip off down a blind-alley to find out! I know Enough Vi To Get > By(tm) but it's by no means my favourite editor. Emacs is a complete > mystery to me. > > I guess I *could* use IDLE and Screem together, but that's a clunky > solution! > > all opinions greatfully received, > -andyj > -- > http://mail.python.org/mailman/listinfo/python-list > From Mark.English at liffe.com Tue Jan 25 08:02:18 2005 From: Mark.English at liffe.com (Mark English) Date: Tue, 25 Jan 2005 13:02:18 -0000 Subject: threading.py Condition wait overflow error Message-ID: <40E605146701DE428FAF21286A97D309174515@wphexa02.corp.lh.int> Every once in a while since I moved to Python 2.4 I've been seeing the following exception in threading.py Condition: File "mctest3.py", line 1598, in WaitForMessages self.condResponses.wait(1.0) File "C:\Program Files\Python24\lib\threading.py", line 221, in wait delay = min(delay * 2, remaining, .05) OverflowError: long int too large to convert to int Is there something I'm doing wrong here ? I've looked at my code, and glanced at threading.py, and I can't see any obvious errors (multiplying a float by 2, using the result of the time.time() call none of which use longs as far as I know). I added some print statements to threading.py and the exception is thrown on the first iteration when delay is 0.0005 and remaining is 1.0 However the code does keep running... ----------------------- Delay: 0.0005 Remaining: 1.0 Traceback (most recent call last): File "", line 1, in ? File "mctest3.py", line 2665, in getLogonResponse respLogon.WaitForMessages() File "mctest3.py", line 1598, in WaitForMessages self.condResponses.wait(1.0) File "C:\Program Files\Python24\lib\threading.py", line 222, in wait delay = min(delay * 2, remaining, .05) OverflowError: long int too large to convert to int Delay: 0.016 Remaining: 8.07899999619 Delay: 0.032 Remaining: 8.01600003242 Delay: 0.05 Remaining: 7.95399999619 Done Message response handler got message ----------------------- Is this something to do with min ? Converting 1.0 ? Thanks for any help. Mark ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From brent.hughes at comcast.net Tue Jan 25 14:38:13 2005 From: brent.hughes at comcast.net (Brent W. Hughes) Date: Tue, 25 Jan 2005 12:38:13 -0700 Subject: How to input one char at a time from stdin? Message-ID: I'd like to get a character from stdin, perform some action, get another character, etc. If I just use stdin.read(1), it waits until I finish typing a whole line before I can get the first character. How do I deal with this? Brent From antbyte.The.Flow at gmail.com Thu Jan 27 20:39:00 2005 From: antbyte.The.Flow at gmail.com (The Flow) Date: 27 Jan 2005 17:39:00 -0800 Subject: [perl-python] 20050127 traverse a dir References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> <1106875259.426213.252030@z14g2000cwz.googlegroups.com> Message-ID: <1106876340.013509.296840@f14g2000cwb.googlegroups.com> Sorry about that... (I forgot what he was trying to teach) Thanks for the clarification -- The Flow From sara_fwd at yahoo.com Thu Jan 13 07:51:22 2005 From: sara_fwd at yahoo.com (Sara Fwd) Date: Thu, 13 Jan 2005 04:51:22 -0800 (PST) Subject: module on files & directories Message-ID: <20050113125122.43539.qmail@web50504.mail.yahoo.com> Hi all Can anybody help me find a module or a function that looks in a directory and defines whether the objects in there are files or directories? Thanks, Sara __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 11:50:48 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-2?Q?Martin_MOKREJ=A9?=) Date: Mon, 10 Jan 2005 17:50:48 +0100 Subject: Writing huge Sets() to disk In-Reply-To: References: Message-ID: <41E2B268.1020803@ribosome.natur.cuni.cz> Batista, Facundo wrote: > [Martin MOKREJ?] > > #- > At least you'll need a disk of 34694 EXABYTES!!! > #- > #- Hmm, you are right. So 20E15 then? I definitely need to be > > Right. Now you only need 355 PETABytes. Nowadays disk is cheap, but... > > > #- in range 1-14. ;-) > > Why? I need to test for occurence every such combination in some real-world examples. Many many will be missing, and those I have to keep. I've no clue what size will be the drop, so I rather expect full size. So, the generated, theoretical lexicon I could generate on the fly, but the results I have to keep. Even if I give up on this, can I write Sets onto a disk while keeping their nice, built-in methods? M. From jerf at jerf.org Sun Jan 23 06:35:25 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 23 Jan 2005 06:35:25 -0500 Subject: File objects? - under the hood question References: <20050119034955.75129.qmail@web50306.mail.yahoo.com> <20050118225310.1939807216.whereU@now.com> Message-ID: On Sun, 23 Jan 2005 08:27:49 -0800, EP wrote: > >> My brain-teaser: What I'd like to do is read the last ~2K of a large >> number of large files on arbitrary servers across the net, without >> having to read each file from the beginning (which would be slow and >> resource inefficient)... >> >> > Proper googling would have revealed that HTTP 1.1 includes a Range > Request. My bad. > > http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html > > Before I reinvent the wheel (and make it a little squarer than it has to > be) has anyone seen a "cookbook" recipe for adding the HTTP 1.1 range > request to a urllib urlopener (or something similar)? I posted a followup already to your previous message, I just changed the subject since it no longer applied, and it is the type of thing one would google for. (Those need proper subjects.) See: "Retrieving the last bit Re: File objects? - under the hood question". From itsme at yahoo.com Wed Jan 5 19:19:32 2005 From: itsme at yahoo.com (It's me) Date: Thu, 06 Jan 2005 00:19:32 GMT Subject: Another PythonWin Excel question References: <1104968382.403653.267060@f14g2000cwb.googlegroups.com> Message-ID: "Kartic" wrote in message news:1104968382.403653.267060 at f14g2000cwb.googlegroups.com... > I am not sure about this but I believe you can give a parameter > after="sheet1". to Add(), like so, Add(after="sheet1"). > I get a "got an expected keyword argument 'after'" from Add(). > Unfortunately I do not have Excel installed on this machine to confirm > this. > > A tip: if you have VBA (which you should if you have Excel) installed, > lookup the Add method for the Worksheets collection. VBA will show the > code completion, with all the arguments for the method call. Try the > same for any of the methods. > Yes, I read about that but unfortunately I have no experience with VBA *at all*. :=( > Thanks, > --Kartic > From vze4rx4y at verizon.net Sun Jan 30 00:25:52 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 30 Jan 2005 05:25:52 GMT Subject: is this sort method the same as the one in python 2.4 References: Message-ID: "Lowell Kirsh" > I'm trying to emulate the sorted() method introduced in python 2.4. The > only difference is that it takes a sequence as one of its arguments > rather than being a method of the sequence class. Does my method do the > same as the sorted()? Almost. This is closer to the mark: def sorted(iterable, cmp=None, key=None, reverse=False): "return a sorted copy of its input" if sys.version_info >= (2,4): return sorted(iterable, cmp, key, reverse) 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 Try it against the tests in Lib/test/test_builtin.py. The differences from your version: * >= 2.4 rather than just > 2.4 * renamed the parameter to iterable * handle the case where both cmp and key are defined * add an enumerated tie breaker to prevent full key comparisons * preserve by using reverse twice The real sorted() does the same thing but is implemented a bit differently. A custom key wrapper is applied to each object so that only the key value gets compared (no need for a full tuple with a tie breaker value). Raymond Hettinger From pythongnome at hotmail.com Sun Jan 16 18:20:01 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Sun, 16 Jan 2005 23:20:01 GMT Subject: List problems in C code ported to Python In-Reply-To: <41ead925$0$87061$a1866201@visi.com> References: <41ead925$0$87061$a1866201@visi.com> Message-ID: Grant Edwards wrote: > On 2005-01-16, Lucas Raab wrote: > >>I'm done porting the C code, but now when running the script I >>continually run into problems with lists. I tried appending and >>extending the lists, but with no avail. Any help is much appreciated >>Please see both the Python and C code at >>http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py > > > http://www.catb.org/~esr/faqs/smart-questions.html > I didn't expect to get bitched out just because I didn't follow "protocol." From petite.abeille at gmail.com Thu Jan 27 17:02:45 2005 From: petite.abeille at gmail.com (PA) Date: Thu, 27 Jan 2005 23:02:45 +0100 Subject: ANN: Tao Scripting Language 0.8.5 beta released! In-Reply-To: References: Message-ID: <397cc8578b5e9adf0e31f18ffa556593@gmail.com> On Jan 27, 2005, at 22:54, Limin Fu wrote: > I found that, a language with simple syntax, convenient text > processing functionality, powerful numeric computation capability, and > simple C/C++ interfaces would be very useful You bet. Have you looked at Lua? http://www.lua.org/about.html Or perhaps Io? http://www.iolanguage.com/About/ Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From ncoghlan at iinet.net.au Tue Jan 4 04:31:37 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 04 Jan 2005 19:31:37 +1000 Subject: Deferred expressions (was Re: Lambda as declarative idiom) In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: <41DA6279.1010105@iinet.net.au> Steven Bethard wrote: > Nick Coghlan: def-from syntax [4] > (def f(a) + o(b) - o(c) from (a, b, c)) > (def x * x from (x)) > (def x from ()) > (def x.bar(*a, **k) from (*a, **k)) > ((def x(*a, **k) from ()) for x, a, k in funcs_and_args_list) After a bit more musing, this is definitely my preferred syntax. I'd call it a 'deferred expression' rather than an anonymous function, though. The name change may seem minor, but it changes the emphasis of the feature from how it's implemented to what it is useful for (i.e. deferring evaluation of an expression until call time). It's also conducive to a clean no-argument syntax - simply make the 'from' claus optional when the argument list is empty. 'def' and 'from' are already keywords, so there shouldn't be any compatibility problems. Michael Spencer's idea of using 'for' instead of 'from' was quite interesting, but the use of 'for' without a corresponding 'in' feels a bit misleading :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From RajaSrinivasan at hotmail.com Tue Jan 4 16:59:28 2005 From: RajaSrinivasan at hotmail.com (RajaSrinivasan at hotmail.com) Date: 4 Jan 2005 13:59:28 -0800 Subject: Looking for CORBA (omniORB) examples Message-ID: <1104875968.342963.181970@z14g2000cwz.googlegroups.com> can we script CORBA objects/events with python. my search for simple examples has not yielded any results. any help appreciated. From http Wed Jan 5 07:00:44 2005 From: http (Paul Rubin) Date: 05 Jan 2005 04:00:44 -0800 Subject: Concepts RE: Python evolution: Unease References: <20050105002302.542768387.EP@zomething.com> <7xr7l06qfc.fsf@ruckus.brouhaha.com> Message-ID: <7xwtus9jbn.fsf@ruckus.brouhaha.com> Paul Rubin writes: > There is nothing in Wikipedia about [Generic programming]. Oops: http://en.wikipedia.org/wiki/Generic_programming This helps. But I don't see how it's different from what used to be called polymorphism. From bokr at oz.net Thu Jan 13 17:25:40 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 22:25:40 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: <41e6f4b7.777345834@news.oz.net> On Thu, 13 Jan 2005 09:29:49 -0500, Steve Holden wrote: >Fredrik Lundh wrote: > >> Antoon Pardon wrote: >> >> >>>Well, it seems that Guido is wrong then. The documentation clearly >>>states that an expression is a statement. >> >> >> no, it says that an expression statement is a statement. if you don't >> understand the difference, please *plonk* yourself. >> >OK then, "The documentation clearly states that not all statements can >be expressions". Specifically Guido has justified the fact that an >assignment does not return any value, and therefore cannot be used as a >component of an expression. > Hm, that makes me wonder, is there an intermediate "returning of value" in x = y = z = 123 ? >Mea culpa, but I'm not going to *plonk* myself - then *nobody* would be >listening to me :-) Regards, Bengt Richter From craig at postnewspapers.com.au Thu Jan 13 15:20:07 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 14 Jan 2005 04:20:07 +0800 Subject: Free python server. In-Reply-To: <002301c4f99a$cb4dcd50$55a01d53@unqku4k1fl8nea7> References: <002301c4f99a$cb4dcd50$55a01d53@unqku4k1fl8nea7> Message-ID: <1105647607.4001.18.camel@albert.localnet> On Thu, 2005-01-13 at 19:07 +0100, rootshell at gazeta.pl wrote: > Thank you very much. > Arbornet.org seems to be ok > Unforutnately I was convinced that I only have to only copy my *.py file to > /public_hml directory and everything will be all right. Your file probably need to (a) be in the cgi-bin, not public_html, (b) be flagged executable ("chmod a+x file.py"), and (c) begin with the line: '#!/usr/bin/env python' If the server doesn't provide you with CGI (or, strongly preferable, SCGI or mod_python), you're probably out of luck. -- Craig Ringer From aleaxit at yahoo.com Sun Jan 30 03:52:07 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 30 Jan 2005 09:52:07 +0100 Subject: Need programming tip References: <1107071340.486489.146580@f14g2000cwb.googlegroups.com> Message-ID: <1gr74ck.kncteuqczambN%aleaxit@yahoo.com> wrote: ... > 1511156 As Requested 2000 adv server -2000AdvSrv.vol001+02.PAR2 (1/4) - > 21/27 > 1511157 As Requested 2000 adv server -2000AdvSrv.vol001+02.PAR2 (2/4) - > 21/27 ... > would be to look for (1/ in the subject string then find the > denominator and loop thru as many times as the denominator to create > the part of the nzb file. Is this the best way or is there an > easier method? Also what would be the best way to search for the (1/ > using string searches or RegExp? If REgExp could someone provide me > with the RegExp for searching for this string? If the only thing that identifies these posts as part of one logical post is that (n/m) in the subject then I guess there's nothing for it but analysis of the subject, and a re seems appropriate. import re re_n_of_m = re.compile(r'(.*)\s*\((\d+)/(\d+)\)') might be one approach. Then, somewhere in your loop, mo = re_n_of_m.search(subject) sets mo to None if it doesn't match the pattern; if it does match, then mo is a match object with three groups. mo.group(1) is the part of the subject before the (n/m) marker; mo.group(2) is n as a string; mo.group(3) is n as a string. You can use mo.group(1) as the key into a dictionary where you collect (n,m) pairs as values, so that once you've collected all posts you can tell which one are multipart and also check for inconsistency (different m values), duplicates, missing parts. What you need to do in each case, I don't know... Alex From 2004b at usenet.alexanderweb.de Tue Jan 25 16:08:01 2005 From: 2004b at usenet.alexanderweb.de (Alexander Schremmer) Date: Tue, 25 Jan 2005 22:08:01 +0100 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) References: Message-ID: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> On Tue, 25 Jan 2005 12:22:13 -0700, Steven Bethard wrote: > >>This is a serious issue. > >> > >>It's also one that brings Tcl, mentioned several > >>times in this thread, back into focus. Tcl presents > >>the notion of "safe interpreter", that is, a sub- > >>ordinate virtual machine which can interpret only > >>specific commands. It's a thrillingly powerful and > >>correct solution to the main problem Jeff and others > >>have described. > > > > A better (and of course *vastly* more powerful but unfortunately only > > a dream ;-) is a similarly limited python virutal machine..... > > Yeah, I think there are a lot of people out there who would like > something like this, but it's not quite clear how to go about it. If > you search Google Groups, there are a lot of examples of how you can use > Python's object introspection to retrieve "unsafe" functions. IMHO a safe Python would consist of a special mode that disallows all systemcalls that could spy/harm data (IO etc.) and imports of non-whitelisted modules. Additionally, a loop counter in the interpreter loop would ensure that the code does not stall the process/machine. >>> sys.safecall(func, maxcycles=1000) could enter the safe mode and call the func. I am not sure how big the patch would be, it is mainly a C macro at the begginning of every relevant function that checks the current "mode" and raises an exception if it is not correct. The import handler would need to check if the module is whitelisted (based on the path etc.). Python is too dynamic to get this working while just using tricks that manipulate some builtins/globals etc. Kind regards, Alexander From Mark.English at liffe.com Thu Jan 20 06:24:12 2005 From: Mark.English at liffe.com (Mark English) Date: Thu, 20 Jan 2005 11:24:12 -0000 Subject: Class introspection and dynamically determining function arguments Message-ID: <40E605146701DE428FAF21286A97D30917450D@wphexa02.corp.lh.int> I'd like to write a Tkinter app which, given a class, pops up a window(s) with fields for each "attribute" of that class. The user could enter values for the attributes and on closing the window would be returned an instance of the class. The actual application I'm interested in writing would either have simple type attributes (int, string, etc.), or attributes using types already defined in a c-extension, although I'd prefer not to restrict the functionality to these requirements. The only way I can imagine to do this is to create an instance of the class in question, and then start poking around in its attributes dictionary (initially just using dir). So firstly, if there is instead a way to do this without creating an instance I'd be interested. Secondly, the code won't know exactly how to initialise the class instance used to determinte the attributes. Do I need to make it a prerequesite that all instances can be created with no arguments ? Should I force/allow the user to pass an instance instead of a class ? Should I be using inspect.getargspec on the class __init__ method and then a loop with a try and a lot of except clauses, or is there a nicer way to do this ? Presumably the pickling code knows how do serialise/deserialise class instances but I'm not sure how I'd use this without already having a class instance to hand. Lastly, does such an app already exist ? Thanks for any help. ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From terti at mighty.co.za Tue Jan 18 13:43:44 2005 From: terti at mighty.co.za (tertius) Date: Tue, 18 Jan 2005 20:43:44 +0200 Subject: hex notation funtion Message-ID: Hi, Is there a builtin function that will enable me to display the hex notation of a given binary string? (example below) many thanks Tertius 0000(0000) 02 11 00 00 46 5A 1A 82 02 11 00 39 36 39 33 39 ....FZ.....96939 0016(0010) 36 39 33 00 0A 30 33 37 34 34 39 35 38 25 DD 01 693..03744958%.. From aleaxit at yahoo.com Sun Jan 2 18:19:40 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 3 Jan 2005 00:19:40 +0100 Subject: How to make executable file ? References: <33r5gcF449bt0U1@individual.net> <41d868ff@news.unimelb.edu.au> Message-ID: <1gpse2o.v5dt3254u05uN%aleaxit@yahoo.com> Maurice LING wrote: > Hi all, > > This may be OT but is there a way to do the same for *nix type of > system? Like cast a python interpreter with scripts together? Yes, but fortunately on the Mac you don't need that. > I'm running Mac OSX here. Assuming we're talking Mac OS X 10.3 or later, Python itself comes with the operating system (it's used somewhere in stuff provided with the system, such as fax handling). As I saw others suggest, google for py2app, it's probably the best way to handle this for the Mac today. Alex From matthew.garrish at sympatico.ca Sun Jan 9 13:19:19 2005 From: matthew.garrish at sympatico.ca (Matt Garrish) Date: Sun, 9 Jan 2005 13:19:19 -0500 Subject: unicode support References: <1105259315.471816.291600@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1105259315.471816.291600 at c13g2000cwb.googlegroups.com... # -*- coding: utf-8 -*- # python supports unicode in source code by putting a coding declaration # as the first line. print "look chinese chars: ?????" # Note, however, identifiers cannot use unicode chars. # e.g. you cannot define a function with unicode char. So why are you posting to a Perl newsgroup? You can "use utf8" if you want to write your Perl programs in utf-8 (though you should upgrade to 5.8 as well). Or is this your lame attempt at trolling at python group? Matt From http Fri Jan 28 21:12:37 2005 From: http (Paul Rubin) Date: 28 Jan 2005 18:12:37 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> Message-ID: <7xacqt56ga.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > > Let's see, the urandom module was recently released in 2.4, I think > > initially at my urging. > > There is no urandom module in Python 2.4. Oops, sorry, it's in the os module: http://docs.python.org/lib/os-miscfunc.html The difference is simply a matter of the packaging. It's important functionality and it was added after an amount of review and testing that was deemed to be reasonable. Unless you're saying that if I wanted to add AES to the string module (so you could say 'spam and sausage'.aes_encrypt('swordfish banana')) instead of writing a separate module, then we wouldn't need this discussion. (Putting it in the string module is not a serious proposal but it wouldn't be completely insane.) What matters is the code complexity, not whether something is in a separate module or not. > > If Guido says "no crypto", is that something other than a > > policy? And are you speaking for him when you say that? > > If he had said such a thing in general, it would be a policy > (although it best would be documented somewhere). I don't think > he said that, in general, and with the intent of stating a policy. Well, if he indicates that it's not a policy and that the question is still open, then I could see getting interested again in writing an AES module. At the moment I continue to see his python-dev post as quite discouraging. > We don't normally invite people to work on anything. People pick the > things they work on themselves. Not true. For example, you once invited me to work on an ancillary message feature for the socket module (SF bug 814689), and so it's been on my want-to-do-one-of-these-days list since then. I think it's reasonable for me to have taken your message there as an expression of interest, sufficient to get me to want to work on it. So it's bogus to say the Python developers should avoid expressing interest in something that hasn't already been written. > > IETF often decides and announces that a feature is good long before > > any such details are decided or agreed on. > > No. They decided that spam machinery in DNS would be a good thing, > people started to work on it, and then they decided that it is not > such a good thing, after all, because it causes too many problems. There's no contradiction. IETF decided something based on some reasonable beliefs that later turned out to be wrong, so they had to undo the original decision because the original expectations couldn't be met. That happens sometimes. Everyone has worked on projects that ended up failing and getting cancelled for reasons like that. There are few ironclad guarantees of anything, only reasonable beliefs. But real-world organizations are not afraid to start projects based on reasonable beliefs regardless. Otherwise, few things would ever get done. > It does matter for me, yet Python is still more than the core. > > You might be ignoring that, but it surely is more to the many > developers which create Python libraries and distribute them > themselves, see > > http://www.python.org/pypi > THIS IS ALL PYTHON. No. Those are programs people have written in Python or as Python extensions. I've written programs like that myself. I don't consider them to be part of Python. They are separate programs. If one of them gets accepted into the distro (as this thread is about), then it becomes part of Python. See : 1.1.6 How do I obtain a copy of the Python source? The latest Python source distribution is always available from python.org, at http://www.python.org/download/. The latest development sources can be obtained via anonymous CVS from SourceForge, at http://www.sourceforge.net/projects/python. Python is what you get from following the download instructions and installing the result. In , where it asks "why is Python installed on my machine?", that is what they are referring to by "Python". > > Obviously those require a different type of consideration. I'm > > talking about patches where there's a core developer with an interest. > > I though you were talking about the AES module... No, when this started you were talking about modules in general. From stefan at eischet.com Mon Jan 17 15:50:06 2005 From: stefan at eischet.com (Stefan Eischet) Date: Mon, 17 Jan 2005 21:50:06 +0100 Subject: Excel module for Python In-Reply-To: <87brbpdqct.fsf@andreasen.org> References: <87brbpdqct.fsf@andreasen.org> Message-ID: <5E8E534C-68C9-11D9-B712-000A95857E5C@eischet.com> Hi, I didn't catch older mails in this thread, so excuse me if this has already been pointed out: http://pyxlwriter.sourceforge.net/ "It's a port of John McNamara's Perl Spreadsheet::WriteExcel module" and it's really easy to use. I'm not sure if it does formulae, but it handles formatting fine. Putting together a file with complicated layout can be a lot of work, so for large prebuilt files (which I sometimes have to "fill in" programmatically), I just use COM with Excel. You'll have to run on Windows for that, of course. ;-) Cheers Stefan On 16.01.2005, at 22:19, Erwin S. Andreasen wrote: > Simon Brunning writes: > >> On Wed, 12 Jan 2005 23:19:44 +0800, sam wrote: >>> >>> No, I don't use MS windows. I need to generate Excel file by printing >>> data to it, just like Perl module Spreadsheet::WriteExcel. > >> If you need to write out formulae, formratting, that kind of thing, >> then I think you'll need to write a 'real' Excel file. I don't have a >> clue how to do that - sorry. > > There's actually an ancient open spreadsheet format called SYLK which > is a step above CSV: it allows formatting of data, formulas etc. > > Google for SYLK to get the rather sparse specification (and skip over > the first few links!) > > If you want to generate "real" Office files from UNIX, another > alternative is to automate OpenOffice (which has a COM-like interface > too) or generate OO XML files and feed them to OO asking to conver > them with a bit of OO macro magic. > From pinard at iro.umontreal.ca Thu Jan 13 11:18:18 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 13 Jan 2005 11:18:18 -0500 Subject: finding/replacing a long binary pattern in a .bin file In-Reply-To: <3e8ca5c80501122251483f4b8f@mail.gmail.com> References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> <3e8ca5c80501122251483f4b8f@mail.gmail.com> Message-ID: <20050113161818.GA21609@phenix.progiciels-bpi.ca> [Stephen Thorne] > On 12 Jan 2005 22:36:54 -0800, yaipa wrote: > > > What would be the common sense way of finding a binary pattern in > > a .bin file, say some 200 bytes, and replacing it with an updated > > pattern of the same length at the same offset? The file itself > > isn't so large, maybe 32 kbytes is all and the need for speed is not > > so great, but the need for accuracy in the search/replacement is > > very important. > Okay, given the requirements. > f = file('mybinfile') > contents = f.read().replace(oldbinstring, newbinstring) > f.close() > f = file('mybinfile','w') > f.write(contents) > f.close() > Will do it, and do it accurately. But it will also read the entire > file into memory. 32Kb is a small file indeed, reading it in memory is not a problem! People sometimes like writing long Python programs. Here is about the same, a bit shorter: :-) buffer = file('mybinfile', 'rb').read().replace(oldbinstring, newbinstring) file('mybinfile', 'wb').write(buffer) -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From simon.brunning at gmail.com Fri Jan 7 05:23:57 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 7 Jan 2005 10:23:57 +0000 Subject: python reading/writing ms-project files? In-Reply-To: <1105056307.322989.54930@z14g2000cwz.googlegroups.com> References: <1105056307.322989.54930@z14g2000cwz.googlegroups.com> Message-ID: <8c7f10c6050107022325e00192@mail.gmail.com> On 6 Jan 2005 16:05:07 -0800, zslist at gmail.com wrote: > any existing or pointers on how to do this? If you are running on Windows and have a copy of Project, then COM automation is probably your best bet. See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/279003 for a very basic example of COM scripting. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From __peter__ at web.de Wed Jan 26 06:11:06 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Jan 2005 12:11:06 +0100 Subject: string.atoi and string.atol broken? References: Message-ID: Peter Otten wrote: > def itoa(n, base): > assert 2 <= base <= 16 > if n < 0: > digits = ["-"] > n = -n > else: > digits = [] > while n: > n, m = divmod(n, base) > digits.append(string.hexdigits[m]) > digits.reverse() > return "".join(digits) This is junk, sorry. Doesn't handle n<=0 correctly (at least). Peter From pythonista at gmail.com Mon Jan 31 19:26:39 2005 From: pythonista at gmail.com (Sean Blakey) Date: Mon, 31 Jan 2005 16:26:39 -0800 Subject: Java Integer.ParseInt translation to python In-Reply-To: <008d01c507f4$451d9b30$2820790d@stso.xcdg.xerox.com> References: <008d01c507f4$451d9b30$2820790d@stso.xcdg.xerox.com> Message-ID: <372a762405013116263a4e93b7@mail.gmail.com> On Mon, 31 Jan 2005 19:23:35 -0500, jose isaias cabrera wrote: > > Greetings! > > I've looked through the internet (not long, though) but I have not been able > to find a python translation to > > buffer[0] = (byte)Integer.parseInt(string,16); > > Has anyone ported any java programs to python and has translated this? > > any help would be greatly appreciated. > > thanks. > > jos? > buffer[0] = int(string, 16) http://docs.python.org/lib/built-in-funcs.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 richie at entrian.com Fri Jan 21 09:47:10 2005 From: richie at entrian.com (Richie Hindle) Date: Fri, 21 Jan 2005 14:47:10 +0000 Subject: ElementTree.findtext() In-Reply-To: References: Message-ID: [me] > >>> print tree.findtext("html/head/title") > None I realised what the problem was the second after I hit Send (why is it never the second *before*?) The tree represents the top-level element, so of course searching within it for 'html' fails. What I should say is this: >>> print tree.findtext("head/title") The title Sorry to waste people's time! -- Richie Hindle richie at entrian.com From irmen at -nospam-remove-this-xs4all.nl Sat Jan 8 15:04:29 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 08 Jan 2005 21:04:29 +0100 Subject: there's a socket.sendall(), so why no socket.recvall()? In-Reply-To: References: Message-ID: <41e03ccc$0$6208$e4fe514c@news.xs4all.nl> Robert Brewer wrote: > Irmen de Jong wrote: > >>Subject says it all; >>there's a socket.sendall(), so why no socket.recvall()? > [...] > If you call .makefile() and then .read() the _fileobject, you get the > same behavior (only better). Adding recvall would just duplicate that, I > think. But that's desirable IMO. Hm, I didn't consider makefile(). But I'm not sure if that works in all cases. Until now, I've been using a loop rather like the one you posted. But, as I pointed out earlier, there is the MSG_WAITALL option on various platforms (Linux for instance). So instead of sticking it in an explicitly programmed loop in Python, or using an extension module such as this one: http://mail.python.org/pipermail/python-list/2003-January/143051.html , I'd rather have a recvall method on the socket object that essentially uses MSG_WAITALL if available, and uses a loop construction if not. I may even write a patch for socketmodule.c right now :-D --Irmen de Jong From aleaxit at yahoo.com Sat Jan 22 06:20:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 12:20:36 +0100 Subject: need help on need help on generator... References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> <1106387175.4103.16.camel@albert.localnet> Message-ID: <1gqshv6.linw9y1anlov0N%aleaxit@yahoo.com> Craig Ringer wrote: > .>>> data = ''.join(x for x in infile) Maybe ''.join(infile) is a better way to express this functionality? Avoids 2.4 dependency and should be faster as well as more concise. > Might it be worth providing a way to have file objects seek back to the > current position of the iterator when read() etc are called? If not, I It's certainly worth doing a patch and see what the python-dev crowd thinks of it, I think; it might make it into 2.5. > favour the suggestion in the referenced post - file should probably fail > noisily, or at least emit a warning. Under what conditions, exactly, would you want such an exception? Alex From daranrife at yahoo.com Mon Jan 10 14:35:33 2005 From: daranrife at yahoo.com (drife) Date: 10 Jan 2005 11:35:33 -0800 Subject: Reading Fortran binary files Message-ID: <1105385733.855390.83220@c13g2000cwb.googlegroups.com> Hello, I need to read a Fortran binary data file in Python. The Fortran data file is organized thusly: nx,ny,nz,ilog_scale # Record 1 (Header) ihour,data3D_array # Record 2 Where every value above is a 2 byte Int. Further, the first record is a header containing the dimensions of the data that follows, as well as the scaling factor of the data (log base 10). The second record contains the hour, followed by the 3D array of data, which is dimensioned by nx,ny,nz. I also need to convert all the 2 byte Int values to 'regular' Int. I realize that similar questions have previously been posted to the group, but the most recent inquiries date back to 2000 and 2001. I thought there may be newer and easier ways to do this. Thanks in advance for your help. Daran Rife daranrifeNOS at PAMyahoo.com From jeff at ccvcorp.com Mon Jan 3 15:06:49 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 03 Jan 2005 12:06:49 -0800 Subject: what is lambda used for in real code? In-Reply-To: References: <1gpngqs.gi6p511azrvn4N%aleaxit@yahoo.com> Message-ID: <10tj9677oetse30@corp.supernews.com> Steven Bethard wrote: > The only ones that make me a little nervous are examples like: > > inspect.py: def formatargspec(args, varargs=None, varkw=None, > ... > formatvarargs=lambda name: '*' + name, > formatvarkw=lambda name: '**' + name, > formatvalue=lambda value: '=' + repr(value), > > where the lambdas are declaring functions as keyword arguments in a def. At least in this case, a number of these can be handled with curry / partial(), I think -- ... formatvarargs = partial(operator.add, '*'), formatvarkw = partial(operator.add, '**'), ... The last is a bit more complicated, since it's got an extra (deferred) function call, so I'm not sure exactly how to deal with that cleanly. Actually, in this specific case, since these are all creating strings, it'd be pretty trivial to simply do this manipulation inside of the function body rather than inside of the arglist: def formatargspec(..., formatvarargs, formatkwargs, formatvalue, ...): formatvarargs = '*' + formatvarargs formatvarkw = '**' + formatvarkw formatvalue = '=' + repr(value) This has the disadvantage of having names typed multiple times, which is definitely a minus, but it's arguably a bit more clear to explicitly manipulate the strings within the function body rather than burying that manipulation somewhere in the argument list. Personally I'd call this a wash, though I expect that others will disagree with me. ;) And whatever the merits of this particular case, similar cases may not be so easy to avoid in this fashion... Jeff Shannon Technician/Programmer Credit International From tjreedy at udel.edu Sun Jan 9 21:53:47 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 9 Jan 2005 21:53:47 -0500 Subject: Long strings as function parameters References: <1105288564.441842.13060@c13g2000cwb.googlegroups.com> <1105290325.030128.146490@c13g2000cwb.googlegroups.com> Message-ID: "Dan Bishop" wrote in message news:1105290325.030128.146490 at c13g2000cwb.googlegroups.com... > In Python, *every* expression is a pointer. Minor but to me important nit: this should start "In the CPython implementation of Python" ... Humans can understand and execute Python code without knowing about computer memory addresses (pointers). Other computer languages can also do something slightly different from CPython, as I believe is the case with Jython. The Python language is defined by sematics, not by mechanisms, especially low-level interpreter-specific mechanisms. This is a large part of what makes it readable. To the OP: a Python function call binds argument objects to either local parameter names or slots within a named catchall list or dict. Like other binding (assignment) operations, there is no copying. Terry J. Reedy From jurgenex at hotmail.com Sun Jan 9 04:01:07 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sun, 09 Jan 2005 09:01:07 GMT Subject: unicode support References: <1105259315.471816.291600@c13g2000cwb.googlegroups.com> Message-ID: xah at xahlee.org wrote: > # -*- coding: utf-8 -*- > # python supports unicode in source code by putting a coding > declaration > # as the first line. So? > In perl, support of unicode is very flaky. The language does not > support it, but packages that changes behaviors of string handling (in > its regex, for instance.) Really? You may want to check your sources. They seem to be a little bit outdated, like several years old? jue From ianb at colorstudy.com Mon Jan 3 16:36:36 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Mon, 03 Jan 2005 15:36:36 -0600 Subject: Ann: CherryPy-2.0-beta released In-Reply-To: <1104785774.524707.214290@f14g2000cwb.googlegroups.com> References: <1104774372.943278.302050@f14g2000cwb.googlegroups.com> <1104783888.664232.72720@f14g2000cwb.googlegroups.com> <1104785774.524707.214290@f14g2000cwb.googlegroups.com> Message-ID: <41D9BAE4.6050003@colorstudy.com> remi at cherrypy.org wrote: > Well, you can easily run CherryPy behind Apache (see > http://trac.cherrypy.org/cgi-bin/trac.cgi/wiki/BehindApache). > Since CherryPy provides a WSGI interface (although it's still > experimental), you can also run your CherryPy app with any > WSGI-compatible HTTP server (although I don't really see any advantage > to doing this). In the future when more WSGI environments are deployed, I think the benefits will be nice. For instance, under WSGIKit (http://svn.colorstudy.com/trunk/WSGIKit) you should be able to create a file: # cherry_app.py: from cherrypy import cpg, wsgiapp from my_cherry_app import root_instance cpg.root = root_instance wsgiapp.init() # This variable name is automatically picked up: application = wsgiapp.wsgiApp Then your application would be available under cherry_app/ (wherever you happened to put that file in the URL space). Note that WSGIKit isn't a server itself, just a set of middleware that delegates to different applications. It occurs to me that it would be considerably cleaner if it looked more like this: from cherrypy import wsgiapp from my_cherry_app import root_instance application = wsgiapp.Application(my_cheery_app) Otherwise you can only run one CherryPy application in a process...? That would be very limiting. Anyway, the idea is you can deploy a CherryPy-based application fairly easily alongside other WSGI Python web applications. The particulars still need some work -- I don't like the little Python file used to put the pieces together -- but I think it's a good direction. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From skip at pobox.com Thu Jan 13 09:06:56 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 13 Jan 2005 08:06:56 -0600 Subject: why not datetime.strptime() ? In-Reply-To: <16869.62773.572880.581805@montanaro.dyndns.org> References: <20050111021152.GA20127@yucs.org> <16867.59681.423983.244528@montanaro.dyndns.org> <20050111173335.GB26246@yucs.org> <16869.62773.572880.581805@montanaro.dyndns.org> Message-ID: <16870.32896.616979.730581@montanaro.dyndns.org> Skip> I just checked in your changes. Thanks for the effort. Jeez Skip... That reads poorly. How about "Thanks for your contribution"? In any case, thanks. Skip From hikenboots at yahoo.com Fri Jan 7 10:56:00 2005 From: hikenboots at yahoo.com (John French) Date: Fri, 7 Jan 2005 09:56:00 -0600 Subject: [Pyro] Newbie Question Regarding Pyro Message-ID: <2hyDd.1$Jh.0@bignews4.bellsouth.net> I'm putting together a new project which I'm using to learn Python and have questions about pyro. I like the idea of the abstraction that pyro offers from sockets programming but I cannot determine if I'm giving up some possibly needed functionality. If the server needs to send an unsolicited ad hoc message to a given client, is this possible? (New message or a reminder, for instance) I suppose I could poll a server side list from the client but I'm wondering if the server can initiate the exchange. Also, if a client wishes to converse with another particular client (in a chat or IM situation, for instance). What's a good mechanism for this? Does pyro create a persistent client/server connection? What happens if a pyro client goes down hard? Does it's process continue or is there a cleanup mechanism? Thanks in advance. From belred at gmail.com Sun Jan 30 21:18:57 2005 From: belred at gmail.com (Bryan) Date: Sun, 30 Jan 2005 18:18:57 -0800 Subject: Regarding exception handling In-Reply-To: References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> Message-ID: Dan Perl wrote: > "Aggelos I. Orfanakos" wrote in message > news:1107127179.863445.55310 at c13g2000cwb.googlegroups.com... > >>Thanks. This should now be OK: >> >>#try: >># try: >># s = ... # socket opens >># >># # various code ... >># except socket.error, x: >># # exception handling >>#finally: >># s.close() # socket closes >> > > > Why the nested try's? If I understand your intention correctly this should > do the same thing: > > try: > s = ... # socket opens > # various code ... > except socket.error, x: > # exception handling > s.close() # socket closes > > You would need the try-finally statement only if you expect it to handle > other exceptions than socket.error or if the socket.error is re-raised in > the "except" clause. Otherwise, the try-finally statement is redundant > because no socket.error are getting out of the try-except statement. > > Dan > > i always use the try/finally statement with resources, but in a slightly different way than the above two examples: s = ... # socket opens try: # various code ... finally: s.close() or, if i want to handle the socket.error if s gets successfully bound, s = ... # socket opens try: try: # various code except socket.error e: # exception handling finally: s.close() i disagree with the statement: "You would need the try-finally statement only if you expect it to handle other exceptions than socket.error or if the socket.error is re-raised in the "except" clause. Otherwise, the try-finally statement is redundant because no socket.error are getting out of the try-except statement." IMO, that is not the reason for the try/finally statement and it is not redundant. the try/finally statement guarantees the resource is closed and the try/finally statement only gets executed if and only if the opening of the resource doesn't raise an exception. it has nothing to do with exception handling. in the previous 2 examples s = ... was placed inside the try/finally, but if an exception occures and s doesn't get bound to an object, then s.close() in both examples will raise a NameError on s. bryan From tdelaney at avaya.com Sun Jan 16 17:45:56 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 17 Jan 2005 09:45:56 +1100 Subject: generator expressions: performance anomaly? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025202AA@au3010avexu1.global.avaya.com> Raymond Hettinger wrote: > Check out the current source. The time machine beat you to it. Nick's other suggestion - that genexps propagate __len__ - might still be interesting. Of course, it would only be applicable for unconditional genexps(i.e. no if clause). Tim Delaney From steven.bethard at gmail.com Thu Jan 27 16:37:10 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 14:37:10 -0700 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <2fCdnYr1l-CZwmTcRVn-ig@comcast.com> Francis Girard wrote: >>>>a = "10" >>>>b = 10 >>>>a > b > True > >>>>b > a > False > >>>>id(a) > 1077467584 > >>>>id(b) > 134536516 Just to thoroughly explain this example, the current CPython implementation says that numbers are smaller than everything but None. The reason you get such a small id for 'b' is that there is only one 10 object (for efficiency reasons): py> 10 is 5 + 5 True py> 99 is 50 + 49 True py> 100 is 50 + 50 False Note that there may be many different instances of integers 100 and above (again, in the current CPython implementation). So to get an integer id above a string id, your integer must be at least 100: py> a = "100" py> b = 100 py> id(a), id(b) (18755392, 18925912) py> a > b True py> b > a False So, even though b's id is higher than a's, b still compares as smaller because the current CPython implementation special-cases the comparison to guarantee that numbers are always smaller than all other non-None objects. Again, these are *all* implementation details of the current CPython, and depending on these details might run you into troubles if they change in a future version of CPython, or if you use a different implementation (e.g. Jython or IronPython). Steve From dave.benjamin at gmail.com Mon Jan 3 11:16:01 2005 From: dave.benjamin at gmail.com (Dave Benjamin) Date: Mon, 03 Jan 2005 09:16:01 -0700 Subject: Lambda as declarative idiom (was RE: what is lambda used for in real code?) In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: <%ceCd.6596$232.5209@fed1read05> Roman Suzi wrote: > I wish lambdas will not be deprecated in Python but the key to that is > dropping the keyword (lambda). If anybody could think of a better syntax for > lambdas _with_ arguments, we could develop PEP 312 further. Well, my vote is still with Ruby-style codeblock syntax, but as a compromise, what about the following: fun(a, b): a + b as a replacement for: lambda a, b: a + b Advantages: - Doesn't use the l-word - Uses parentheses always - "fun" is shorter and self-describing - Makes Python code more "fun" ;) Disadvantages: - Requires a new keyword, breaking backward compatibility (I'm assuming we're still talking about Py3k here) - (Still) doesn't interface statements with expressions Dave From segphault at sbcglobal.net Mon Jan 24 11:02:22 2005 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 24 Jan 2005 16:02:22 GMT Subject: What is print? A function? References: Message-ID: On Sun, 23 Jan 2005 18:01:50 +0000, Frans Englich wrote: > > Nah, I don't think it's a function, but rather a builtin "statement". But > it's possible to invoke it as an function; print( "test" ) works fine. > > So I wonder, what _is_ exactly the print statement? The untraditional > way of invoking it(without paranteses) makes me wonder. > > The reason I thinks about this is I need to implement a debug print for > my program; very simple, a function/print statement that conditionally > prints its message whether a bool is true. Not overly complex. > > I tried this by overshadowing the print keyword, but that obviously > didn't work.. Is defining a two-liner function the right way to go, or > is there better ways to approach it? > > > Cheers, > > Frans Unfortunately, it isnt possible to add new kinds of statements to python. you might want to have a look at Ruby, in which paren are entirely optional. Ruby is similar to python in a lot of ways, but its also quite different. It provides lots of syntactic sugar and a superior object model, but its a resource hog compared to python. You may also be interested in Logix. Logix is a language framework built on top of python that allows you to dynamically extend python syntax at run-time. Unfortunately, Logix is still rather new, and its incredibly slow. http://logix.livelogix.com/ From kent3737 at yahoo.com Fri Jan 21 06:03:11 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Fri, 21 Jan 2005 06:03:11 -0500 Subject: Overloading ctor doesn't work? In-Reply-To: References: <35ab8oF4idc25U1@individual.net> Message-ID: <41f0defb$1_3@newspeer2.tds.net> Nick Craig-Wood wrote: > Martin H?cker wrote: > >> Now I thought, just overide the ctor of datetime so that year, month and >> day are static and everything should work as far as I need it. >> >> That is, it could work - though I seem to be unable to overide the ctor. :( > > Its a bug! > > http://sourceforge.net/tracker/index.php?func=detail&aid=720908&group_id=5470&atid=105470 > > However its been fixed in a recent Python 2.3. My example was developed in Python 2.4. The problem was the immutability of datetime. Kent > > (I was bitten by the same thing which used to fail but now works after > an upgrade of python 2.3!) From itsme at yahoo.com Wed Jan 12 13:42:24 2005 From: itsme at yahoo.com (It's me) Date: Wed, 12 Jan 2005 18:42:24 GMT Subject: counting items References: Message-ID: Yes, Mark, I came up with almost the same code (after reading back old answers from this list): def flatten(seq): for x in seq: if hasattr(x, "__iter__"): for subx in flatten(x): yield subx else: yield x def count_item(data): return len([(i,x) for i, x in enumerate(flatten(data))]) data = [[1,5,2],8,4] print count_item(data) Thanks everybody. "Mark McEahern" wrote in message news:mailman.579.1105554265.22381.python-list at python.org... > It's me wrote: > > >Okay, I give up. > > > >What's the best way to count number of items in a list [that may contain lists]? > > > > > a = [[1,2,4],4,5,[2,3]] > > def iterall(seq): > for item in seq: > try: > for subitem in iterall(item): > yield subitem > except TypeError: > yield item > > all = [x for x in iterall(a)] > print len(all) > From http Wed Jan 12 15:35:45 2005 From: http (Paul Rubin) Date: 12 Jan 2005 12:35:45 -0800 Subject: encryption/decryption help References: Message-ID: <7xwtuibd26.fsf@ruckus.brouhaha.com> "drs" writes: > Hi, I need to send secure data over an insecure network. To that end, I am > needing to encrypt serialized data and then decrypt it. Is there a builtin > way to do this in Python? MD5, SHA, etc encrypt, but I am not seeing a way > to get back my data. No, Python doesn't include any reversible encryption functions, because of regulatory obstacles in some countries. Here's a function based on SHA: http://www.nightsong.com/phr/crypto/p3.py It's not ideal and it's nonstandard, but it's written in pure Python and still has reasonable performance and should have ok security. It works on 32-bit processors but a simple fix is needed to make it work on 64-bit processors. I'll put that in when I get a chance. > Encryption is totally new to me, so any pointers of what to read up > on would be appreciated. Rule #1 is that there are a lot of subtle mistakes that can kill you. Try to use standard solutions when you can, instead of doing anything ad-hoc. The standard reference about crypto implementation is "Applied Cryptography" by Bruce Schneier. That's got all kinds of stuff about algorithms and protocols. You could also look at "Practical Cryptography" by Bruce Schneier and Niels Ferguson. That is more about what kinds of precautions you should take when implementing crypto. I disagree with some of what it says, but it's a start. Also, anyone implementing any type of security system (crypto or not) should read "Security Engineering" by Ross Anderson. > As a side note, I understand that I could use https, but this would involve > changing things that I may not be at liberty to change -- though if this > turns out to be the best solution, then I'll find a way to use it. Using https is almost certainly a better solution than rolling up something yourself. Do it if the option is available to you. From c.helmbold at gmx.de Mon Jan 24 05:16:02 2005 From: c.helmbold at gmx.de (Christian Helmbold) Date: Mon, 24 Jan 2005 11:16:02 +0100 Subject: Pointer: CfV de.comp.lang.python Message-ID: hi I ask german speaking python programmers to contest the election to establish the german python newsgroup de.comp.lang.python. You can find the ballot in de.admin.news.annouce or via Google http://tinyurl.com/5g5gf. Thank You! Christian From exogen at gmail.com Sat Jan 1 19:24:12 2005 From: exogen at gmail.com (Brian Beck) Date: Sat, 01 Jan 2005 19:24:12 -0500 Subject: What can I do with Python ?? In-Reply-To: <1gpqhbl.125l3evz09uefN%aleaxit@yahoo.com> References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> <1gpqhbl.125l3evz09uefN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > You _gotta_ be kidding, right...? The Beginner's Guide link takes you > right to the BeginnersGuide page which starts with the reassurance that > Python is easy to learn even if you're new to programming and continues > with a zillion useful links. The Python Books link takes you to a huge While I agree that there is much useful content on the official Python site, I particularly hate the BeginnersGuide and much of the resulting introduction pages. Often when I happily refer Python to someone who wants to learn a simple language, I go to the Python site and imagine where I would start if I were them. Once I get to the BeginnersGuide I don't see anything immediately useful, and when I look for it I get frustrated. -- Brian Beck Adventurer of the First Order From jeff at ccvcorp.com Thu Jan 6 13:38:53 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jan 2005 10:38:53 -0800 Subject: The Industry choice In-Reply-To: <41DD4E62.1020404@holdenweb.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> <41DD4E62.1020404@holdenweb.com> Message-ID: <10tr15fabtpnf97@corp.supernews.com> Steve Holden wrote: > Bulba! wrote: >> I was utterly shocked. Having grown up in Soviet times I have >> been used to seeing precious resources wasted by organizations >> as if resources were growing on trees, but smth like this?! In a >> shining ideal country of Germany?! Unthinkable. >> > Indeed not. Quite often the brown paper bag is a factor in purchases > like this. I wouldn't be at all surprised if somebody with a major input > to the decision-making process retired to a nice place in the country > shortly afterwards. You appear to be making the mistake of believing > that people will act in the larger interest, when sadly most individuals > tend to put their own interests first (some would go as far as to define > self-interest as the determinant of behavior). Indeed, it is almost expected that those in charge of any large organization (whether government, corporation, trade union, industry association, fan club, or whatever else) are likely to act in their personal interests at the expense of the organization's interests. This is why things like public-disclosure laws and oversight committees exist. As they say, power corrupts. (Of course, this is not at all limited to people in charge; it's just most notable there, since those people can direct the efforts of the rest of the organization for their personal gain, whereas a rank-and-file member can typically only direct their own efforts.) It's also noteworthy to consider that many times, waste happens not because of corruption or self-interest, but simply because of errors of judgement. Humans being as we are, it's inevitable that over time, some "obvious" important details will escape our attention, and the resulting imperfect information will result in poor decisions. This is a simple fact of human nature, and (ob-Python ;) ) it's one of the reasons that Python is designed as it is -- it makes a serious effort to reduce the number of details that might escape detection. (One should also consider that many business failures are a case of simply having played the odds and lost. Many ventures depend on outside events playing in a certain way; when by chance those events happen, the decision-makers are called "bold and insightful", but if things don't work out, they're called foolish or misguided. Often, though, it was not foolishness but shrewd risk-taking -- if you take a one-in-three chance of making a tenfold return on investment, then 66% of the time you'll lose.... but if you hit those odds just once, you'll come out way ahead.) Jeff Shannon Technician/Programmer Credit International From steven.bethard at gmail.com Mon Jan 31 11:21:55 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 31 Jan 2005 09:21:55 -0700 Subject: Nested scopes and class variables In-Reply-To: <1gr97zk.1nm8ijn3art4cN%aleaxit@yahoo.com> References: <1gr97zk.1nm8ijn3art4cN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: >>>>def f(x): > > ... class C: > ... x = x > ... return C > ... > [snip] > >>>>def f(x): > > ... def g(): > ... x = x > ... return x > ... return g > ... > [snip] > > See the difference? In a function, the 'x = x' compiles into LOAD_FAST, > STORE_FAST, which only looks at locals and nowhere else. In a > classbody, it compiles to LOAD_NAME, STORE_NAME, which looks at locals > AND globals -- but still not at closure cells... Is there a reason why the class body doesn't look at closure cells? That is, are there cases where this lookup scheme is preferred to one that checks locals, closure cells and globals? Steve P.S. Question disclaimer: My questions here are founded in a curiosity about language design, and are not intended as an attack on Python. =) From anu.shantha at wipro.com Tue Jan 25 14:47:29 2005 From: anu.shantha at wipro.com (anu.shantha at wipro.com) Date: Wed, 26 Jan 2005 01:17:29 +0530 Subject: Returned mail: Data format error Message-ID: <200501252003.j0PK3n9N003802@dbdp30.itg.ti.com> -------------- next part -------------- [Filename: file.zip, Content-Type: application/octet-stream] The original attachment to this message was of a file type currently being blocked in the TI environment. For more information, contact the sender of this message. From craig at postnewspapers.com.au Fri Jan 21 11:34:47 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 22 Jan 2005 00:34:47 +0800 Subject: need help on generator... In-Reply-To: <200501211654.52900.francis.girard@free.fr> References: <63b5e209.0501210558.686f5c10@posting.google.com> <1106318290.19065.11.camel@bucket.localnet> <1106320014.19065.14.camel@bucket.localnet> <200501211654.52900.francis.girard@free.fr> Message-ID: <1106325287.19065.50.camel@bucket.localnet> On Fri, 2005-01-21 at 16:54 +0100, Francis Girard wrote: > First, I think that you mean : > > consecutive_sets = [ x[offset:offset+subset_size] > for subset_size in xrange(2, len(x)) > for offset in xrange(0, len(x) + 1 - subset_size)] > > (with square brackets). > I'm just trying to understand and obviously I'm missing the point. Yep. This: ( x for x in xrange(10) ) will return a generator that calculates things as it goes, while this: [ x for x in xrange(10) ] will return a list. Check out: http://www.python.org/peps/pep-0289.html http://docs.python.org/whatsnew/node4.html http://www.python.org/dev/doc/newstyle/ref/genexpr.html for details. -- Craig Ringer From hanzspam at yahoo.com.au Thu Jan 13 11:20:39 2005 From: hanzspam at yahoo.com.au (hanz) Date: 13 Jan 2005 08:20:39 -0800 Subject: lambda In-Reply-To: References: Message-ID: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> Antoon Pardon wrote: > So if I have a call with an expression that takes more than > one line, I should assign the expression to a variable and > use the variable in the call? Yes, that's sometimes a good practice and can clarify the call. > But wait if I do that, people will tell me how bad that it > is, because it will keep a reference to the value which > will prevent the garbage collector from harvesting this > memory. Nobody will tell you that it's bad. Python was never about super performance, but about readability. Besides, using such temporaries won't consume much memory (relatively). > Besides python allows more than one statement on the same line. But it's discouraged in general. From nobody at invalid.domain Sat Jan 8 00:05:45 2005 From: nobody at invalid.domain (Dan Valentine) Date: Sat, 08 Jan 2005 05:05:45 GMT Subject: how to extract columns like awk $1 $5 References: Message-ID: <487rklcxbidr$.gwsa68us9f3a.dlg@40tude.net> On Fri, 07 Jan 2005 12:15:48 -0500, Anand S Bisen wrote: > Is there a simple way to extract words speerated by a space in python > the way i do it in awk '{print $4 $5}' . I am sure there should be some > but i dont know it. i guess it depends on how faithfully you want to reproduce awk's behavior and options. as several people have mentioned, strings have the split() method for simple tokenization, but blindly indexing into the resulting sequence can give you an out-of-range exception. out of range indexes are no problem for awk; it would just return an empty string without complaint. note that the index bases are slightly different: python sequences start with index 0, while awk's fields begin with $1. there IS a $0, but it means the entire unsplit line. the split() method accepts a separator argument, which can be used to replicate awk's -F option / FS variable. so, if you want to closely approximate awk's behavior without fear of exceptions, you could try a small function like this: def awk_it(instring,index,delimiter=" "): try: return [instring,instring.split(delimiter)[index-1]][max(0,min(1,index))] except: return "" >>> print awk_it("a b c d e",0) a b c d e >>> print awk_it("a b c d e",1) a >>> print awk_it("a b c d e",5) e >>> print awk_it("a b c d e",6) - dan From bpeng at rice.edu Sun Jan 9 16:53:45 2005 From: bpeng at rice.edu (Bo Peng) Date: Sun, 09 Jan 2005 15:53:45 -0600 Subject: compiler version mismatch when building ext_modules with MSVC Message-ID: Dear list, I was using autoconf/automake etc to build my python extension. Since distutil seems to be easier, I have switched to this method. However, when I build the module under windows, I am told that compiler version mismatch... I am using msvc 7 and python was build by msvc 6.0. I am not sure why compiler version matters here since 1. if proceed by removing corresponding lines in distutil, the generated module works fine (as far as I can tell). 2. I am told that I can use minGW gcc ... Isn't mingw differ more with msvc6 than msvc7? 3. I was using msvc7 (automake etc, not distutil) and everything was fine. I was not even warned about potential problems. Since there are many different Python out there (Official, ActivePython, Enthough), do I have to figure out which compiler they use to build my module for them? Currently, my MSVC7 built module works fine with all of them. Thanks. From paul at subsignal.org Thu Jan 27 11:23:31 2005 From: paul at subsignal.org (paul koelle) Date: Thu, 27 Jan 2005 17:23:31 +0100 Subject: Transparent (redirecting) proxy with BaseHTTPServer Message-ID: <35sfdaF4hka1hU1@individual.net> Hi list, My ultimate goal is to have a small HTTP proxy which is able to show a message specific to clients name/ip/status then handle the original request normally either by redirecting the client, or acting as a proxy. I started with a modified[1] version of TinyHTTPProxy postet by Suzuki Hisao somewhere in 2003 to this list and tried to extend it to my needs. It works quite well if I configure my client to use it, but using iptables REDIRECT feature to point the clients transparently to the proxy caused some issues. Precisely, the "self.path" member variable of baseHTTPRequestHandler is missing the and the host (i.e www.python.org) part of the request line for REDIRECTed connections: without iptables REDIRECT: self.path -> GET http://www.python.org/ftp/python/contrib/ HTTP/1.1 with REDIRECT: self.path -> GET /ftp/python/contrib/ HTTP/1.1 I asked about this on the squid mailing list and was told this is normal and I have to reconstuct the request line from the real destination IP, the URL-path and the Host header (if any). If the Host header is sent it's an (unsafe) nobrainer, but I cannot for the life of me figure out where to get the "real destination IP". Any ideas? thanks Paul [1] HTTP Debugging Proxy Modified by Xavier Defrang (http://defrang.com/) From tim.golden at viacom-outdoor.co.uk Thu Jan 20 04:26:24 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 20 Jan 2005 09:26:24 -0000 Subject: Automatic Windows printer creation? Message-ID: <9A28C052FF32734DACB0A288A35339910359D2@vogbs009.gb.vo.local> [Roger Upole] | | You can probably do it through WMI. (class is Win32_Printer) | WMI works well with win32com, and there's also a wrapper module | | http://tgolden.sc.sabren.com/python/wmi.html | | for simplified access. | I imagine getting all the device parameters and port | configuration right will be messy, though. | And here's a handy link (warning: long URL): http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/ wmi_tasks__printers_and_printing.asp (I got that by googling for Win32_Printer and then for AddPrinterConnection). But... you'd better be using XP or 2K3 because, almost comically, each of the examples is prefixed by a " does not work on Windows 2000, Windows NT, Windows 98, Windows 95". 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 bearophileHUGS at lycos.com Mon Jan 31 18:39:22 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 31 Jan 2005 15:39:22 -0800 Subject: set, dict and other structures Message-ID: <1107214762.198058.55680@f14g2000cwb.googlegroups.com> I'm frequently using Py2.4 sets, I find them quite useful, and I like them, even if they seem a little slower than dicts. Sets also need the same memory of dicts (can they be made to use less memory, not storing values? Maybe this requires too much code rewriting). I presume such sets are like this because they are kind of dicts. If this is true, then converting a dict to a set (that means converting just the keys; this is often useful for a successive processing with set operators like intersection, etc) can be a very quick operation; but this little code shows me that this isn't true, set-ify a dict is even slower than doing it on a list. Can this operation made faster (by people that writes Python interpreter)? .from time import clock .for p in xrange(16, 20): . n = 2**p . l = range(n) . t = clock() . set(l) . print n, round(clock()-t,3), . d = {}.fromkeys(xrange(n)) . t = clock() . set(d) . print round(clock()-t,3) ==> 65536 0.082 0.1 131072 0.205 0.218 262144 0.45 0.562 524288 1.014 1.029 ---------------------- Dicts and sets are two different data structures, but they share some similarities. So instead of always converting dicts to sets, maybe some fast set-like operations/methods can be added to dicts, like intersection, mass removal, etc. (The result of *some* of such operations between two dicts can be a regular set, and not a dict. This is maybe not very "clear" from an formal/theoretical point of view). ------------- I've studied the nice sets python module from Py2.3, and I am... well... writing something similar, a (python) graph module for sparse graphs. I've found 3 modules like that around on the Net, but I think they can be improved (even if I'm not an expert of Python, and I know, my code is probably quite rough/naive compared to "sets" module one...) Graphs are complex data structures, so probably one person needs from a graph data structure are different from other people needs, so it's probably not easy to define a "standard" graph module fit for everyone. Still, I think it can be useful to have a standard module to manage them. Do you think it be useful to add a (well made) standard module like that? Bear hugs, Bearophile From g.tagliarettiNO at SPAMparafernalia.org Sat Jan 22 08:04:19 2005 From: g.tagliarettiNO at SPAMparafernalia.org (Gian Mario Tagliaretti) Date: Sat, 22 Jan 2005 14:04:19 +0100 Subject: [perl-python] 20050121 file reading & writing References: <1106395060.211314.54530@f14g2000cwb.googlegroups.com> Message-ID: <35f1akF4n2t5mU1@individual.net> Xah Lee wrote: > # the second argument of open can be > # 'w' for write (overwrite exsiting file) > # 'a' for append (ditto) > # 'r' or read only are you sure you didn't forget something? > # reading the one line > # line = f.realine() wrong > [...] Maybe you didn't get the fact the you won't see a flame starting between python people and perl friends? throw yourself somewhere and... Xah.flush() -- Gian Mario Tagliaretti PyGTK GUI programming http://www.parafernalia.org/pygtk/ From timj at tolisgroup.com Mon Jan 17 14:10:47 2005 From: timj at tolisgroup.com (brucoder) Date: 17 Jan 2005 11:10:47 -0800 Subject: Adjusting the 1024 byte stdin buffer limit Message-ID: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> Are there runtime settings that can be used to adjust the default 1024 byte stdin buffer limit or a buildtime setting in pyconfig.h? I have a need to pump this up to permit input of a large data block via stdin. Tim Jones From ncoghlan at iinet.net.au Fri Jan 7 12:55:24 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 03:55:24 +1000 Subject: Developing Commercial Applications in Python In-Reply-To: <41DD5B0B.6070901@comcast.net> References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> <87pt0iegga.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <41DD5B0B.6070901@comcast.net> Message-ID: <41DECD0C.8010504@iinet.net.au> Stephen Waterbury wrote: > A notable example is Verity's search engine -- see > http://python.oreilly.com/news/PythonSS.pdf Not to mention the kind words of the current reigning king of the search engine world. . . Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From EP at zomething.com Mon Jan 31 02:19:13 2005 From: EP at zomething.com (EP) Date: Sun, 30 Jan 2005 23:19:13 -0800 Subject: variable declaration In-Reply-To: References: Message-ID: <20050130231913.1213891237.EP@zomething.com> > ------------Original Message------------ > From: Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org (Alexander Zatvornitskiy) > > 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! Hmmm. I am surely an expert in writing buggy code, but I can not say I make this error in Python. Why is that? I'm not sure, but a couple things that may help me miss making this mistake in practice may be (somewhat informal in my case) unit testing - I test for correct results for at least a few cases. It may also help that with Python I can code at a somewhat higher conceptual level, or maybe it is just the syntax that helps avoid these problems: >>> for epsilon in range (0,10): S=S+epsilon >>> for epsilon in range (0,10): S=S+epselon Traceback (most recent call last): File "", line 2, in ? S=S+epselon NameError: name 'epselon' is not defined It may seem like jumping off a cliff, but the improvement in readability (the variable declarations being visual clutter) makes it much easier for me to see my code, and any typos in it. It seems it would be simple enough to have one's code, or another script, automatically print out a sorted list of the variables - which would make the error you note obvious. But I haven't needed this, yet at least. You might like Python and find the lack of variable declaration checking not a problem. It's worth a shot. From kartic.krishnamurthy at gmail.com Wed Jan 5 10:37:59 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 07:37:59 -0800 Subject: Image capture In-Reply-To: References: Message-ID: <1104939479.011181.147650@f14g2000cwb.googlegroups.com> Catalin, Some explanation about what you are tring to do will be of immense help. Did you want to capture some other Windows object from Python or do you want to capture a Python GUI application from Python? I might be able to help out, but please send more details. Thank you, --Kartic From klachemin at comcast.net Sat Jan 22 01:05:34 2005 From: klachemin at comcast.net (Kamilche) Date: 21 Jan 2005 22:05:34 -0800 Subject: Reload Tricks In-Reply-To: References: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> Message-ID: <1106373934.652297.59210@z14g2000cwz.googlegroups.com> That's a powerful advantage - not having to track class instances. Thanks for the tip! I just got done doing it 'my way' though, now I'll have to change it. It took me all day! :-D From paul.kooistra at leaseplan.nl Mon Jan 31 18:32:59 2005 From: paul.kooistra at leaseplan.nl (Paul Kooistra) Date: Tue, 1 Feb 2005 00:32:59 +0100 Subject: Browsing text ; Python the right tool? References: <10vdpohm549g44a@corp.supernews.com> <1106707324.874852.208520@z14g2000cwz.googlegroups.com> <10vfqra5knegoa3@corp.supernews.com> <1106783975.472873.21420@z14g2000cwz.googlegroups.com> <10vgerafeom164b@corp.supernews.com> Message-ID: <41fec02f$0$28993$e4fe514c@news.xs4all.nl> Sorry to reply this late guys - I cannot access news from Work, and Google Groups cannot reply to a message so I had to do it at home. Let me address a few of the remarks and questions you guys asked: First of all, the example I gave was just that - an example. Yes, I know Python starts with 0, and I know that you cannot fit a 4-digit number in 2 positions, this was just to give the idea. To clarify, at THIS moment I need to browse 1-80 Mb size tekstfiles. At this moment, I have 16 different record definitions, numbered A,B, C1-C8, D-H. Each record definition has 20-60 different attributes. Not only that, but these formats change regularly; and I want to create or use something I can use on *other* applications or sites as well. As I said, I have encountered the type of problem I've described in numberous places already. > John wrote: > I have a Python script that takes layout info and an input file and can > produce an output file in one of two formats: Yes John, I was thinking along these lines myself. The problem is that I have to parse several of these large files each day (debugging) and browsing converted output seems just to tedious and inefficient. I would REALLY like a GIU, and preferable something portable I can re-use later on. > This should be pretty easy. If each record is CRLF terminated, then you > can get one record at a time simply by iterating over the file ("for line > in open('myfile.dat'): ..."). Jeff, this was indeed the way I was thinking. But instead of iterating I need the ability to browse forward and backward. > You can have a dictionary of classes or factory functions, one for each > record type, keyed off of the 2-character identifier. Each class/factory > would know the layout of that record type, and return a(n) > instance/dictionary with fields separated out into attributes/items. This is of course a clean approach, but would mean re-coding every time a records is changed - frequently! I really would like to edit only a data definition file. > The trickiest part would be in displaying the data; you could potentially > use COM to insert it into a Word or Excel document, or code your own GUI > in Python. The former would be pretty easy if you're happy with fairly > simple formatting; the latter would require a bit more effort, but if you > used one of Python's RAD tools (Boa Constructor, or maybe PythonCard, as > examples) you'd be able to get very nice results. I will at least look into Boa and PythonCard. Thanks for the hint. > This is plausible only under the condition that Santa Claus is paying > you $X per class/factory or per line of code, or you are so speed-crazy > that you are machine-generating C code for the factories. Unfortunately, neither is the case :) > I'd suggest "data driven" Yeah! > Then you need a function to load this layout file into dictionaries, > and build cross-references field_name -> field_number (0,1,2,...) and > vice versa. > As your record name is not in a fixed position in the record, you will > also need to supply a function (file_type, record_string) -> > record_name. I thought about supplying a flat ASCII definition such as: [record type] [fieldname] [start] [end] > Then you have *ONE* function that takes a file_type, a record_name, and > a record_string, and gives you a list of the values. That is all you > need for a generic browser application. I like this. > You *don't* have to hand-craft a class for each record type. And you > wouldn't want to, if you were dealing with files whose spec keeps on > having fields added and fields obsoleted. Exactly. > I think that's overly pessimistic. I *was* presuming a case where the > number of record types was fairly small, and the definitions of those > records reasonably constant. For ~10 or fewer types whose spec doesn't > change, hand-coding the conversion would probably be quicker and/or more > straightforward than writing a spec-parser as you suggest. Unfortunately, all wrong :) Lots of records, lots of changes, lots of different record types - hardcoding doesnt seem the right way. > "Parse"? No parsing, and not much code at all: The routine to "load" > (not "parse") the layout from the layout.csv file into dicts of dicts > is only 35 lines of Python code. The routine to take an input line and > serve up an object instance is about the same. It does more than the > OP's browsing requirement already. The routine to take an object and > serve up a correctly formatted output line is only 50 lines of which > 1/4 is comment or blank. John,do you have suggestions where I can find examples of these functions? I can program, but not being proficient in Python, any help or examples I can adapt would be nice > Also, files used to "create printed pages by > an external company" (especially by a company that had "leaseplan" in > its e-mail address) would indicate "many" and "complicated" to me. How right you are. Think about production runs of 150.000 invoices, each invoice consisting of 2-10 records, and you are on the right track. > I suspect > that we're both assuming a case similar to our own personal > experiences, which are different enough to lead to different > preferred solutions. ;) Seconded. > My personal experiences and attitudes: (1) extreme aversion to having > to type (correctly) lots of numbers (column positions and lengths), and > to having to mentally translate start = 663, len = 13 to [662:675] or > having ugliness like [663-1:663+13-1] (2) cases like 17 record types > and 112 fields in one file, 8 record types and 86 fields in a second -- > this being a new relatively clean simple exercise in exchanging files > with a government department (3) Past history of this govt dept is that >there are at least another 7 file types in regular use and they change > the _major_ version number of each file type about once a year on >average (3) These things tend to start out deceptively small and simple >and turn into monsters. Our experiences are remarkably similair... Cheers, Paul From Serge.Orlov at gmail.com Tue Jan 11 08:49:32 2005 From: Serge.Orlov at gmail.com (Serge.Orlov at gmail.com) Date: 11 Jan 2005 05:49:32 -0800 Subject: Locale confusion In-Reply-To: References: Message-ID: <1105451372.655977.165250@f14g2000cwb.googlegroups.com> Jorgen Grahn wrote: [snip] > > frailea> cat foo > import locale > print locale.getlocale() > locale.setlocale(locale.LC_CTYPE) > print locale.getlocale() > > When I paste it into an interactive Python session, the locale is already > set up correctly (which is what I suppose interactive mode /should/ do): > > >>> import locale > >>> print locale.getlocale() > ['sv_SE', 'ISO8859-1'] > >>> locale.setlocale(locale.LC_CTYPE) > 'sv_SE' > >>> print locale.getlocale() > ['sv_SE', 'ISO8859-1'] > >>> > > When I run it as a script it isn't though, and the setlocale() call does not > appear to fall back to looking at $LANG as it's supposed to(?), so my > LC_CTYPE remains in the POSIX locale: > > frailea> python foo > (None, None) > (None, None) > > The corresponding program written in C works as expected: > > frailea> cat foot.c > #include > #include > int main(void) { > printf("%s\n", setlocale(LC_CTYPE, 0)); > printf("%s\n", setlocale(LC_CTYPE, "")); > printf("%s\n", setlocale(LC_CTYPE, 0)); > return 0; > } > frailea> ./foot > C > sv_SE > sv_SE > > So, is this my fault or Python's? I realize I could just adapt and set > $LC_CTYPE explicitly in my environment, but I don't want to capitulate for a > Python bug, if that's what this is. Try locale.setlocale(locale.LC_CTYPE,"") as in your C program. It would be great if locale.setlocale with one parameter would be deprecated, because it suddenly acts like getlocale. It's unpythonic. By the way, since you took time to setup various LC_* variables there is no need to play with LC_CTYPE category. Just use the standard idiom. import locale locale.setlocale(LC_ALL,"") Serge. From steve at holdenweb.com Mon Jan 31 07:40:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 07:40:40 -0500 Subject: The next Xah-lee post contest In-Reply-To: <1107137465.973491.42050@f14g2000cwb.googlegroups.com> References: <20050130114008.797088857.whereU@now.com> <1107137465.973491.42050@f14g2000cwb.googlegroups.com> Message-ID: gene.tani at gmail.com wrote: > Tragi-comic. really. BTW you forgot cross-post to c.l.scheme, C, > smalltalk and C++ > Would there, I wonder, be any enthusiasm for a "Best Xah Lee impression" prize at PyCon? 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 samantha7395 at hotmail.com Thu Jan 20 14:41:24 2005 From: samantha7395 at hotmail.com (Samantha) Date: Thu, 20 Jan 2005 11:41:24 -0800 Subject: Print to Windows default Printer References: <41efd18e$1@nntp0.pdx.net> Message-ID: Thanks Scott, Not wasting any paper yet. I can't seem to get the file to print at all yet. S "Scott David Daniels" wrote in message news:41efd18e$1 at nntp0.pdx.net... > Tim Golden wrote: >> [Samantha] >> | I am new to Python and I am having considerable trouble | trying to >> print | (using a simple script) to the default printer rather than the >> screen. >> | Thanks for any help. >> | S It may be that something here will help you: >> >> http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html >> >> Specifically, I think that the section print raw text is >> closest to what you're asking (although not necessarily >> to what you'll eventually want): >> >> http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html#win32print >> > You might be interested in using PDFCreator to save paper during > your tests. It is a windows printer driver that creates a PDF file: > > http://sourceforge.net/projects/pdfcreator/ > > --Scott David Daniels > Scott.Daniels at Acm.Org From http Mon Jan 10 06:36:14 2005 From: http (Paul Rubin) Date: 10 Jan 2005 03:36:14 -0800 Subject: Port blocking References: <34f6sgF4asjm7U1@individual.net> Message-ID: <7x3bx9sehd.fsf@ruckus.brouhaha.com> Mark Carter writes: > Supposing I decide to write a server-side application using something > like corba or pyro. > > What's the chance that in big corporations, the client's ports (in > both senses of the word: fee-paying, and application) will be blocked, > thereby immediately scuppering whatever I have written? Has this > problem ever arisen for anyone? Usually you wouldn't run a public corba or pyro service over the internet. You'd use something like XMLRPC over HTTP port 80 partly for the precise purpose of not getting blocked by firewalls. > Also, is there a good tool for writing database UIs? Yes, quite a few. From ncoghlan at iinet.net.au Wed Jan 19 08:53:28 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 19 Jan 2005 23:53:28 +1000 Subject: delay and force in Python In-Reply-To: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Message-ID: <41EE6658.8000409@iinet.net.au> Will Stuyvesant wrote: > The program below creates a stream with the numbers 1..995 > and then filters the stream, keeping only the even numbers, > and then prints the second number in the stream (implemented > as the first number of the tail, just like in the 3.5 > Section in the Wizard book). How's this: Py> from itertools import islice Py> print islice((x for x in xrange(1, 996) if x % 2 == 0), 1, 2).next() 4 Breaking it into pieces: Py> from itertools import islice Py> stream = (x for x in xrange(1, 996) if x % 2 == 0) Py> second_item = islice(stream, 1, 2).next() Py> print second_item 4 And most of the stream hasn't been consumed yet: Py> print stream.next() 6 Py> unconsumed = list(stream) Py> len(unconsumed) 494 And this version has no problem with recursion limits: Py> print islice((x for x in xrange(1, sys.maxint) if x % 2 == 0), 1, 2).next() 4 (xrange can't handle Python longs, unfortunately, so we *are* constrained by sys.maxint. However, since my machine only has half a gig of RAM, the above is still a damn sight quicker than the equivalent list comprehension would be!) > Something else: this crashes with a "maximum recursion reached" > . print stream_enumerate_interval(1,998) > > while this does not crash > . print stream_enumerate_interval(1,900) > this means Python has a maximum of something like 900 > recursions? The CPython implementation is limited by the stack size allocated by the C runtime library. The exact recursion limit is platform dependent, but something around 1000 sounds fairly normal. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tchur at optushome.com.au Sat Jan 1 23:02:33 2005 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 02 Jan 2005 15:02:33 +1100 Subject: Frameworks for "Non-Content Oriented Web Apps" In-Reply-To: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <41D77259.30004@optushome.com.au> mirnazim at gmail.com wrote: > Hi, > > There are great Python Web Application Framework. But most of them are > meant for content oriented web apps. > > Is there something that can ease the development of application that > are not content oriented(I call them "NON CONTENT-ORIENTED WEB > APPLICATIONS" because I don't know what else to call them). I mean the > applications like, accounting, high volume data entry apps, where > normally GUI clients have ruled. I know very high quality ERP and > similar packages have been implemented in a web based environment. But > problem is that they have been developed with the tools that were > actually meant for content oriented apps like Zope, PHP, etc. Can you give some URL for publicly accessible examples of what you mean by a "NON CONTENT-ORIENTED WEB APPLICATIONS", so we can get a better idea of what you mean? Tim C From michael.bierenfeld at web.de Fri Jan 21 09:43:27 2005 From: michael.bierenfeld at web.de (michael) Date: 21 Jan 2005 06:43:27 -0800 Subject: Dynamic properties Message-ID: Hello again, I have a dictionary with the following content : 'LZ': {'type': 'N', 'bytes': '00008'}, 'LVI000': {'type': 'N', 'bytes': '000010'} This could be seen as a interface description to deal with an external program that needs a 18 Byte communication area. 8 and 18 Bytes have to be interpreted as a "Number" String representation. eg like '00000180000000200' means LZ = 180 and LVI000 = 200 I am now thinking about doing the following class a .... def some_crap () ... for key in dict.keys (): setattr (self, key, value) so that pgm = a () pgm.LZ = 300 would cause the rekonstruktion of the byte field. ===>> Properties My first try is : fget = lambda self: mygetattr(self, attrname) fset = lambda self, value: mysetattr (self, attrname, value) fdel = lambda self: mydelattr(self, attrname) # fget, fset, fdel are used to reconstruct the byte field setattr (self, key, property (fget, fset, fdel)) :-) This inserts me pgm.LZ and pgm.LVI000 but when trying to access print pgm.LZ it gives me What am I doing wrong here Regards Michael From ajikoe at gmail.com Mon Jan 31 12:55:02 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 31 Jan 2005 09:55:02 -0800 Subject: stop program in komodo Message-ID: <1107194102.482439.272480@c13g2000cwb.googlegroups.com> Hello, How can we stop this peace of code in KOMODO: while 1: print "helo" I can't stop it, even using Ctrl+C pujo From jstroud at mbi.ucla.edu Wed Jan 12 18:24:26 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 12 Jan 2005 15:24:26 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <41E5097F.2070109@pcblokes.com> References: <41E5097F.2070109@pcblokes.com> Message-ID: <1105572266.26934.25.camel@lipscomb.mbi.ucla.edu> Don't fight it, lite it! You should parse the fasta and put it into a database: http://www.sqlite.org/index.html Then index by name and it will be superfast. James From JiggaHertz at nospam.com Fri Jan 7 13:07:19 2005 From: JiggaHertz at nospam.com (JiggaHertz) Date: Fri, 07 Jan 2005 13:07:19 -0500 Subject: pygtk swallowing external app Message-ID: I am trying to write a gui with pygtk that swallows an external application. I've tried the plug/sockets example in the documentation modifying the plug to be an xterm. However, the xterm isn't swallowed by the python script. I have seen some c code which accomplishes this via an X reparent call. I was wondering how I would implement this with pygtk? From donn at drizzle.com Fri Jan 21 00:37:37 2005 From: donn at drizzle.com (Donn Cave) Date: 20 Jan 2005 23:37:37 -0600 Subject: spawn syntax + os.P_WAIT mode behavior + spawn stdout redirection References: Message-ID: <41f09521$1_1@127.0.0.1> Quoth Derek Basch : | *First question* | | If the syntax of spawnl is: | | spawnl(mode, path, ...) | | Why does everyone write it like: | | os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') | | or: | | os.spawnl(os.P_WAIT, "/var/www/db/smm/smm_train", "smm_train", | "SMMTrainInput.xml") | | How is the first 'cp' a path to a file? As you may have guessed, 'cp' doesn't have to be a path because the spawnlp() variant finds that file among a list of directories in PATH. | why does the desired executable have to be named again as the first parameter? Because you're supplying the "argv" argument list, which for normal programs (i.e., not written in Python) includes argv[0] as specified by the invoker. This would be more obvious if you consider the spawnv() function, where these arguments are supplied as a list. You can look at the implementation in os.py for more insight into how all this works, particularly see the execve(2) function that is at the bottom of all this. I was recently quite cheesed to find that the Haskell "executeFile" function supplies its own argv[0], depriving the caller of the occasionally useful opportunity to set this value. Python system interface functions are generally pretty good about not watering down functionality. | *Second question* | | I have a script test.py which calls another script sleep.py using a spawn. | | -------------------------------------------------------------- | #test.py | import os | | os.spawnv(os.P_WAIT, "/var/www/db/cgi-bin/sleep.py", ["python", "sleep.py"]) | #pid = os.spawnl(os.P_WAIT, 'sh', 'sh', '-cv', 'sleep 10; echo fark > | /tmp/test.out') | -------------------------------------------------------------- | | -------------------------------------------------------------- | #sleep.py | import time | | time.sleep(10) | -------------------------------------------------------------- | | I would expect that the test.py script should take 10sec to return. However it | returns immediatly. Perhaps I am calling the sleep.py script incorrectly? | Shouldn't it take 10sec to execute since the spawn mode argument is os.P_WAIT? Might want to verify that it's really executing. I suspect it isn't, since your parameters are wrong (the file to invoke is python, not sleep.py.) If you're writing anything important, you need to do what you can to verify that the commands you're executing are actually successful. | *Third question* | | If I uncomment the second spawn call in test.py I do not get any output to | /tmp/test.out and it also returns immediatly. Can anyone tell me why? Might be a problem finding 'sh', since in this case you call spawnl(), not spawnlp(). Just a guess. Also you ought to know that the return from os.spawnl(os.P_WAIT, ...) will not be a pid, rather a status that carries a little (very little) information about the problem. Donn Cave, donn at drizzle.com From craig at postnewspapers.com.au Fri Jan 7 00:17:31 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 07 Jan 2005 13:17:31 +0800 Subject: Embedding a restricted python interpreter In-Reply-To: References: <41db7e8f$1@news.unimelb.edu.au> Message-ID: <1105075050.28776.43.camel@rasputin.localnet> On Thu, 2005-01-06 at 23:05, Peter Maas wrote: > Craig Ringer schrieb: > It would certainly be difficult to track all harmful code constructs. > But AFAIK the idea of a sandbox is not to look at the offending code > but to protect the offended objects: files, databases, URLs, sockets > etc. and to raise a security exception when some code tries to offend > them. That's a good point. I'm not sure it's really all that different in the end though, because in order to control access to those resources you have to restrict what the program can do. It'd probably be valid to implement a restricted mode at CPython level (in my still-quite-new-to-the-Python/C-API view) by checking at the "exit points" for important resources such as files, etc. I guess that's getting into talk of something like the Java sandbox, though - something Java proved is far from trivial to implement. Of course, CPython is just a /tad/ smaller than Java ;-) . Personally, I'd be worried about the amount of time it'd take and the difficulty of getting it right. One wouldn't want to impart a false sense of security. My original point, though, was that I don't think you can use the standard interpreter to create a restricted environment that will be both useful and even vaguely secure. I'd be absolutely delighted if someone could prove me wrong. > Python is a very well designed language but progress is made by > criticism not by satisfaction ;) Heh, I'm hardly complacent... I run into quite enough problems, especially with embedding and with the C API. Maybe one day I'll have the knowledge - and the time - to have a chance at tackling them. I'd love a restricted mode - it'd be great. I'm just not very optimistic about its practicality. -- Craig Ringer From invalidemail at aerojockey.com Sat Jan 8 18:55:49 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 8 Jan 2005 15:55:49 -0800 Subject: python3: 'where' keyword In-Reply-To: References: <3480qqF46jprlU1@individual.net> Message-ID: <1105228549.608275.148740@c13g2000cwb.googlegroups.com> Peter Hansen wrote: > Andrey Tatarinov wrote: > > >>> print words[3], words[5] where: > > >>> words = input.split() > > > > - defining variables in "where" block would restrict their visibility to > > one expression > > Then your example above doesn't work... print takes a > sequence of expressions, not a tuple as you seem to think. You misunderstand. There "where" is not part of the expression but the statement. The above example would be a modified print statement, a print...where statement, if you will. Under this suggestion, there would be modified versions of various simple statements. This wouldn't be a problem parsing, of course, because "where" would be a keyword. -- CARL BANKS From steve at holdenweb.com Fri Jan 28 13:24:03 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Jan 2005 13:24:03 -0500 Subject: [PyCon] Reg: Registration In-Reply-To: <20050128182019.GB19054@panix.com> References: <3e475f5b0501280929717ce3b3@mail.gmail.com> <20050128182019.GB19054@panix.com> Message-ID: <41FA8343.8020007@holdenweb.com> Aahz, writing as pycon at python.org, wrote: > It's still January 28 here -- register now! I don't know if we'll be > able to extend the registration price beyond that. Just in case anybody else might be wondering when the early bird registration deadline is, I've asked the registration team to allow the early bird price as long as it's January 28th somewhere in the world. There have been rumors that Guido will not be attending PyCon this year. I am happy to scotch them by pointing out that Guido van Rossum's keynote address will be on its traditional Thursday morning. I look forward to joining you all to hear Guido speak on "The State of Python". 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 paritosh.mahana at gmail.com Mon Jan 24 14:05:04 2005 From: paritosh.mahana at gmail.com (paritosh mahana) Date: Tue, 25 Jan 2005 00:35:04 +0530 Subject: how to call python code from C# Message-ID: <15a90b2705012411051c4b36a6@mail.gmail.com> Hi all, How can I call python code from my C# code. One thing is to make an .exe file of the python program and then try to call it from my C# code. But I don't like that idea. Is there any other way to do this. Like making a .dll file from the python code and somehow call it from C# program.But I couldn't find anything on this topic on the net. Actually my GUI is in C# and rest part is in python, and i need to call python from my C# program. Please correct me if I am wrong anywhere. thanks paritosh. From mmokrejs at ribosome.natur.cuni.cz Mon Jan 17 07:32:27 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?windows-1252?Q?Martin_MOKREJ=8A?=) Date: Mon, 17 Jan 2005 13:32:27 +0100 Subject: Writing huge Sets() to disk In-Reply-To: References: Message-ID: <41EBB05B.8000108@ribosome.natur.cuni.cz> Duncan Booth wrote: > Martin MOKREJ? wrote: > > >>Hi, >> could someone tell me what all does and what all doesn't copy >>references in python. I have found my script after reaching some >>state and taking say 600MB, pushes it's internal dictionaries >>to hard disk. The for loop consumes another 300MB (as gathered >>by vmstat) to push the data to dictionaries, then releases >>little bit less than 300MB and the program start to fill-up >>again it's internal dictionaries, when "full" will do the >>flush again ... > > > Almost anything you do copies references. But what does this?: x = 'xxxxx' a = x[2:] b = z + len(x) dict[a] = b >> The point here is, that this code takes a lot of extra memory. >>I believe it's the references problem, and I remeber complains >>of frineds facing same problem. I'm a newbie, yes, but don't >>have this problem with Perl. OK, I want to improve my Pyhton >>knowledge ... :-)) >> >> >> >> > > > >> >> The above routine doesn't release of the memory back when it >>exits. > > That's probably because there isn't any memory it can reasonable be > expected to release. What memory would *you* expect it to release? Thos 300MB, they get allocated/reserved when the posted loop get's executed. When the loops exits, almost all is returned/deallocated. Yes, almost. :( > > The member variables are all still accessible as member variables until you > run your loop at the end to clear them, so no way could Python release > them. OK, I wanted to know if there's some assignment using a reference, which makes the internal garbage collector not to recycle the memory, as, for example, the target dictionary still keeps reference to the temporary dictionary. > > Some hints: > > When posting code, try to post complete examples which actually work. I > don't know what type the self._dict_on_diskXX variables are supposed to be. > It makes a big difference if they are dictionaries (so you are trying to > hold everything in memory at one time) or shelve.Shelf objects which would > store the values on disc in a reasonably efficient manner. The self._dict_on_diskXX are bsddb files, self._tmpdictXX are builtin dictionaries. > > Even if they are Shelf objects, I see no reason here why you have to I gathered from previous discussion it's faster to use bsddb directly, so no shelve. > process everything at once. Write a simple function which processes one > tmpdict object into one dict_on_disk object and then closes the That's what I do, but in the for loop ... > dict_on_disk object. If you want to compare results later then do that by OK, I got your point. > reopening the dict_on_disk objects when you have deleted all the tmpdicts. That's what I do (not shown). > > Extract out everything you want to do into a class which has at most one > tmpdict and one dict_on_disk That way your code will be a lot easier to > read. > > Make your code more legible by using fewer underscores. > > What on earth is the point of an explicit call to __add__? If Guido had > meant us to use __add__ he woudn't have created '+'. To invoke additon directly on the object. It's faster than letting python to figure out that I sum up int() plus int(). It definitely has helped a lot when using Decimal(a) + Decimal(b), where I got rid of thousands of Decimal(__new__), __init__ and I think few other methods of decimal as well - I think getcontext too. > What is the purpose of dict_on_disk? Is it for humans to read the data? If > not, then don't store everything as a string. Far better to just store a For humans is processed later. > tuple of your values then you don't have to use split or cast the strings bsddb creaps on me that I can store as a key or value only a string. I'd love to store tuple. >>> import bsddb >>> _words1 = bsddb.btopen('db1.db', 'c') >>> _words1['a'] = 1 Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/bsddb/__init__.py", line 120, in __setitem__ self.db[key] = value TypeError: Key and Data values must be of type string or None. >>> How can I record a number then? > to integers. If you do want humans to read some final output then produce > that separately from the working data files. > > You split out 4 values from dict_on_disk and set three of them to 0. If > that really what you meant or should you be preserving the previous values? No, overwrite them, i.e. invalidate them. Originally I recorded only first, but to compute the latter numbers is so expensive I have to store them. As walking through the dictionaries is so slow, I gave up on an idea to store just one, and a lot later in the program walk once again through the dictionary and 'fix' it by computing missing values. > > Here is some (untested) code which might help you: > > import shelve Why shelve? To have the ability to record tuple? Isn't it cheaper to convert to string and back and write to bsddb compared to this overhead? > > def push_to_disc(data, filename): > database = shelve.open(filename) > try: > for key in data: > if database.has_key(key): > count, a, b, expected = database[key] > database[key] = count+data[key], a, b, expected > else: > database[key] = data[key], 0, 0, 0 > finally: > database.close() > > data.clear() > > Call that once for each input dictionary and your data will be written out > to a disc file and the internal dictionary cleared without any great spike > of memory use. Can I use the mmap() feature on bsddb or any .db file? Most of the time I do updates, not inserts! I don't want to rewrite all the time 300MB file. I want to update it. What I do need for it? Know the maximal length of a string value keept in the .db file? Can I get rid of locking support in those huge files? Definitely I can improve my algorithm. But I believe I'll always have to work with those huge files. Martin From bokr at oz.net Wed Jan 12 23:13:11 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 04:13:11 GMT Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: <41e5ebee.709560864@news.oz.net> On 12 Jan 2005 14:46:07 -0800, "Chris Lasher" wrote: >Hello, >I have a rather large (100+ MB) FASTA file from which I need to >access records in a random order. The FASTA format is a standard format >for storing molecular biological sequences. Each record contains a >header line for describing the sequence that begins with a '>' >(right-angle bracket) followed by lines that contain the actual >sequence data. Three example FASTA records are below: > Others have probably solved your basic problem, or pointed the way. I'm just curious. Given that the information content is 2 bits per character that is taking up 8 bits of storage, there must be a good reason for storing and/or transmitting them this way? I.e., it it easy to think up a count-prefixed compressed format packing 4:1 in subsequent data bytes (except for the last byte which have less than 4 2-bit codes). I'm wondering how the data is actually used once records are retrieved. (but I'm too lazy to explore the biopython.org link). >>CW127_A01 >TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG >TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA >GCATTAAACAT >>CW127_A02 >TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG >TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA >GCATTAAACATTCCGCCTGGGGAGTACGGTCGCAAGATTAAAACTCAAAGGAATAGACGG >>CW127_A03 >TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG >TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA >GCATTAAACATTCCGCCTGGG >... Regards, Bengt Richter From antbyte.The.Flow at gmail.com Thu Jan 27 20:20:59 2005 From: antbyte.The.Flow at gmail.com (The Flow) Date: 27 Jan 2005 17:20:59 -0800 Subject: [perl-python] 20050127 traverse a dir In-Reply-To: References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> Message-ID: <1106875259.426213.252030@z14g2000cwz.googlegroups.com> Xah Lee, Do you want to be taken seriously? First, stop posting. Second, learn perl. Third, learn python. From jeff at ccvcorp.com Mon Jan 24 20:55:58 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 24 Jan 2005 17:55:58 -0800 Subject: is this use of lists normal? In-Reply-To: References: Message-ID: <10vb9e045d73v6b@corp.supernews.com> Gabriel B. wrote: > My object model ended up as > > DataStorageObj > |-itemsIndex (list, could very well be a set...) > | |-[0] = 0 > | |-[1] = 1 > | |-[2] = 5 > | '-[3] = 6 > '-Items (list) > |-[0] = ['cat food', '12,20'] > |-[1] = ['dog food', 8,00'] > |-[2] = ['dead parrot', '25,00'] > '-[3] = ['friendly white bunny', '12,25'] > > the list itemsindex has the DB index of the data, and the list items > has the data. > So if i want something like "SELECT * FROM items WHERE idx=5" i'd use > in my program > self.items[ self.itemsIndex.index(5) ] > i reccon that's not much nice to use when you're gona do /inserts/ but > my program will just read the entire data and never change it. > > Was i better with dictionaries? the tutorial didn't gave me a good > impression on them for custom data... > Tupples? the tutorial mentions one of it's uses 'employee records from > a database' but unfortunatly don't go for it... Yes, I think you'd be better off using dictionaries here. You can spare yourself a level of indirection. Tuples would be a good way to store the individual items -- instead of a list containing a name and a price (or so I presume), you'd use a tuple. Your data storage would then be a dictionary of tuples -- self.items = { 0: ('cat food', '12,20'), 1: ('dog food', '8,00'), 5: ('dead parrot', '25,00'), 6: ('friendly white bunny', '12,25') } Then your SELECT above would translate to my_item = self.items[5] and my_item would then contain the tuple ('dead parrot', '25,00'). Note that the most important difference between tuples and lists, for this example, is conceptual. Tuples generally express "this is a collection of different things that are a conceptual group", whereas lists express "this is a series of similar objects". > i think the 'ideal' data model should be something like > ({'id': 0, 'desc': 'dog food', 'price': '12,20'}, ...) > But i have no idea how i'd find some item by the ID within it withouy > using some loops You could use a dictionary for each item, as you show, and then store all of those in a master dictionary keyed by id -- in other words, simply replace the tuples in my previous example with a dict like what you've got here. You could also create a simple class to hold each item, rather than using small dicts. (You'd probably still want to store class instances in a master dict keyed by id.) Generally, any time your problem is to use one piece of information to retrieve another piece (or set) of information, dictionaries are very likely to be the best approach. Jeff Shannon Technician/Programmer Credit International From fuzzyman at gmail.com Tue Jan 25 04:29:31 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2005 01:29:31 -0800 Subject: how to ncurses on win32 platform In-Reply-To: References: Message-ID: <1106645371.925189.3740@z14g2000cwz.googlegroups.com> Tim Golden wrote: > [Jorgen Grahn] > | [Alan Gauld ] > | > You can use ncurses via cygwin. > | > There are DOS ports too but I couldn't get any of them to > | > work on my XP box, YMMV... > | > | Or, as Alex Martelli wrote in "Python in a nutshell": > | > | "The curses package works only on Unix-like platforms > | (there are persis- > | tent rumors of Windows ports of it, but I've never found a > | working one)." > > This is the only one I've seen which claims > (at least partial) compatibility. I've looked > it over, but never had a chance to try it out: > > http://flangy.com/dev/python/curses/ > > TJG It's a shame there isn't (as far as I can see) a source distribution, or a 2.4 binary. It works very well for the parts implemented. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > > ________________________________________________________________________ > 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 steven.bethard at gmail.com Wed Jan 12 15:19:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 13:19:17 -0700 Subject: counting items In-Reply-To: <1105559439.538736.87370@z14g2000cwz.googlegroups.com> References: <1105559439.538736.87370@z14g2000cwz.googlegroups.com> Message-ID: Michael Hartl wrote: > (Once you can iterate over an arbitrary sequence, the > flattened version is just > [element for element in walk(sequence)].) Or, better yet: list(walk(sequence)) Steve From jeff at ccvcorp.com Tue Jan 18 18:52:41 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 18 Jan 2005 15:52:41 -0800 Subject: Assigning to self In-Reply-To: References: <10uo6hbn040qt24@news.supernews.com> Message-ID: <10ur80gf6utag00@corp.supernews.com> Marc 'BlackJack' Rintsch wrote: > Frans Englich wrote: > >>Then I have some vague, general questions which perhaps someone can reason >>from: what is then the preferred methods for solving problems which requires >>Singletons? > > As already mentioned it's similar to a global variable. If I need a > "Singleton" I just put it as global into a module. Either initialize it > at module level or define a function with the content of your __init__(). If one is determined to both use a Singleton and avoid having a plain module-global variable, one could (ab)use function default parameters: class __Foo: "I am a singleton!" pass def Foo(foo_obj = __Foo()): assert isinstance(foo_obj, __Foo return foo_obj Of course, this suffers from the weakness that one might pass an object as an argument to the factory function and thus temporarily override the Singleton-ness of __Foo... but a determined programmer will work around any sort of protection scheme anyhow. ;) In general, ISTM that if one wants a Singleton, it's best to create it via a factory function (even if that function then masquerades as a class). This gives you pretty good control over the circumstances in which your Singleton will be created and/or retrieved, and it also makes it trivial to replace the Singleton with some other pattern (such as, e.g., a Flyweight or Borg object) should the need to refactor arise. Jeff Shannon Technician/Programmer Credit International From pythongnome at hotmail.com Tue Jan 11 20:33:53 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 12 Jan 2005 01:33:53 GMT Subject: [OT] SciTe Message-ID: <58%Ed.4827$C52.2609@newsread2.news.atl.earthlink.net> I didn't want to go through the rigamole of adding myself to the SciTe mailing list, so I'm asking my question here. How do I choose a different C/C++ compiler to compile in?? I don't use the g++ compiler; I use the VC 7 compiler. TIA, Lucas From steve at holdenweb.com Fri Jan 14 17:24:37 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 17:24:37 -0500 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: <7xacrcdhzh.fsf@ruckus.brouhaha.com> References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Fredrik Lundh" writes: > >>>Huh? Expressions are not statements except when they're "expression >>>statements"? What kind of expression is not an expression statement? >> >>any expression that is used in a content that is not an expression statement, >>of course. > > > Come on, that is vacuous. The claim was "expressions are not > statements". But it turns out that expressions ARE statements. The > explanation is "well, that's because they're expression statements". > And there is no obvious case of an expression that can't be used as a > statement. So it's not inherently obvious that there needs to be any > kind of statement that can't be used as an expression. It's just an > artifact. Whether the artifact is a desirable one is a matter of > discussion. Excuse me, coould we get back to discussing how many angels can dance on the head of a pin? or-something-interesting-like-that-sly y'rs - 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 tim.peters at gmail.com Mon Jan 3 00:29:30 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 3 Jan 2005 00:29:30 -0500 Subject: thread/queue bug In-Reply-To: <41B9D041.5050200@anvilcom.com> References: <41B9D041.5050200@anvilcom.com> Message-ID: <1f7befae050102212962c58afb@mail.gmail.com> [phillip.watts at anvilcom.com] Note that python-bugs-list is a moderated list for use only by automated reports generated from SourceForge. I'm redirecting the reply to python-list at python.org. > I have a very strange bug. A thread in a .pyc stops dead. > > This program has many threads and queues and has worked > great for months. > One thread listens for UDP messages from other programs, > and puts the messages in listenq. > Procmsgs gets from listenq and for a certain kind of > message creates another mq = Queue(0). > > I don't wish to distribute the source to pnetx.py > so I have a short program pnet.py import it, that is > pnetx.pyc. > > Then the procmsgs thread dies at the Queue statement. > But if I run pnetx.py as the main program, all works fine. > > So if pnetx.py or .pyc is imported this thread dies. ??? > > I've tried this with 2.3.3 and 2.3.4. Anyone? Sounds like your module spawns a thread as a side effect of being imported. Don't do that -- you'll get in deadlock trouble with "the import lock" if you do (use Google to learn more about that). From jloden at toughguy.net Thu Jan 20 13:51:43 2005 From: jloden at toughguy.net (Jay Loden) Date: Thu, 20 Jan 2005 13:51:43 -0500 Subject: What's the best python web-developer's editor In-Reply-To: <41EFFCD9.7060302@wild-flower.co.uk> References: <41EFFCD9.7060302@wild-flower.co.uk> Message-ID: <200501201351.43884.jloden@toughguy.net> You didn't mention platform, but I'm guessing from the mention of Screem that you're using a Linux platform. On Linux I like kwrite and kate (both similar, kate includes some other features like a built in terminal where you can run some commands, ability to support projects, open multiple files tiled to read all the code at once, etc). They both use the same editing portion, which has syntax highlighting for Python and html both. Because of KDE network transparency, you can edit files over ftp/save to an ftp site. Just in case, I'll recommend my favorite Windows editor for those times when I'm stuck on Windows - Crimson Editor, http://www.crimsoneditor.com Has syntax highlights, and just about every feature I could possibly ask for in an editor. I actually missed this app the most when moving to Linux. -Jay On Thursday 20 January 2005 1:47, andy wrote: > Anybody like to comment on which editor they use for python web app > development - for both discrete and mixed python and html code, and why? > > I'm comfortable with IDLE (used it for years) but of course it lacks ftp > or webDAV abilities, obviously because it's not intended for that type > of use. > > I've had a look at Screem - and that seems to do python syntax > highlighting, but it dosn't seem to be python syntax aware (unless > there's a hidden option somewhere). Although I can live without auto > indent, I'd rather not... > > I'm sure emacs, xemacs, vi, elvis and so on can do the same, but I have > no experience with them for heavy python or html coding, nor the time > to trip off down a blind-alley to find out! I know Enough Vi To Get > By(tm) but it's by no means my favourite editor. Emacs is a complete > mystery to me. > > I guess I *could* use IDLE and Screem together, but that's a clunky > solution! > > all opinions greatfully received, > -andyj From mnations at gmail.com Wed Jan 19 12:16:35 2005 From: mnations at gmail.com (Mudcat) Date: 19 Jan 2005 09:16:35 -0800 Subject: How to fill available screen size then scroll In-Reply-To: <1106086897.788340.267550@f14g2000cwb.googlegroups.com> References: <1106086897.788340.267550@f14g2000cwb.googlegroups.com> Message-ID: <1106154995.830101.257430@z14g2000cwz.googlegroups.com> bump From jeff at ccvcorp.com Mon Jan 17 13:11:23 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 17 Jan 2005 10:11:23 -0800 Subject: hash patent by AltNet; Python is prior art? In-Reply-To: References: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> Message-ID: <10unvkgh02aiab1@corp.supernews.com> Robert Kern wrote: > I don't know the details [...] Neither do I, but... > I'm also willing to bet that the patent won't > hold up in court because there's quite a lot of prior art with respect > to cryptographic hashes, too. The problem with that is that someone needs to be able to *afford* to challenge it in court. Even patents that are blatantly non-original on the face of things can be difficult and expensive to challenge. Most companies would rather just avoid the legal risks involved in making such a challenge, and most individuals can't afford the kind of legal team that'd be necessary. I'll join in encouraging Europeans to do their best to reject these styles of patents. It's a bit too late for the US, but maybe if we have concrete examples of the benefits of limiting patents then there might be hope for the future. And if things get too bad here, I'd like to have somewhere pleasant to emigrate to. ;) Jeff Shannon Technician/Programmer Credit International From evan at tokenexchange.com Mon Jan 17 13:00:42 2005 From: evan at tokenexchange.com (Evan Simpson) Date: Mon, 17 Jan 2005 12:00:42 -0600 Subject: Producer/consumer Queue "trick" In-Reply-To: <41E945EA.4040507@iinet.net.au> References: <7xmzvbnigr.fsf@ruckus.brouhaha.com> <41E945EA.4040507@iinet.net.au> Message-ID: <41EBFD4A.1090707@tokenexchange.com> Nick Coghlan wrote: > Paul Rubin wrote: > >> That's weird. Preemption should happen every few dozen milliseconds >> unless you've purposely increased the preemption delay. > > > To me, it smells like a call into a C extension which isn't releasing > the GIL before starting a time-consuming operation. Sorry, I think I misled you both -- "a long time" is actually the few dozen milliseconds of a normal preemption, which is only long relative to the single millisecond that the consumer typically takes to handle a request. Cheers, Evan @ 4-am From michele.simionato at gmail.com Wed Jan 12 00:56:19 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 11 Jan 2005 21:56:19 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: <7xmzvfn096.fsf@ruckus.brouhaha.com> References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: <1105509379.301556.178130@z14g2000cwz.googlegroups.com> Paul Rubin: > michele.simion... at gmail.com writes: >> > It wasn't obvious how to do it in Scheme either. There was quite > a bit of head scratching and experimental implementation before > there was consensus. Actually I am not convinced there is consensus yet, i.e. there is a non-negligible minority of schemers convinced that original Lisp macros where better, not to talk of common lispers ;) >> 3. We would add to Python the learning curve of macros and their >> subtilities and we do not want it. > I can't imagine how it could be worse than the learning curve of > __metaclass__, which we already have. To me, learning macros *and their subtilities* was much more difficult than learning metaclasses. >> 4. Macros would complicate a lot Python module system. > I don't see how, but maybe I'm missing something. Go to comp.lang.scheme and google for "macros and module system"; you will get everything you want to know and much more! >> 5. We have Guido providing a good syntax for us all, why we should be >> fiddling with it? More seriously, if some verbosity is recognized >> in the language (think to the "raison d'etre" of decorators, for >> instance) I very much prefer to wait for Guido to take care of >> that, once and for all, than having 100 different custom made >> solutions based on macros. > Every time some newbie asks an innocent "how do I ..." question, we > see unbelievably horrid answers from gurus. Just check the FAQ about > conditional expressions, etc. I just don't see Python syntax changes > as forthcoming. Well, I see this as a positive fact. If a syntax is contrived (such as a ternary operator, for instance) it is better *not* to have it than to have one hundred custom made syntaxes. At the end, we are just talking about syntax sugar here, not about lack of functionality. >> What I would be interested in is a Lisp/Scheme implementation >> compiling to Python bytecode, but I am not aware of any project >> in that direction. > But that sounds like a bizarre idea. Python bytecode is just a > CPython artifact, not part of the language. And it's not even that > good an artifact. Good Lisp/Scheme implementations compile to native > code that beats the pants off of CPython bytecode. It would make much > more sense to have a Python implementation that compiles Python to > S-expressions and then lets a high performance Lisp or Scheme system > take care of the rest. This is a bizarre idea if you want to make Python run faster. It is not so bizarre if what you want is to have access to Python from Lisp/Scheme in the same sense Jython has access to Java. Michele Simionato From http Mon Jan 31 23:18:57 2005 From: http (Paul Rubin) Date: 31 Jan 2005 20:18:57 -0800 Subject: need for binary floats (except performance)? References: <81300027.0501312006.72454fd6@posting.google.com> Message-ID: <7xmzuoq5e6.fsf@ruckus.brouhaha.com> kartik_vad at yahoo.com (kartik) writes: > Since the Decimal type can represent any given fractional number > exactly, It can't. For example, it can't represent 1/3 exactly. > including all IEEE binary floating-point numbers, wouldn't it be > advisable to use Decimals for all floating point numbers (except > possibly for performance)? The notion has some appeal, though algorithms on binary floats have been studied a lot over the past several decades, while decimal floats are not used very much at the moment. It will get more interesting if and when we start seeing decimal floating point hardware again. From b at b.b Tue Jan 11 03:59:49 2005 From: b at b.b (Roose) Date: Tue, 11 Jan 2005 08:59:49 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> <7xu0ppyjjg.fsf@ruckus.brouhaha.com> <9yzEd.9081$wZ2.6859@newssvr13.news.prodigy.com> <7xr7ksrf17.fsf@ruckus.brouhaha.com> Message-ID: <9AMEd.9356$wZ2.1350@newssvr13.news.prodigy.com> > Huh? I'm just baffled why you think writing a scheduler in an OS is > harder than writing one in an application. You have some means of > doing a coroutine switch in one situation, and some means of doing a > hardware context switch in the other. Aside from that the methods are > about the same. Because of performance. Task schedulers and device drivers tend to be timing sensitive. Go look up "task schedular latency". The longer your scheduler spends trying to figure out which thread to run, the longer the latency will be. I mean in the worst case, if you are interpreting everything, what if you change the task scheduler code? Then an interrupt happens, and oh shit we have to parse and recompile all the scheduling code. Oh wait now we ran out of kernel memory -- now we have to run the garbage collector! Let your interrupt wait, no? It just seems nonsensical. Maybe not impossible, as I've already said. I haven't tried it. But go ahead and try it -- I would honestly be interested in the results, all kidding aside. It shouldn't be too time-consuming to try, I suppose. Get Python running in the Linux kernel, and then replace the task scheduling algorithm with some Python code. See how it works. I suspect you will degrade the performance of an average system significantly or unacceptably. But who knows, I could be wrong. Of course, hardware is getting faster as you say. But multitasking performance is still an active and important area of OS research, and I doubt that any designer of an OS (that is actually meant to be used) would spend any cycles to have their task scheduler in Python -- and that will be probably be true for a very long time. Or maybe I'm wrong -- go bring it up on comp.os.linux or whatever the relevant newsgroup is. I'd like to hear what they have to say. > > Why do you think there's anything difficult about doing this stuff in > Python, given the ability to call low level routines for some hardware > operations as needed? From mwm at mired.org Mon Jan 3 17:42:38 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 03 Jan 2005 16:42:38 -0600 Subject: input record sepArator (equivalent of "$|" of perl) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> <1103657476.495700.191020@f14g2000cwb.googlegroups.com> <1103671235.093738.198680@z14g2000cwz.googlegroups.com> Message-ID: <86wtuup21t.fsf@guru.mired.org> Christos "TZOTZIOY" Georgiou writes: > [1] through the French "m?tre" of course; great job, those > revolutionaries did with the metric system. As Asimov put it, "how many > inches to the mile?" Trivia question: Name the second most powerfull country on earth not using the metric system for everything. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From ods at strana.ru Tue Jan 11 12:05:26 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Tue, 11 Jan 2005 20:05:26 +0300 Subject: os.spawnv & stdin trouble In-Reply-To: <20050111163036.808E91C00CE9@mwinf0108.wanadoo.fr> References: <20050111163036.808E91C00CE9@mwinf0108.wanadoo.fr> Message-ID: <20050111200526.1bd60ebd.ods@strana.ru> On Tue, 11 Jan 2005 17:31:07 +0100 "Jelle Feringa // EZCT / Paris" wrote: > ##I know I should be using 2.4 and os.Popen, I know, I know. > ##However, since most modules I need, I'm using 2.3 for this script There is os.popen in 2.3, as well as popen2 module. Did you mean subprocess? I guess it's ported to 2.3 too. > Here's where I run into trouble. > In my os.system version, I'm perfectly able to pipe into another file, > since the process has no real connection to python whatsoever. > Would someone be able to explain me how to do this, all the tools I'm > using for this script are unix-like tools and heavily rely on piping. os.system passes commend to shell, which handles redirect for you instead of passing '>' to xform.exe as parameter. Use os.system or subprocess (a.k.a. popen5). > program = 'xform.exe' > path = 'c:\Radiance\bin\' ^^ Syntax error here. Did you mean 'c:\\Radiance\\bin\\xform.exe'? > args = ['-t 0 8 0', 'wall0.rad', '>', 'wall0.TRANS.rad'] > os.spawnv(os.P_WAIT, path, ('xform', args)) This corresponds to c:\Radiancein\ '-t 0 8 0' wall0.rad '>' wall0.TRANS.rad' command line. > here's the cmd error message: > xform: cannot find file ">" Don't understand how you got this error having syntax error and wrong path to executable. > ##for your info I'm on win/xp, python 2.3.4 BTW, you are trying to redirect stdout. Wrong subject? -- Denis S. Otkidach http://www.python.ru/ [ru] From nid_oizo at yahoo.com_remove_the_ Tue Jan 4 11:15:23 2005 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Tue, 04 Jan 2005 11:15:23 -0500 Subject: python 3000 and removal of builtin callable In-Reply-To: <33v6l6F40l7hqU1@individual.net> References: <33v6l6F40l7hqU1@individual.net> Message-ID: Mirko Zeibig wrote: > This is not an option for e.g. IDEs as some functions might actually do > something when called ;-) and I like `callable` for introspection. > > Other ways would be to check for the `__call__` attribute or use several > methods of the `inspect`-Module, both of which are not better than > `callable` IMHO. I totally agree with you. The callable function could be moved to a module and be built-in, but it cannot really be removed. Calling a callable and know if an object is a callable without calling it is definitely not the same thing. Regards, Nicolas From rnd at onego.ru Wed Jan 5 09:54:03 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 5 Jan 2005 17:54:03 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: <1gpx56v.yb9ubn188tj2yN%aleaxit@yahoo.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> <1gpx56v.yb9ubn188tj2yN%aleaxit@yahoo.com> Message-ID: On Wed, 5 Jan 2005, Alex Martelli wrote: >Dave Brueck wrote: > ... >> No, not at all - I'm just trying to better understand what you mean. Words >> like "generic" and "concepts" don't yet have a widely recognized, strict >> definition in the context of programming. If somebody has assigned some >> specific definition to them, that's great, it's just not universal yet so >> references and additional explanations are helpful. > >Googling for "generic programming" (with the quotes) gets 100,000 + >hits. The first couple pages of hits, at least, seem to all be speaking >about exactly the same thing. The terminology appears to be settled >enough that Oxford's St Anne College feels they can organize a "Summer >School on Generic Programming", Nottingham University a "Workshop on >Generic Programming", etc, etc, without fearing ambiguity. That is why I was pretty sure people undestand me. >Exactly what extra support Roman would want from Python for 'concepts', >beyond that offered by, say, C++, I'm not sure. Protocols, interfaces >and design-by-contract are other terms often used to try and capture >pretty similar issues. I just happen to like the term 'concept' more than Protocols, interfaces, and design-by-contract ;-) Alex, I think you are +10 for adding interfaces into Python. "Concept" is more compact word and I am sure it is not used as a name in existing projects, unlike other words. Also, Python concept collection could be used as a teaching example or templates for high quality code. Concepts need not appear in every script out there, but as a result of design. What else Python needs to support GP? A possibility to formally define a concept (and concept relations) with (optionally) checks of implementations. I do not even insist in making it all run-time! Perhaps concepts could be checked in PyChecker. And (perhaps) the whole type-checking could be done this way. However sweety it is, I also hope to have keystrokes saved when I use ready-maid concept in my program. Just imagine we have a concept for table and use (as adaptor) it for db-connectivity, CSV-readers/writers, XML/HTML parsers/writers, arrays, lists, ... Right now Python _almost_ has it. However, small differences in small details do not allow to interchange even different dbm-modules! I remember getting into trouble when I switched from bsddb to gdbm: some places needed 'r' to be explicitly specified! Same problems with db-api 2.0 "almost" conformant modules, datetime types and other small details which are similar but differ in small details at the same time. I think the same has place with XML-DOM implementations and such. I think concepts could be guards against such things and also make life easier for those who implement some standard protocols. That is, concepts could be internal (Python) standardizing and quality control technique. We can use constant publicId, systemId a-la XML for concepts, so upgrade path will be similar to HTMLs. This will make concept-changing visible between versions. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From google at smilechaser.com Thu Jan 20 18:06:36 2005 From: google at smilechaser.com (smilechaser) Date: 20 Jan 2005 15:06:36 -0800 Subject: Embedding: Question about modules Message-ID: <1106258999.633728.203400@z14g2000cwz.googlegroups.com> Hi All, A question about embedding: If I take the example code on embedding (Section 5.3 of Extending and Embedding the Python Interpreter 2.4) and add the lines: PyRun_SimpleString("import sys"); PyRun_SimpleString("print globals()"); Just after the part where the code loads the module, and then I have a script that looks like: # mod_test.py def foo(x): for g in globals(): print g The first printout of the globals shows the sys module, but the second one does not. Can someone explain why this is ? And how do I make the sys module accessible to the module I load (as per the 5.3 example). TIA, smilechaser From timr at probo.com Sun Jan 23 00:19:07 2005 From: timr at probo.com (Tim Roberts) Date: Sat, 22 Jan 2005 21:19:07 -0800 Subject: getting file size References: Message-ID: <6qc6v0hhfedf0uncp9gieahj38srh46khk@4ax.com> Bob Smith wrote: >Are these the same: > >1. f_size = os.path.getsize(file_name) > >2. fp1 = file(file_name, 'r') > data = fp1.readlines() > last_byte = fp1.tell() > >I always get the same value when doing 1. or 2. Is there a reason I >should do both? When reading to the end of a file, won't tell() be just >as accurate as os.path.getsize()? On Windows, those two are not equivalent. Besides the newline conversion done by reading text files, the solution in 2. will stop as soon as it sees a ctrl-Z. If you used 'rb', you'd be much closer. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From abpillai at gmail.com Wed Jan 5 08:16:04 2005 From: abpillai at gmail.com (Anand) Date: 5 Jan 2005 05:16:04 -0800 Subject: Using python to deploy software In-Reply-To: <1104326227.266388.224060@z14g2000cwz.googlegroups.com> References: <1104295227.491861.207050@z14g2000cwz.googlegroups.com> <1104300281.832625.138070@f14g2000cwb.googlegroups.com> <1104326227.266388.224060@z14g2000cwz.googlegroups.com> Message-ID: <1104930964.467419.293540@c13g2000cwb.googlegroups.com> Hmm... did not watch this thread. Regarding sharing code, well I am sure you will be able to quickly produce some working client/server using Pyro for doing your task. Pyro makes it very easy to do RMI due to its network broadcast way of querying the name server. If you are not able to make any headway, mail me and I can give you his email address. Rgds -Anand From http Sat Jan 29 10:35:41 2005 From: http (Paul Rubin) Date: 29 Jan 2005 07:35:41 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> Message-ID: <7xr7k4qmcy.fsf@ruckus.brouhaha.com> Paul Rubin writes: > actually: mxCrypto is the most capable of these packages and might be > the one with the most users, but it's completely unsuitable for the > core because of its size). Oops, I should say, mxCrypto itself isn't that large; the issue is that it needs OpenSSL which is a big unwieldy program. Having mxCrypto in the core as an OpenSSL interface is a legitimate notion. But there should be something that doesn't depend on OpenSSL. From samantha7395 at hotmail.com Thu Jan 20 16:17:35 2005 From: samantha7395 at hotmail.com (Samantha) Date: Thu, 20 Jan 2005 13:17:35 -0800 Subject: Print to Windows default Printer References: <9A28C052FF32734DACB0A288A35339910359DA@vogbs009.gb.vo.local> Message-ID: Thanks for the URL. I finally am able to print the temp file. Not exactly what I wanted, but it will work. The code I used to print was this: os.system ("start /min notepad /P temp.txt") Thanks ALL! S "Kristian Zoerhoff" wrote in message news:mailman.970.1106248792.22381.python-list at python.org... > On Thu, 20 Jan 2005 19:14:10 -0000, Tim Golden > wrote: >> [Kristian Zoerhoff] >> | >> | On Thu, 20 Jan 2005 18:58:25 -0000, Tim Golden >> | wrote: >> | > >> | > Can anyone else try a "PRINT blah" or a "COPY blah LPT1:" >> | > on XP SP2? >> | >> | The printer is probably connected via USB, not the parallel port >> | (LPT1), so the above won't work. I googled, and found some sage advice >> | here: >> | >> | http://www.winnetmag.com/Article/ArticleID/39674/39674.html >> | >> | that may assist the OP. From abpillai at gmail.com Thu Jan 6 04:53:43 2005 From: abpillai at gmail.com (Anand) Date: 6 Jan 2005 01:53:43 -0800 Subject: Contributor's List Message-ID: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> A list of contributors to Python Cookbook (Second Edition) is available at the following links. Original list courtesy Alex Martelli. Since the book is not yet in print, the lists are still tentative because of potential last minute editing changes. List of first authors o http://harvestman.freezope.org/cookbook/credau.html List of all authors o http://harvestman.freezope.org/cookbook/creds.html -Anand From eric_brunel at despammed.com Tue Jan 11 04:00:51 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 11 Jan 2005 10:00:51 +0100 Subject: PyChecker messages In-Reply-To: References: Message-ID: <41e393f0$0$25812$8fcfb975@news.wanadoo.fr> Frans Englich wrote: > Hello, > > I take PyChecker partly as an recommender of good coding practice, but I > cannot make sense of some of the messages. For example: > > runner.py:878: Function (main) has too many lines (201) > > What does this mean? Cannot functions be large? Or is it simply an advice that > functions should be small and simple? This is an advice. You can set the number after which the warning is triggered via the maxLines option in your .pycheckrc file. > runner.py:200: Function (detectMimeType) has too many returns (11) > > The function is simply a long "else-if" clause, branching out to different > return statements. What's wrong? It's simply a "probably ugly code" advice? Same thing; the corresponding option in .pycheckrc is maxReturns. Other options that may interest you are maxBranches, maxArgs, maxLocals and maxReferences. Please see PyChecker's documentation for more details. > A common message is these: > > runner.py:41: Parameter (frame) not used > > But I'm wondering if there's cases where this cannot be avoided. For example, > this signal handler: > > #------------------------------------------- > def signalSilencer( signal, frame ): > """ > Dummy signal handler for avoiding ugly > tracebacks when the user presses CTRL+C. > """ > print "Received signal", str(signal) + ", exiting." > sys.exit(1) > #------------------------------------------- > > _must_ take two arguments; is there any way that I can make 'frame' go away? See/set the unusedNames option in .pycheckrc; this is a list of names for which this kind of warnings are not triggered. If you set for example: unusedNames = [ 'dummy' ] in .pycheckrc and if you define your function with: def signalSilencer(signal, dummy): ... the warning will not be triggered. BTW, if your signal handler is just here to catch Ctrl-C, you'd better do a try/except on KeyboardInterrupt... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From orjan at switchcore.com Mon Jan 24 09:18:39 2005 From: orjan at switchcore.com (=?ISO-8859-1?Q?=D6rjan_Gustavsson?=) Date: Mon, 24 Jan 2005 15:18:39 +0100 Subject: pylibpcap and multiple threads Message-ID: Hi All! Sorry if this is not the correct forum for this kind of question (I did not find any pylibpcap related lists). I am trying to use pylibpcap to capture network traffic from several ethernet devices at the same time, each nic having a separate thread assigned to it. My problem is that when one thread is blocking inside pcap.loop() for instance, it seems to have acquired the GIL, so that no other threads can run. Does anyone know a way to do this with threads, or is the only way to have separate processes for each NIC? Regards, ?rjan Gustavsson From anon at anon.com Fri Jan 28 15:20:22 2005 From: anon at anon.com (Todd_Calhoun) Date: Fri, 28 Jan 2005 12:20:22 -0800 Subject: Where can I find sample "beginner" programs to study? Message-ID: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> I'm trying to learn Python (and programming), and I'm wondering if there are any places where I can find small, simple programs to study. Thanks. From steven.bethard at gmail.com Mon Jan 24 14:59:07 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Jan 2005 12:59:07 -0700 Subject: Tuple slices In-Reply-To: References: <35kn4mF4o44ufU1@individual.net> Message-ID: <-cWdndzlhLgYzmjcRVn-vw@comcast.com> Fredrik Lundh wrote: > Steven Bethard wrote: >> >>My impression was that full tuple copies didn't actually copy, but that slicing a subset of a >>tuple might. Not exactly sure how to test this, but: >> >>py> a = 1, 2, 3 >>py> a[:2] is a[:2] >>False > > yup. and to figure out why things are done this way, consider this case: > > >>> a = give_me_a_huge_tuple() > >>> len(a) > (a rather large number) > >>> b = a[:2] > >>> del a > > (IIRC, I proposed to add "substrings" when I implemented the Unicode string > type, but that idea was rejected, for the very same "and how do you get rid of > the original object" reason) Ahh. Yeah, that seems sensible. I don't think I've ever written code like that, but if I did, I'd almost certainly want it to work as it does now... Steve From BOOGIEMANPN at YAHOO.COM Sat Jan 1 15:57:32 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Sat, 1 Jan 2005 21:57:32 +0100 Subject: What can I do with Python ?? Message-ID: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> Beginners question, but really what can you do with it ? How hard is Python to learn compared with other languages (let's say C#). Can you make fullscreen game with it (for example) ? I've looked at http://www.python.org but nothing concrete there From firstname.lastname at iki.fi-spam Mon Jan 3 04:34:06 2005 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 03 Jan 2005 11:34:06 +0200 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: <87u0py6elt.fsf@sme.intra.citec.fi> Ron Garret writes: > (with-output-to-string (s) > (let ( (*standard-output* s) ) > (call-html-generating-code) > s)) > > Is there an equivalent Python trick to capture a function call's output > as a string? I've sometimes replaced sys.stdout (and/or sys.stderr) to capture/redirect debugging information in existing code that has unwisely just "print"ed error and warning messages, instead of using sys.stderr or error logging modules. py> def with_output_to_string (func): ... try: ... sys.stdout = StringIO.StringIO () ... func () ... return sys.stdout.getvalue () ... finally: ... sys.stdout = sys.__stdout__ ... py> def printing_code (): ... print "Foobar" ... py> with_output_to_string (printing_code) 'Foobar\n' py> br, S From grante at visi.com Sun Jan 16 16:14:13 2005 From: grante at visi.com (Grant Edwards) Date: 16 Jan 2005 21:14:13 GMT Subject: List problems in C code ported to Python References: Message-ID: <41ead925$0$87061$a1866201@visi.com> On 2005-01-16, Lucas Raab wrote: > I'm done porting the C code, but now when running the script I > continually run into problems with lists. I tried appending and > extending the lists, but with no avail. Any help is much appreciated > Please see both the Python and C code at > http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py http://www.catb.org/~esr/faqs/smart-questions.html -- Grant Edwards grante Yow! Did an Italian CRANE at OPERATOR just experience visi.com uninhibited sensations in a MALIBU HOT TUB? From tim.peters at gmail.com Fri Jan 7 12:31:46 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 7 Jan 2005 12:31:46 -0500 Subject: sorting on keys in a list of dicts In-Reply-To: <41DEC423.3030506@iinet.net.au> References: <10tr9ejf05pv660@corp.supernews.com> <41DEC423.3030506@iinet.net.au> Message-ID: <1f7befae0501070931699c5996@mail.gmail.com> [Nick Coghlan] ... > Python 2.3 has a stable sort, and Python 2.4 brought the guarantee that it shall > remain that way. I'm not sure about Python 2.2 and earlier. No list.sort() implementation before 2.3 was stable. It was confusing, though, because the samplesort/binary_insertion_sort hybrid Python used for the 4 years preceding 2.3 *was* stable for all "small enough" lists. More than one person got fooled by guessing that stability observed in small test cases meant it was always stable. From t-meyer at ihug.co.nz Sun Jan 9 19:05:58 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 10 Jan 2005 13:05:58 +1300 Subject: Please Contribute Python Documentation! In-Reply-To: Message-ID: > I'm changing the subject so that hopefully people who have > long ago tuned out the "Python evolution: Unease" subject > will read this note. Worked for me :) Two other pages that are probably of use to people interested in this are: These document the current (well, current when the wiki page was last updated) state of various document patches, and list things that people have noticed need work. There's also a place for volunteers to put their name if they are willing to provide module documentation, so that work isn't duplicated. (I don't know how up-to-date the latter one is. I think the former is reasonably so). > You do not (repeat, *do not*) > need to install any tools to contribute content to the > documentation. Just whip out your favorite text editor and > type plain old text. There are plenty of us around who know > enough LaTeX to markup anything you contribute. Don't let > lack of a specific set of tools be a barrier to contribution! I don't think I've seen such a statement before - the stuff I've seen all indicates that one should be submitting proper LaTeX docs/patches. If plain-text contributions are welcome, could this be added to the doc about contributing to the docs? (I suppose I could submit a patch, but that seems overkill ). > In either case, select "Documentation" as the category. There is > no need to assign it to anyone. It will get seen shortly. > The correctness of a documentation fix is generally easier to > verify than that for a code fix, so they tend to get applied > pretty quickly. Is it a mistake to attach a patch to a bug report? Should it be a new patch tracker instead? I ask because I (ages ago) submitted documentation for zipimport (it's linked from the ModulesThatNeedDocs page above) and although it's been included on that wiki page and in discussion on python-dev about missing documentation, it's never been looked at, AFAIK. (If there are problems, I'm happy to amend the patch, as the comment says). This is somewhat at odds with the "shortly" and "pretty quickly" <0.5 wink>. =Tony.Meyer From nick at craig-wood.com Sat Jan 29 15:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 29 Jan 2005 20:30:01 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> <7xacqsbfk2.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > An AES or DES addition to an existing module that implements just one > call: > ECB(key, data, direction) > would be a huge improvement over what we have now. A more complete > crypto module would have some additional operations, but ECB is the > only one that's really essential. I would hate to see a module which only implemented ECB. Sure its the only operation necessary to build the others out of, but its the least secure mode of any block cipher. If you don't offer users a choice, then they'll use ECB and just that along with all its pitfalls, meanwhile thinking that they are secure because they are using AES/DES... For those people following along at home (I'm sure everyone who has contributed to thread knows this already) I tried to find a simple link to why ECB is bad, this PDF is the best I could come up with, via Google's Cache. http://www.google.com/search?q=cache:U5-RsbkSs0MJ:www.cs.chalmers.se/Cs/Grundutb/Kurser/krypto/lect04_4.pdf -- Nick Craig-Wood -- http://www.craig-wood.com/nick From aahz at pythoncraft.com Wed Jan 19 15:11:40 2005 From: aahz at pythoncraft.com (Aahz) Date: 19 Jan 2005 15:11:40 -0500 Subject: shelve to DB conversion? Message-ID: I'd like to hear some experiences about converting a shelf with pickles to database with pickles, particularly if someone has handy code for proxying shelve code. We're using PostgreSQL if that makes any difference. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From lance-news at augustmail.com Wed Jan 26 03:05:17 2005 From: lance-news at augustmail.com (Lance Hoffmeyer) Date: Wed, 26 Jan 2005 02:05:17 -0600 Subject: script to search ebay? References: <1106722674.838311.308520@z14g2000cwz.googlegroups.com> Message-ID: Thanks for the script. I haven't been on ebay for a while. Wasn't aware of the Favorite searches. Favorite Search is probably the way to go. Thanks for the info. Lance On Tue, 25 Jan 2005 22:57:54 -0800, Kamilche wrote: > This script works. But why not make a 'Favorite Search' in ebay, and > have it send you daily email for a year? > > --Kamilche > > |import urllib > |import smtplib > | > |def main(): > | # Perform the search > | results = SearchEbay(['So long and thanks for all the fish', > | 'NOMATCHFOUND', > | 'Python Programming']) > | > | # Email the results > | Email('me at somewhere.com', > | 'you at somewhere.com', > | 'eBay Search Results', > | results) > | > |def SearchEbay(searchstrings): > | ' Search eBay for the desired items' > | searchURL = "http://search.ebay.com/%s" > | results = "" > | s = "eBay Search Results:\n" > | print s, > | results += s > | for i in range(len(searchstrings)): > | > | # Build the search URL > | search = searchstrings[i].replace(' ', '-') > | s = searchURL % search + " : " > | print s, > | results += s > | > | # Download the URL > | url = urllib.urlopen(searchURL % search) > | data = url.read() > | url.close() > | > | # Write the URL to a file for debugging > | fd = open('ebay %d.html' % i, 'w') > | fd.write(data) > | fd.close() > | > | # Search for the number of items found > | c = data.find('items found for') > | if c >= 0: > | start = data.rfind('', 0, c) + 3 > | stop = data.find('', start + 1) > | cnt = data[start:stop] > | else: > | cnt = '0' > | s = "%s items found.\n" % cnt > | print s, > | results += s > | > | return results > | > |def Email(fromaddr, toaddr, subject, msg): > | ' Send email' > | msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % \ > | (fromaddr, toaddr, subject, msg)) > | server = smtplib.SMTP('your.smtp.server.here') > | server.set_debuglevel(1) > | server.sendmail(fromaddr, toaddr, msg) > | server.quit() > | > |main() From aleaxit at yahoo.com Sat Jan 22 04:10:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 10:10:36 +0100 Subject: need help on need help on generator... References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> Message-ID: <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> Francis Girard wrote: ... > But besides the fact that generators are either produced with the new "yield" > reserved word or by defining the __new__ method in a class definition, I > don't know much about them. Having __new__ in a class definition has nothing much to do with generators; it has to do with how the class is instantiated when you call it. Perhaps you mean 'next' (and __iter__)? That makes instances of the class iterators, just like iterators are what you get when you call a generator. > In particular, I don't know what Python constructs does generate a generator. A 'def' of a function whose body uses 'yield', and in 2.4 the new genexp construct. > I know this is now the case for reading lines in a file or with the new > "iterator" package. Nope, besides the fact that the module you're thinking of is named 'itertools': itertools uses a lot of C-coded special types, which are iterators but not generators. Similarly, a file object is an iterator but not a generator. > But what else ? Since you appear to conflate generators and iterators, I guess the iter built-in function is the main one you missed. iter(x), for any x, either raises an exception (if x's type is not iterable) or else returns an iterator. > Does Craig Ringer answer mean that list > comprehensions are lazy ? Nope, those were generator expressions. > Where can I find a comprehensive list of all the > lazy constructions built in Python ? That's yet a different question -- at least one needs to add the built-in xrange, which is neither an iterator nor a generator but IS lazy (a historical artefact, admittedly). But fortunately Python's built-ins are not all THAT many, so that's about it. > (I think that to easily distinguish lazy > from strict constructs is an absolute programmer need -- otherwise you always > end up wondering when is it that code is actually executed like in Haskell). Encapsulation doesn't let you "easily distinguish" issues of implementation. For example, the fact that a file is an iterator (its items being its lines) doesn't tell you if that's internally implemented in a lazy or eager way -- it tells you that you can code afile.next() to get the next line, or "for line in afile:" to loop over them, but does not tell you whether the code for the file object is reading each line just when you ask for it, or whether it reads all lines before and just keeps some state about the next one, or somewhere in between. The answer for the current implementation, BTW, is "in between" -- some buffering, but bounded consumption of memory -- but whether that tidbit of pragmatics is part of the file specs, heh, that's anything but clear (just as for other important tidbits of Python pragmatics, such as the facts that list.sort is wickedly fast, 'x in alist' isn't, 'x in adict' IS...). Alex From steve at holdenweb.com Fri Jan 14 17:46:31 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 17:46:31 -0500 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <41e5ebee.709560864@news.oz.net> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> Message-ID: Bengt Richter wrote: > On 12 Jan 2005 14:46:07 -0800, "Chris Lasher" wrote: > [...] > Others have probably solved your basic problem, or pointed > the way. I'm just curious. > > Given that the information content is 2 bits per character > that is taking up 8 bits of storage, there must be a good reason > for storing and/or transmitting them this way? I.e., it it easy > to think up a count-prefixed compressed format packing 4:1 in > subsequent data bytes (except for the last byte which have > less than 4 2-bit codes). > > I'm wondering how the data is actually used once records are > retrieved. (but I'm too lazy to explore the biopython.org link). > Revealingly honest. Of course, adopting an encoding that only used two bits per base would make it impossible to use the re module to search for patterns in them, for example. So the work of continuously translating between representations might militate against more efficient representations. Or, of course, it might not :-) it's-only-storage-ly y'rs - 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 ncoghlan at iinet.net.au Mon Jan 17 05:11:22 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 17 Jan 2005 20:11:22 +1000 Subject: (objects as) mutable dictionary keys In-Reply-To: References: Message-ID: <41EB8F4A.2080301@iinet.net.au> Antoon Pardon wrote: > What are good arguments or bad and how much weight they have depends > on the person and on the circumstances. So a simple rule like: > Never use a mutable as a key in a dictionary will sometimes not be > the best solution. True - but I think a purely identity based dictionary *is* the solution for most such cases where the standard Python rule doesn't apply :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ggg at zzz.it Thu Jan 6 13:27:18 2005 From: ggg at zzz.it (deelan) Date: Thu, 06 Jan 2005 19:27:18 +0100 Subject: File Handling Problems Python I/O In-Reply-To: <1105034789.700445.291380@z14g2000cwz.googlegroups.com> References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> <1105034789.700445.291380@z14g2000cwz.googlegroups.com> Message-ID: Josh wrote: > Peter, > > Thank you for the rookie correction. That was my exact problem. I > changed the address to use forward slashes and it works perfect. I did > not know that a backslash had special meaning within a string, but now > I do! Thanks again you may want to check "python gotchas" to avoid other typical newbie errors: HTH, deelan -- "Vedrai come ti tratteranno le mie TV" Berlusconi a Follini (Luglio 2004) From mt at 3planes.com Sun Jan 30 23:04:26 2005 From: mt at 3planes.com (Michael Tobis) Date: 30 Jan 2005 20:04:26 -0800 Subject: Fortran pros and cons (was Re: Coding style article with interesting section on white space) In-Reply-To: <1107124832.327010.181490@f14g2000cwb.googlegroups.com> References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> <1107105022.827941.114510@c13g2000cwb.googlegroups.com> <1107124832.327010.181490@f14g2000cwb.googlegroups.com> Message-ID: <1107144265.980844.9830@z14g2000cwz.googlegroups.com> beliavsky at aol.com wrote: > Michael Tobis wrote: > Fortran 90/95 is more expressive than Fortran 77 in many ways, as > described in ... > http://www.nr.com/CiP97.pdf . > > ... expresses more science per > line of code and per programming workday. The example shown on p 10 illustrates a shorter piece of code in f90 than in f77, but it is not obviously more expressive or less complex. Arguably the f77 code is easier to write and maintain, even though it has more linefeeds in it, so I find the example far from compelling. In fact, I find the f90 example impenetrable. Specifically, what does array_copy(source,dest,n,nn) do? I note that n and nn are uninitialized at call time. Are these outputs from array_copy(), appearing, in that inimitable Fortran way, in the call signature? Here it is in Python with NumArray: b = sort(compress(less(v,200.) * greater(v,100.),m )) result = b[(len(b)+3)//4] I certainly think this example is competitive for whatever that's worth. It has the added benefit of handling the case of an empty list with a nice catchable IndexError exception. However, if this were intended to be maintainable code I would find it most effectively expressed something like this: ... def magthresh(vel,mag,vmin=100.,vmax=200.): ... selector = less(vel,vmax) * greater(vel,vmin) ... sortedmags = sort(compress(selector,mag)) ... if len(sortedmags): ... index = (len(sortedmags) + 3) // 4 ... return sortedmags[index] ... else: ... raise IndexError,"No velocities in range." mt From francis.girard at free.fr Thu Jan 27 15:54:58 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 27 Jan 2005 21:54:58 +0100 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <200501272154.58220.francis.girard@free.fr> Oops, I misunderstood what you said. I understood that it was now the case that objects of different types are not comparable by default whereas you meant it as a planned feature for version 3. I really hope that it will indeed be the case for version 3. Francis Girard Le jeudi 27 Janvier 2005 21:29, Steven Bethard a ?crit?: > Francis Girard wrote: > > Le jeudi 27 Janvier 2005 20:16, Steven Bethard a ?crit : > >>flamesrock wrote: > >>>The statement (1 > None) is false (or any other value above 0). Why is > >>>this? > >> > >>What code are you executing? I don't get this behavior at all: > >> > >>py> 100 > None > >>True > >>py> 1 > None > >>True > >>py> 0 > None > >>True > >>py> -1 > None > >>True > >>py> -100 > None > >>True > > > > Wow ! What is it that are compared ? I think it's the references (i.e. > > the adresses) that are compared. The "None" reference may map to the > > physical 0x0 adress whereas 100 is internally interpreted as an object > > for which the reference (i.e. address) exists and therefore greater than > > 0x0. > > > > Am I interpreting correctly ? > > Actually, I believe None is special-cased to work like this. From > object.c: > > static int > default_3way_compare(PyObject *v, PyObject *w) > { > ... > if (v->ob_type == w->ob_type) { > ... > Py_uintptr_t vv = (Py_uintptr_t)v; > Py_uintptr_t ww = (Py_uintptr_t)w; > return (vv < ww) ? -1 : (vv > ww) ? 1 : 0; > } > ... > /* None is smaller than anything */ > if (v == Py_None) > return -1; > if (w == Py_None) > return 1; > ... > } > > So None being smaller than anything (except itself) is hard-coded into > Python's compare routine. My suspicion is that even if/when objects of > different types are no longer comparable by default (as has been > suggested for Python 3.0), None will still compare as smaller than > anything... > > Steve From case.nelson at gmail.com Tue Jan 11 18:39:29 2005 From: case.nelson at gmail.com (Case Nelson) Date: 11 Jan 2005 15:39:29 -0800 Subject: Help Optimizing Word Search Message-ID: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Hi there I've just been playing around with some python code and I've got a fun little optimization problem I could use some help with. Basically, the program needs to take in a random list of no more than 10 letters, and find all possible mutations that match a word in my dictionary (80k words). However a wildcard letter '?' is also an acceptable character which increases the worst case time significantly. So if the letters are ['a','b','c'] check a, b, c, ab, ac, ba, bc, ca, cb, abc, acb, bac, bca, cab, cba where only a, ba and cab would be added to the dict of words. If the letters are ['?','?'] check a-z, aa, ab, ac, ad, ..., az, ba, bb, bc, bd, ..., zz I'm using a trie structure to load and query my dictionary, which returns a 1 if the word is found, 4 if a partial word is found, and 3 if there is no possible word. I guess I'm wondering if anyone could think of a faster way to deal with the wildcards, perhaps removing the inner for-loop or else something entirely different (iterative, don't use the trie?). Any other suggestions would be welcome findword recursion runs in 9.16300010681 secs words.log is simply my list of words: ['hats', 'easts', 'baizes',...,'sash'] --- Code Begin --- PY> import trie PY> import time PY> PY> print 'loading trie ...', PY> mytrie = trie.Trie('dicts.txt') PY> print 'done.' PY> PY> alpha = list('abcdefghijgklmnopqrstuvwxyz') PY> PY> words = {} PY> def findword(word, letters): PY> # run out of letters, recursion stop point PY> if letters == []: PY> return PY> PY> if word != "": PY> # Check if word is valid PY> result = mytrie.query(word) PY> PY> # Found a word, add it to the database PY> if result == 1: PY> words[word] = 1 PY> PY> # No other word starts with my current word, recursion stop point PY> if result == 3: PY> return PY> PY> # Run through every letter in our list PY> for i,letter in enumerate(letters): PY> # Remove current letter and recurse PY> newletters = letters[:] PY> newletters.pop(i) PY> PY> # if current letter is ? must recurse through all 26 letters PY> if letter == '?': PY> for c in alpha: PY> # recurse word+wildcard letter PY> findword(word+c,newletters) PY> else: PY> # recurse word+letter PY> findword(word+letter,newletters) PY> PY> letters = list('abae?s?') PY> s = time.time() PY> findword("",letters) PY> print time.time() - s PY> PY> output = open('words.log','w') PY> print >> output, words.keys() PY> output.close() PY> --- Code End --- Thanks (Hopefully google doesn't eat my whitespace) From info at dohnosoft.com Sat Jan 1 14:21:02 2005 From: info at dohnosoft.com (DohnoSoft) Date: Sat, 1 Jan 2005 11:21:02 -0800 Subject: Publish your program for free and enjoy worry free earning. 100% FREE (AND WE MEAN IT - FREE) Message-ID: Dear software developer!!! If you have some program or utility that you think may be interesting to somebody else, go ahead and submit it to www.DohnoSoft.com This is 100% FREE!!! and DohnoSoft will take care of all issues related to sales, payments and customer support. You will just enjoy worry free earning, which will be 89% of each sold program. NO CREDIT CARDS, BANK INFORMATION OR ANY OTHER PAYMENT INFORMATION IS REQUIRED. After DohnoSoft sends money with PayPal, you receive an email letting you know about your payment. After clicking on the link included in the email, you can log in to PayPal or sign up for a new account (100% FREE). The money will immediately appear in your account balance. Learn more about it on www.dohnosoft.com Thank you, Problems? Questions? From sjmachin at lexicon.net Sun Jan 23 16:59:31 2005 From: sjmachin at lexicon.net (John Machin) Date: 23 Jan 2005 13:59:31 -0800 Subject: Fuzzy matching of postal addresses [1/1] References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <1106517571.768306.23430@f14g2000cwb.googlegroups.com> Andrew McLean wrote: > In case anyone is interested, here is the latest. > def insCost(tokenList, indx, pos): > """The cost of inserting a specific token at a specific normalised position along the sequence.""" > if containsNumber(tokenList[indx]): > return INSERT_TOKEN_WITH_NUMBER + POSITION_WEIGHT * (1 - pos) > elif indx > 0 and containsNumber(tokenList[indx-1]): > return INSERT_TOKEN_AFTER_NUMBER + POSITION_WEIGHT * (1 - pos) > elif tokenList[indx][0] in minorTokenList: > return INSERT_MINOR_TOKEN > else: > return INSERT_TOKEN + POSITION_WEIGHT * (1 - pos) > > def delCost(tokenList, indx, pos): > """The cost of deleting a specific token at a specific normalised position along the sequence. > This is exactly the same cost as inserting a token.""" > return insCost(tokenList, indx, pos) Functions are first-class citizens of Pythonia -- so just do this: delCost = insCost Re speed generally: (1) How many addresses in each list and how long is it taking? On what sort of configuration? (2) Have you considered using pysco -- if not running on x86 architecture, consider exporting your files to a grunty PC and doing the match there. (3) Have you considered some relatively fast filter to pre-qualify pairs of addresses before you pass the pair to your relatively slow routine? Soundex?? To put it bluntly, the _only_ problem to which soundex is the preferred solution is genealogy searching in the US census records, and even then one needs to know what varieties of the algorithm were in use at what times. I thought you said your addresses came from authoritative sources. You have phonetic errors? Can you give some examples of pairs of tokens that illustrate the problem you are trying to overcome with soundex? Back to speed again: When you look carefully at the dynamic programming algorithm for edit distance, you will note that it is _not_ necessary to instantiate the whole NxM matrix -- it only ever refers to the current row and the previous row. What does space saving have to do with speed, you ask? Well, Python is not FORTRAN; it takes considerable effort to evaluate d[i][j]. A relatively simple trick is to keep 2 rows and swap (the pointers to) them each time around the outer loop. At the expense of a little more complexity, one can reduce this to one row and 3 variables (north, northwest, and west) corresponding to d[i-1][j], d[i-1][j-1], and d[i][j-1] -- but I'd suggest the simple way first. Hope some of this helps, John From Scott.Daniels at Acm.Org Mon Jan 10 16:35:42 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 10 Jan 2005 13:35:42 -0800 Subject: Writing huge Sets() to disk In-Reply-To: References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> Message-ID: <41e2f24d$1@nntp0.pdx.net> Tim Peters wrote: > [Martin MOKREJ?] >> just imagine, you want to compare how many words are in English, German, >>Czech, Polish disctionary. You collect words from every language and record >>them in dict or Set, as you wish. > > Call the set of all English words E; G, C, and P similarly. > >> Once you have those Set's or dict's for those 4 languages, you ask >>for common words > > This Python expression then gives the set of words common to all 4: > E & G & C & P >>and for those unique to Polish. > P - E - G - C One attack is to define a hash to get sizes smaller. Suppose you find your word sets are 10**8 large, and you find you need to deal with sets of size 10**6. Then if you define a hash that produces an integer below 100, you'll find: E & G & C & P == Union(E_k & G_k & C_k & P_k) for k in range(100) P - E - G - C == Union(P_k - E_k - G_k - C_k) for k in range(100) where X_k = [v for v in X if somehash(v) == k] This means, you can separate the calculation into much smaller buckets, and combine the buckets back at the end (without any comparison on the combining operations). For calculating these two expressions, you can dump values out to a file per hash per language, sort and dupe-elim the contents of the various files (maybe dupe-elim on the way out). Then hash-by-hash, you can calculate parts of the results by combining iterators like inboth and leftonly below on iterators producing words from files. def dupelim(iterable): source = iter(iterable) former = source.next() # Raises StopIteration if empty yield former for element in source: if element != former: yield element former = element def inboth(left, right): '''Take ordered iterables and yield matching cases.''' lsource = iter(left) lhead = lsource.next() # May StopIteration (and we're done) rsource = iter(right) for rhead in rsource: while lhead < rhead: lhead = lsource.next() if lhead == rhead: yield lhead lhead = lsource.next() def leftonly(left, right): '''Take ordered iterables and yield matching cases.''' lsource = iter(left) rsource = iter(right) try: rhead = rsource.next() except StopIteration: # empty right side. for lhead in lsource: yield lhead else: for lhead in lsource: try: while rhead < lhead: rhead = rsource.next() if lhead < rhead: yield lhead except StopIteration: # Ran out of right side. yield lhead for lhead in lsource: yield lhead break > Real-word dictionaries shouldn't be a problem. I recommend you store > each as a plain text file, one word per line. Then, e.g., to convert > that into a set of words, do > > f = open('EnglishWords.txt') > set_of_English_words = set(f) > f.close() > > You'll have a trailing newline character in each word, but that > doesn't really matter. > > Note that if you sort the word-per-line text files first, the Unix > `comm` utility can be used to perform intersection and difference on a > pair at a time with virtually no memory burden (and regardless of file > size). In fact, once you've sorted these files, you can use the iterators above to combine those sorted files. For example: Ponly = open('polishonly.txt', 'w') every = open('every.txt', 'w') for hashcode in range(100): English = open('english_%s.txt' % hashcode) German = open('german_%s.txt' % hashcode) Czech = open('czech_%s.txt' % hashcode) Polish = open('polish_%s.txt' % hashcode) for unmatched in leftonly(leftonly(leftonly(dupelim(Polish), dupelim(English)), dupelim(German)), dupelim(Czech)): Ponly.write(unmatched) English.seek(0) German.seek(0) Czech.seek(0) Polish.seek(0) for matched in inboth(inboth(dupelim(Polish), dupelim(English)), inboth(dupelim(German), dupelim(Czech))): every.write(matched) English.close() German.close() Czech.close() Polish.close() Ponly.close() every.close() --Scott David Daniels Scott.Daniels at Acm.Org From pierre.barbier at cirad.fr Tue Jan 18 08:29:56 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Tue, 18 Jan 2005 14:29:56 +0100 Subject: extension module, thread safety? In-Reply-To: References: <41ecbaae$0$1046$626a14ce@news.free.fr> <41eccfe4$0$16621$636a15ce@news.free.fr> Message-ID: <41ed0ee9$0$2522$636a15ce@news.free.fr> Nick Coghlan a ?crit : > The Python 2.4 docs claim the functions were added in Python 2.3, even > though they aren't documented in the 2.3.4 docs. > > The 2.3 release PEP (PEP 283) confirms that PEP 311 (which added these > functions) went in. Indeed, I just tested it and now it works fine :) Thanks a lot :) > > Cheers, > Nick. > From tim.golden at viacom-outdoor.co.uk Tue Jan 4 09:24:14 2005 From: tim.golden at viacom-outdoor.co.uk (Tim G) Date: 4 Jan 2005 06:24:14 -0800 Subject: Problem remotely shutting down a windows computer with python In-Reply-To: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> References: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> Message-ID: <1104848654.965978.63000@z14g2000cwz.googlegroups.com> > I have a problem when using the python script found here: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/360649 > > It is a script to remotely shutdown a windows computer. When I use it, > the computer shuts down, but doesn't power off like with a regular > shutdown. It stays on the "Safe to power off" screen and I have to push > the power button to actually power off. Anyone know why this happens > with this script? Thanks for any help. > > Eric I see that others have answered the question pretty completely, but just to add the obligatory WMI solution: [ assumes you're using the wmi module from http://tgolden.sc.sabren.com/python/wmi.html ] import wmi c = wmi.WMI (computer="other_machine", privileges=["RemoteShutdown"]) os = c.Win32_OperatingSystem (Primary=1)[0] os.Win32Shutdown (Flags=12) The Flags=12 bit should shut down all the way. TJG From skip at pobox.com Sun Jan 30 22:20:24 2005 From: skip at pobox.com (Skip Montanaro) Date: Sun, 30 Jan 2005 21:20:24 -0600 Subject: {Spam?} Re: naive doc question In-Reply-To: References: <5175a81c050129163826fcd734@mail.gmail.com> Message-ID: <16893.41976.351896.710133@montanaro.dyndns.org> >> I wanted a list of all the methods of dict for example... where can i >> find it? Terry> Lib Ref 2.3.8 Mapping Types. Do browse chapter 2 so you know Terry> what is there. I think the best doc page to bookmark is the global module index: http://docs.python.org/lib/modindex.html Not only does it give you a quick index to the modules, but if you click __builtin__ it will refer you to section 2.1. In the dev docs (2.5a0) it refers you to chapter 2, even better as far as I'm concerned. With the above bookmark I don't really have to remember where much else in the docs live. Skip From peter at engcorp.com Thu Jan 20 23:39:19 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Jan 2005 23:39:19 -0500 Subject: global variable, ok for string, bad for int In-Reply-To: <41f07e65$1_2@aeinews.> References: <41f07e65$1_2@aeinews.> Message-ID: francisl wrote: > I have a problem when I declare global variable. > If it is string, dict, array or tuple, everything goes fine, but with > int, I get an "used before declaration" error. > > here a sample : > vardict = {'un':1, 'deux':2} > > def print_value(): > print vardict['un'] > ######### ok, that works > > -------------------- > #!/bin/python > varint = 1 > > def print_value(): > print varint > ######### ok, that failed Please *always* post tracebacks, the actual traceback cut and pasted with the mouse from your session, when you are asking for help with errors like this. There is nothing called a "used before declaration" error... Was what you actually got an "UnboundLocalError: local variable 'varint' referenced before assignment", or something else? Don't retype: cut and paste. Also, please post only the actual code you are running, reduced to the simplest form which still reproduces the problem. The above code runs perfectly well, even if you add the missing call to print_value() at the end of the module. -Peter From cybermanxu at hotmail.com Fri Jan 21 17:59:55 2005 From: cybermanxu at hotmail.com (Jinming Xu) Date: Fri, 21 Jan 2005 16:59:55 -0600 Subject: Tuple size and memory allocation for embedded Python In-Reply-To: <1f7befae0501211451402a79aa@mail.gmail.com> Message-ID: >From: Tim Peters >Reply-To: Tim Peters >To: python-list at python.org >Subject: Re: Tuple size and memory allocation for embedded Python >Date: Fri, 21 Jan 2005 17:51:21 -0500 > >[Jinming Xu] > >> Python seems unstable, when allocating big memory. For > >> example, the following C++ code creates a tuple of tuples: > >> > >> PyObject* arCoord = PyTuple_New(n); > >> double d = 1.5; > >> for(int i=0; i >> { > >> PyObject* coord = PyTuple_New(2); > >> PyTuple_SetItem(coord,0, PyFloat_FromDouble(d));//x > >> PyTuple_SetItem(coord,1, PyFloat_FromDouble(d));//y > >> PyTuple_SetItem(arCoord,i, coord); > >> } > >> > >> When the n is small, say 100, the code works fine. when n > >> is big, say > 10,000, Python has trouble allocating > >> memory, saying: > >> > >> "Exception exceptions.IndexError: 'tuple index out of range' > >> in 'garbage collection' ignored > >> Fatal Python error: unexpected exception during garbage > >> collection > >> Aborted" > >[Craig Ringer] > > You're not checking for errors from PyTuple_SetItem. > >Or from PyTuple_New(), or from PyFloat_FromDouble(). They can all >fail, and indeed: > > > You need to do so, otherwise exceptions will go uncaught > > and may pop up at weird points later in your software's > > execution, or crash things. > >That's right. There's no point thinking about this at all before >every C API call is checked for an error return. > >BTW, since the error occurred during garbage collection, there's >really no reason to believe that the true cause of the problem is in >the code shown. It could simply be that allocating a whole lot of >tuples here triggers a round of garbage collection, which in turn >reveals an error in code we haven't been shown. In fact, I expect >that's actually the case. The possible errors the OP is ignoring here >are overwhemingly possible failures of malloc() to find more memory, >and in those cases the C API calls shown would return NULL, and a >segfault would be very likely soon after. >-- >http://mail.python.org/mailman/listinfo/python-list Hi folks, Thank you all for your prompt answers. I'll take a look for my code in the days coming. Have a good weekend! Jinming _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! hthttp://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From H.Duerer at gmx.net Thu Jan 27 11:44:44 2005 From: H.Duerer at gmx.net (Holger Duerer) Date: Thu, 27 Jan 2005 16:44:44 +0000 Subject: parsing WSDL References: <6bc0c3c.0501270529.5b9d8e00@posting.google.com> Message-ID: <87oefa7rer.fsf@ronaldann.demon.co.uk> >>>>> "Alessandro" == Alessandro Crugnola writes: Alessandro> Is there a way, maybe using 4suite, to read a wsdl Alessandro> file and find for every method all the input/output Alessandro> params and their type? Have you had a look at the Python WS tools? They do have some sort of WSDL support, so I assume you could get the info from those classes. http://pywebsvcs.sf.net/ Holger From oliver.eichler at dspsolutions.de Fri Jan 28 03:50:47 2005 From: oliver.eichler at dspsolutions.de (Oliver Eichler) Date: Fri, 28 Jan 2005 09:50:47 +0100 Subject: get list of member variables from list of class Message-ID: Hi what will be the fastest solution to following problem class a: def __init__(self): self.varA = 0 self.varB = 0 s.o. ... listA = [a]*10 varA = [] varB = [] for l in listA: varA.append(l.varA) varB.append(l.varB) s.o. ... I could think of: [varA.append(l.varA) for l in listA] [varB.append(l.varB) for l in listA] s.o. ... But is this faster? After all I have to iterate over listA several times. Any better solutions? Oliver From zhen.ren at gmail.com Thu Jan 27 14:04:55 2005 From: zhen.ren at gmail.com (Blues) Date: 27 Jan 2005 11:04:55 -0800 Subject: gnuplot on Canvas widget Message-ID: <1106852695.371569.234820@f14g2000cwb.googlegroups.com> Hey, I have used two great models - Tkinter and Gnuplot.py - for a while. I can display an image on a Canvas widget using Tkinter and I can also generate a gnuplot from Python on the fly in a separate window. Does anyone know how to display such a gnuplot on the Canvas widget with an image in it? Thanks. Michael From jtr at ofb.net Mon Jan 3 18:56:31 2005 From: jtr at ofb.net (John Reese) Date: Mon, 3 Jan 2005 23:56:31 +0000 (UTC) Subject: using HTTP Digest auth with arbitrary HTTP methods? References: Message-ID: On 03 Jan 2005 18:11:06 +0000, John J. Lee wrote: > (Re ternary operator: Everybody who read this list at certain times in > the past is painfully aware of that fact, and of precisely why it's > not quite true, and of all the syntax alternatives for real ternary > conditionals that will never be part of Python ;-) Yeah, I ran across the PEP after I posted this. Sorry to bring up a sore subject.... > Nobody is really in charge: just go ahead and submit a patch. Drop me > an email when you do, and I'll try to review it. The only reason > urllib2 doesn't already do arbitrary HTTP methods is that nobody has > spent the time to think carefully if a .set_method() really is the > right way to do it, then followed through with the work needed to get > a patch applied. Patch id #1095362 on Sourceforge. It turns out one of the bugs had already been fixed in CVS -- the digest bug was the only one left, so this is a one-line fix. > > As always, a precondition for change is that somebody thinks something > through carefully, writes tests, documentation, patch and submits all > three to the SF patch tracker with a brief explanation like the one > you give above. > > BTW, Greg Stein started work on adding the stuff you need at the > httplib level (as module httpx). He seems too busy to finish it, but > see modules httpx and davlib (one or both are in the Python CVS > sandbox). He thinks httplib is a better place for DAV than urllib2, > and he should know. But go ahead and fix urllib2 anyway... :-) These files are 2 and 3 years old. He's probably right that an interface more like httplib would be more appropriate for a DAV client; urllib2 is more about generalizing open() to use URLs than fully exposing the protocol. But urllib2 does have all those convenient handler-chains, and a good DAV client needs to handle a lot of those same situations, so it might be a good idea to at least find a way to share the handler classes. From kp8 at mac.com Tue Jan 11 15:58:04 2005 From: kp8 at mac.com (kpp9c) Date: 11 Jan 2005 12:58:04 -0800 Subject: Time script help sought! In-Reply-To: <1105474524.083536.129220@f14g2000cwb.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> Message-ID: <1105477084.525279.312970@f14g2000cwb.googlegroups.com> I also notice that there is the is the 'datetime' module, which is new to version 2.3, which i now have access to. My feeling is that this will do much of what i want, but i can't get my head round the standard library reference stuff http://www.python.org/doc/lib/module-datetime.html I don't have any texts with me either and it probably is too new to be in the Python Standard Library book by Fredrik Lundh or the Python Essential Reference by David Beazley -kevin- From frank at chagford.com Sat Jan 29 11:03:45 2005 From: frank at chagford.com (frank at chagford.com) Date: 29 Jan 2005 08:03:45 -0800 Subject: Line graphics on Linux console Message-ID: <1107014625.348051.239750@f14g2000cwb.googlegroups.com> Hi all I don't think this is strictly a Python problem, but as it manifests itself in one of my Python programs, I am hoping that somebody in this group can help me. The following is a message I sent to co.os.linux.setup - "My question concerns line graphics on a text-based console. ?My actual problem relates to a [Python] program I have written using ncurses, b?ut you can easily test it by running a program like minicom. If you call up the minicom menu, it should be surrounded by ?a nice box made up of horizontal and vertical lines, corners, etc. It used to work up until Redhat 7. Since upgrading to Redhat 9, and now Fedo?ra, it (and my program) has stopped working." I received the following reply from Thomas Dickey - "That's because Redhat uses UTF-8 locales, and the Linux cons?ole ignores vt100 line-drawing when it is set for UTF-8. (screen also d?oes this). ncurses checks for $TERM containing "linux" or "screen" (sin?ce there's no better clues for the breakage) when the encoding is UTF-8?, and doesn't try to use those escapes (so you would get +'s and -'s). co?mpiling/linking with libncursesw would get the lines back for a properly-wri?tten program." I don't really understand the last sentence. Does anyone know if it is possible to do this (or anything else) or am I stuck. TIA for any advice. Frank Millman From skip at pobox.com Mon Jan 17 10:01:25 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 17 Jan 2005 09:01:25 -0600 Subject: strange note in fcntl docs In-Reply-To: <20050117053949.GA28456@grulic.org.ar> References: <20050117053949.GA28456@grulic.org.ar> Message-ID: <16875.54085.712019.524951@montanaro.dyndns.org> John> In the fnctl docs for both python 2.3 and 2.4 there is a note at John> the bottom that says John> The os.open() function supports locking flags and is available on John> a wider variety of platforms than the lockf() and flock() John> functions, providing a more platform-independent file locking John> facility. John> however, in neither of those versions does os.open support any John> kind of mysterious "locking flags", nor is there any reference in John> os to any kind of locking magic (nor do any C open()s I know of John> support any kind of locking semantics). The note seems bogus; am I John> missing something, or should it be elided? I could have sworn that os.open supported the O_SHLOCK and O_EXLOCK flags. I'm pretty sure I've used them in the past, but don't see them now. (They aren't in 2.2 either.) If you try this: O_SHLOCK = 0x0010 O_EXLOCK = 0x0020 (those are the definitions on my Mac - YMMV) does os.open("somefile", O_SHLOCK|) work? Skip From http Sat Jan 1 19:41:05 2005 From: http (Paul Rubin) Date: 01 Jan 2005 16:41:05 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> Message-ID: <7xsm5kfyse.fsf@ruckus.brouhaha.com> beliavsky at aol.com writes: > Overall I agree with you and would like to have OPTIONAL static type > declarations in Python, as has often been discussed. But without > facilities for generic programming, such as templates in C++, static > type declarations can force one to duplicate a LOT of code, with one > sorting routine each for integer, floats, strings, etc. I don't see that big a problem. The current Python sorting routine operates on instances of class "object" and calls the __cmp__ method to do comparisons. Every class of sortable objects either defines a __cmp__ method or inherits one from some superclass, and sort calls those methods. Static type declarations would not require writing any additional sorting routines. From fumanchu at amor.org Wed Jan 19 16:38:06 2005 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 19 Jan 2005 13:38:06 -0800 Subject: RuntimeError: dictionary changed size during iteration Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398208@exchange.hqamor.amorhq.net> Roman Suzi wrote: > I think, the behaviour below is misfeature: > > >>> [e for e in vars()] > Traceback (most recent call last): > File "", line 1, in ? > RuntimeError: dictionary changed size during iteration > >>> e = None > >>> [e for e in vars()] > ['e', '__builtins__', 'rlcompleter', '__file__', '_[1]', > 'atexit', '__name__', > 'readline', '__doc__'] But not unexpected, since vars() returns a dictionary, and binding 'e' changes that dictionary while you are iterating over it. Try either: [e for e in vars().keys()] or e = None [e for e in vars()] or the generator expression if you have Python 2.4. Robert Brewer MIS Amor Ministries fumanchu at amor.org From g.franzkowiak at web.de Sat Jan 15 13:37:54 2005 From: g.franzkowiak at web.de (G.Franzkowiak) Date: Sat, 15 Jan 2005 19:37:54 +0100 Subject: interpret 4 byte as 32-bit float (IEEE-754) In-Reply-To: <41e952b9$1@nntp0.pdx.net> References: <34t1p2F4foiplU1@individual.net> <41e952b9$1@nntp0.pdx.net> Message-ID: <41E96302.4020003@web.de> Scott David Daniels schrieb: > franzkowiak wrote: > >> I've read some bytes from a file and just now I can't interpret 4 >> bytes in this dates like a real value. An extract from my program: >> def l32(c): >> return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) + >> (ord(c[3])<<24) >> ... >> value = l32(f.read(4)) <--- 3F 8C CC CD should be 1.11 >> > OK, here's the skinny (I used blocks & views to get the answer): > > import struct > bytes = ''.join(chr(int(txt, 16)) for txt in '3F 8C CC CD'.split()) > struct.unpack('>f', bytes) > > I was suspicious of that first byte, thought it might be an exponent, > since it seemed to have too many on bits in a row to be part of 1.11. > > -Scott David Daniels > Scott.Daniels at Acm.Org Ok, I the string exist with "mystr = f.read(4)" and the solution for this case is in your line "struct.unpack('>f', bytes)" But what can I do when I want the interpret the content from the Integer myInt (*myInt = 0x3F8CCCCD) like 4-byte-real ? This was stored with an othes system in a binary file to CD CC 8C 3F and now is it in python in value. The conversion is not possible. It's right... one of this bytes is an exponent. I want copy the memory content from the "value address" to "myReal address" and use print "%f" %myReal. Is myReal then the right format ? What can I do with python, in FORTH is it simple ( >f f. ) gf From sean_mcilroy at yahoo.com Mon Jan 10 22:48:44 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 10 Jan 2005 19:48:44 -0800 Subject: unicode mystery Message-ID: I recently found out that unicode("\347", "iso-8859-1") is the lowercase c-with-cedilla, so I set out to round up the unicode numbers of the extra characters you need for French, and I found them all just fine EXCEPT for the o-e ligature (oeuvre, etc). I examined the unicode characters from 0 to 900 without finding it; then I looked at www.unicode.org but the numbers I got there (0152 and 0153) didn't work. Can anybody put a help on me wrt this? (Do I need to give a different value for the second parameter, maybe?) Peace, STM PS: I'm considering looking into pyscript as a means of making diagrams for inclusion in LaTeX documents. If anyone can share an opinion about pyscript, I'm interested to hear it. Peace From takarov2003 at yahoo.com Wed Jan 26 17:00:36 2005 From: takarov2003 at yahoo.com (takarov2003 at yahoo.com) Date: 26 Jan 2005 14:00:36 -0800 Subject: 20050126 find replace strings in file In-Reply-To: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> Message-ID: <1106776836.679242.167880@c13g2000cwb.googlegroups.com> Xah Lee wrote: > ? # -*- coding: utf-8 -*- > ? # Python > ? > ? import sys > ? > ? nn = len(sys.argv) > ? > ? if not nn==5: > ? print "error: %s search_text replace_text in_file out_file" % > sys.argv[0] > ? else: > ? stext = sys.argv[1] > ? rtext = sys.argv[2] > ? input = open(sys.argv[3]) > ? output = open(sys.argv[4],'w') I guess there is no way to check if the file opened fine? What if the filesystem or file is locked for this user/session. Pretty puny language if it cannot tell you that it cannot do what you tell it to. > ? > ? for s in input: > ? output.write(s.replace(stext,rtext)) > ? output.close() > ? input.close() Same for the close. Is there no way check a good close? > > ------------------------- > save this code as find_replace.py > run it like this: > python find_replace.py findtext replacetext in_file out_file > > the sys.argv is from sys. sys.argv[0] is the program's name itself. > > note the idiom > "for variable_name in file_object" > > note that since this code reads each > line in turn, so huge file is of no-problemo > > the code is based from Python > Cookbook of Alex Martelli & David > Ascher, page 121 > > in Python terminal, type help() then > 'FILES' and or 'sys' > for reference. > > try to modify this file for your > needs. > -------------------------------------- > In perl, similar code can be achieved. > the following code illustrates. > > if (scalar @ARGV != 4) {die "Wrong arg! Unix BNF: $0 > \n"} > $stext=$ARGV[0]; > $rtext=$ARGV[1]; > $infile = $ARGV[2]; > $outfile = $ARGV[3]; > open(F1, "<$infile") or die "Perl fucked up. Reason: $!"; > open(F2, ">$outfile") or die "Perl fucked up. Reason: $!"; In 7 years of perl programming, I have never seen an open error that had anything to do with perl processing. Normally, if I get an error, the file does not exist, or has permissions set so that the current user/session is not allowed to open the file. > while ($line = ) { > chomp($line); > $line =~ s/$stext/$rtext/g; > print F2 "$line\n"; > } > close(F1) or die "Perl fucked up. Reason: $!"; > close(F2) or die "Perl fucked up. Reason: $!"; Same here. Never seen Perl fuck up on closing a file. Usually something in the OS or file system that does it. > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html From Dennis.Benzinger at gmx.net Thu Jan 27 03:35:06 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Thu, 27 Jan 2005 09:35:06 +0100 Subject: String Fomat Conversion In-Reply-To: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Message-ID: <41f8a7b9$1@news.uni-ulm.de> mcg wrote: > Investigating python day 1: > > Data in file: > x y > 1 2 > 3 4 > 5 6 > > > Want to read file into an array of pairs. > > in c: scanf("%d %d",&x,&y)---store x y in array, loop. > > How do I do this in python?? > In the actual application, the pairs are floating pt i.e. -1.003 > Either do what the other posters wrote, or if you really like scanf try the following Python module: Scanf --- a pure Python scanf-like module http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/ Bye, Dennis From tmohr at s.netic.de Thu Jan 13 15:20:06 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Thu, 13 Jan 2005 21:20:06 +0100 Subject: reference or pointer to some object? References: Message-ID: Hi, > Could you give us a more concrete use case? My suspicion is that > anything complicated enough to be passed to a method to be modified will > probably be more than a simple int, float, str or tuple... In which > case, it will probably have methods to allow you to update it... yes, to be more explicit: I'm quite new to python and i wrote a small function that does a hexdump of a string. That string can be quite large, so i suspected a large overhead when the string would be copied and handed over to the function. But i think my understanding was wrong (though it is not yet clear). If i hand over a large string to a function and the function had the possibility to change it, wouldn't that mean that it is necessary to hand over a _copy_ of the string? Else, how could it be immutable? Thinking about all this i came to the idea "How would i write a function that changes a string with not much overhead?". def func(s): change s in some way, remove all newlines, replace some charaters by others, ... return s s = func(s) This seems to be a way to go, but it becomes messy if i hand over lots of parameters and expect some more return functions. Maybe it is because i did lots of perl programming, but func(\$s) looks easier to me. > In my case, rather than your original example, which you want to look > something like: > > def func(x): > x += 123 > > x = 5 > func(x) > > I'd just write: > > x = 5 > x += 123 You're right, of course. I'm sorry the second example is still a bit constructed, but i came across it by writing the hexdump utility and wanted to reduce overhead. Best regards, Torsten. From tonino.greco at gmail.com Fri Jan 21 06:46:13 2005 From: tonino.greco at gmail.com (Tonino) Date: 21 Jan 2005 03:46:13 -0800 Subject: tkinter socket client ? In-Reply-To: <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> Message-ID: <1106307973.536723.297940@z14g2000cwz.googlegroups.com> thanks for the reply . just one problem - I do not know how to sit in a "loop" accepting messages on the socket connection - writting them to the Text() widget - refreshing the the GUI - and then starting all over .... where do I put the loop for the socket ? Thanks Tonino From dave at pythonapocrypha.com Fri Jan 28 15:20:47 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 28 Jan 2005 13:20:47 -0700 Subject: Best python postgres module? In-Reply-To: <41fa75ef_1@news.arcor-ip.de> References: <41fa75ef_1@news.arcor-ip.de> Message-ID: <41FA9E9F.1070401@pythonapocrypha.com> Roland Heiber wrote: > i recently migrated from mysql to postgresql and did use severel python > postgres-modules. All do what they are designed for, so which one would > you use? psycopg, pygresql, pypgsql? psycopg seems to be the best > solution for heavy traffic/multiple connections .... i have no real > testing environment, so any advice which one to use for different > usecases would be nice. Hi Roland, We've been using psycopg (via Zope and straight Python programs) for about a year and haven't had any problems at all. We don't store much binary data so I don't know how well psycopg handles blobs and what-not, but performance and reliability has been fine. I have no idea how psycopg stacks up against the others; in the end we chose it because the project appeared to be active, it was easy enough to set up, and a few test scripts we made all worked (how's that for rigorous evaluation? ;-) ). HTH, Dave From reinhold-birkenfeld-nospam at wolke7.net Tue Jan 18 12:45:49 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 18 Jan 2005 18:45:49 +0100 Subject: [perl-python] 20050118 keyed list In-Reply-To: References: <1106027360.920787.321590@z14g2000cwz.googlegroups.com> Message-ID: <3550aeF4hi6bhU1@individual.net> J?rgen Exner wrote: >> ? # see "perldoc perldata" for an unix-styled course. > > Excuse me? Do you mind explaining where exactly perldata is "Unix-styled"? Remember: Perl == Unix == Satan. Reinhold From jtr at ofb.net Mon Jan 3 19:30:29 2005 From: jtr at ofb.net (John Reese) Date: Tue, 4 Jan 2005 00:30:29 +0000 (UTC) Subject: HTTP GET request with basic authorization? References: <7c60b60505010215123462c90e@mail.gmail.com> Message-ID: On 03 Jan 2005 18:27:52 +0000, John J. Lee wrote: > Jonas Galvez writes: > >> Christopher J. wrote: >> > I tried this, but it didn't work: >> > conn.request("GET", "/somepage.html", None, >> > {"AUTHORIZATION": "Basic username:password"}) > [...] >> import re, base64, urllib2 >> >> userpass = ('user', 'pass') >> url = 'http://somewhere' >> >> request = urllib2.Request(url) >> authstring = base64.encodestring('%s:%s' % userpass) >> authstring = authstring.replace('\n', '') >> request.add_header("Authorization", "Basic %s" % authstring) >> >> content = urllib2.urlopen(request).read() > > There are handlers in urllib2 to do this for you, you shouldn't need > to do it by hand. I rarely do, so I won't risk an example... > > > John > The way to do it with the handlers follows; oddly, it's just about as long. import urllib2 url = 'http://somewhere' realm, user, pass = 'realm', 'user', 'pass' hm = urllib2.HTTPPasswordMgrWithDefaultRealm() hm.add_password(realm, url, user, pass) od = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(hm)) content = od.open(url).read() From simon.brunning at gmail.com Fri Jan 21 11:46:21 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 21 Jan 2005 16:46:21 +0000 Subject: circular iteration In-Reply-To: References: Message-ID: <8c7f10c6050121084633a474ae@mail.gmail.com> On 21 Jan 2005 08:31:02 -0800, Flavio codeco coelho wrote: > hi, > > is there a faster way to build a circular iterator in python that by doing this: > > c=['r','g','b','c','m','y','k'] > > for i in range(30): > print c[i%len(c)] I don''t know if it's faster, but: >>> import itertools >>> c=['r','g','b','c','m','y','k'] >>> for i in itertools.islice(itertools.cycle(c), 30): ... print i -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From maxm at mxm.dk Fri Jan 14 17:03:16 2005 From: maxm at mxm.dk (Max M) Date: Fri, 14 Jan 2005 23:03:16 +0100 Subject: oddities in the datetime module In-Reply-To: References: <41e79a1a$0$264$edfadb0f@dread12.news.tele.dk> Message-ID: <41e84175$0$258$edfadb0f@dread12.news.tele.dk> Serge Orlov wrote: > Max M wrote: > Yes, you did. datetime.timetuple is those who want *time module* format, you should use datetime.data, datetime.time, datetime.year > and so on... > > As they say, if the only tool you have is timetuple, everything looks like tuple > Try this: > >>>>dt = datetime(2005, 1, 1, 12, 0, 0) >>>>dt.date() > > datetime.date(2005, 1, 1) This doesn't solve it. I don't think you understand my issue. First of, it should be possible to easily convert between the datetime objects. And eg. the date object doesn't have a datetime() method. Which it could easily have. Neither does time. They could have. But I don't think that is the way to solve it. It is a problem if you make a subclass of datetime. Often you will ned to make datetime arithmetics with the new class. Like: datetime_subclass_1 + datetime_subclass_2 The result of that is a plain datetime In that case you will rather want your own subclass returned. But subclasses of datetime returns datetime objects. Not the subclass. So to do an add of your own objects you must convert the output to your own class "manually" class my_datetime(datetime): def __add__(self, other): result = datetime.__add__(self, other) return my_datetime(result.timetuple()[:6]) datetime(), time() etc. methods will not help with this. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From brianobush at gmail.com Thu Jan 13 23:36:19 2005 From: brianobush at gmail.com (brianobush at gmail.com) Date: 13 Jan 2005 20:36:19 -0800 Subject: Class initialization from a dictionary, how best? Message-ID: <1105677379.632236.17020@z14g2000cwz.googlegroups.com> # # My problem is that I want to create a # class, but the variables aren't known # all at once. So, I use a dictionary to # store the values in temporarily. # Then when I have a complete set, I want to # init a class from that dictionary. # However, I don't want to specify the # dictionary gets by hand # since it is error prone. # Thanks for any ideas, Brian # So I have a class defined that accepts a number of variables # and they must be all present at object creation time. class Test: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def __str__(self): return '%s, %s, %d' % (self.a, self.b, self.c) # For example: t1 = Test('asd', 'sdf', 9) print t1 # However, due to parsing XML, I am # creating the values incrementally # and I want to store them in a dictionary # and then map them easily to a class dictionary = {} # a mapping from source to destination mapping = { 'a': str, 'b': str, 'c': int, } # a sample source of values test_source = { 'a': 'test', 'b': 'asdf', 'c': 45 } # now we go through and extract the values # from our source and build the dictionary for attr_name, function in mapping.items(): dictionary[attr_name] = function(test_source.get(attr_name)) print dictionary # Here is the problem I want to avoid: # Having to list the variable names # as strings in multiple places. It is enought to # have them in the 'mapping' # dictionary above t2 = Test(dictionary.get('a'), dictionary.get('b'), dictionary.get('c')) print t2 From tdelaney at avaya.com Mon Jan 3 17:54:17 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 4 Jan 2005 09:54:17 +1100 Subject: Developing Commercial Applications in Python Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE02520251@au3010avexu1.global.avaya.com> Christophe Cavalaria wrote: > eeykay at gmail.com wrote: > >> Hello All, >> I am trying to convince my client to use Python in his new product. >> He is worried about the license issues. Can somebody there to point >> me any good commercial applications developed using python ?. The >> licence clearly says Python can be used for commercial applications. >> Is there any other implications like that of GPL to make the source >> open ? Thanks for any help. eeykay > Troika games use Python in their games. It seems you can even get the > source .py files for Vampires: Bloodlines :) Absolutely - it's a slightly modified version of 2.1.2. Troika also used Python for the Temple of Elemental Evil. I even compiled psyco to work with Bloodlines and modified the .py source to call it - worked perfectly well, but didn't give me any significant performance improvement :( I'm CPU limited, so I thought it was worth a try. I'm wondering if I can hack Python 2.4 into Bloodlines ... the biggest problem is that Bloodlines used .vpk files for packaging, and I believe the major modifications to 2.1 are to allow these to be read. I've already extracted all of these though ... Anyway, back to the original question: http://www.python.org/doc/faq/general.html#are-there-copyright-restricti ons-on-the-use-of-python Tim Delaney From jeff at ccvcorp.com Thu Jan 27 20:25:29 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 27 Jan 2005 17:25:29 -0800 Subject: inherit without calling parent class constructor? In-Reply-To: References: Message-ID: <10vj4ovqee29oc9@corp.supernews.com> Christian Dieterich wrote: > On D?ardaoin, Ean 27, 2005, at 14:05 America/Chicago, Jeff Shannon wrote: > >> the descriptor approach does. In either case, the calculation happens >> as soon as someone requests D.size ... > > Agreed. The calculation happens as soon as someone requests D.size. So > far so good. Well, maybe I'm just not into it deep enough. As far as I > can tell, In your class D the calculation happens for every > instantiation of D, right? For my specific case, I'd like a construct > that calculates D.size exactly once and uses the result for all > subsequent instantiations. Okay, so size (and the B object) is effectively a class attribute, rather than an instance attribute. You can do this explicitly -- class D(object): _B = None def __getattr__(self, attr): if self._B is None: if myB is None: myB = B() D._B = myB return getattr(self._B, attr) Now, when the B object is first needed, it's created (triggering that expensive calculation) and stored in D's class object. Since all instances of D share the class object, they'll all share the same instance of B. Probably not worth the trouble in this particular case, but maybe in another case... :) Jeff Shannon Technician/Programmer Credit International From aleaxit at yahoo.com Sat Jan 1 15:38:54 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 1 Jan 2005 21:38:54 +0100 Subject: what is lambda used for in real code? References: <1gpq3nl.8f2klu80m2z0N%aleaxit@yahoo.com> Message-ID: <1gpqbfo.66l1sy191iqz8N%aleaxit@yahoo.com> Steve Holden wrote: ... > >>And you'd create an anonymous type how, exactly? > > > >>>>type('',(),{}) ... > Indeed. And then you'd insert all the methods as lambdas by .... > > We both know that the Python language framework has enough introspection > capabilities to do this, but I'm pretty sure you wouldn't try to pretend > that this would represent a realistic programming style. Or am I wrong? Calling 'type' to make a new type on the fly is occasionally neat -- not quite as often as (say) using 'lambda', maybe;-). Neither should be a 'programming _style_' as opposed to an occasional convenience -- of the two, lambda has more sensible use cases, but is also more prone to overuse in practice. Also, the ability to call 'type' to make a type adds zero complexity or issues to the language: it's basically zero cost, just like the ability to call 'int' to make an int, and so on. This can't be said of lambda, alas: it has a non-zero cost in terms of (slightly) 'fattening' the language. Alex From apardon at forel.vub.ac.be Thu Jan 13 03:39:13 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 08:39:13 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-01-12, Steve Holden schreef : > > Given that Guido is on record as saying that expressions aren't > statements because he wants those things to be separate, I don't really > see why there's this consistent pressure to reverse that decision. Well, it seems that Guido is wrong then. The documentation clearly states that an expression is a statement. More specifically, everywhere you can use a statement, you can simply use an expression according to the python syntax. That makes the set of expressions a subset of the set of statements and thus makes an expression a statement. > Which would be a worthier goal than trying to graft macros on to Python. > You responded that macros would be difficult to implement in m4 because > (in essence) of the indented structure of Python. I'm not convinced > they'd be any easier in Python, and I'm *certainly* not convinced that > their addition would improve Python's readability. > > At best it would offer new paradigms for existing constructs (violating > the "there should be one obvious way to do it" zen); at worst it would > obfuscate the whole language. That zen is already broken. Look at the number of answers one gets if a newbee askes for a ternary operator. I think that a simple ternary operator or macro's with an official supported macro that implemented the ternary operator would have been far closer to the spirit of only having one obvious way than what we have now. -- Antoon Pardon From steven.bethard at gmail.com Mon Jan 24 17:40:10 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Jan 2005 15:40:10 -0700 Subject: Instances of class object not modifiable? In-Reply-To: References: Message-ID: Krzysztof Stachlewski wrote: > I tried to run the following piece of code: > > 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. > >>>>o = object() >>>>o.a = 5 > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'object' object has no attribute 'a' > > But if I do: > >>>>class c(object): >>>> pass >>>>o = c() >>>>o.a = 5 > > > ...then it, of course, works. > So what's wrong with the first example? It's an instance of class object. ;) If my memory serves me right, instances of object have no __dict__. py> o = object() py> o.__dict__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'object' object has no attribute '__dict__' Yup, that looks right. As I understand it, the reason for this is so that classes which *really* need to be memory efficient can define __slots__ instead and save some overhead. If you're interested in having a builtin object that can be used as above, you should help me rally for my Bunch type PEP. They haven't given me a PEP number for it yet, but a patch is available[1] and I've included the current draft of the PEP below. [1]http://sourceforge.net/tracker/?func=detail&atid=305470&aid=1094542&group_id=5470 Steve ---------------------------------------------------------------------- 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 update method of Bunch objects supports similar arguments. If Bunch objects are used to represent hierarchical data, comparison of such objects becomes a concern. For this reason, Bunch objects support object equality:: >>> 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: ... result.update(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)) ... result.update(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' and 'Struct'. 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 nun at example.com Sat Jan 15 06:24:50 2005 From: nun at example.com (Mitja) Date: Sat, 15 Jan 2005 12:24:50 +0100 Subject: How to del item of a list in loop? References: Message-ID: On Sat, 15 Jan 2005 15:27:08 -0500, skull wrote: > lst = [1, 2, 3] > for i in lst: > print i > if i == 2: > lst.remove(i) > > the result is: > > 1 > 2 As others have suggested, you can use a copy of the list. Alternatively and depending on what you're trying to accomplish (how complicated it is), lst = [i for i in lst if i!=2] might look better. -- Mitja From g.horvath at gmx.at Thu Jan 27 13:14:48 2005 From: g.horvath at gmx.at (Gregor Horvath) Date: Thu, 27 Jan 2005 19:14:48 +0100 Subject: HTML Tree View with
        and Message-ID: Hi, Before I reinvent the wheel I`d like to ask if someone has done this before since I did not find an advice at Google. The goal is to create a dynamic Tree View in HTML. Say I have a data strucure like this: structList = {'Sun':{'Sun.1':['Sun1.1','Sun1.2'],'Sun.2':['Sun2.1','Sun2.2']},'Kupa':['Kupa1']} I want to transform this into HTML:
        1. Sun
          1. Sun.1
            1. Sun1.1
            2. Sun1.2
          2. Sun.2
            1. Sun2.1
            2. Sun2.2
        2. Kupa
          1. Kupa1
        If the user clicks on a branch-link say 'Sun.1' then the branch below opens/closes (not printed by the servlet). Like a tree view control in an native GUI app. Has this, or a similar approach, been done before in python ( I am using webware/cheetah)? -- Greg From ncoghlan at iinet.net.au Fri Jan 7 10:34:18 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 01:34:18 +1000 Subject: sorting on keys in a list of dicts In-Reply-To: <10tr9ejf05pv660@corp.supernews.com> References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: <41DEABFA.2020006@iinet.net.au> Jeff Shannon wrote: > I suppose that your version has the virtue that, if the sortkey value is > equal, items retain the order that they were in the original list, > whereas my version will sort them into an essentially arbitrary order. > Is there anything else that I'm missing here? Stability in sorting is a property not to be sneezed at - it means switching to sorting by a second key gives the effect of "sort by key 1, then by key 2", whereas that doesn't hold with an unstable sort algorithm. If you've ever used an application with an unstable sorting process and that only allows sorting a table on one column at a time, you'll appreciate the frustration that can cause :) Also, it's required to match the behaviour of the Python 2.4 version (which gets to take advantage of the stability of the builtin sort). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From foo at bar.com Sun Jan 16 11:38:00 2005 From: foo at bar.com (Steve Menard) Date: Sun, 16 Jan 2005 11:38:00 -0500 Subject: Integration with java (Jpype vs. JPE) In-Reply-To: References: <34s5krF4c85d5U1@individual.net> Message-ID: <41EA9868.70806@bar.com> Cameron Laird wrote: > In article <34s5krF4c85d5U1 at individual.net>, > Jon Perez wrote: > >>Can someone summarize in a nutshell what is the >>difference between JPype and JPE? > > > JPE's the original. It provided more functionality than JPype has > achieved so far, I believe (though that could change any day). I > think no one now maintains JPE. > > Someone really ought to include a couple of sentences to that effect > on the front page of . Well, Cameron summed it up pretty good :) I'd add that The only major (and yes I know it is VERY major) funtionailty missing in JPype is the ability to subclass Java classes in Python. On the other hand JPype will (soon) have functionality that JPE doesnt have. Java arrays can already (in 0.4) be iterated as regular Python collections. Version 0.5 will add that same behavior for Java collections (Map, List, Set, Iterator). Of course, the above is based on the JPE documentation, because I havent been able to get JPE to work. About Cameron's suggestion, sure. I'll do it as soon as I (or someone else) can get both JPype and JPE to work so they can be compared through more than just their respective documentation. Steve a.k.a devilwolf on sourceforge From bokr at oz.net Tue Jan 25 23:44:43 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 26 Jan 2005 04:44:43 GMT Subject: Classical FP problem in python : Hamming problem References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> <41f6162f.1768893674@news.oz.net> <10vd84er6bjr2ad@corp.supernews.com> Message-ID: <41f71fef.1836924838@news.oz.net> On Tue, 25 Jan 2005 11:46:04 -0800, Jeff Shannon wrote: >Bengt Richter wrote: > >> On 25 Jan 2005 08:30:03 GMT, Nick Craig-Wood wrote: >> >>>If you are after readability, you might prefer this... >>> >>>def hamming(): >>> def _hamming(): >>> yield 1 >>> for n in imerge(imap(lambda h: 2*h, iter(hamming2)), >>> imerge(imap(lambda h: 3*h, iter(hamming3)), >>> imap(lambda h: 5*h, iter(hamming5)))): >>> yield n >>> hamming2, hamming3, hamming5, result = tee(_hamming(), 4) >>> return result >> >> Are the long words really that helpful? >> >> def hamming(): >> def _hamming(): >> yield 1 >> for n in imerge(imap(lambda h: 2*h, iter(hg2)), >> imerge(imap(lambda h: 3*h, iter(hg3)), >> imap(lambda h: 5*h, iter(hg5)))): >> yield n >> hg2, hg3, hg5, result = tee(_hamming(), 4) # four hamming generators >> return result > >Well, judging by the fact that shortening the identifiers made it so >that you felt the need to add a comment indicating what they were >identifying, I'd say that yes, the long words *are* helpful. ;) >Comments are good, but self-documenting code is even better. The comment was a conscious factoring decision, in terms of documentation ;-) Regards, Bengt Richter From gurpreet.sachdeva at gmail.com Tue Jan 11 06:04:04 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Tue, 11 Jan 2005 16:34:04 +0530 Subject: Upgraded to python2.3 but httpd taking old version Message-ID: I upgraded my python to 2.3 from 2.2 but Apache (V 2.0.4) is taking old libraries for processing. I also made a soft link redirecting the old files to new files but of no help... These error logs shows that it is still using 2.2 :o( [Tue Jan 11 16:18:45 2005] [error] [client 127.0.0.1] import cgi [Tue Jan 11 16:18:45 2005] [error] [client 127.0.0.1] File "/usr/lib/python2.2/cgi.py", line 38, in ? Please help -- Garry From fredrik at pythonware.com Sat Jan 22 15:35:11 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 21:35:11 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> Message-ID: "rm" wrote: > furthermore, "users will suffer too", I'm suffering if I have to use C++, with all its exceptions > and special cases. and when you suffer, your users will suffer. in the C++ case, they're likely to suffer from spurious program crashes, massively delayed development projects, obscure security holes, etc. From boisgera at isia.cma.fr Thu Jan 13 07:32:22 2005 From: boisgera at isia.cma.fr (Sebastien Boisgerault) Date: 13 Jan 2005 04:32:22 -0800 Subject: Pickling a class instead of an instance Message-ID: Hi, It seems to me that it's not possible with the pickle module to serialize a class rather than an instance, as in >> from pickle import * >> >> class C(object): >> "... doc ..." >> a = 1 >> >> pickstr = dumps(C) I mean, it does *something*, there is no error indeed, but from the string pickstr, I am unable to rebuild the class C in a brand new context (got a "you're really stupid, all you deserve is an AttributeError because you know there is no attribute 'C' in the 'module' object" error). Am I wrong ? Why would the "(new-style) classes are regular objects too" mantra not apply in this case ? Could we imagine a patch to the pickle module to handle this kind of situation ? SB From mike at hobbshouse.org Tue Jan 4 17:13:45 2005 From: mike at hobbshouse.org (Michael Hobbs) Date: Tue, 04 Jan 2005 22:13:45 -0000 Subject: Optional Static Typing: Part II References: <10tluavnqqufg07@news.supernews.com> Message-ID: <10tm58phn0spucd@corp.supernews.com> John Roth wrote: > Now, the base objective seems to be to incorporate PyChecker > functionality into the root. This in turn requires type inference, > which in turn strongly suggests type annotations to help the > inferencer out over rough spots. > > I like this approach a lot. If he makes the type inferencer "proud", that might help alleviate the fears around here that it will become standard practice to put type annotations on everything. That is, if you explicitly annotate a function in the same way that the inferencer would have inferenced it, the PyChecker thingie would emit a message saying: "I'm no dummy! I could have told you that foo() takes an 'int' and returns a 'bool'. What do you think I am, stupid? Duuu-uhhh!" :) From jeff at ccvcorp.com Thu Jan 27 14:15:09 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 27 Jan 2005 11:15:09 -0800 Subject: subprocess.Popen() redirecting to TKinter or WXPython textwidget??? In-Reply-To: <41f811fe$0$148$3a628fcd@reader1.nntp.hccnet.nl> References: <41f80b1b$0$148$3a628fcd@reader1.nntp.hccnet.nl> <1106775371.049857.36360@z14g2000cwz.googlegroups.com> <41f811fe$0$148$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <10vif2imjcnvne5@corp.supernews.com> Ivo Woltring wrote: > The output of mencoder is not readable with readlines (i tried it) because > after the initial informational lines You don't get lines anymore (you get a > linefeed but no newline) > The prints are all on the same line (like a status line) > something like > Pos: 3,1s 96f ( 0%) 42fps Trem: 0min 0mb A-V:0,038 [171:63] Hm, I'm inferring that what you mean is that you get a carriage return (ASCII 0x0C) but no linefeed (ASCII 0x0A) -- CR returns you to the beginning of the current line, and LF advances you to the next line. Rather than using readlines(), you could simply read() a few characters (or a single character) at a time, buffering it yourself and passing it on when you see the CR. You're likely to run into I/O blockage issues no matter how you do this, though -- even if you're reading a single character at a time, read(1) won't return until you've read that character, and if the program on the other end of the pipe isn't writing anything, then your app is stuck. The "simple" way to do this is by using an i/o thread, which does something like this: buffer = [] while 1: char = outpipe.read(1) if char == '\0x0A': notify_gui_thread( ''.join(buffer) ) buffer = [] else: buffer.append(char) if StopEvent.IsSet(): raise CustomStopException Note that you don't want to try to update your GUI widgets directly from the worker (i/o) thread -- very few GUI toolkits are threadsafe, so you need to make all GUI calls from a single thread. Jeff Shannon Technician/Programmer Credit International From phleum_nospam at chello.se Fri Jan 28 11:42:04 2005 From: phleum_nospam at chello.se (Carl) Date: Fri, 28 Jan 2005 17:42:04 +0100 Subject: Installing Numeric with ATLAS and LAPACK References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> Message-ID: drife wrote: > Hello, > > Could someone please provide instructions for install Numeric > with ATLAS and LAPACK? > > I've actually done this correctly, I think. But I don't see any > difference in the speed. > > I'm calculating eigenvalues for a 3600 X 3600 covariance matrix. > > Calculating the eigenvalues for this matrix requires a mere 7 min > in Matlab 6.5...which uses ATLAS and LAPACK. > > > Thanks, > > > Daran What functions from ATLAS and LAPACK are you using? Carl From steve at holdenweb.com Sat Jan 8 14:09:09 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 08 Jan 2005 14:09:09 -0500 Subject: The best way to do web apps with Python? In-Reply-To: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41E02FD5.5080703@holdenweb.com> worzel wrote: > What is the best way to web developemnt with Python? Is there anything > close to PHP style in-page script placement that can create and use > other Python objects? I am not really interested in Zope (I believe that > is more a CMS than anything else?) I am also looking for something a > little more structured than a series of CGI Scripts. > More ways than you can shake a stick at, but nowadays you should consider using WSGI if you want your code to be portable across many frameworks. The Web SIG worked very hard last year on defining this gateway interface, with the intention that it should become widely available, and implementations are available now on environments as diverse as mod_python and CherryPy. You can read about it in Philip Eby's excellent PEP at http://www.python.org/peps/pep-0333.html > While on the topic - what is the expectataion of Python for this kind of > stuff? Would one use Python for certain other things but turn to PHP for > web apps - or would one use their Python skills in place of PHP? > Python is a real programming language, whereas PHP was originally intended as a simple way of scripting web content. Since then it has grown to encompass many of the same features as Python, but since they were retrofitted rather than designed in they are sometimes kind of clunky (as, IMHO, is Perl, although in a different way). But there's a lot of good work been done in both PHP and Perl, and I'd usually recommend using existing functionality in either language over a just-for-the-sake-of-it rewrite in Python. But that could just be because I don't like re-inventing wheels. 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 frans.englich at telia.com Sun Jan 23 13:01:50 2005 From: frans.englich at telia.com (Frans Englich) Date: Sun, 23 Jan 2005 18:01:50 +0000 Subject: What is print? A function? Message-ID: <200501231801.50080.frans.englich@telia.com> Nah, I don't think it's a function, but rather a builtin "statement". But it's possible to invoke it as an function; print( "test" ) works fine. So I wonder, what _is_ exactly the print statement? The untraditional way of invoking it(without paranteses) makes me wonder. The reason I thinks about this is I need to implement a debug print for my program; very simple, a function/print statement that conditionally prints its message whether a bool is true. Not overly complex. I tried this by overshadowing the print keyword, but that obviously didn't work.. Is defining a two-liner function the right way to go, or is there better ways to approach it? Cheers, Frans From hanchunhui at gmail.com Thu Jan 20 20:21:42 2005 From: hanchunhui at gmail.com (neutrino) Date: 20 Jan 2005 17:21:42 -0800 Subject: Print a string in binary format References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> Message-ID: <1106270502.219126.322790@f14g2000cwb.googlegroups.com> Mmm, the output format that I want is like: 0001110011111111000000001111111100000000.... I tried your code on Cygwin under Windows 2000, and on Linux, but it prints out ASCII characters. From cjbottaro at alumni.cs.utexas.edu Mon Jan 3 21:42:27 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Mon, 03 Jan 2005 20:42:27 -0600 Subject: HTTP GET request with basic authorization? References: <7c60b60505010215123462c90e@mail.gmail.com> <652efjvb.fsf@pobox.com> Message-ID: John J. Lee wrote: > Jonas Galvez writes: > >> Christopher J. wrote: >> > I tried this, but it didn't work: >> > conn.request("GET", "/somepage.html", None, >> > {"AUTHORIZATION": "Basic username:password"}) > [...] >> import re, base64, urllib2 >> >> userpass = ('user', 'pass') >> url = 'http://somewhere' >> >> request = urllib2.Request(url) >> authstring = base64.encodestring('%s:%s' % userpass) >> authstring = authstring.replace('\n', '') >> request.add_header("Authorization", "Basic %s" % authstring) >> >> content = urllib2.urlopen(request).read() > > There are handlers in urllib2 to do this for you, you shouldn't need > to do it by hand. I rarely do, so I won't risk an example... > > > John > Thank you all. The webpage I was reading didn't say anything about base64 encoding the authentication string. Also thanks for the tip on the urllib2 handlers. From http Sat Jan 1 17:27:09 2005 From: http (Paul Rubin) Date: 01 Jan 2005 14:27:09 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xfz1lal5d.fsf@ruckus.brouhaha.com> Message-ID: <7xekh423b6.fsf@ruckus.brouhaha.com> Steve Holden writes: > > It seems to me > > that IDLE and a lot of the rest of Python are examples of someone > > having a cool idea and writing a demo, then releasing it with a lot of > > missing components and rough edges, without realizing that it can't > > reasonably be called complete without a lot more work. > > ^Python^open source^ I wouldn't say so. I'd say the Linux kernel, GCC, Emacs, Apache, Mozilla, etc. are all developed with a much more serious attitude than Python is. Of course there are lots of other FOSS programs that someone wrote for their own use and released, that are less polished than Python, but that are also the subject of less advocacy than Python. From zanesdad at bellsouth.net Mon Jan 10 13:13:37 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Mon, 10 Jan 2005 13:13:37 -0500 Subject: ftplib with unknown file names In-Reply-To: References: Message-ID: <41E2C5D1.6020605@bellsouth.net> rbt wrote: > How can I use ftplib to retrieve files when I do not know their names? > I can do this to get a listing of the directory's contents: > > ftp_server.retrlines('LIST') > > > The output from this goes to the console and I can't figure out how to > turn that into something I can use to actually get the files (like a > list of file names). I read a bit about the callback function that can > be passed to retrlines but I couldn't figure out how to use it. > > Any help is appreciated. > > Thanks! .nlst(argument) will return a list of file names. Here are the docs for the nlst command: http://www.python.org/doc/current/lib/ftp-objects.html HTH, Jeremy Jones From lee at example.com Wed Jan 26 16:26:09 2005 From: lee at example.com (Lee Harr) Date: Wed, 26 Jan 2005 21:26:09 GMT Subject: Inherting from object. Or not. References: Message-ID: > What is the difference between inherting form object, and not doing it? E.g, > what's the difference between the two following classes? > > class foo: > pass > > class bar(object): > pass > > Sometimes people inherit from it, and sometimes not. I don't see a pattern in > their choices. > > I think this is the best source: http://www.python.org/2.2.3/descrintro.html Subclassing object gets you a "new style" class and some additional capabilities. Maybe eventually it will not matter. From BOOGIEMANPN at YAHOO.COM Mon Jan 3 17:38:34 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Mon, 3 Jan 2005 23:38:34 +0100 Subject: How do I make Windows Application with Python ? References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> Message-ID: <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> On Mon, 03 Jan 2005 17:19:22 -0500, Peter Hansen wrote: > What do you mean by "Windows Applications"? I'm running > Python on Windows XP, so every program I write with > Python is a "Windows application" by my definition. Obviously > you are using a different one. > > (And if you just mean "it has a GUI", then my answer is > "I use wxPython with Python". There is also Tkinter, and > other options. Please ask a more specific, detailed question > to get useful answers.) Well, I programmed a little in MS Visual Studio 2003, and there you have Console apllication and Windows application (among others). Windows one is with buttons and other gadgets. So, I want to make applications that doesn't open console to display result, I want to display it into the message box. Also, I want to use that application on the computers where Python isn't installed From tjreedy at udel.edu Mon Jan 10 16:02:24 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Jan 2005 16:02:24 -0500 Subject: Old Paranoia Game in Python References: <2005010903390916807%spk00@coxnet> Message-ID: Never saw this specific game. Some suggestions on additional factoring out of duplicate code. > def next_page(this_page): > print "\n" > if this_page == 0: > page = 0 > return The following elif switch can be replaced by calling a selection from a list of functions: [None, page1, pag2, ... page57][this_page]() > elif this_page == 1: > page1() > return > elif this_page == 2: > page2() > return ... > elif this_page == 57: > page57() > return Also, a chose3 function to complement your chose (chose2) function would avoid repeating the choose-from-3 code used on multiple pages. Terry J. Reedy From bill.mill at gmail.com Fri Jan 28 10:52:29 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 28 Jan 2005 10:52:29 -0500 Subject: Dynamic class methods misunderstanding In-Reply-To: <41fa5d3d$0$2024$626a14ce@news.free.fr> References: <41fa5d3d$0$2024$626a14ce@news.free.fr> Message-ID: <797fe3d4050128075213c34060@mail.gmail.com> On 28 Jan 2005 15:41:49 GMT, F. Petitjean wrote: > Le Fri, 28 Jan 2005 10:20:30 -0500, Bill Mill a ?crit : > > Hello all, > > > > I have a misunderstanding about dynamic class methods. I don't expect > > this behavior: > > > > In [2]: class test: > > ...: def __init__(self, method): > > ...: self.method = method > > ...: self.method() > > ...: > > > > In [3]: def m(self): print self > > ...: > > > > In [4]: test(m) > > --------------------------------------------------------------------------- > > exceptions.TypeError Traceback (most recent call > > last) > > > > /cygdrive/c/Documents and Settings/Wmill/ > > > > /cygdrive/c/Documents and Settings/Wmill/ in __init__(self, method) > > > > TypeError: m() takes exactly 1 argument (0 given) > > ----------------------------------------------------------------------------- > > > > Why doesn't m get the implicit self parameter in the self.method() > > call? How would I make it a proper member of the class, so that a > > self.method() call would work with the above "m" function? > The "def m(self):" was not properly indented. So here, "m" is a module level > function, not a method of your class. I know this; I should have been clearer. I want to define a function outside of a class, then pass it to a class and make it a method of that class. > > > > Peace > > Bill Mill > > bill.mill at gmail.com > -- > http://mail.python.org/mailman/listinfo/python-list > From devries at idolstarastronomer.com Mon Jan 3 20:50:46 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: 3 Jan 2005 17:50:46 -0800 Subject: How do I make Windows Application with Python ? References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> Message-ID: <1104803446.648811.253820@f14g2000cwb.googlegroups.com> There are several GUI toolkits for python. Tkinter comes with python, but wxPython, a binding to wxWindows is popular, as is pyQT, and pyGTK. You can also build native win32 GUIs using PythonWin, part of win32all. A more complete list of options is available here: http://www.python.org/cgi-bin/moinmoin/GuiProgramming . I have heard a couple good things about Boa Constructor (http://boa-constructor.sourceforge.net/) as an IDE. It includes a GUI designer. I have not used it though. Stand alone GUI designers such as wxGlade (http://wxglade.sourceforge.net/) are available as well. As far as packaging the application for use on computers where python is not installed. If you are distributing to windows computers you can use py2exe to make a windows executable from a python program. It will include dlls you need to distribute with your program. cx_Freeze and Gordon McMillan's Installer also can create windows executable files. Good luck... and be sure to read through the online tutorials and wikis, there is a wealth of information out there. A book isn't a bad investment either, I always feel better with a good reference book around. Python in a nutshell is a good reference book, while Learning Python gives you a good introduction to the language. Chris From ptmcg at austin.rr._bogus_.com Tue Jan 11 09:12:16 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 11 Jan 2005 14:12:16 GMT Subject: Old Paranoia Game in Python References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> <1105318366.966577.107460@c13g2000cwb.googlegroups.com> <1105400673.731851.87080@f14g2000cwb.googlegroups.com> Message-ID: <49REd.6654$RW3.4383@fe1.texas.rr.com> "McBooCzech" wrote in message news:1105400673.731851.87080 at f14g2000cwb.googlegroups.com... > Newbie in Python. > I did copy the whole script form the web and save it as para1.py. I did > download pyparsing module and save it to > C:\\Python23\\Lib\\pyparsing122. > I did run following script: > > import sys > sys.path.append('C:\\Python23\\Lib\\pyparsing122') > > from pyparsing import * > extraLineBreak = White(" ",exact=1) + LineEnd().suppress() > text = file("Para1.py").read() > newtext = extraLineBreak.transformString(text) > file("para2.py","w").write(newtext) > > I did try to run para2.py script, but following message > > File "para2.py", line 169 > choose(4,"You give your correct clearance",5,"You lie and claim > ^ > SyntaxError: EOL while scanning single-quoted string > > So my questions are: > Why pyparser didn't correct the script? > What I am doing wrong? > Is it necessary to correct the script by hand anyway? > > Petr > Petr - After running the little script, I still had to make one correction by hand, on line 1057. There was a line that needed to be indented that wasn't. This little pyparsing script only takes out the line-breaks that were added because of the news server's word wrapping algorithm, and does not catch indentation errors. After correcting that by hand, I ran the program para2.py successfully. Did you extract *just* the Python code in the previous post? I did not find the line you listed as line 169 in either my pre-pyparsing nor post-pyparsing versions of the program. In para1.py, your line 169 shows up as my line 159, in para2.py, it is line 152, and it looks like: choose(4,"You give your correct clearance",5,"You lie and claim Ultraviolet clearance") (of course, this is likely to get word-wrapped again, but the point is, it includes the rest of the quoted string after the word 'claim'). What encoding are you using? I am currently working on a Unicode-compatible pyparsing, and this may help resolve your problem. Since your e-mail domain country code is cz, it's possible that the encoding for spaces and/or line breaks is treated differently. This is just a wild guess. Anyway, in the interest of tracking down a potential pyparsing problem, could you please e-mail me your para1.py file? -- Paul From steve at holdenweb.com Mon Jan 10 19:44:42 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Jan 2005 19:44:42 -0500 Subject: Securing a future for anonymous functions in Python In-Reply-To: <1105381339.922714.23200@c13g2000cwb.googlegroups.com> References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <1105381339.922714.23200@c13g2000cwb.googlegroups.com> Message-ID: <1oFEd.71967$Jk5.45632@lakeread01> Anna wrote: > You cut something from that... > > """It's not, after all, the word "lambda" itself; I would still > have some issues with using, say "function", instead of "lambda", but > at least then I would immediately know what I was looking at...""" > > I would have fewer ambiguities about using, say "func" rather than > lambda. Lambda always makes me feel like I'm switching to some *other* > language (specifically, Greek - I took a couple of semesters of Attic > Greek in college and quite enjoyed it.) But, the fact that lambda Good God, you mean there's a language just for the attic? Those Greeks certainly believed in linguistic specialization, didn't they? > doesn't MEAN anything (and has come - I mean - DELTA at least has a > fairly commonly understood meaning, even at high-school level math. > But, lambda? If it was "func" or "function" or even "def", I would be > happier. At least that way I'd have some idea what it was supposed to > be... > Well, I suspect that Church originally chose lambda precisely because of its meaninglessness, and I'm always amused when mathematical types try to attribute an intuitive meaning to the word. It's purely a learned association, which some arrogantly assume simply *everyone* knows or should know. Not that I'm trying to write off lambda supporters as arrogant (though I *do* have a suspicion that many of them break the wrong end of their boiled eggs). > BTW - I am *quite* happy with the proposal for "where:" syntax - I > think it handles the problems I have with lambda quite handily. > Whereas I find it to be an excrescence, proving (I suppose) that one man's meat is another person's poison, or something. regards Steve [who only speaks Ground Floor English] -- 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 tim.golden at viacom-outdoor.co.uk Thu Jan 20 12:05:40 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 20 Jan 2005 17:05:40 -0000 Subject: Print to Windows default Printer Message-ID: <9A28C052FF32734DACB0A288A35339910359D8@vogbs009.gb.vo.local> [Samantha] [... snip my explanation of PRINT / COPY LPTx: ...] | Thanks Tim, | That is exactly what I want to do. | How do I map the printer to LPT1? | S Depends on a lot of things: whether the printer is local or networked; what version of Windows you're running, &. As a very basic starting point: if it's a local printer (ie plugged into the back of your machine) it's probably on LPT1: already, or you could go to the Add Printer wizard and tell it to configure it for LPT1: there. If it's networked, then something like: NET USE LPT1: \\servername\printerqueue should achieve the right effect. 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 farcepest at gmail.com Sun Jan 30 14:39:11 2005 From: farcepest at gmail.com (Andy Dustman) Date: 30 Jan 2005 11:39:11 -0800 Subject: An mysql-python tutorial? In-Reply-To: References: Message-ID: <1107113951.790582.184140@z14g2000cwz.googlegroups.com> It definitely looks like an access control problem; recheck your grants. From nothanks at nothere.com Mon Jan 17 09:50:34 2005 From: nothanks at nothere.com (Emiliano Molina) Date: Mon, 17 Jan 2005 14:50:34 GMT Subject: PUG in Melbourne Australia? Message-ID: <_gQGd.122103$K7.32923@news-server.bigpond.net.au> Does anyone here know if there is a Python Users Group in Melbourne Australia? A google search shows an attempt to start one at meetups.com or something like that but it now seems defunct. From case.nelson at gmail.com Wed Jan 12 00:58:49 2005 From: case.nelson at gmail.com (snoe) Date: 11 Jan 2005 21:58:49 -0800 Subject: Help Optimizing Word Search In-Reply-To: References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: <1105509529.664370.16080@f14g2000cwb.googlegroups.com> Mike, Thanks, this worked great, and was 4x faster than my method! Thanks everyone for replying! The changes I made were: !rest = ''.join([chr(i) for i in range(256) if chr(i).upper() not in WORD]) !# a wildcard in the word means that we check all letters !if '?' in WORD: ! rest = '' !translator = string.maketrans('','') and ! try: ! pool.remove( char ) ! except ValueError: ! # nested try to remove possible wildcard ! try: ! pool.remove( '?' ) ! except ValueError: ! return False From fu.limin.tao at gmail.com Thu Jan 27 06:34:56 2005 From: fu.limin.tao at gmail.com (Limin Fu) Date: Thu, 27 Jan 2005 12:34:56 +0100 Subject: ANN: Tao Scripting Language 0.8.5 beta released! Message-ID: Dear all, I am glad to announce in this mailing list that the lastest version of a new scripting language has come out. Welcome to try it out. Comments are welcome. Suggestions are appreciated. ======================= Here are some details: ======================= Design Goals: 1. Simple and efficient. 2. Integrate nice features of other languages whenever possible. Implementation language: C++ with STL. Designer: Fu Limin Email: fu [dot] limin [dot] tao [at] gmail.com Key features have been supported: 1. Dynamic-typing variables, supporting complex data structures such as array/list, hash/dictionary and matrix etc. 2. Object-oriented programming ( multi-inheritance not supported yet ). 3. Basic string regular expression matching. 4. Automatic garbage collection capable of collecting cyclically referenced objects. 5. Numeric data types: complex number and matrix, and their basic operations. 6. Convenient namespacing and dynamic creation of subroutines and classes. 7. Dynamic loading of C/C++ modules ( not complete, but enough for playing with it ^_^ ). 8. An embedded tiny XML parser. ToBeDone: More string operations, multi-inheritance of classes, improvements on C/C++ module loading, more on regular expression matching and possible optimizations etc. Documentation: http://taoscript.sourceforge.net/brief_tao.php Sample scripts: http://taoscript.sourceforge.net/sample.php Download: http://taoscript.sourceforge.net/downloads.php Best regards, Limin -- Homepage for Tao Language: http://taoscript.sourceforge.net Tao Language project at sourceforge.net: http://sourceforge.net/projects/taoscript From jerf at jerf.org Mon Jan 24 11:45:34 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 24 Jan 2005 11:45:34 -0500 Subject: Why I use private variables (WAS: RE:"private" variables a.k.a. name mangling?) References: Message-ID: On Mon, 24 Jan 2005 15:35:11 -0600, Philippe C. Martin wrote: > The real reason behind my using private variables is so they do not appear > in the epydoc generated documentation and confuse my users. You mean single or double underscores? I just checked and at least epydoc 2.1 doesn't include single-underscore values, but those aren't "private" in sense we're talking in this thread (some form of compiler enforcement). From lmhaskins at yahoo.com Fri Jan 28 19:03:08 2005 From: lmhaskins at yahoo.com (lmhaskins at yahoo.com) Date: 28 Jan 2005 16:03:08 -0800 Subject: move bugs from Zope BITS into Bugzilla? Message-ID: <1106956988.391329.320610@z14g2000cwz.googlegroups.com> I inherited a bug reporting system at work, and it's currently in Zope BITS (Bug Information Tracking System). This version of BITS uses ZODB -- not the RDBMS version. I would like to export all the incident reports from BITS to later import into Bugzilla, but as of yet I haven't quite figured it out. As soon as I'm done with this, that's it for BITS and Zope, so I'd like to avoid writing a Zope app just for this. Anyone solved this problem, or at least the part about exporting from BITS? I'd hand-enter the open issues, but they also want the closed ones for tracking & posterity. Thanks! -lmh From Jared.Cohen at noaa.gov Wed Jan 5 17:24:41 2005 From: Jared.Cohen at noaa.gov (Jared Cohen) Date: Wed, 05 Jan 2005 17:24:41 -0500 Subject: Please help -- Pmw PanedWidget inside ScrolledFrame Message-ID: <41DC6929.9080704@noaa.gov> Almost forgot, here's the code sample: #!/usr/bin/env python import sys, os, Tkinter, types, tkFont, Pmw def makeResizable(widget): for i in range(0, widget.grid_size()[0]): widget.columnconfigure(i, weight=1) for i in range(0, widget.grid_size()[1]): widget.rowconfigure(i, weight=1) def main(): root = Tkinter.Tk() root.geometry("500x500+0+0") Pmw.initialise(root) scrolledFrame = Pmw.ScrolledFrame(root, usehullsize=1, borderframe=0, hscrollmode='static', vscrollmode='static') scrolledFrame.grid(row=0, rowspan=20, column=0, columnspan=20, sticky='nsew') panes = Pmw.PanedWidget(scrolledFrame.interior(), orient='horizontal', hull_borderwidth=2, hull_relief='sunken') panes.grid(row=0, rowspan=20, column=0, columnspan=20, sticky='nsew') for i in range(5): pane = panes.add("pane"+str(i), size=1/5.0) button = Tkinter.Button(pane, text="This Is A Very Long Name For A Button") button.grid(row=0, rowspan=1, column=i, columnspan=1, sticky='nsew') makeResizable(root) makeResizable(scrolledFrame.interior()) makeResizable(panes) root.mainloop() if __name__=='__main__': main() From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Jan 20 02:56:20 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Do Re Mi chel La Si Do) Date: Thu, 20 Jan 2005 08:56:20 +0100 Subject: ElementTree cannot parse UTF-8 Unicode? References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106181323.553028.290370@z14g2000cwz.googlegroups.com> Message-ID: <41ef646a$0$19406$8fcfb975@news.wanadoo.fr> Hi ! >>> ...Usenet to transmit it properly newsgroups (NNTP) : yes, it does it usenet : perhaps (that depends on the newsgroups) clp : no Michel Claveau From ncoghlan at iinet.net.au Fri Jan 28 06:21:51 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 28 Jan 2005 21:21:51 +1000 Subject: Inherting from object. Or not. In-Reply-To: References: <1106774681.501533.156220@f14g2000cwb.googlegroups.com> <200501262214.40597.frans.englich@telia.com> Message-ID: <41FA204F.3050403@iinet.net.au> Nick Craig-Wood wrote: > Nick Coghlan wrote: > >> Exactly. My advice is to use new-style classes unless you have a >> reason not to (if you're inheriting from a builtin type, then there >> is no need to inherit from object as well - the builtin types >> already have the correct basic type). > > > Except for Exception! > > Exception and anything that inherits from it is an old style class. And 'classobj' is the correct basic type for an Exception, since, as you mentioned, new-style classes are currently unraisable :) Cheers, Nick. I think there *is* work in progress to change that. . . -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steven.bethard at gmail.com Wed Jan 12 19:37:50 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 17:37:50 -0700 Subject: else condition in list comprehension In-Reply-To: References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: Steve Holden wrote: > Nick Coghlan wrote: >> z = [newval(i) for i in range(10)] using: >> def newval(x): >> if x % 2: >> return x - 2 >> else: >> return x + 2 >> >> Just some more mental twiddling relating to the thread on statement >> local namespaces. >> > I presume the point of this is to avoid polluting the local namespace > with "newval". I further presume you also have plans to do something > about "i"? ;-) Well, while I'm not at all a fan of the "using" syntax, getting rid of 'i' is simple: z = list(newval(i) for i in range(10)) =) Steve From jeff at ccvcorp.com Wed Jan 26 18:09:43 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 26 Jan 2005 15:09:43 -0800 Subject: inherit without calling parent class constructor? In-Reply-To: References: Message-ID: <10vg8ecra1anp9f@corp.supernews.com> Christian Dieterich wrote: > Hi, > > I need to create many instances of a class D that inherits from a class > B. Since the constructor of B is expensive I'd like to execute it only > if it's really unavoidable. Below is an example and two workarounds, but > I feel they are not really good solutions. Does somebody have any ideas > how to inherit the data attributes and the methods of a class without > calling it's constructor over and over again? You could try making D a container for B instead of a subclass: class D(object): def __init__(self, ...): self._B = None def __getattr__(self, attr): if self._B is None: self._B = B() return getattr(self._B, attr) Include something similar for __setattr__(), and you should be in business. If it will work for numerous D instances to share a single B instance (as one of your workarounds suggests), then you can give D's __init__() a B parameter that defaults to None. Jeff Shannon Technician/Programmer Credit International From simoninusa2001 at yahoo.co.uk Sat Jan 29 02:05:48 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 28 Jan 2005 23:05:48 -0800 Subject: Pystone benchmark: Win vs. Linux (again) In-Reply-To: References: Message-ID: <1106978997.909778.272440@z14g2000cwz.googlegroups.com> Franco Fiorese wrote: > Is there any way, that you know, to get better performance under Linux? Build Python yourself, using relevant CFLAGS and TARGET for your processor? I've always noticed that Windows Python takes a lot longer to startup than Linux, but never really looked at runtime performance. From notvalid at email.com Mon Jan 17 01:38:42 2005 From: notvalid at email.com (Ala Qumsieh) Date: Mon, 17 Jan 2005 06:38:42 GMT Subject: [perl-python] 20050116 defining a function In-Reply-To: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> References: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> Message-ID: Xah Lee wrote: > ? my $n= @_[0]; Do you ever test your code before making fun of yourself in front of millions? *plonk* --Ala From kent3737 at yahoo.com Fri Jan 7 15:50:03 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Fri, 07 Jan 2005 15:50:03 -0500 Subject: Tkinter: passing parameters to menu commands In-Reply-To: References: Message-ID: <41def3cd$1_1@newspeer2.tds.net> Philippe C. Martin wrote: > I have many menu items and would like them all to call the same method > -However, I need the method called to react differently depending on the > menu item selected. Since the menu command functions do not seem to > receive any type of event style object, is there some type of Tkinter > call that would let my method know the menu id selected ? Much as it seems to be out of favor, IMO this is a place where a lambda expression is very handy. You can make a callback for each menu item that binds an extra parameter to the handler: # Based on an example by Fredrik Lundh from Tkinter import * def callback(code): print "called the callback with code", code root = Tk() # create a menu menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="New", command=lambda: callback('New')) filemenu.add_command(label="Open...", command=lambda: callback('Open')) filemenu.add_separator() filemenu.add_command(label="Exit", command=lambda: callback('Exit')) mainloop() Of course you could do this with named forwarding functions if you prefer. Kent From 2004b at usenet.alexanderweb.de Tue Jan 11 10:39:32 2005 From: 2004b at usenet.alexanderweb.de (Alexander Schremmer) Date: Tue, 11 Jan 2005 16:39:32 +0100 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> Message-ID: On 10 Jan 2005 18:45:16 -0800, Paul Rubin wrote: > I need to set up a wiki for a small group. I've played with MoinMoin > a little bit and it's reasonably straightforward to set up, but > limited in capabilities and uses BogusMarkupConventions. At which point do you see limitations? And what of the markup don't you like? > In the larger world, though, there's currently One True wiki package, > namely Mediawiki (used by Wikipedia). It is just very famous because of Wikipedia IMHO. > Mediawiki is written in PHP and > is far more complex than MoinMoin, plus it's database backed, meaning > you have to run an SQL server as well as the wiki software itself > (MoinMoin just uses the file system). Having a DBMS backend is good in your opinion? It has some severe disadvantages like not easy to scale (you would need to setup DBMS replication), two potential points of failure, more complex setup, bigger memory requirements, etc. > Plus, I'll guess that it really > needs mod_php, while MoinMoin runs tolerably as a set of cgi's, at > least when traffic is low. Both should run fine in CGI mode I guess. > What I'm getting at is I might like to install MoinMoin now and > migrate to Mediawiki sometime later. Anyone have any thoughts about > whether that's a crazy plan? If you really want to use the wiki for content, you have to agree on a markup style. You could use an independent one (like RestructuredText) and hope that MediaWiki supports it (MoinMoin does). Or you end up writing complex migration scripts just for the markup. Finding some script which just imports the data files into the DB should be rather easy. > Should I just bite the bullet and run Mediawiki from the beginning? IMHO you should not bite it but choose MoinMoin. :-) > Is anyone here actually running Mediawiki who can say just how > big a hassle it is? A few months I tried to install it. I got it running. But I did not like the necessary complex administration tasks. > The other one will be public and is planned grow to medium size (a few > thousand active users), but which I don't need immediately. I > definitely want the second one to eventually run Mediawiki. I can > probably keep the first one on MoinMoin indefinitely, but that would > mean I'm eventually running two separate wiki packages, which gets > confusing. There are even MoinMoin sites that are as big as that. Maybe you should rethink your kind of prejudice and re-evaluate MoinMoin. Kind regards, Alexander From peter at engcorp.com Wed Jan 26 10:38:24 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 Jan 2005 10:38:24 -0500 Subject: smtplib bug with Windows XP In-Reply-To: References: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> <1106673048.851591.324490@f14g2000cwb.googlegroups.com> Message-ID: Steve Christensen wrote: > In article <1106673048.851591.324490 at f14g2000cwb.googlegroups.com>, stewart.midwinter at gmail.com wrote: >>thank Peter, elbert, for the suggestions. I hadn't thought of using >>telnet to try to connect to the SMTP server. and when I do try, telnet >>can't connect either, at least on port 25. On port 110, it has no >>problem. So, perhaps the IT people have made some configuration >>changes; I'll have a chat with them. I'm relieved that it's not a >>Python problem, though. > > We had similar issues when our systems were upgraded to McAfee VirusScan > 8.0. If you're running that locally (on the system trying to connect to > the SMTP server), try disabling the rule in the Access Control dialog > that's labeled 'Prevent mass mailing worms from sending email' How do such tools still allow the sending of valid emails? -Peter From hpk at trillke.net Tue Jan 4 04:50:06 2005 From: hpk at trillke.net (holger krekel) Date: Tue, 4 Jan 2005 10:50:06 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> Message-ID: <20050104095006.GA32217@solar.trillke.net> On Fri, Dec 31, 2004 at 19:18 +0100, Alex Martelli wrote: > Cameron Laird wrote: > ... > > Yippee! The martellibot promises to explain Unicode for Pythoneers. > > http://groups-beta.google.com/group/comp.lang.python/msg/6015a5a05c206712 > > Uh -- _did_ I? Eeep... I guess I did... mostly, I was pointing to > Holger Krekel's very nice recipe (not sure he posted it to the site as > well as submitting it for the printed edition, but, lobby _HIM_ about > that;-). FWIW, i added the recipe back to the online cookbook. It's not perfectly formatted but still useful, i hope. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361742 cheers, holger P.S: happy new year. From genezhang at gmail.com Sun Jan 9 19:06:08 2005 From: genezhang at gmail.com (Gene) Date: 9 Jan 2005 16:06:08 -0800 Subject: path to python file given module Message-ID: <1105315568.887724.260370@c13g2000cwb.googlegroups.com> Is there a way to get a relative or absolute path to a python file once it's been imported as a module? For example, I type: >>> import filegen and I want a string that represents the path to filegen.py (either relative to current working directory or the absolute path) From bokr at oz.net Wed Jan 26 03:11:38 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 26 Jan 2005 08:11:38 GMT Subject: is there better 32 clock() timing? References: <41f61372.1768192005@news.oz.net> <41f63d79.1778950866@news.oz.net> Message-ID: <41f746c3.1846865602@news.oz.net> On Tue, 25 Jan 2005 15:46:30 +0000, Stephen Kellett wrote: >In message <41f63d79.1778950866 at news.oz.net>, Bengt Richter > writes >>I believe that is quite wrong as a general statement. > >Actually my initial statement should have been written >"accessing a resource, the accuracy of which is no better than 10ms.". I >was thinking of the 1ms multimedia timer but wrote about clock() >instead. > >10ms, coincidentally is the approx minimum scheduling granularity for >threads unless you are in a multimedia thread (or real time thread - not >sure about real time threads in NT). > >>If the "resource" only had ~1ms granularity, >>the minimum would be zero, as it is if you call time.time() in a tight loop, > >Correct. Write your app in C and call clock(). Thats what you get. You >can call clock 20000 times and still get a delta of zero. The next delta >(on my system) is 10ms at about 22000 calls. > >>>There are various timers available, documented and undocumented, all of >>>which end up at 1ms or 1.1ms, give or take. For anything shorter you > >Whoops here we go, same typo - should have been 10ms or 11ms. There is a >1ms timer in the multimedia timing group. > >>>need QueryPerformanceCounter() (but that *is* a slow call), or use the >>Have you timed it, to make that claim? > >Yes. > >>What do you mean by "slow"? > >Slower than any other Win32, CRT or Undocumented NT function you can use >to get timer information. Yes, I have timed them all, a few years ago. > >QueryPerformanceCounter is 47 times slower to call than clock() on my >1Ghz Athlon. That really makes me wonder. Perhaps the Athlon handles RDTSC by way of an illegal instruction trap and faking the pentium instruction? That might explain the terrible timing. Try it on a pentium that supports RDTSC. The clock() usually gets high resolution bits from a low order 16 bits of the timer chip that drives the old 55ms clock that came from IBM using cheap TV crystal based oscillators instead of defining an OS-implementer-friendly time base, I think. The frequency was nominally 1193182 hz I believe. Obviously the OS didn't get interrupted that often, but if you divide by 2**16, you get the traditional OS tick of ~55ms: >>> 1193182./2**16 18.206512451171875 >>> (1193182./2**16)**-1 0.054925401154224583 So that's a clue. By grabbing tick count and bits read from the fast-counting harware clock register, you can compute time fairly accurately for the moment you are sampling that register. IIRC, you couldn't get the whole 16 bits because it was a toggling trigger or some such. > >QueryPerformanceCounter may have finer granularity, but called in a >tight loop it'll crush your program. Maybe on your Athlon, but my experience is different ;-) > >>>RDTSC instruction which is fast but gives a count of instruction cycles >>>executed and is thus not totally accurate (multiple execution pipelines, >>>plus multithreading considerations). >>Accurate for what. > >See below - you haven't taken things into account, despite my comment in >brackets above which gives a big hint. I've absorbed a lot of hints since around '59 when I began to work with computers and timing issues ;-) > >>A single clock AFAIK drives RDTSC > >Correct. > >>The main problem with a CPU clock based reading is that it's very stable unless >>there's variable clock rate due to power management. > >Try running multiple apps at the same time you are doing your >measurement, each of which has a variable loading. Each of these apps is >contributing to the count returned by RDTSC. That is what I was >referring to. Ok, but that's another issue, which I also attempted to draw attention to ;-) Quoting myself: """ > >Even with the attribute lookup overhead, it's not several hundred microseconds >as a *minimum*. But on e.g. win32 you can get preempted for a number of milliseconds. >E.g., turn that to a max instead of a min: > >I see a couple 20-30 ms ones ;-/ > > >>> max(abs(time.clock()-time.clock()) for i in xrange(10**5)) > 0.0085142082264155761 > >>> max(abs(time.clock()-time.clock()) for i in xrange(10**5)) > 0.0088125700856949152 > >>> max(abs(time.clock()-time.clock()) for i in xrange(10**5)) > 0.0022125710913769581 > >>> max(abs(clock()-clock()) for i in xrange(10**5)) > 0.023374472628631793 > >>> max(abs(clock()-clock()) for i in xrange(10**5)) > 0.030183995400534513 > >>> max(abs(clock()-clock()) for i in xrange(10**5)) > 0.0017130664056139722 > >>> max(abs(clock()-clock()) for i in xrange(10**5)) > 0.0070844179680875641 > """ Depending on what your timing requirements are, you may be able to run a zillion trials and throw out the bad data (or plot it and figure out some interesting things about timing behavior of your system due to various effects). E.g., timeit presumably tries to get a minimum and eliminate as many glitches as possible. But as mentioned, the big picture of requirements was not clear. Certainly you can't expect to control ignition of a racing engine reliably with an ordinary windows based program ;-) Regards, Bengt Richter From http Wed Jan 19 23:38:32 2005 From: http (Paul Rubin) Date: 19 Jan 2005 20:38:32 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> Message-ID: <7xis5szpdj.fsf@ruckus.brouhaha.com> Tim Peters writes: > Python's basic list type is a flat vector instead of a > recursively-defined S-expression, and that there's no direct way to > break out of a containing loop from a nested loop. Huh? [1,2,[3,4,5],[6,[[[[7]],8]]]] is a perfectly valid Python list. And you can break out of a containing loop from a nested loop with try/raise. More troublesome is not being able to see a variable in a containing scope from a nested scope, unless the containing scope is the global one. Why bother debating lexical scope for years before deciding to add it, only to stop halfway? From RajaSrinivasan at hotmail.com Tue Jan 4 16:57:06 2005 From: RajaSrinivasan at hotmail.com (RajaSrinivasan at hotmail.com) Date: 4 Jan 2005 13:57:06 -0800 Subject: Bad Interpreter In-Reply-To: <1104784496.231137.117250@f14g2000cwb.googlegroups.com> References: <1104783849.754892.47560@c13g2000cwb.googlegroups.com> <1104784496.231137.117250@f14g2000cwb.googlegroups.com> Message-ID: <1104875826.291380.94330@c13g2000cwb.googlegroups.com> sounds like it. vi sock.py shows '$' at the end of each line. however when i went to a unix machine and recreated the file, the problem went away. thanks for all the help regards From stephen.thorne at gmail.com Thu Jan 20 01:06:48 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 20 Jan 2005 16:06:48 +1000 Subject: list item's position In-Reply-To: References: Message-ID: <3e8ca5c8050119220669d6c87c@mail.gmail.com> On Wed, 19 Jan 2005 22:04:44 -0500, Bob Smith wrote: > Hi, > > I have a Python list. I can't figure out how to find an element's > numeric value (0,1,2,3...) in the list. Here's an example of what I'm doing: > > for bar in bars: > if 'str_1' in bar and 'str_2' in bar: > print bar > > This finds the right bar, but not its list position. The reason I need > to find its value is so I can remove every element in the list before it > so that the bar I found somewhere in the list becomes element 0... does > that make sense? Given a list and a function: def dropPredicate(x): return not 'somecontents' in x mylist = ['a', 'b', 'c', 'xxxxsomecontentsxxx', 'd', 'e', 'f'] import itertools mylist = list(itertools.dropwhile(dropPredicate, mylist)) assert mylist == ['xxxxsomecontentsxxx', 'd', 'e', 'f'] This will drop everything at the start of the list for which 'dropPredicate' returns true. This will mean that even if dropPredicate returns false for more than one element of the list, it will stop at the first element. If there are no elements for which dropPredicate returns true, the result will be an empty list. Regards, Stephen Thorne. From mahs at telcopartners.com Tue Jan 25 19:20:27 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 25 Jan 2005 16:20:27 -0800 Subject: python without OO In-Reply-To: <1106694083.199064.240680@f14g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> Message-ID: Davor wrote: > Thanks, > > I do not hate OO - I just do not need it for the project size I'm > dealing with - and the project will eventually become open-source and > have additional developers - so I would prefer that we all stick to > "simple procedural" stuff rather than having to deal with a developer > that will be convincing me that his 50 layers inheritance hierarchy is > good since it exists in some weird pattern that he saw somewhere on > some Java design patterns discussion board :-) and other "proper" OO > design issues... Once I opted for C++ in a very small project and > believed everyone will stick with C subset + better type checking > offered through C++ - but I simply could not manage to keep them off > using OO stuff which was just making program more complicated than it > should have been. (note, I am not an experienced developer, nor the > others I'll be working with (even though some think they are:-)), so I > prefer preemptively dealing with issue of everyone showing off their OO > design skills) > > Davor > Perhaps pylint (http://www.logilab.org/projects/pylint) or its ilk can help you enforce a coding style Michael From richie at entrian.com Mon Jan 24 10:33:11 2005 From: richie at entrian.com (Richie Hindle) Date: Mon, 24 Jan 2005 15:33:11 +0000 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <41F510E0.40301@rogers.com> References: <41F427EB.3000200@rogers.com> <1f7befae0501231720428ca3c@mail.gmail.com> <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> <41F510E0.40301@rogers.com> Message-ID: [me] > why the `self.btree = None` in the last line? [Mike] > It's to allow the Closer object to act as a substitute for a .close() > method on the object [...] If the user explicitly calls storage.close() > we don't want the __del__ trying to re-close the storage later. In > other words, its an explicit requirement for *this* __del__, not a general > requirement. I see, yes. Very clever - thanks for the explanation! -- Richie Hindle richie at entrian.com From FBatista at uniFON.com.ar Thu Jan 20 13:46:53 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 20 Jan 2005 15:46:53 -0300 Subject: RuntimeError: dictionary changed size during iteration Message-ID: [Terry Reedy] #- You must be having a bad day ;-). From Lib Ref 2.1 Built-in Well, that's actually true, :( #- corresponding to the object's symbol table. The returned #- dictionary should #- not be modified: the effects on the corresponding symbol table are #- undefined I actually read that, but didn't understood that it returns THE dictionary (well, that another name binding for the same object was happening). Whatever, I don't get divorced every week, so forgive me. I think that, as it's normal to do... l = list(...) for e in l[:]: l.remove(e) ...insted of... l = list(...) for e in l: l.remove(e) ..., in this case we should do... >>> [e for e in vars().copy()] ['_[1]', 'e', 'v', '__builtins__', '__name__', '__doc__'] . 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 exarkun at divmod.com Sun Jan 2 14:33:49 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 02 Jan 2005 19:33:49 GMT Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <20050102183402.GC8357@monkeyfist.com> Message-ID: <20050102193349.26823.1129392051.divmod.quotient.1041@ohm> On Sun, 2 Jan 2005 13:34:02 -0500, Kendall Clark wrote: >On Sun, Jan 02, 2005 at 10:03:10AM -0500, Steve Holden wrote: > > > I did actually do some sort-of-related work in this area, which I > > presented at PyCon DC 2004 - you can access the paper at > > > > http://www.python.org/pycon/dc2004/papers/18/Setting_A_Context.pdf > > > > An audience member mentioned the Smalltalk and Scheme-based work on web > > continuation frameworks, and I was sorry my answer at the time seemed > > unduly dismissive. > > That was me, actually. I remain surprised that there isn't a move > afoot either to implement something like Seaside or Borges in Python > or to adapt one of the existing web frameworks to be > modal/continuation style. There is at least one. I'm sure I could find several, if I looked. The problem is that there are dozens of "web frameworks" in Python, all off in their separate corners ignoring each other for the most part, and for the most part being ignored by everyone outside their immediate community. Maybe PEP 333 will help by making movement between frameworks simpler for application developers. Of course, it may not, since it ignores complex things (it certainly comes nowhere close to addressing the requirements for a Seaside-alike), and any developer who wants to remain portable will not be able to take advantage of this technique. Jp From yaipa at yahoo.com Fri Jan 14 18:40:27 2005 From: yaipa at yahoo.com (yaipa) Date: 14 Jan 2005 15:40:27 -0800 Subject: finding/replacing a long binary pattern in a .bin file In-Reply-To: <41e7a190.821594009@news.oz.net> References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> <41e6293f.725257715@news.oz.net> <10udjc3fmnhro9d@corp.supernews.com> <41e7a190.821594009@news.oz.net> Message-ID: <1105746027.819673.236650@c13g2000cwb.googlegroups.com> Bengt, and all, Thanks for all the good input. The problems seems to be that .find() is good for text files on Windows, but is not much use when it is binary data. The script is for a Assy Language build tool, so I know the exact seek address of the binary data that I need to replace, so maybe I'll just go that way. It just seemed a little more general to do a search and replace rather than having to type in a seek address. Of course I could use a Lib function to convert the binary data to ascii and back, but seems a little over the top in this case. Cheers, --Alan Bengt Richter wrote: > On Thu, 13 Jan 2005 11:40:52 -0800, Jeff Shannon wrote: > > >Bengt Richter wrote: > > > >> BTW, I'm sure you could write a generator that would take a file name > >> and oldbinstring and newbinstring as arguments, and read and yield nice > >> os-file-system-friendly disk-sector-multiple chunks, so you could write > >> > >> fout = open('mynewbinfile', 'wb') > >> for buf in updated_file_stream('myoldbinfile','rb', oldbinstring, newbinstring): > >> fout.write(buf) > >> fout.close() > > > >What happens when the bytes to be replaced are broken across a block > >boundary? ISTM that neither half would be recognized.... > > > >I believe that this requires either reading the entire file into > >memory, to scan all at once, or else conditionally matching an > >arbitrary fragment of the end of a block against the beginning of the > >oldbinstring... Given that the file in question is only a few tens of > >kbytes, I'd think that doing it in one gulp is simpler. (For a large > >file, chunking it might be necessary, though...) > > > Might as well post this, in case you're interested... warning, not very tested. > You want to write a proper test? ;-) > > ----< sreplace.py >------------------------------------------------- > def sreplace(sseq, old, new, retsize=4096): > """ > iterate through sseq input string chunk sequence treating it > as a continuous stream, replacing each substring old with new, > and generating a sequence of retsize returned strings, except > that the last may be shorter depedning on available input. > """ > inbuf = '' > endsseq = False > out = [] > start = 0 > lenold = len(old) > lennew = len(new) > while not endsseq: > start, endprev = old and inbuf.find(old, start) or -1, start > if start<0: > start = endprev # restore find start pos > for chunk in sseq: inbuf+= chunk; break > else: > out.append(inbuf[start:]) > endsseq = True > else: > out.append(inbuf[endprev:start]) > start += lenold > out.append(new) > if endsseq or sum(map(len, out))>=retsize: > s = ''.join(out) > while len(s)>= retsize: > yield s[:retsize] > s = s[retsize:] > if endsseq: > if s: yield s > else: > out = [s] > > if __name__ == '__main__': > import sys > args = sys.argv[:] > usage = """ > Test usage: [python] sreplace.py old new retsize [rest of args is string chunks for test] > where old is old string to find in chunked stream and new is replacement > and retsize is returned buffer size, except that last may be shorter""" > if not args[1:]: raise SystemExit, usage > try: > args[3] = int(args[3]) > args[0] = iter(sys.argv[4:]) > print '%r\n-----------\n%s\n------------' %(sys.argv[1:], '\n'.join(sreplace(*args[:4]))) > except Exception, e: > print '%s: %s' %(e.__class__.__name__, e) > raise SystemExit, usage > -------------------------------------------------------------------- > > As mentioned, not tested very much beyond what you see: > > [ 2:43] C:\pywk\ut>py24 sreplace.py x _XX_ 20 This is x and abcxdef 012x345 zzxx zzz x > ['x', '_XX_', '20', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] > ----------- > Thisis_XX_andabc_XX_ > def012_XX_345zz_XX__ > XX_zzz_XX_ > ------------ > > [ 2:43] C:\pywk\ut>py24 sreplace.py x _XX_ 80 This is x and abcxdef 012x345 zzxx zzz x > ['x', '_XX_', '80', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] > ----------- > Thisis_XX_andabc_XX_def012_XX_345zz_XX__XX_zzz_XX_ > ------------ > > [ 2:43] C:\pywk\ut>py24 sreplace.py x _XX_ 4 This is x and abcxdef 012x345 zzxx zzz x > ['x', '_XX_', '4', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] > ----------- > This > is_X > X_an > dabc > _XX_ > def0 > 12_X > X_34 > 5zz_ > XX__ > XX_z > zz_X > X_ > ------------ > > [ 2:44] C:\pywk\ut>py24 sreplace.py def DEF 80 This is x and abcxdef 012x345 zzxx zzz x > ['def', 'DEF', '80', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] > ----------- > ThisisxandabcxDEF012x345zzxxzzzx > ------------ > > If you wanted to change a binary file, you'd use it something like (although probably let > the default buffer size be at 4096, not 20, which is pretty silly other than demoing. > At least the input chunks are 512 ;-) > > >>> from sreplace import sreplace > >>> fw = open('sreplace.py.txt','wb') > >>> for buf in sreplace(iter(lambda f=open('sreplace.py','rb'):f.read(512), ''),'out','OUT',20): > ... fw.write(buf) > ... > >>> fw.close() > >>> ^Z > > > [ 3:00] C:\pywk\ut>diff -u sreplace.py sreplace.py.txt > --- sreplace.py Fri Jan 14 02:39:52 2005 > +++ sreplace.py.txt Fri Jan 14 03:00:01 2005 > @@ -7,7 +7,7 @@ > """ > inbuf = '' > endsseq = False > - out = [] > + OUT = [] > start = 0 > lenold = len(old) > lennew = len(new) > @@ -17,21 +17,21 @@ > start = endprev # restore find start pos > for chunk in sseq: inbuf+= chunk; break > else: > - out.append(inbuf[start:]) > + OUT.append(inbuf[start:]) > endsseq = True > else: > - out.append(inbuf[endprev:start]) > + OUT.append(inbuf[endprev:start]) > start += lenold > - out.append(new) > - if endsseq or sum(map(len, out))>=retsize: > - s = ''.join(out) > + OUT.append(new) > + if endsseq or sum(map(len, OUT))>=retsize: > + s = ''.join(OUT) > while len(s)>= retsize: > yield s[:retsize] > s = s[retsize:] > if endsseq: > if s: yield s > else: > - out = [s] > + OUT = [s] > > if __name__ == '__main__': > import sys > > > Regards, > Bengt Richter From peter at engcorp.com Sat Jan 29 21:58:43 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 Jan 2005 21:58:43 -0500 Subject: cx_freeze error In-Reply-To: <1107048210.548048.152870@z14g2000cwz.googlegroups.com> References: <1107048210.548048.152870@z14g2000cwz.googlegroups.com> Message-ID: zyqnews at 163.net wrote: > I am new to Python. I made a script, and compiled it with cx_freeze, > but I got the following message from it: > > [cxfreeze]$./FreezePython hello.py > Traceback (most recent call last): > File "initscripts/ConsoleKeepPath.py", line 15, in ? > exec code in m.__dict__ > File "FreezePython.py", line 1, in ? > File "optparse.py", line 72, in ? > File "textwrap.py", line 32, in ? > File "textwrap.py", line 81, in TextWrapper > AttributeError: 'module' object has no attribute 'compile' > Does anyone know what I should do ? Possibly do not use the name "re.py" for your own module, as it is the name of a standard library module as well. At least, that's what an analysis of line 81 of "textwrap.py" suggests might be your problem. Do you have a module named "re.py"? -Peter From timj at tolisgroup.com Mon Jan 17 14:21:36 2005 From: timj at tolisgroup.com (brucoder) Date: 17 Jan 2005 11:21:36 -0800 Subject: Adjusting the 1024 byte stdin buffer limit In-Reply-To: References: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> Message-ID: <1105989696.900138.108260@z14g2000cwz.googlegroups.com> Currently, when sending a data stream that exceeds 1024 bytes via stdin, the stream blocks at the 1024th byte. This precludes completion of the submission of the data stream. Tim From daranrife at yahoo.com Fri Jan 28 17:41:22 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 14:41:22 -0800 Subject: Installing Numeric with ATLAS and LAPACK In-Reply-To: References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> <1106940704.164253.134630@c13g2000cwb.googlegroups.com> Message-ID: <1106952082.259581.260410@z14g2000cwz.googlegroups.com> Hi John, When I built Numeric with ATLAS and LAPACK, the eigenvalue calculation took the same amount of time. Per your suggestion, I will capture the output of the build and post it to the Numpy discussion group. Thanks, Daran From jzgoda at gazeta.usun.pl Mon Jan 3 16:57:22 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 03 Jan 2005 22:57:22 +0100 Subject: How do I make Windows Application with Python ? In-Reply-To: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> Message-ID: BOOGIEMAN wrote: > Well that's it, how do I make Windows Application with Python ??? > Is there simple way that works 100% ? How can I rework visual design > done in VS 2003 to use it for my python program ? Close your eyes, see this model-view-controller in your application, rewrite it in Python using one of its MVC frameworks. You see? It's easy, like that! -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From theller at python.net Tue Jan 11 16:15:36 2005 From: theller at python.net (Thomas Heller) Date: Tue, 11 Jan 2005 22:15:36 +0100 Subject: Windows GUIs from Python References: Message-ID: Luke Skywalker writes: > On Tue, 11 Jan 2005 12:55:42 -0600, Doug Holton wrote: >>You might also be interested in PyGUI although it doesn't have a native >>Windows implementation yet: >>http://nz.cosc.canterbury.ac.nz/~greg/python_gui/ > > Generally speaking, appart from MFC-style programming with Python32, > what are the non-alpha alternatives to write purely Windows apps in > Python today, ie. without the weight of extra bagage like wxWidgets? > > I'm not looking at fancy options, since the apps I write would be fine > with just the core Windows widgets along with a few add-ons like a > grid and the extended Win95 widgets. Well, venster. Although it is most certainly alpha. But with some work... Thomas From mail at tuxipuxi.org Mon Jan 24 04:03:56 2005 From: mail at tuxipuxi.org (Michael Goettsche) Date: Mon, 24 Jan 2005 10:03:56 +0100 Subject: Alternative Ways to install Python 2.4? In-Reply-To: <41F43373.4020003@v.loewis.de> References: <41F43373.4020003@v.loewis.de> Message-ID: <200501241003.56860.mail@tuxipuxi.org> On Monday 24 January 2005 00:29, "Martin v. L?wis" wrote: > Michael Goettsche wrote: > > I convinced my CS teacher to use Python in school. We currently have 2.2 > > installed on a Windows 2000 Terminal server. I asked the system > > administrator to upgrade to Python 2.4, but he didn't succeed in doing > > it. He used the microsoft installer package, which according to him > > crashed when starting. So my question is if there's an alternative way to > > install it(must be easy). Would it be an option to remove 2.2 first and > > then try to install 2.4 again? > > That would be an option, but I doubt it helps. Please have a look at > > http://www.python.org/2.4/bugs.html > > Most likely, you need to upgrade Visual Basic on that machine. > > Of course, without a precise error description, it is hard to tell. > > Regards, > Martin Hi Martin, thanks for your answer, I'll let him know! Michael From steven.bethard at gmail.com Tue Jan 11 02:22:08 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 11 Jan 2005 00:22:08 -0700 Subject: Python3: on removing map, reduce, filter In-Reply-To: References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> Message-ID: <2P2dndqyGbA8437cRVn-sQ@comcast.com> David M. Cooke wrote: > Steven Bethard writes: > >>Some timings to verify this: >> >>$ python -m timeit -s "def square(x): return x*x" "map(square, range(1000))" >>1000 loops, best of 3: 693 usec per loop >> >>$ python -m timeit -s "[x*x for x in range(1000)]" >>10000000 loops, best of 3: 0.0505 usec per loop > > > Maybe you should compare apples with apples, instead of oranges :-) > You're only running the list comprehension in the setup code... > > $ python2.4 -m timeit -s "def square(x): return x*x" "map(square, range(1000))" > 1000 loops, best of 3: 464 usec per loop > $ python2.4 -m timeit "[x*x for x in range(1000)]" > 1000 loops, best of 3: 216 usec per loop > > So factor of 2, instead of 13700 ... Heh heh. Yeah, that'd be better. Sorry about that! Steve From beable+unsenet at beable.com.invalid Fri Jan 14 20:18:13 2005 From: beable+unsenet at beable.com.invalid (Brian Eable) Date: 15 Jan 2005 11:18:13 +1000 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <1105739748.306557.72120@z14g2000cwz.googlegroups.com> Message-ID: <6e1xcnjxre.fsf@dingo.beable.com> "mr_little" writes: > Brian Eable wrote: > > perl -e '$a="194.109.137.226"; @a = reverse split /\./, $a; for $i > (0..3) { $sum += $a[$i]*(256**$i) } print "sum = $sum\n"' > > > > 226 + 35072 + 7143424 + 3254779904 = 3261958626 > > > > http://3261958626/ > > > > Which is NOT 666. > > Comrade, why perl here? :) Huh? Alt.prophecies.nostradamus is ALL ABOUT PERL! And at the end of the age There shall be a mysterious language Filled with punctuation It will connect many things. > Are you afraid python? :) I asked you to stop calling me python. Feel free to write a python version if you want to. -- It's explained on my website.. but you have to have a bona fide degree in science to understand it Mr. Ruken Dukin Kookin. -- George Hammond http://beable.org From bulba at bulba.com Sun Jan 2 13:39:30 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 02 Jan 2005 19:39:30 +0100 Subject: Speed ain't bad References: <0189t05r3226bkp5e1vtmp0gd6odcsf2qp@4ax.com> <41d6a39b$0$33656$edfadb0f@dread16.news.tele.dk> Message-ID: On Sat, 1 Jan 2005 14:20:06 +0100, "Anders J. Munch" wrote: >> One of the posters inspired me to do profiling on my newbie script >> (pasted below). After measurements I have found that the speed >> of Python, at least in the area where my script works, is surprisingly >> high. > >Pretty good code for someone who calls himself a newbie. >One line that puzzles me: >> sfile=open(sfpath,'rb') >You never use sfile again. Right! It's a leftover from a previous implementation (that used bzip2). Forgot to delete it, thanks. >Another way is the strategy of "it's easier to ask forgiveness than to >ask permission". >If you replace: > if(not os.path.isdir(zfdir)): > os.makedirs(zfdir) >with: > try: > os.makedirs(zfdir) > except EnvironmentError: > pass >then not only will your script become a micron more robust, but >assuming zfdir typically does not exist, you will have saved the call >to os.path.isdir. Yes, this is the kind of habit that low-level languages like C missing features like exceptions ingrain in a mind of a programmer... Getting out of this straitjacket is kind of hard - it would not cross my mind to try smth like what you showed me, thanks! Exceptions in Python are a GODSEND. I strongly recommend to any former C programmer wanting to get rid of a "straightjacket" to read the following to get an idea how not to write C code in Python and instead exploit the better side of VHLL: http://gnosis.cx/TPiP/appendix_a.txt -- It's a man's life in a Python Programming Association. From apardon at forel.vub.ac.be Thu Jan 13 04:42:51 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 09:42:51 GMT Subject: reference or pointer to some object? References: <10ubcp136drsu97@corp.supernews.com> Message-ID: Op 2005-01-12, Jeff Shannon schreef : > Torsten Mohr wrote: > >> I still wonder why a concept like "references" was not >> implemented in Python. I think it is (even if small) >> an overhead to wrap an object in a list or a dictionary. > > Because Python uses a fundamentally different concept for variable > names than C/C++/Java (and most other static languages). In those > languages, variables can be passed by value or by reference; neither > term really applies in Python. (Or, if you prefer, Python always > passes by value, but those values *are* references.) I would think the reference was the id. As such python always passes by reference, as the id of the parameter is the id of the argument. > Python doesn't > have lvalues that contain rvalues; Python has names that are bound to > objects. Passing a parameter just binds a new name (in the called > function's namespace) to the same object. > > It's also rather less necessary to use references in Python than it is > in C et. al. You use nothing but references in Python, that is the reason why if you assign a mutable to a new name and modify the object through either name, you see the change through both names. -- Antoon Pardon From cumontrealtrip*nospam* at yahoo.com Sun Jan 30 16:41:13 2005 From: cumontrealtrip*nospam* at yahoo.com (Ian) Date: Sun, 30 Jan 2005 16:41:13 -0500 Subject: Help! Host is reluctant to install Python References: Message-ID: On Wed, 26 Jan 2005 01:40:39 GMT, phr at localhost.localdomain wrote: ... >I think you should look into some type of virtual hosting that gives >you more ability to install your own software. Typing "uml hosting" >(UML is user-mode Linux) into Google finds a lot of such services. If >you find one that you like, post it here, I'm interested in this myself. I'm very happy with uml from tummy.com for 25 USD/month, with good support by email for configuring mod_python in my case. They are also a Pycon sponsor. Ian From harold.fellermann at upf.edu Wed Jan 12 13:16:35 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Wed, 12 Jan 2005 19:16:35 +0100 Subject: Why would I get a TypeEror? In-Reply-To: References: Message-ID: <17ED9138-64C6-11D9-B3E0-003065FB7B26@upf.edu> On 12.01.2005, at 18:35, It's me wrote: > For this code snip: > > a=3 > .... > b=(1,len(a))[isinstance(a,(list,tuple,dict))] > > Why would I get a TypeError from the len function? the problem is, that (1,len(a)) is evaluated, neither what type a actually has (python has no builtin lazy evaluation like ML). You have to do it this way instead: a=3 ... b = isinstance(a,(list,tuple,dict)) and len(a) or 1 - harold - -- The opposite of a correct statement is a false statement. But the opposite of a profound truth may be another profound truth. -- Niels Bohr From bjourne at gmail.com Sun Jan 30 17:33:43 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sun, 30 Jan 2005 23:33:43 +0100 Subject: search engine In-Reply-To: <1107112770.301449.49070@c13g2000cwb.googlegroups.com> References: <1107112770.301449.49070@c13g2000cwb.googlegroups.com> Message-ID: <740c3aec05013014331d15e9d6@mail.gmail.com> > hi all, i?m doing a search engine using python for the spider and php > to make a web for the search. The Database i have choosen is > postgreSQL. Do you think it is a good choosen? Any suggestion? "Databases are implementation details! Considering the database should be deferred as long as possible. Far too many applications are inextricably tied to their databases because they were designed with the database in mind from the beginning. Remember the definition of abstraction: the amplification of the essential and the elimination of the irrelevant. The database is irrelevant at this stage of the project; it is merely a technique used for storing and accessing data, nothing more." (Robert C. Martin, Agile Software Development, p. 194) -- mvh Bj?rn From ajikoe at gmail.com Wed Jan 26 17:50:32 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 26 Jan 2005 14:50:32 -0800 Subject: access private field in python 2.4 In-Reply-To: References: <1106754371.637295.82160@z14g2000cwz.googlegroups.com> <4prkc2-ini.ln1@pluto.i.infosense.no> <1106769651.371856.107960@f14g2000cwb.googlegroups.com> Message-ID: <1106779832.759591.62320@c13g2000cwb.googlegroups.com> thanks Steve.... pujo From dbasch at yahoo.com Thu Jan 20 19:20:09 2005 From: dbasch at yahoo.com (Derek Basch) Date: Thu, 20 Jan 2005 16:20:09 -0800 (PST) Subject: spawn syntax + os.P_WAIT mode behavior + spawn stdout redirection Message-ID: <20050121002009.93434.qmail@web20825.mail.yahoo.com> Hello, *First question* If the syntax of spawnl is: spawnl(mode, path, ...) Why does everyone write it like: os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') or: os.spawnl(os.P_WAIT, "/var/www/db/smm/smm_train", "smm_train", "SMMTrainInput.xml") How is the first 'cp' a path to a file? why does the desired executable have to be named again as the first parameter? *Second question* I have a script test.py which calls another script sleep.py using a spawn. -------------------------------------------------------------- #test.py import os os.spawnv(os.P_WAIT, "/var/www/db/cgi-bin/sleep.py", ["python", "sleep.py"]) #pid = os.spawnl(os.P_WAIT, 'sh', 'sh', '-cv', 'sleep 10; echo fark > /tmp/test.out') -------------------------------------------------------------- -------------------------------------------------------------- #sleep.py import time time.sleep(10) -------------------------------------------------------------- I would expect that the test.py script should take 10sec to return. However it returns immediatly. Perhaps I am calling the sleep.py script incorrectly? Shouldn't it take 10sec to execute since the spawn mode argument is os.P_WAIT? *Third question* If I uncomment the second spawn call in test.py I do not get any output to /tmp/test.out and it also returns immediatly. Can anyone tell me why? Thank You Mighty Python Guru's, Derek Basch __________________________________ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250 From philippe at philippecmartin.com Tue Jan 18 19:18:44 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Wed, 19 Jan 2005 00:18:44 GMT Subject: Tkinter in thread hangs on windows but not on Linux References: Message-ID: Actually, the following link: http://www.astro.washington.edu/owen/TkinterSummary.html seems to say my code is illegal - so I'm now just launching a modless window from the main thread - _seems_ to work On Tue, 18 Jan 2005 11:45:28 +0100, Philippe C. Martin wrote: > Hi, > > I need to pop-up in a "modless" manner some windows from an existing > Tkinter loop. The following code works OK under Linux: the second window > opens, shows the information, and quits cleanly when destroyed. However, > under windows, I get the second window without the content (so I hang in > run I guess), and both the thread and the calling process hang. > > Any clue ? > > Thanks > Philippe > > > > > > #******************************************************************************* > class SC_DOCS(threading.Thread): > __m_smg = None > __m_title = None > def __init__(self,p_msg,p_title): > threading.Thread.__init__(self) > self.__m_msg = p_msg > self.__m_title = p_title > > #******************************************************************************* > def run (self): > l_r = Tk() > l_r.title(self.__m_title) > l_f = Frame(l_r) > l_f.pack(side=TOP, expand=YES, fill=BOTH) > l_st = ScrolledText(l_f) > l_st.pack(side=TOP, expand=YES, fill=BOTH) > l_st.insert(END,self.__m_msg) > > l_r.mainloop() > > > . > . > . > > l_d = SC_DOCS('A MESSAGE', 'A TITLE') > l_d.start() > > > . > . > . From air_jlin at yahoo.com Fri Jan 21 14:13:20 2005 From: air_jlin at yahoo.com (Johnny Lin) Date: 21 Jan 2005 11:13:20 -0800 Subject: Unbinding multiple variables In-Reply-To: <35bnkeF4jpeetU1@individual.net> References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> <35bnkeF4jpeetU1@individual.net> Message-ID: <1106334800.868412.27650@f14g2000cwb.googlegroups.com> thanks everyone for the replies! John Hunter, yep, this is Johnny Lin in geosci :). re using return: the problem i have is somewhere in my code there's a memory leak. i realize return is supposed to unbind all the local variables, but since the memory leak is happening despite return, i thought it might help me track down the leak if i unbound everything explicitly that i had defined in local scope before i returned. or if anyone has recomm. on plugging leaks, would be thankful for any pointers there too. my understanding about locals() from the nutshell book was that i should treat that dictionary as read-only. is it safe to use it to delete entries? thanks again! From philippecmartin at sbcglobal.net Mon Jan 31 17:32:27 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 31 Jan 2005 16:32:27 -0600 Subject: serializing data structures Message-ID: <1107210747.8008.16.camel@localhost> Hi, I am trying to figure out the traps/issues about sending data structures through a TCP/IP socket under the following circumstances: 1) there could be a different O/S on both side of the socket 2) there could be a difference CPU architecure on both side of the socket 3) there could be a different major release of python (ex 2.3 and 2.4) on both side of the socket. I once wrote something in C to do that, but since python usually has a solution for me .... Any clue ? Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From cookedm+news at physics.mcmaster.ca Wed Jan 5 18:33:31 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 05 Jan 2005 18:33:31 -0500 Subject: date/time References: Message-ID: Thomas Guettler writes: > Am Wed, 05 Jan 2005 15:08:37 +0100 schrieb Nader Emami: > >> L.S., >> >> Could somebody help me how I can get the next format of date >> from the time module? > > I don't understand your question. Do you want to have the next day? > > 20041231 --> 20050101 ? > > You can do it like this: > - parse the string with time.strptime > - timetuple[2]+=1 > - mktime(timetuple) # --> secs > - strftime(localtime(secs)) Or using the datetime module: import time, datetime tt = time.strptime('20041231', '%Y%m%d') t = datetime.date.fromtimestamp(time.mktime(tt)) # now in a easier-to-handle form than the time tuple t += datetime.timedelta(days=1) print t.strftime('%Y%m%d') -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From http Sat Jan 22 20:16:04 2005 From: http (Paul Rubin) Date: 22 Jan 2005 17:16:04 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> Message-ID: <7xbrbhosh7.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > > You're not making any bloody sense. > > oh, I make perfect sense, and I think most people here understand > why I found your little "lecture" so funny. if you still don't get > it, maybe some- one can explain it to you. I would appreciate it if someone did. From bokr at oz.net Sun Jan 16 00:55:22 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 16 Jan 2005 05:55:22 GMT Subject: interpret 4 byte as 32-bit float (IEEE-754) References: <34t1p2F4foiplU1@individual.net> <41e952b9$1@nntp0.pdx.net> <41E96302.4020003@web.de> <41e964bc$1@nntp0.pdx.net> Message-ID: <41e9fae6.975536557@news.oz.net> On Sat, 15 Jan 2005 11:00:36 -0800, Scott David Daniels wrote: >G.Franzkowiak wrote: >> Scott David Daniels schrieb: >> >>> franzkowiak wrote: >>> >>>> I've read some bytes from a file and just now I can't interpret 4 >>>> bytes in this dates like a real value. An extract from my program: >>>> def l32(c): >>>> return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) + >>>> (ord(c[3])<<24) >>>> ... >>>> value = l32(f.read(4)) <--- 3F 8C CC CD should be 1.11 >>>> >>> OK, here's the skinny (I used blocks & views to get the answer): >>> >>> import struct >>> bytes = ''.join(chr(int(txt, 16)) for txt in '3F 8C CC CD'.split()) >>> struct.unpack('>f', bytes) >>> >>> I was suspicious of that first byte, thought it might be an exponent, >>> since it seemed to have too many on bits in a row to be part of 1.11. >>> >>> -Scott David Daniels >>> Scott.Daniels at Acm.Org >> >> >> Ok, I the string exist with "mystr = f.read(4)" and the solution for >> this case is in your line "struct.unpack('>f', bytes)" >> But what can I do when I want the interpret the content from the Integer >> myInt (*myInt = 0x3F8CCCCD) like 4-byte-real ? >> This was stored with an othes system in a binary file to >> CD CC 8C 3F and now is it in python in value. The conversion is not >> possible. It's right... one of this bytes is an exponent. >> I want copy the memory content from the "value address" to "myReal >> address" and use print "%f" %myReal. >> Is myReal then the right format ? >> What can I do with python, in FORTH is it simple >> ( >f f. ) >> >> gf >> >> >> >If you really want to do this kind of byte fiddling: > http://members.dsl-only.net/~daniels/block.html > >Then: > from block import Block, View > b = Block(4) # enough space for one float (more is fine) > iv = View('i', b) # getting to it as an integer > fv = View('f', b) # same memory as floating point > iv[0] = 0x3F8CCCCD # Here is a sample just using the integer > print fv[0] > >On an Intel/Amd/Generic "PC" machine, you should get 1.1 > Ok, for most bit patterns (except QNANs), you can do it in pure python: ----< i32as_single.py >------------------------------------ class NoQNAN(ValueError): pass # use to flag inability to return QNANs def i32as_single(i): """ (UIAM in my interpretation of a 1995 Pentium Processor Developer's Manual) This converts bits in a 32-bit integer as if they were bits of a single-precision IEEE 754 floating point number to python float +---+---+---+---+---+---+---+---+---+---+---+---+ ... +---+---+---+---+ | s | e e e e e e e eb| b b b ... b b b b0 | +---+---+---+---^---+---+---+---^---+---+---+---^ ... ^---+---+---+---+ 31 30 29 28 27 26 25 24 23 22 21 20 3 2 1 0 where s is the sign bit, and is the only thing that changes between + and - and e..eb is an 8-bit biased (by 127) exponent, and eb is the hidden unit 1 bit followed by 23 b..b0 significant "fraction" bits", normalized so that the most significant bit is always 1 and therefore doesn't have to be stored at eb, except that when all but the sign bit are zero, eb is ignored and the value is then a signed zero value. The binary fraction starting bit is after the hidden '1' bit eb at 23, so viewing bits 0..23 as an integer, we have to divide by 2**23 (or adjust the exponent) to get the 1.xxxx values when the official unbiased exponent is zero (offset value 127). Thus 0x3f800000 is zero unbiased exponent and no other bits, for a value of 1.0 A biased exponent of 255 signifies a NaN, and a biased exponent of zero signifies a denormal (which doesn't have a hidden bit, and whose unit bit is bit 22). Single precision denormals can be normalized in python (double) float format, which is done for the return value. """ signbit = i&0x80000000 if not i&0x7fffffff: return signbit and -0.0 or 0.0 # if -0.0 available biased_exp = (i>>23) & 0xff # bits 30-23 unitbit = biased_exp and 0x800000 or 0 # bit 23, or 0 for denormals significand = i & 0x7fffff # bits 22-0 if biased_exp == 255: if significand: raise NoQNAN, "Sorry, can't generate QNAN from %08x" % i return signbit and -1e9999 or 1e9999 # XXX s/b INF's for sure?? adjexp = (biased_exp or 1) - 127 - 23 # adjusted for denormal posvalue = (significand + unitbit)*2.0**adjexp return signbit and -posvalue or posvalue def test(): import struct num = 0 for sign in (0, 2*(-2**30)): for i3 in xrange(128): num3 = i3<<24 for i2 in xrange(256): print '\r%08x'%(num,), # show progress num2 = i2<<16 # skip mid byte of significand, make 0 # and twiddle only a few bits at the bottom for num0 in xrange(8): num = sign+num3+num2+num0 s = ''.join(map(chr,(num0, 0, i2,((sign and 0x80 or 0)+i3)))) try: ti32as = i32as_single(num) except NoQNAN: continue tstruct = struct.unpack('f', s)[0] # XXX ' no INF ?? if ti32as != tstruct: print '\n%x =>%r\n%r => %r' % (num, ti32as, s, tstruct) if __name__ == '__main__': test() ----------------------------------------------------------- [21:47] C:\pywk\clp>i32as_single.py C:\pywk\clp\i32as_single.py:31: FutureWarning: hex/oct constants > sys.maxint will return positi ve values in Python 2.4 and up signbit = i&0x80000000 7fff0007C:\pywk\clp\i32as_single.py:51: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up print '\r%08x'%(num,), # show progress ff7f0007C:\pywk\clp\i32as_single.py:38: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up raise NoQNAN, "Sorry, can't generate QNAN from %08x" % i fffe0007 Of course, the test() gives a clue how you might write the whole thing using struct by just summing the four chr-ed extracted bytes from the input i ;-) Anyway, a couple things (how to make a QNAN in python without calling struct, and '<' in struct): >>> from i32as_single import i32as_single as i32f >>> i32f(0x3f8ccccd) 1.1000000238418579 >>> i32f(0x00000000) 0.0 >>> i32f(0x7f800000) 1.#INF >>> i32f(0xff800000) -1.#INF But I don't know how to build QNaNs: >>> i32f(0x7f800001) Traceback (most recent call last): File "", line 1, in ? File "i32as_single.py", line 38, in i32as_single raise NoQNAN, "Sorry, can't generate QNAN from %08x" % i i32as_single.NoQNAN: Sorry, can't generate QNAN from 7f800001 Whereas struct does: >>> import struct >>> struct.unpack('f','\x00\x00\x80\x7f')[0] 1.#INF >>> struct.unpack('f','\x01\x00\x80\x7f')[0] 1.#QNAN BTW, your example: >>> struct.unpack('f','\xcd\xcc\x8c\x3f')[0] 1.1000000238418579 >>> i32f(0x3f8ccccd) 1.1000000238418579 But what does this mean? (I wanted to test with little endian unpacking, since that is what I knew I created, but that isn't what '<' means?? ...) >>> struct.unpack('f','\x00\x00\x80\x7f')[0] 1.#INF >>> struct.unpack('<41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <1105229619.776339.218900@c13g2000cwb.googlegroups.com> Message-ID: <41e09f53.362269896@news.oz.net> On 8 Jan 2005 16:13:39 -0800, "Carl Banks" wrote: > >Bengt Richter wrote: >> And, is the whole thing after the '=' an expression? E.g., >> >> x = ( foo(x) where: >> x = math.pi/4.0 >> ) where: >> def foo(x): print 'just for illustration', x > >How would that be any improvement over this? Not in any way except that the idea was not to show the best code, but to show an illustration of possible rules of parsing ;-) > >. x = foo(x) where: >. x = math.pi/4.0 >. def foo(x): print 'just for illustration', x > >Can anyone think of a use case for embedding "where" inside an >expression as opposed to making it part of a simple statement? And, if >so, is the benefit of it worth the massive hit in readability. I guess that might depend on the local-scope effects of 'where:' -- I think it is too early to jump to conclusions one way or the other. At this point I just wanted to clarify what the proposal really was, by asking questions about silly code snippets. > > >> or is this legal? >> >> for y in ([foo(x) for x in bar] where: >> bar = xrange(5) >> ): baz(y) where: >> def baz(arg): return arg*2 > >Here, I can only hope not. One reason I proposed a where...do syntax >is so that, if you wanted to localize a variable to a for loop or some >other compound statement, you could do it with a minimum of fuss. Just because something contorted is _possible_ is not a good reason for limiting a general capability IMO. Why not say instead, "I can only hope no one uses it that way."? > >. where: >. bar = xrange(5) >. def baz(arg): return arg*2 >. do: >. for y in [foo(x) for x in bar]: >. baz(y) > > >> Not trying to sabotage the idea, really, just looking for >clarification ;-) > >That's ok. For it fly, it's got to be able to withstand the flak. I actually like it quite a bit, in spite of the NIH ego thing ;-) Regards, Bengt Richter From nick at craig-wood.com Sun Jan 30 06:30:03 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 30 Jan 2005 11:30:03 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> Message-ID: Skip Montanaro wrote: > Fine. Go build a sumo distribution and track the normal CPython. > The problem isn't all that new. (Take a look at scipy.org for one > take on that theme. Of course Linux distros have been doing their > take on this forever.) If I'm writing code just for fun. I'll be doing on Debian Linux, then I can do apt-get install python-crypto and I'm away. However if I'm writing code for work, it has to work on windows as well, which introduces a whole extra barrier to using 3rd party modules. Something else to compile. Something else to stick in the installer. Basically a whole heap of extra work. I think one of the special things about Python is its batteries included approach, and a crypto library would seem to be an obvious battery to install since it doesn't (or needn't) depend on any other library or application. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Mon Jan 10 18:06:57 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?utf-8?Q?Michel_Claveau_-_abstraction_m=C3=A9t?= =?utf-8?Q?a-galactique_non_triviale_en_fui?= =?utf-8?Q?te_perp=C3=A9tuelle.?=) Date: Tue, 11 Jan 2005 00:06:57 +0100 Subject: Python & unicode Message-ID: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> Hi ! If Python is Ok with Unicode, why the next script not run ? # -*- coding: utf-8 -*- def ?????(toto): return(toto*3) aret = ?????(4) @-salutations -- Michel Claveau -------------- next part -------------- An HTML attachment was scrubbed... URL: From apardon at forel.vub.ac.be Mon Jan 10 08:12:28 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Jan 2005 13:12:28 GMT Subject: tuples vs lists References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dfe2a6$0$22729$636a15ce@news.free.fr> Message-ID: Op 2005-01-08, Bruno Desthuilliers schreef : > worzel a ?crit : >> I get what the difference is between a tuple and a list, but why would I >> ever care about the tuple's immuutability? > > Because, from a purely pratical POV, only an immutable object can be > used as kay in a dict. This is not true. > So you can use tuples for 'composed key'. lists can be so used too. Just provide a hash. -- Antoon Pardon From inyeol.lee at siimage.com Tue Jan 11 18:37:29 2005 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Tue, 11 Jan 2005 15:37:29 -0800 Subject: smtpd.py in python2.4/bin directory? Message-ID: <20050111233729.GA27685@siliconimage.com> After installing Python 2.4 from src tarball I found one new executable in python/bin directory - "smtpd.py". I also found the same file in python/lib/python2.4/. Is this intentional or just a minor bug in build script? Inyeol From fredrik at pythonware.com Mon Jan 24 18:05:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 Jan 2005 00:05:02 +0100 Subject: Looking for Form Feeds References: <41F5696D.9030100@novasyshealth.com> <200501241701.33232.hancock@anansispaceworks.com> Message-ID: Terry Hancock wrote: >> I also tried to create a ^M^L (typed in as Q M L) but that >> gives me a syntax error when I try to run the program (re does not like >> the control characters, I guess). Is it possible for me to pull out the >> formfeeds in a straightforward manner? > > I suspect you should convert that to hexadecimal codes: '\x0c\x0b' > (at least I *think* those are the characters you mean, I'm not really > familiar with the ^X notation). you're off by one: >>> hex(ord("M") - 64) '\0xd' >>> hex(ord("L") - 64) '\0xc' >>> chr(ord("M") - 64) '\r' >>> chr(ord("L") - 64) '\x0c' >>> "\f" '\x0c' From ncoghlan at iinet.net.au Thu Jan 27 04:54:32 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 27 Jan 2005 19:54:32 +1000 Subject: Inherting from object. Or not. In-Reply-To: <200501262214.40597.frans.englich@telia.com> References: <1106774681.501533.156220@f14g2000cwb.googlegroups.com> <200501262214.40597.frans.englich@telia.com> Message-ID: <41F8BA58.9060108@iinet.net.au> Frans Englich wrote: > On Wednesday 26 January 2005 21:24, M.E.Farmer wrote: > >>Hello Frans, >>What you are seeing is a step on the path to unification of types and >>classes. > > > I changed all base classes in my project to inherit object. There appears to > be no reason to not do it, AFAICT. Exactly. My advice is to use new-style classes unless you have a reason not to (if you're inheriting from a builtin type, then there is no need to inherit from object as well - the builtin types already have the correct basic type). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ola.natvig at infosense.no Tue Jan 18 09:01:42 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Tue, 18 Jan 2005 15:01:42 +0100 Subject: generator expressions: performance anomaly? In-Reply-To: <354h9gF4fgsqgU1@individual.net> References: <377Hd.77904$Jk5.30235@lakeread01> <354gj7F4etgn8U1@individual.net> <354h9gF4fgsqgU1@individual.net> Message-ID: Diez B. Roggisch wrote: >>Would it be a bad solution to make that a list or tuple of ten >>time.time() calls, you could also restrict what theese prebuilding >>sequenses could contain, or perhaps try to prebuild them, and then fail >>if it's impossible. > > > I don't fully understand what you mean. Restricting them would mean to add > static declarations that say "I return the same whenever you call me" - > which is even more than the already fragile "const" declaration of c++ > allows. > > And for your second suggestion - how exactly do you check for failing? > Generating 2 elements and checking if they are equal to the first two of > the old list? What about overloaded __cmp__/__eq__, or just the last > element differing? > > This problem is too complex to solve automatically - domain knowledge is > needed. As the code Antoon presented also suggests the simple solution: > > > lst = list(time.time() for i in xrange(10)) > tpl = tuple(lst) > > > I don't see why this is a desirable feature at all. Keep in mind that > putting statements or even stackframes between those two statements above > utterly complicates things. And we even didn't dig into the dynamic > features of python that for example make it possible to alter time.time > like this > > time.time = random.random() > > so that it behaves totally different - while the syntactically equivalence > still holds. No chance of catching that. My thoughts where to let the 'leftmost' section of the expression to be intact so that any of the dynamic things done to this part, i.e. replacing time.time with random.random are taken into consideration. What can be done is to extract the expression into a loopless structure lst = list(time.time() for i in xrange(10)) would be compiled to the bytecode version of: lst = [time.time(), time.time(), time.time(), time.time() ...] Then time.time can do whatever it wants to. It's the (x)range function that we need to enshure returns the same values in every execution. This *IS* a useless feature, but I think it's possible to make it work. ola From flamesrock at gmail.com Tue Jan 4 04:17:56 2005 From: flamesrock at gmail.com (flamesrock) Date: 4 Jan 2005 01:17:56 -0800 Subject: Python evolution: Unease In-Reply-To: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> Message-ID: <1104830276.579755.133870@f14g2000cwb.googlegroups.com> Well, I'm not a seasoned programmer like you but I have to say Python is the singlebest language I've worked with to date. In a matter of weeks I learned to do things that took me months in other languages and even found the process enjoyable. Maybe you are right. If so, couldn't Python be forked into something like you describe, while still remaining compatible at the core? (if anyones willing) Python++ anyone? From jacek.generowicz at cern.ch Thu Jan 13 11:41:01 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 Jan 2005 17:41:01 +0100 Subject: from __future__ import decorators References: Message-ID: Skip Montanaro writes: > Jacek> Crazy idea ... would it be possible to shadow 2.3's parser with > Jacek> one stolen from 2.4 ? > > If you're willing to go to that much trouble, why not just upgrade to 2.4? *I* upgraded to 2.4 sometime when it was in alpha. From fumanchu at amor.org Fri Jan 7 16:08:05 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 7 Jan 2005 13:08:05 -0800 Subject: DOS problem (simple fix??) Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398131@exchange.hqamor.amorhq.net> Gavin Bauer wrote: > My DOS window (running in windows ME) closes the second it finishes > running my programs. As you can imagine, this makes it hard to see the > results. I've gotten in the habit of putting raw_input("Press enter to > exit") at the end of every program, and in addition to being pain in > the butt, it often fails to work. Being new to programming in general, > I make more mistakes than most people. My programs often have errors > before they get to my raw_input command. They then display the error > and immediately close. It is naturally a lot easier to fix an error > when you know what the error is. This makes debugging even more > annoying than it ordinarily would be, if you can imagine that. I've > heard that it should be a simple preference fix, but I've asked around > and no one seems to know how. > > Thank you, and please make all answers simple enough to be understood > by a highschool student and his father :) . Even after all the IPO hype, the map integration, and the Suggest beta, Google is STILL your friend: http://www.google.com/search?q=windows+console+remain+open In other words, use the /k switch to cmd.exe Robert Brewer MIS Amor Ministries fumanchu at amor.org From rkern at ucsd.edu Sun Jan 30 02:38:15 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 29 Jan 2005 23:38:15 -0800 Subject: Trouble installing numeric In-Reply-To: <20050129232540162-0800@news.claremont.edu> References: <20050129232540162-0800@news.claremont.edu> Message-ID: Chris Weisiger wrote: > I'm trying to install numeric on my MacOS X box using Darwin, with the > eventual goal of satisfying all of PyGame's dependencies so I can > finally start working on my semester project. I would be using MacPython, > except that I can't seem to get its Package Manager to work. Anyway, > when I try to install numeric, I get the following error: > > [HMC-58-125:~/proj/Numeric-23.7] chriswei% sudo ./setup.py install > Password: > running install > running build > running build_py > running build_ext > building 'lapack_lite' extension > gcc -Wl,-F. -Wl,-F. -bundle -framework Python build/temp.darwin-7.6.0- > Power_Macintosh-2.3/Src/lapack_litemodule.o build/temp.darwin-7.6.0- > Power_Macintosh-2.3/Src/blas_lite.o build/temp.darwin-7.6.0-Power_ > Macintosh-2.3/Src/f2c_lite.o build/temp.darwin-7.6.0-Power_Macintosh-2.3/ > Src/zlapack_lite.o build/temp.darwin-7.6.0-Power_Macintosh-2.3/Src/ > dlapack_lite.o -L/usr/lib/atlas -llapack -lcblas -lf77blas -latlas -lg2c - > o build/lib.darwin-7.6.0-Power_Macintosh-2.3/lapack_lite.so -framework > vecLib > ld: can't locate file for: -llapack > error: command 'gcc' failed with exit status 1 > > Previously it had been complaining about a missing directory '/usr/lib/ > atlas', but I just created that (without any idea what it wanted it for > or why it couldn't create it itself, natch). You can delete it. That is the directory specified by default to look for the ATLAS libraries which are a portable optimized LAPACK and BLAS. You don't need it on the Mac because you have vecLib, which is an Apple-provided version of ATLAS, pre-installed. > From what I've found online, > it's now having problems because a linear algebra module it needs ( > lapack) can't be found. However, isn't numeric supposed to have its own > "light" linear algebra code? Yes, however, the ATLAS or vecLib libraries will be much, much faster. > Looking in setup.py, I found the following > section: > > # delete all but the first one in this list if using your own LAPACK/ > BLAS > sourcelist = [os.path.join('Src', 'lapack_litemodule.c'), > # os.path.join('Src', 'blas_lite.c'), > # os.path.join('Src', 'f2c_lite.c'), > # os.path.join('Src', 'zlapack_lite.c'), > # os.path.join('Src', 'dlapack_lite.c') > ] ] > > I tried uncommenting the lines, but no dice. Also modify the library_dirs_list and libraries_list variables, but keep these *_lite.c files commented out. library_dirs_list = [] libraries_list = [] That way, Numeric will just pick up vecLib. This is fixed in CVS. -- 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 rganesan at myrealbox.com Wed Jan 12 03:59:54 2005 From: rganesan at myrealbox.com (Ganesan R) Date: 12 Jan 2005 14:29:54 +0530 Subject: Help Optimizing Word Search References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: >>>>> "Case" == Case Nelson writes: > Hi there I've just been playing around with some python code and I've > got a fun little optimization problem I could use some help with. > Basically, the program needs to take in a random list of no more than > 10 letters, and find all possible mutations that match a word in my > dictionary (80k words). However a wildcard letter '?' is also an > acceptable character which increases the worst case time significantly. > So if the letters are ['a','b','c'] check a, b, c, ab, ac, ba, bc, ca, > cb, abc, acb, bac, bca, cab, cba where only a, ba and cab would be > added to the dict of words. If the letters are ['?','?'] check a-z, aa, > ab, ac, ad, ..., az, ba, bb, bc, bd, ..., zz You're trying to cheat at scrabble aren't you ;-). I once wrote a solution using regular expressions, which I brushed up and posted here. Can you check how it compares with your version? Call as "wordsearch abcd". You can also use wildcards. ===== .#!/usr/bin/python . .import sys .import os .import re . .wordlist = "/usr/share/dict/words" . .def get_freq(str): . """Create a hash of number of times a character occurs in string""" . freq = { } . for c in str: . freq[c] = freq.get(c, 0) + 1 . return freq . . .def main(argv = sys.argv): . chars = argv[1] . if argv[2]: . wordlist = argv[2] . wild = chars.count("?") . if wild: . chars = chars.replace("?", "") # remove the wild cards . if chars: . charpat = "[" + chars + "]*" . else: . charpat = "" . . # create a regexp suitable for matching . pattern = charpat . for w in xrange(wild): . pattern += ".?" + charpat . pattern = "^" + pattern + "$" . print >> sys.stderr, pattern . . # char count for our list of chars . charfreq = get_freq(chars) . . pattern_re = re.compile(pattern, re.IGNORECASE) . # for line in os.popen("zegrep -i '%s' %s" % (pattern, wordlist)): . for line in open(wordlist): . line = line.rstrip() . if not pattern_re.search(line): . continue . if not line or len(line) > len(chars) + wild: . continue . line = line.lower() . linefreq = get_freq(line) . . # check if chars occur fewer times than in the given string . extra = 0 . for c in linefreq.keys(): . if linefreq[c] > charfreq.get(c, 0): . extra += linefreq[c] - charfreq.get(c, 0) . if extra > wild: . break . else: . print line . .if __name__=='__main__': . main() ===== From a at b.c Tue Jan 11 13:51:19 2005 From: a at b.c (Doug Holton) Date: Tue, 11 Jan 2005 12:51:19 -0600 Subject: Game programming in Python In-Reply-To: References: Message-ID: Baza wrote: > I'm looking for any books or on-line resources on game programming using > Python. Does anyone have any advice? See http://pygame.org/ There is also a book called "Game Programming with Python". From chris.lasher at gmail.com Fri Jan 14 15:27:31 2005 From: chris.lasher at gmail.com (Chris Lasher) Date: 14 Jan 2005 12:27:31 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: <1105734450.961150.32980@z14g2000cwz.googlegroups.com> Forgive my ignorance, but what does using mmap do for the script? My guess is that it improves performance, but I'm not sure how. I read the module documentation and the module appears to be a way to read out information from memory (RAM maybe?). From fredrik at pythonware.com Mon Jan 31 12:02:14 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 18:02:14 +0100 Subject: variable declaration References: <1107188359.375703.110590@f14g2000cwb.googlegroups.com> <1107190028.911373.158940@z14g2000cwz.googlegroups.com> Message-ID: Michael Tobis wrote: >> that's a nice theory, but since the decorator line is executed by the >> interpreter, it's a little weak. > > Well, uh, who else would process it? the compiler. from __future__ is a declaration. @expression is an executable statement. From jjcollins at cableone.net Sat Jan 1 22:31:56 2005 From: jjcollins at cableone.net (jcollins) Date: Sat, 1 Jan 2005 19:31:56 -0800 Subject: screen clear question Message-ID: <10teqpdvramua3@corp.supernews.com> Is there a command in Python to clear the screen? That is without writing multiple blank lines. Thanks. Jim C From decoder-x-mac-gujarati at mozilla.org Mon Jan 31 09:08:12 2005 From: decoder-x-mac-gujarati at mozilla.org (decoder-x-mac-gujarati at mozilla.org) Date: Mon, 31 Jan 2005 19:08:12 +0500 Subject: Report Message-ID: <20050131142033.6AAF31E4008@bag.python.org> The original message was received at Mon, 31 Jan 2005 19:08:12 +0500 from [140.253.248.170] ----- The following addresses had permanent fatal errors ----- python-list at python.org From golux at comcast.net Sat Jan 22 21:37:41 2005 From: golux at comcast.net (Stephen Waterbury) Date: Sat, 22 Jan 2005 21:37:41 -0500 Subject: [OT] XML design intent ... further musings In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> <41F2C840.2050304@comcast.net> Message-ID: <41F30DF5.6040002@comcast.net> Peter Hansen wrote: > If merely thinking about the purpose of XML doesn't make it > clear where Steve got that idea ... I meant no disparagement of Steve, and it is quite clear where he got that (correct!) idea ... It's also clear that the XML user community sees that as part of *their* purpose in applying XML. But here we are talking about intent of its designers, and "merely thinking about the purpose of XML" won't enable me to read their minds. ;) > read up a little bit more in > the spec [... in which it is stated rather explicitly!] > > I would ask what part of that, or of the simple phrase > "data object", or even of the basic concept of a markup language, > doesn't cry out "data interchange metalanguage" to you? It does indeed -- my apologies for not reading the annotations more carefully! I missed that one in particular. Okay, you've dragged me, kicking and screaming, to agree that the actual, published design intent of XML is to provide a "data interchange metalanguage". Thanks to Fredrik for the link he included (elsewhere in the "YAML" thread) to JavaScript Object Notation (JSON). JSON looks like a notable improvement over XML for data objects that are more fine-grained (higher ratio of markup to non-markup -- e.g., most relational data sets, RDF, etc.) than those at the more traditional "document" end of the spectrum (less markup, more text). The latter types of data objects are the ones I happen to believe are in the sweet spot of XML's design, regardless of its designers' more sweeping pronouncements (and hopes, no doubt). I should note that I have to deal with XML a lot, but always kicking and screaming (though much less now because of Fredrik's Elementtree package ;). Thanks, Fredrik and Peter, for the references. ;) Peace. Steve From stephen.thorne at gmail.com Mon Jan 31 18:24:57 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Tue, 1 Feb 2005 09:24:57 +1000 Subject: Want to meet any of these people? They are registered for PyCon In-Reply-To: References: Message-ID: <3e8ca5c80501311524614ab544@mail.gmail.com> On Mon, 31 Jan 2005 17:49:53 -0500, Steve Holden wrote: > Aahz wrote: > > In article , > > Steve Holden wrote: > > > >>Note that the sort order isn't perfect - I just sorted on the second > >>"word" in each name. PyCon is a *great* place to meet people and discuss > >>ideas. Hope to see you there. > > > > > > Good thing I'm not coming this year, eh? ;-) > > If you mean specifically for sorting purposes, it would have put the > null second name at the beginning just like you'd expect. Odd, the naive way I would have written such a script would have been: all_names = (line.split() for line in sys.stdin) sys.stdout.writelines(' '.join(x[1])+'\n' for x in sorted((name[1], name) for name in all_names)) which would not have worked correctly, it would have thrown an exception because "Aahz\n".split()[1] does not exist. I guess the second iteration would use name[1:] instead... unfortunately-not-going-to-pycon-ly y'rs. Stephen Thorne From onlyonemc at gmail.com Sun Jan 9 11:36:04 2005 From: onlyonemc at gmail.com (onlyonemc at gmail.com) Date: 9 Jan 2005 08:36:04 -0800 Subject: Long strings as function parameters Message-ID: <1105288564.441842.13060@c13g2000cwb.googlegroups.com> I would like to have functions that operate on long strings, 10-100 MB. In C I would of course pass a pointer to the string for a quick function call. What is an efficient way to do this in python? Cheers, -mark From leipoldw at ace-net.com Sun Jan 2 09:12:58 2005 From: leipoldw at ace-net.com (Walter S. Leipold) Date: Sun, 2 Jan 2005 09:12:58 -0500 Subject: Problems programming with Tkinter Message-ID: Svenglenn writes: > But, i want the program to open a new dialogue when i press > the button "Visa ruta" and in that dialogue will be a field > where you can enter a value directly in the program, but a > can't get it to work because is don't know how i shall do to > open a new dialogue window in the program? For simple data entry (and file choosing, too!), use the built-in Tk dialogs. For example: . import tkSimpleDialog . . answer = tkSimpleDialog.askString( . "Dialog title", . "Prompt", . parent=root, . initialvalue="Howdy!") . if answer is not None: . ...do something... -- Walt From miki.tebeka at zoran.com Tue Jan 11 03:30:56 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 11 Jan 2005 10:30:56 +0200 Subject: embedded scripts debugging In-Reply-To: <347dpqF45nskbU1@individual.net> References: <347dpqF45nskbU1@individual.net> Message-ID: <20050111083028.GE3808@zoran.com> Hello Andrey, > So the question is: Is there suitable library for simple python gui > debugger, or may be there are some other techniques for debugging > embedded scripts? What I usually do is add from pdb import set_trace in the embedded module somewhere and then add a call to set_trace (breakpoint) whenever I with. When the code reaches the call to set_trace, you'll have pdb prompt and you can debug as you like. Note that you can't add breakpoint dynamically this way. HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From http Fri Jan 21 01:24:22 2005 From: http (Paul Rubin) Date: 20 Jan 2005 22:24:22 -0800 Subject: What's the best python web-developer's editor References: Message-ID: <7xwtu7uwo9.fsf@ruckus.brouhaha.com> andy writes: > Anybody like to comment on which editor they use for python web app > development - Emacs For both discrete and mixed python and html code, and why? There's no reason to use anything else. From rnd at onego.ru Sun Jan 9 10:54:03 2005 From: rnd at onego.ru (Roman Suzi) Date: Sun, 9 Jan 2005 18:54:03 +0300 (MSK) Subject: Python3: on removing map, reduce, filter In-Reply-To: <7x4qhqr6cx.fsf@ruckus.brouhaha.com> References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> <7x4qhqr6cx.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 9 Jan 2005, Paul Rubin wrote: >Andrey Tatarinov writes: I hope there will be from __past__ import functional_paradigma in Python 3 ;-) And, also, what is the best way to replace reduce() ? Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From eurleif at ecritters.biz Tue Jan 11 16:05:44 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 11 Jan 2005 16:05:44 -0500 Subject: Python & unicode In-Reply-To: <1105451779.544442.204920@f14g2000cwb.googlegroups.com> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> <1105451779.544442.204920@f14g2000cwb.googlegroups.com> Message-ID: <34itatF4d4i9kU1@individual.net> Serge.Orlov at gmail.com wrote: > So is the support of Unicode in virtually every computer language > because they don't support ... digits except 0..9. Hex digits aren't 0..9. Python 2.4 (#2, Dec 3 2004, 17:59:05) [GCC 3.3.5 (Debian 1:3.3.5-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 0xCF 207 >>> hex(123) '0x7b' From golux at comcast.net Mon Jan 3 15:16:20 2005 From: golux at comcast.net (Stephen Waterbury) Date: Mon, 03 Jan 2005 15:16:20 -0500 Subject: Developing Commercial Applications in Python In-Reply-To: References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <41D9A814.7000502@comcast.net> It's me wrote: > Shaw-PTI (www.pti-us.com) uses Python in their software. ... but the "Python Powered" logo is conspicuous by its absence from their site. Too bad that some commercial exploiters of Python don't advertise that fact more often. Every little bit helps! Steve From skip at pobox.com Tue Jan 4 20:54:43 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Jan 2005 19:54:43 -0600 Subject: Python evolution: Unease In-Reply-To: <7x652che6z.fsf@ruckus.brouhaha.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> Message-ID: <16859.18659.342325.317468@montanaro.dyndns.org> Paul> Skip Montanaro writes: >> Start writing (or reorganizing). Folks, this is open source. I'm >> sure by the traffic on the list most people here know how to write. Paul> Irrelevant, the issue isn't what docs can be written if someone Paul> wants to do it, it's what docs are actually already there. How do you think we got the docs we already have? Somebody wrote them. If there aren't enough docs or if they have mistakes, then somebody has to correct them. I'm just suggesting that more people put their money where they mouths are so-to-speak. >> This being the Internet and all, it's not clear that referencing >> external documentation is somehow worse than incorporating it >> directly into the distribution. Paul> The same thing could be said for software. So why not eliminate Paul> the Python library and let everyone download each module Paul> separately? Because it's bogus is why. Paul> It really does matter whether something is included or just Paul> referenced. Okay, then start doing the work necessary to incorporate that stuff into the core. Get Fredrik to say "okay" to including his Tkinter docs, then do what it takes to incorporate it. The fact that Fredrik can check those docs in himself but hasn't after several years suggests that he prefers the status quo for one or more reasons. I'm not saying references are perfect. I'm saying that given the time constraints of the existing developer crowd and the relative priority of various open tasks that folding in external documentation hasn't risen to the top of the queue yet. The best way to make that happen is for it to be your highest priority and then for you to make it happen. That's a longer-winded way to say what I meant with "this is open source". Paul> And that was just about Tkinter, for which good docs exist but Paul> just don't happen to be in the distro. How about something like Paul> SocketServer, for which no reasonable docs exist at all? I'm at a loss. Is there something about this quote taken directly from the section of the library reference manual entitled "Undocumented Modules" that is unclear? Here's a quick listing of modules that are currently undocumented, but that should be documented. Feel free to contribute documentation for them! (Send via email to docs at python.org.) The list there is itself incomplete. There is a reference manual section for SocketServer, btw: http://www.python.org/doc/current/lib/module-SocketServer.html If that needs examples or corrections or is incomplete, feel free to submit a patch to either SourceForge or by email to docs at python.org. Paul> I'm not trying to bash Python, which is excellent in many ways, or Paul> I wouldn't be using it. I just see various other free software Paul> projects as trying to live up to higher standards and I think Paul> Python should aspire to the same thing. I'm sorry, I don't know quite how to respond to that. Sure, I imagine there are other communities that do it better. I've seen PHP mentioned here recently, and have direct experience with CPAN (and actually like it pretty well). Look, I don't have much free time, and what free time I do have I mostly spend moonlighting on other software (much to my wife's chagrin). I imagine most of the other people who contribute to the Python distribution are similarly time-afflicted. Here are a couple ideas: 1. Do you have more money than time? Donate a few bucks to the PSF: http://www.python.org/psf/ Someone will probably do #2. 2. Do you have more time than money? Write a proposal to the PSF to implement/improve/polish off some aspect of the distribution: http://www.python.org/psf/ 3. Got some free time and don't care about a few extra bucks? Check out how to contribute to Python: http://www.python.org/dev/ >> As for stuff that exists in PEPs and release notes, they should >> already all have the necessary copyright (either they were placed in >> the public domain or they are already part of the Python >> distribution) to allow you do just check out a CVS tree, make the >> necessary edits and either check the files back in or submit a patch >> to SourceForge. Paul> And about that full featured Python web browser and native-code Paul> Python compiler, all you have to do is go write it. Come on. Where did I say to go write a browser or a native-code Python compiler? If that's your bag you can try resurrecting something Grail-like (browser) or contribute time top PyPy or Psyco. When I said "write", I literally meant write, as in English text. Paul> Having to piece together info from a dozen obscure and Paul> inconsistent PEP's and stuff in the CVS tree and source comments Paul> is not what most people think of as "documentation". Paul> Documentation means I can look in the manual and the info is right Paul> there, properly referenced in the table of contents and in the Paul> proper section for that type of language feature, unified with the Paul> rest of the docs. I was suggesting that maybe you might like to take the pieces and make them something coherent. If it was trivial it would have probably been done by now. >> In the documentation arena, I think more thought should probably be >> given to producing online docs that can be directly annotated, thus >> further reducing the barrier to more complete documentation (and more >> updates). Take a look at latex2html, propose or implement changes, >> or just rewrite the damn thing in Python. I think latex2html is >> probably a recurring nightmare for Fred Drake. Paul> I've personally been happy with Texinfo for other kinds of docs Paul> and would consider it easier to deal with than latex2html. It Paul> might even be feasible to edit it in a wiki, so anyone could Paul> improve it easily. Another idea is web-based doc comments like Paul> PHP and MySQL have, so the doc editors can incorporate the info Paul> from the comments in subsequent doc releases. I rather like reST (much of www.python.org is being reimplemented in reST), but that's just me. The key point I was trying to make is that an annotation capability would probably help. With such a feature you could add examples or links to the online Python Cookbook, whatever. Need some ideas? Look here: http://www.amk.ca/diary/archives/003336.html As Andrew indicated, it's a "half-hour hack", but it might give someone something to think about. Skip From ovazquez at gmail.SPAM.com Tue Jan 25 00:49:32 2005 From: ovazquez at gmail.SPAM.com (Orlando Vazquez) Date: Tue, 25 Jan 2005 05:49:32 GMT Subject: Another scripting language implemented into Python itself? In-Reply-To: <10vb8cve125v0b0@corp.supernews.com> References: <10vb8cve125v0b0@corp.supernews.com> Message-ID: Jeff Shannon wrote: snip > Because you cannot make Python secure against a malicious (or ignorant) > user -- there's too much flexibility to be able to guard against every > possible way in which user-code could harm the system. Parsing your own > (limited) scripting language allows much better control over what > user-code is capable of doing, and therefore allows (at least some > measure of) security against malicious code. I don't see how that would equate to something that the original programmer should be concerned about. You could include a bit in your licensing scheme that voids all support on code that has been modified in any way. You shouldn't be obligated and no one expects you to support something the end-user has mucked with. You could trivially enforce this by keeping checksums of all the system files. In any case, there's nothing you can really do to "secure" your code. This is true of any language, C, C++, and especially scripting languages like Python. Anyone who has the determination get at and modify the code probably will. The only time where I can see someone using another language in place of Python for a scripting language is just domain-specific factors, e.g. if you need the extension language to be easily used non-programmers. Just a thought. -- Orlando Vazquez From steven.bethard at gmail.com Wed Jan 26 15:23:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 13:23:17 -0700 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> Message-ID: Jack Diederich wrote: > On Wed, Jan 26, 2005 at 10:23:03AM -0700, Steven Bethard wrote: > >>Jack Diederich wrote: >> >>>Yes, this comes up every couple months and there is only one answer: >>>This is the job of the OS. >>>Java largely succeeds at doing sandboxy things because it was written that >>>way from the ground up (to behave both like a program interpreter and an >>>OS). >>>Python the language was not, and the CPython interpreter definitely was >>>not. >>> >>>Search groups.google.com for previous discussions of this on c.l.py >> >>Could you give some useful queries? Every time I do this search, I get >>a few results, but never anything that really goes into the security >>holes in any depth. (They're ususally something like -- "look, given >>object, I can get int" not "look, given object, I can get eval, >>__import__, etc.) > > > A search on "rexec bastion" will give you most of the threads, > search on "rexec bastion diederich" to see the other times I tried to > stop the threads by reccomending reading the older ones *wink*. > > Thread subjects: > Replacement for rexec/Bastion? > Creating a capabilities-based restricted execution system > Embedding Python in Python > killing thread ? Thanks for the keywords -- I hadn't tried anything like any of these. Unfortunately, they leave me with the same feeling as before... The closest example that I saw that actually showed a security hole made use of __builtins__. As you'll note from the beginning of this thread, I was considering the case where no builtins are provided and imports are disabled. I also read a number of messages that had the same problems I do -- too many threads just say "look at google groups", without saying what to search for. They also often spend most of their time talking about abstract problems, without showing code that illustrates how to break the "security". For example, I never found anything close to describing how to retrieve, say, 'eval' or '__import__' given only 'object'. What would be really nice is a wiki that had examples of how to derive "unsafe" functions from 'object'. I'd be glad to put one together, but so far, I can't find many examples... If you want to consider reading and writing of files as "unsafe", then I guess this might be one: file = object.__subclasses__()[16] If I could see how to go from 'object' (or 'int', 'str', 'file', etc.) to 'eval' or '__import__', that would help out a lot... Steve From nszabolcs at gmail.com Mon Jan 17 16:13:59 2005 From: nszabolcs at gmail.com (nszabolcs) Date: 17 Jan 2005 13:13:59 -0800 Subject: Py_Object* Py_BuildValue, Py_INCREF necessary? References: Message-ID: <1105996439.920021.284470@f14g2000cwb.googlegroups.com> no http://python.org/doc/2.4/api/refcountDetails.html nsz From brent.hughes at comcast.net Tue Jan 11 17:13:10 2005 From: brent.hughes at comcast.net (Brent W. Hughes) Date: Tue, 11 Jan 2005 15:13:10 -0700 Subject: Newbie: Pythonwin Message-ID: 1) I'm running a program within Pythonwin. It's taking too long and I want to stop/kill it. What do I do (other than ctrl-alt-del)? 2) I'm running a long program and I want to minimize it to let it continue to run in the background while I do something else in the foreground. I try clicking on Pythonwin's minimize box but it doesn't respond until the Python program finally quits Then it minimizes! Any way I can do what I want here? Brent From Noah.Richards at infineon.com Mon Jan 3 15:39:29 2005 From: Noah.Richards at infineon.com (Richards Noah (IFR LIT MET)) Date: Mon, 3 Jan 2005 15:39:29 -0500 Subject: Bad Interpreter References: <1104783849.754892.47560@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1104783849.754892.47560 at c13g2000cwb.googlegroups.com... > I have seen some previous messages about such a problem. I have this > problem but it is not clear what the solution really was. > > I am running FC2, python 2.3.3 > > the script i have sock.py runs if i say something like : > > python sock.py > > but ./sock.py results in a :bad interpreter error > how do i troubleshoot something like this? > > regards > What does the first line of your script look like? It needs to be pointing to the python interpreter binary, which you can locate with: which python (on the command line). Check and make sure it is. If it is and you are still getting this problem, post some code and the complete error. HTH. From reinhold-birkenfeld-nospam at wolke7.net Sun Jan 23 02:27:24 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 23 Jan 2005 08:27:24 +0100 Subject: default value in a list In-Reply-To: References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> <1gqs9gb.1mmtpcit05ruwN%aleaxit@yahoo.com> <35fordF4llio5U1@individual.net> Message-ID: <35h1uqF4kn2t2U1@individual.net> Nick Coghlan wrote: > Reinhold Birkenfeld wrote: >>>Why not put these together and put it in itertools, since the requirement seems >>>to crop up every other week? >>> >>> >>> line = "A:B:C".split(":") >>> ... >>> >>> def ipad(N,iterable, default = None): >>> ... return it.islice(it.chain(iterable, it.repeat(default)), N) >>> ... >>> >>> a,b,c,d = ipad(4,line) >>> >>> a,b,c,d >>>('A', 'B', 'C', None) >> >> >> Good idea! >> >> (+1 if this was posted on python-dev!) > > Please, please Google the python-dev archives before doing so ;) I have no intent of doing so, I would leave that to more experienced people... Reinhold ;) From jacek.generowicz at cern.ch Thu Jan 13 04:54:04 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 Jan 2005 10:54:04 +0100 Subject: from __future__ import decorators Message-ID: I have some code, which makes copious use of the @decorator syntax which was introduced in Python2.4. Now I find myself in a situation where I have to run the code under Python 2.3. However, I would like to keep developing the code with the new syntax. How could I best automate the process of making the syntax digestible by Python2.3 ? From ialbert at mailblocks.com Wed Jan 12 11:18:17 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 12 Jan 2005 11:18:17 -0500 Subject: java 5 could like python? In-Reply-To: References: Message-ID: <4MSdnSo5J_xU0HjcRVn-2g@giganews.com> vegetax wrote: > previus two python proyects where relatively big,and python didnt feel > well suited for the task. One typical problem that others might talk about in more detail is that you might be writing java code in python. That means using Java style class hierarchies, methods and overall organization. That does not work well in python. > -No naming convention. That is result of open source model that evolved over a long time. > getAttribute,GetAttribute,get_attribute, then i have to go and check the > doc, every time,which is a waste of time. Create a simple wrapper that does exactly what you want. For example it would take just a few minutes to create a URL class that you wanted. Then you have to figure it out only once. > -Is python library half object oriented? half functional oriented? Yes. As should most solutions be. Istvan. From br44114 at yahoo.com Tue Jan 18 10:40:12 2005 From: br44114 at yahoo.com (bogdan romocea) Date: Tue, 18 Jan 2005 07:40:12 -0800 (PST) Subject: script to automate GUI application (newbie) Message-ID: <20050118154012.91608.qmail@web50306.mail.yahoo.com> Dear Python experts, I have a GUI application (Windows; apparently written in Java) which I want to use through a script (without a mouse or keyboard). First, one of several buttons needs to be clicked (no keyboard shortcuts available, but I can measure the coordinates in pixels from the top left corner of the window to the center of the button to be clicked). Then, a window with a few drop-down lists pops up - I have to make some choices and click OK (it's possible to navigate from one drop-down to the next with Tab, and hit Enter for OK). I want to run the script above from code (if this then click "... and OK") and perhaps by means of several desktop shortcuts (one shortcut for each set of GUI inputs). Is such a script possible? If yes, how do I get there? I searched comp.lang.python but didn't find something directly applicable (or so it seemed to me - I'm a beginner). Directions (and sample code, if possible) will be warmly appreciated. Thank you, b. __________________________________ Do you Yahoo!? Yahoo! Mail - Easier than ever with enhanced search. Learn more. http://info.mail.yahoo.com/mail_250 From nelson at monkey.org Thu Jan 20 19:16:39 2005 From: nelson at monkey.org (Nelson Minar) Date: Fri, 21 Jan 2005 00:16:39 GMT Subject: Python and SOAP References: Message-ID: Peter Schaefer writes: > Is SOAPy still the way to go, or are there better methods? SOAPy hasn't been maintained in awhile. The two contemporary options are ZSI or SOAPpy, both at http://pywebsvcs.sourceforge.net/ ZSI seems to have more serious development now, but neither is perfect. You should consider doing a document/literal service instead of rpc/encoded, the old way. Unfortunately in my experience doc/lit doesn't work as well with Python, but it's a better way of doing things. The ZSI guys are working at it. From http Sun Jan 9 02:01:31 2005 From: http (Paul Rubin) Date: 08 Jan 2005 23:01:31 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> Message-ID: <7x7jmn84s4.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > x = (sqrt(a) where (a=2.0)) + (sqrt(b) where (a=3.0)) Hmm, I like that too. From merkosh at hadiko.de Fri Jan 21 19:54:17 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Sat, 22 Jan 2005 01:54:17 +0100 Subject: make install with python References: <35d4i9F4makucU1@individual.net> Message-ID: Friday 21 January 2005 20:47 pm Reinhold Birkenfeld wrote: [...] > The regular way is to use distutils and a setup.py file (google for > documentation). Ok, thanks. The document described just what I was looking for. Any suggestions how I handle uninstallation? This was provided by automake rather mechanically. I didn't find a section on that in the distutils documentation... :( Uwe From wittempj at hotmail.com Mon Jan 17 12:10:14 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 09:10:14 -0800 Subject: List problems in C code ported to Python In-Reply-To: <41ebed38$0$87063$a1866201@visi.com> References: <41ebed38$0$87063$a1866201@visi.com> Message-ID: <1105981814.317402.192940@f14g2000cwb.googlegroups.com> >>> l = [] >>> for i in range(2): for j in range(2): l[i][j] = 'x' Traceback (most recent call last): File "", line 3, in -toplevel- l[i][j] = 'x' IndexError: list index out of range So you still have to dimension the list before you can use it , eg like >l = [] >for i in range(2): > l.append([]) > for j in range(2): > l[i].append(j) then you do not get the indexerror, but I feel a class is what you need here to make life easier and the program more readable From dave at pythonapocrypha.com Mon Jan 24 14:43:50 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 24 Jan 2005 12:43:50 -0700 Subject: how to call python code from C# In-Reply-To: <8LGdneLOysys1WjcRVn-1Q@powergate.ca> References: <8LGdneLOysys1WjcRVn-1Q@powergate.ca> Message-ID: <41F54FF6.30209@pythonapocrypha.com> Peter Hansen wrote: > paritosh mahana wrote: > >> How can I call python code from my C# code. [snip] > You could use ctypes or the pywin32 package to provide your > Python code with an ActiveX interface. Then you could just > use it via COM, like any other COM object. Lots of references > available via Google if you want to learn more about this > approach... Lemme add my two cents and say that this approach works well. We have a component that uses ctypes and runs as a COM local server (its own .exe) and we currently use it both from Internet Explorer and from a C# application. COM can be hairy initially, but if you have any experience with COM then this approach is pretty straightforward. -Dave From jimbo at cordiner.com Sun Jan 23 14:24:07 2005 From: jimbo at cordiner.com (jimbo at cordiner.com) Date: Sun, 23 Jan 2005 14:24:07 -0500 Subject: bdb Message-ID: <59B7644A-6D74-11D9-AF9A-000A95AC3812@cordiner.com> Hi, I am trying to sort how to best programmatically run the debugger on a program, and another way that I am trying to explore is by using the bdb module. There isn't any documentation for this and I have tried reading through the source, which includes an example/test at the end of bdb.py on Python 2.3/OS X. What I can't figure out is how this might work if you wanted to have the function 'step' through each line. I see various functions that suggest that they might be for this but I can not get anything to work. Has anyone any suggestions or point me in the direction of any other docs? Thank you! jms. From the bdb.py: def test(): t = Tdb() t.run('import bdb; bdb.foo(10)') where Tbd subclasses Bdp and overrides the user_ methods (see around line 533 of bdb.py. But what about set_step()? Or am I way off here? From beable+unsenet at beable.com.invalid Tue Jan 11 23:53:49 2005 From: beable+unsenet at beable.com.invalid (Brian Eable) Date: 12 Jan 2005 14:53:49 +1000 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: humblythegreatest at usa.com writes: > python.org = 194.109.137.226 > > 194 + 109 + 137 + 226 = 666 BUT! perl -e '$a="194.109.137.226"; @a = reverse split /\./, $a; for $i (0..3) { $sum += $a[$i]*(256**$i) } print "sum = $sum\n"' 226 + 35072 + 7143424 + 3254779904 = 3261958626 http://3261958626/ Which is NOT 666. -- a house-blowing wolfen sneezer / might be a porcine tortfeasor. -- plorkwort http://beable.com From beliavsky at aol.com Sun Jan 30 10:51:58 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 30 Jan 2005 07:51:58 -0800 Subject: Coding style article with interesting section on white space References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> <1gr74p3.1p45u1v182vecgN%aleaxit@yahoo.com> Message-ID: <1107100318.251828.86360@c13g2000cwb.googlegroups.com> Alex Martelli wrote: > > For scientific computation, consider the case of Numeric > > and Numarray. I don't think Numeric binaries are available for Python > > 2.4, > > ? Just > googled and visited the first hit -- I don't currently use Windows so I > don't know if it's still there, works well, etc. I should have Googled. I will investigate that link. At SourceForge, http://sourceforge.net/project/showfiles.php?group_id=1369 I see a Numarray but not a Numeric Windows binary for Python 2.4. The latest Numeric Windows binary there is for Python 2.3. > > > The recent "Pystone Benchmark" message says that Python is only 75% as > > fast on Linux as on Windows. Fortran programs do not suffer this > > performance hit and are in this respect more portable. In theory, as > > You're saying that using a different and better compiler cannot speed > the execution of your Fortran program by 25% when you move it from one > platform to another...?! This seems totally absurd to me, and yet I see > no other way to interpret this assertion about "Fortran programs not > suffering" -- you're looking at it as a performance _hit_ but of course > it might just as well be construed as a performance _boost_ depending on > the direction you're moving your programs. I had in mind the Polyhedron Fortran 90 benchmarks for Windows and Linux on Intel x86 at http://www.polyhedron.co.uk/compare/linux/f90bench_p4.html and http://www.polyhedron.co.uk/compare/win32/f90bench_p4.html . The speed differences of Absoft, Intel, and Lahey between Linux and Windows for individual programs, not to mention the average differential across all programs, is much less than 25%. The differences on a single OS between compilers can be much larger, but that has less bearing on portability across OS's. Thanks for your earlier informative comments on languages. Sparring with Alex Martelli is like boxing Mike Tyson, except that one experiences brain enhancement rather than brain damage :). From aleaxit at yahoo.com Sat Jan 1 12:41:25 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 1 Jan 2005 18:41:25 +0100 Subject: what is lambda used for in real code? References: Message-ID: <1gpq3nl.8f2klu80m2z0N%aleaxit@yahoo.com> Steve Holden wrote: > Adam DePrince wrote: > [...] > > > > In sort, we must preserve the ability to create an anonymous function > > simply because we can do so for every other object type, and functions > > are not special enough to permit this special case. > > > And you'd create an anonymous type how, exactly? >>> type('',(),{}) maybe...? Alex From steve at holdenweb.com Wed Jan 19 11:38:55 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Jan 2005 11:38:55 -0500 Subject: Accessing MDB files on Windows In-Reply-To: <4262806.PViGKJWPeZ@strongwill.g2ctech> References: <1635068.ZTfiooUzB4@strongwill.g2ctech> <4262806.PViGKJWPeZ@strongwill.g2ctech> Message-ID: <57wHd.80954$Jk5.41342@lakeread01> Jorge Luiz Godoy Filho wrote: > Larry Bates, Quarta 19 Janeiro 2005 14:01, wrote: > > >>I'm assuming the application will be run on Windows. > > > You're right. It will be run on Windows. I discarded some other platform > due to the difficulty of supporting this file format. > > >>You can use ODBC or DAO. >> >>An DAO solution that I wrote (and use) can be found >>at: >> >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303349 > > > Thanks! I'm looking at it. > > >>For ODBC you would just use the standard library module. > > > Thanks. I'll be trying the DAO first. > Note that DAO is a very old library, and nowadays ADO would probably be the preferred method in the Windows environment (can DAO even *use* oledb providers?). ADO libraries are available - see http://www.markcarter.me.uk/computing/python/ado.html for example, or Google for "python ado". Bottom line, there are many ways to skin this particular cat. 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 donn at u.washington.edu Fri Jan 7 14:35:54 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 07 Jan 2005 11:35:54 -0800 Subject: Securing a future for anonymous functions in Python References: <10trlbqnb86tbb0@corp.supernews.com> <7xvfaaaxky.fsf@ruckus.brouhaha.com> <10trupr9cmrtqd0@corp.supernews.com> Message-ID: In article <10trupr9cmrtqd0 at corp.supernews.com>, Jeff Shannon wrote: ... > Hm, I should have been more clear that I'm inferring this from things > that others have said about lambdas in other languages; I'm sadly > rather language-deficient (especially as regards *worthwhile* > languages) myself. This particular impression was formed from a > recent-ish thread about lambdas.... > > http://groups-beta.google.com/group/comp.lang.python/messages/1719ff05118c4a71 > ,7323f2271e54e62f,a77677a3b8ff554d,844e49bea4c53c0e,c126222f109b4a2d,b1c962739 > 0ee2506,0b40192c36da8117,e3b7401c3cc07939,6eaa8c242ab01870,cfeff300631bd9f2?th > read_id=3afee62f7ed7094b&mode=thread > > (line-wrap's gonna mangle that, but it's all one line...) > > Looking back, I see that I've mis-stated what I'd originally > concluded, and that my original conclusion was a bit questionable to > begin with. In the referenced thread, it was the O.P.'s assertion > that lambdas made higher-order and dynamic functions possible. From > this, I inferred (possibly incorrectly) a different relationship > between functions and lambdas in other (static) languages than exists > in Python. One could easily be led astray by that post. He may be right in some literal sense about "the true beauty of lambda function", inasmuch as beauty is in the eye of the beholder, but in practical terms, functions are functions. I took this up on comp.lang.functional some time back. I rewrote a well known piece of Haskell (State monad), moving functions from lambda expressions to named function declarations in a "where" clause and I think undisputably making it easier to understand, and I asserted that this is representative of the general case - lambda is a non-essential feature in Haskell. I don't know if anyone was persuaded, but I didn't see any counter-arguments either. But of course even if I'm right about that, it doesn't mean the feature should be stripped from Haskell, that would be an atrocity. It may not be essential, but it's eminently useful and natural. Is it useful and natural in Python? Is it worth breaking code over? Why do we even bother to discuss this here? There aren't good answers to those questions. Donn Cave, donn at u.washington.edu From swaroopch at gmail.com Tue Jan 25 16:03:29 2005 From: swaroopch at gmail.com (Swaroop C H) Date: Wed, 26 Jan 2005 02:33:29 +0530 Subject: MySQLdb In-Reply-To: <41F6B23E.6010904@bowettsolutions.com> References: <41F6AF8A.3040102@bowettsolutions.com> <351e8871050125125434eb6d2@mail.gmail.com> <41F6B23E.6010904@bowettsolutions.com> Message-ID: <351e887105012513031ff3cc94@mail.gmail.com> > >I think a better option is to have the rows in a text file and then > >use `mysqlimport` or 'load data infile' SQL[1] > > > >[1]: http://dev.mysql.com/doc/mysql/en/load-data.html > > > I remember using that a while ago when I dabbled with mysql so I think > thats a potential solution. With my current solution I get full error > logging with each row i try to insert. Will mysqlimport fail completeley > if one row fails? I've not yet encountered an error using mysqlimport. But the docs at that link say that it might fail completely depending on the type of error. Excerpt: " If you specify IGNORE, input rows that duplicate an existing row on a unique key value are skipped. If you don't specify either option, the behavior depends on whether or not the LOCAL keyword is specified. Without LOCAL, an error occurs when a duplicate key value is found, and the rest of the text file is ignored. With LOCAL, the default behavior is the same as if IGNORE is specified; this is because the server has no way to stop transmission of the file in the middle of the operation. " P.S. Its best to take this discussion off the list since its not directly related to Python. -- Swaroop C H Blog: http://www.swaroopch.info Book: http://www.byteofpython.info From flupke at nonexistingdomain.com Thu Jan 6 10:13:42 2005 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 06 Jan 2005 15:13:42 GMT Subject: 2 versions of python on 1 machine Message-ID: I searched with Google and on this newsgroups and i didn't find any info regarding this. If there is more info, please redirect me to that info. I have version 2.3.4 and 2.4 installed on windows and i thought that by switching the PYTHONPATH parameter to the dir of the 2.4 version that that would make python 2.4 active. However when i envoke python from the commandline, it still runs 2.3.4 Is it possible to have 2 versions installed and switching versions when you need to? How can i do that? Thanks, Benedict From fredrik at pythonware.com Mon Jan 24 06:26:55 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 12:26:55 +0100 Subject: compile python to binary References: <1d6cdae3050123080242bf8994@mail.gmail.com> <1d6cdae30501230826a7b468@mail.gmail.com> Message-ID: Daniel Bickett wrote: >> oh, you mean that "python compiler" didn't mean "the python compiler". >> [snip] > > I simply inferred that he was using the wrong terminology, being that > he said "binary" twice ;-) yeah, but PYC files (which is what the standard compiler produces) are binary files too, in all the usual senses of that word -- and it's not that uncommon that people ship Python programs as a bunch of EXEs/DLLs (or equivalents), and PYC files. From a at b.c Sun Jan 23 02:38:32 2005 From: a at b.c (Doug Holton) Date: Sun, 23 Jan 2005 01:38:32 -0600 Subject: What YAML engine do you use? In-Reply-To: <_cSdnRo1keDOzm7cRVn-ug@comcast.com> References: <35a6tpF4gmat2U1@individual.net> <35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> <_cSdnRo1keDOzm7cRVn-ug@comcast.com> Message-ID: > You might like programming in XML then: http://www.meta-language.net/ Actually, the samples are hard to find, they are here: http://www.meta-language.net/sample.html Programming in XML makes Perl and PHP look like the cleanest languages ever invented. From tanghaibao at gmail.com Wed Jan 26 15:43:19 2005 From: tanghaibao at gmail.com (Haibao Tang) Date: 26 Jan 2005 12:43:19 -0800 Subject: [perl-python] 20050126 find replace strings in file In-Reply-To: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> Message-ID: <1106772199.500554.117700@z14g2000cwz.googlegroups.com> OK. But please don't die throwing that string, or this post will lose its educational purpose as it was meant to be. From rm at rm.net Sat Jan 22 16:43:24 2005 From: rm at rm.net (rm) Date: Sat, 22 Jan 2005 22:43:24 +0100 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> Message-ID: <35fvroF4kngkmU1@individual.net> Doug Holton wrote: > rm wrote: > >> this implementation of their idea. But I'd love to see a generic, >> pythonic data format. > > > That's a good idea. But really Python is already close to that. A lot > of times it is easier to just write out a python dictionary than using a > DB or XML or whatever. Python is already close to YAML in some ways. > Maybe even better than YAML, especially if Fredrik's claims of YAML's > inherent unreliability are to be believed. Of course he develops a > competing XML product, so who knows. true, it's easy enough to separate the data from the functionality in python by putting the data in a dictionary/list/tuple, but it stays source code. rm From peter at somewhere.com Mon Jan 10 02:48:01 2005 From: peter at somewhere.com (Peter Maas) Date: Mon, 10 Jan 2005 08:48:01 +0100 Subject: SuSE 9.1: updating to python-2.4 In-Reply-To: References: Message-ID: Torsten Mohr schrieb: > along with my distribution SuSE 9.1 came python 2.3.3. > > I'd like to update to 2.4 now, is this an easy thing to do > or will lots of installed modules refuse to work then? > > Is there an easy way to find out what i need to update? I uninstalled 2.3.3 and compiled/installed 2.4 from source. Now there is a problem: each time I change my system, SuSE tries to reinstall 2.3.3 because of dependencies. I tried to mark SuSE-Python as tabu (taboo?) but this it isn't stored. Not sure if it is my fault or SuSE's. I'm too lazy to track it down. Perhaps you can do a regular upgrade via FTP. I didn't try that. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From peter at engcorp.com Thu Jan 20 21:02:09 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Jan 2005 21:02:09 -0500 Subject: Print a string in binary format In-Reply-To: <1106270502.219126.322790@f14g2000cwb.googlegroups.com> References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> <1106270502.219126.322790@f14g2000cwb.googlegroups.com> Message-ID: <7OidnfGojPU8_23cRVn-gg@powergate.ca> neutrino wrote: > Mmm, the output format that I want is like: > 0001110011111111000000001111111100000000.... > > I tried your code on Cygwin under Windows 2000, and on Linux, but it > prints out ASCII characters. Generally speaking, trying to work with binary like that will drive you mad. Most people find themselves far more productive learning to work with hexadecimal, which is nice in this case since you'll automatically get the hex representation of any non-printable character if you just print the string with repr() around it. -Peter From cpghost at cordula.ws Thu Jan 13 20:58:31 2005 From: cpghost at cordula.ws (Cordula's Web) Date: 13 Jan 2005 17:58:31 -0800 Subject: Gecko bindings for Python? References: <1105456257.275667.6260@f14g2000cwb.googlegroups.com> Message-ID: <1105667911.010343.275380@c13g2000cwb.googlegroups.com> Yes, that's exactly what I needed! Thanks alot! -cpghost. -- Cordula's Web. http://www.cordula.ws/ From http Thu Jan 6 17:53:19 2005 From: http (Paul Rubin) Date: 06 Jan 2005 14:53:19 -0800 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <10trej2fl8dip65@corp.supernews.com> Message-ID: <7xhdluuq3k.fsf@ruckus.brouhaha.com> Jeff Shannon writes: > Note that the so-called 'viral' nature of GPL code only applies to > *modifications you make* to the GPL software. Well, only under an unusually broad notion of "modification". The GPL applies to any program incorporating GPL'd components, e.g. if I distribute a Python compiler that incorporates some component from GCC, then my entire Python compiler must be GPL'd even though the GCC component is isolated inside the Python compiler and I wrote the rest of the Python compiler myself. If I don't like this, I have an obvious recourse, which is don't use GCC components in my Python compiler. The notion here is that the GCC components are attractive enough that being able to use them provides an incentive to GPL my Python compiler, which I might not do otherwise. > (Problems may come if someone licenses a library under the GPL; that's > what the LGPL was invented for. But the issue here is not that the > GPL is bad, it's that the author used the wrong form of it.) The "problem" is not a problem except that in the case of some libraries, simply being able to use a library module is often not enough incentive to GPL a large application if the library module's functionality is available some other way (including by reimplemntation). If the library does something really unique and difficult, there's more reason to GPL it instead of LGPL'ing it. > The 'infective' nature of the GPL *only* comes when you make use of > the *extra* privelidges that open source grants. So yes, those extra > privelidges come with a price (which is that you share what you've > done); but if you don't want to pay that price, you have the choice of > not using those privelidges. This does not, in any way, prevent you > from using GPL'ed software as a user. Well put. From davorss at gmail.com Wed Jan 26 22:28:45 2005 From: davorss at gmail.com (Davor) Date: Wed, 26 Jan 2005 22:28:45 -0500 Subject: python without OO In-Reply-To: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: I'd like to thank everyone for their replies. The main important lesson I got is: Python does not have that many issues with misuse of OO as compared to Java/C++ because it's *dynamically* typed language and extremely powerful *dictionary* data structure. I browsed docs a bit today, and they also confirm what I have believed - that OO is totally secondary in Python. In fact, object/classes/metaclasses are nothing but *dictionaries with identity* in python. Love this approach. In fact, you can very easily implement your own *OO model* completely separate of Python's OO model... Now I actually strongly believe that Python's author has introduced the whole OO model just to attract and make happy OO population... In fact, *Python's dynamic type checking mechanisms + dictionary is way more powerful than Java/C++'s static type checking mechanisms + their OO mechanisms* and you can definitely be more productive using Python's structured programming than Java/C++ OO programming :-)... and Python is probably the best example why we should have skipped OO all together.. --- second, instead of playing with OO plagued design principles do as follows: 1. separate data, functionality, and structure from each other as much as you can (in Python only valid structural element I've seen so far is module - ignore objects & classes!) 2. do not assume any have identity (even if the underlying language model provides and uses one) - so don't pass them around and crazy stuff... so you get a nice program with separate data structures and functions that operate on these data structures, with modules as containers for both (again ideally separated). Very simple to do and maintain no matter what OO preachers tell you... Davor From steven.bethard at gmail.com Fri Jan 28 20:37:49 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 28 Jan 2005 18:37:49 -0700 Subject: limited python virtual machine In-Reply-To: <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Steven Bethard wrote: > ... > >>If I could see how to go from 'object' (or 'int', 'str', 'file', etc.) >>to 'eval' or '__import__', that would help out a lot... > > >>>>object.__subclasses__() > > [, , , , > , , , 'module'>, , , > , , , 'site._Printer'>, , , ] > > Traipse through these, find one class that has an unbound method, get > that unbound method's func_globals, bingo. Thanks for the help! I'd played around with object.__subclasses__ for a while, but I hadn't realized that func_globals was what I should be looking for. Here's one route to __builtins__: py> string_Template = object.__subclasses__()[17] py> builtins = string_Template.substitute.func_globals['__builtins__'] py> builtins['eval'] py> builtins['__import__'] Steve From python at hope.cz Fri Jan 14 15:37:10 2005 From: python at hope.cz (python at hope.cz) Date: 14 Jan 2005 12:37:10 -0800 Subject: Index server Message-ID: <1105735030.574794.74400@z14g2000cwz.googlegroups.com> Is there an Index server available in Python? For example: I have large intranet with several servers and I would like to index documents like search engines do. Users then can search for a domument in ALL intranet servers like I do on Google. Thanks for answers L.A. From steve at holdenweb.com Sat Jan 8 15:00:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 08 Jan 2005 15:00:05 -0500 Subject: windows mem leak In-Reply-To: References: Message-ID: <41XDd.70234$Jk5.40626@lakeread01> Bob Smith wrote: > Does the Win32 port of Python have a memory leak? I have some code that > runs flawlessly on Linux, but bombs after a few hours on Windows. It's > threaded and uses a lot of memory. > > Thanks! Yes, that's a well-known problem. Code that runs with a few errors will port without any trouble at all to Windows, but once it runs flawlessly on Linux it starts to leak memory on Windows. The PSU suspects a plot in Redmond, the basic details of which ar -- 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 Tue Jan 25 18:50:28 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 16:50:28 -0700 Subject: string.atoi and string.atol broken? In-Reply-To: References: Message-ID: Mike Moum wrote: >>>>> s.atoi('4',3) >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> s.atoi('4',3) >> File "/usr/lib/python2.3/string.py", line 220, in atoi >> return _int(s, base) >> ValueError: invalid literal for int(): 4 What did you expect the value of '4' in base 3 to be? There is no '4' in base 3... only '0', '1' and '2'. >>>>> s.atoi('8',4) >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> s.atoi('8',4) >> File "/usr/lib/python2.3/string.py", line 220, in atoi >> return _int(s, base) >> ValueError: invalid literal for int(): 8 And no '8' in base 3 either. > Is this a bug, or am I missing something obvious? Well, first of all, unless you're using a Python before 2.0, you're missing that string.atoi is deprecated. You should be using int(), which can take the same parameters. I think secondly, you're missing that int(string, base) converts the given string to an int assuming that the string is in the given base. If the numbers you provide are out of the range of the digits that are valid for that base, you will get an error. Steve From jhefferon at smcvt.edu Tue Jan 11 08:45:26 2005 From: jhefferon at smcvt.edu (Jim) Date: 11 Jan 2005 05:45:26 -0800 Subject: Upgraded to python2.3 but httpd taking old version In-Reply-To: References: Message-ID: <1105451126.934903.142100@f14g2000cwb.googlegroups.com> Gurpreet Sachdeva wrote: > I upgraded my python to 2.3 from 2.2 but > [Tue Jan 11 16:18:45 2005] [error] [client 127.0.0.1] import cgi > [Tue Jan 11 16:18:45 2005] [error] [client 127.0.0.1] File > "/usr/lib/python2.2/cgi.py", line 38, in ? Does the first line of your file say #!/usr/bin/python2.3 (or whatever is appropriate for your system)? Jim From luisXX_lupe2XX at netvisaoXX.pt Thu Jan 20 08:05:59 2005 From: luisXX_lupe2XX at netvisaoXX.pt (Luis P. Mendes) Date: Thu, 20 Jan 2005 13:05:59 +0000 Subject: xml parsing escape characters In-Reply-To: <41eeda3a$0$27828$9b622d9e@news.freenet.de> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> Message-ID: <359o5cF4il48kU1@individual.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 this is the xml document: <DataSet> ~ <Order> ~ <Customer>439</Customer> (... others ...) ~ </Order> </DataSet> When I do: print xmldoc.toxml() it prints: <DataSet> ~ <Order> ~ <Customer>439</Customer> ~ </Order> </DataSet> __________________________________________________________ with: stringNode = xmldoc.childNodes[0] print stringNode.toxml() I get: <DataSet> ~ <Order> ~ <Customer>439</Customer> ~ </Order> </DataSet> ______________________________________________________________________ with: DataSetNode = stringNode.childNodes[0] print DataSetNode.toxml() I get: <DataSet> ~ <Order> ~ <Customer>439</Customer> ~ </Order> </DataSet> _______________________________________________________________- so far so good, but when I issue the command: print DataSetNode.childNodes[0] I get: IndexError: tuple index out of range Why the error, and why does it return a tuple? Why doesn't it return: <Order> <Customer>439</Customer> </Order> ?? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFB76y3Hn4UHCY8rB8RAvQsAKCFD/hps8ybQli8HAs3iSCvRjwqjACfS/12 5gctpB91S5cy299e/TVLGQk= =XR2a -----END PGP SIGNATURE----- From crap1234 at hotmail.com Sun Jan 2 10:02:28 2005 From: crap1234 at hotmail.com (Stefan Axelsson) Date: Sun, 02 Jan 2005 16:02:28 +0100 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> Message-ID: <33qgo5F42kl0bU1@individual.net> Roy Smith wrote: > In perl, I always use "use strict", but in Python, I just don't feel the > need. Between the exception mechanism and unit tests, the odds of a > typo going unnoticed for very long are pretty slim. I'll admit I don't > use Pychecker, but if I was doing production code, I would probably use > it as part of my QA process. Well, I don't have any experience with Python in the industrial setting (all my Python has been solo so far). I do have quite a bit of experience with Erlang (http://www.erlang.org) though, and while I agree that it's not quite as bad in practice as the most vocal static typing people would have it, it's not all roses either. The problem with unit tests is that they can be skipped (and frequently are) and you also have to be certain you exercise all code paths, even to detect a simple typo. It's not that these survive for 'very long' or (God forbid) to the final product, but many of them survive for long enough that they cost more than they should/would have. So *if* (substantial 'if' I realise that) my Erlang experiences generalises to this case, I'd say the benefits would outweigh the cost. Then again I'm seriously considering going back to Haskell, so I guess I'm at least a little biased. :-) :-) Stefan, -- Stefan Axelsson (email at http://www.cs.chalmers.se/~sax) From mritty at gmail.com Tue Jan 25 13:36:52 2005 From: mritty at gmail.com (Paul Lalli) Date: Tue, 25 Jan 2005 18:36:52 GMT Subject: [perl-python] 20050125 standard modules References: <1106669614.666772.17750@z14g2000cwz.googlegroups.com> Message-ID: <8lwJd.10520$Dz2.6624@trndny09> "Xah Lee" wrote in message news:1106669614.666772.17750 at z14g2000cwz.googlegroups.com... -------------------------- > in perl, i don't think there is one way to > list available modules. > I'm torn between knowing that I shouldn't feed trolls, and my hatred of leaving faulty information about Perl unchecked, where some unsuspecting newbie might stumble across it. So to those newbies, you should know that just because this clown doesn't think there's a way, does not in any way imply that there actually isn't a way. For a list of standard modules included in your distribution of Perl, run the following command in your shell: perldoc perlmodlib To get a list of non-standard modules that have already been installed, read the documentation for the ExtUtils::Installed module: perldoc ExtUtils::Installed To see what other modules are available to be downloaded, visit http://www.cpan.org Paul Lalli From warren_brown at csgsystems.com Tue Jan 11 17:24:54 2005 From: warren_brown at csgsystems.com (Brown, Warren R) Date: Tue, 11 Jan 2005 17:24:54 -0500 Subject: Python script produces "sem_trywait: Permission denied" Message-ID: <67C0A7BD9AAF714C8A33B986DF5738C40BB019@cmaexch01.csg.csgsystems.com> I've seen these messages too on AIX 5.2. It seems to come from doing an "import" on piped/fork processes with a python parent. (In particular import errno) I don't know the "proper" solution but I got rid of the messages (similar messages came up when I ran my app) by hacking Python/thread_pthread.h. There's a CHECK_STATUS macro the does a perror if any of the sem_* functions don't return an acceptable status. I just commented out the perror (didn't seem to hurt the python tests or my app) but I hope that someone more knowledgeable about Python internals might tell me if a more serious problem is looming. --- warren. -------------- next part -------------- An HTML attachment was scrubbed... URL: From spam-trap-095 at at-andros.demon.co.uk Sun Jan 30 11:11:36 2005 From: spam-trap-095 at at-andros.demon.co.uk (Andrew McLean) Date: Sun, 30 Jan 2005 16:11:36 +0000 Subject: Coding style article with interesting section on white space References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> <1gr74p3.1p45u1v182vecgN%aleaxit@yahoo.com> Message-ID: In article <1gr74p3.1p45u1v182vecgN%aleaxit at yahoo.com>, Alex Martelli writes >You're saying that using a different and better compiler cannot speed >the execution of your Fortran program by 25% when you move it from one >platform to another...?! This seems totally absurd to me, and yet I see >no other way to interpret this assertion about "Fortran programs not >suffering" -- you're looking at it as a performance _hit_ but of course >it might just as well be construed as a performance _boost_ depending on >the direction you're moving your programs. > >I think that upon mature consideration you will want to retract this >assertion, and admit that it IS perfectly possible for the same Fortran >program on the same hardware to have performance that differs by 25% or >more depending on how good the optimizers of different compilers happen >to be for that particular code, and therefore that, whatever point you >thought you were making here, it's in fact totally worthless. Look at the Fortran compiler benchmarks here: http://www.polyhedron.co.uk/compare/win32/f77bench_p4.html for some concrete evidence to support Alex's point. You will see that the average performance across different benchmarks of different Fortran compilers on the same platform can be as much a factor of two. Variation of individual benchmarks as much as a factor of three. Some of you might be surprised at how many different Fortran compilers are available! -- Andrew McLean From tim.golden at viacom-outdoor.co.uk Tue Jan 18 10:58:13 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 18 Jan 2005 15:58:13 -0000 Subject: script to automate GUI application (newbie) Message-ID: <9A28C052FF32734DACB0A288A35339910359CA@vogbs009.gb.vo.local> [bogdan romocea] | I have a GUI application (Windows; apparently written in Java) which I | want to use through a script (without a mouse or keyboard). First, one | of several buttons needs to be clicked (no keyboard shortcuts | available, but I can measure the coordinates in pixels from the top | left corner of the window to the center of the button to be clicked). | Then, a window with a few drop-down lists pops up - I have to | make some | choices and click OK (it's possible to navigate from one drop-down to | the next with Tab, and hit Enter for OK). | | I want to run the script above from code (if this then click "... and | OK") and perhaps by means of several desktop shortcuts (one shortcut | for each set of GUI inputs). | | Is such a script possible? If yes, how do I get there? I searched | comp.lang.python but didn't find something directly applicable (or so | it seemed to me - I'm a beginner). Directions (and sample code, if | possible) will be warmly appreciated. Have a look at WATSUP. I think it's the kind of thing you're after. http://www.tizmoi.net/watsup/intro.html TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From michele.simionato at gmail.com Mon Jan 3 09:40:04 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 3 Jan 2005 06:40:04 -0800 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) In-Reply-To: References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <87u0py6elt.fsf@sme.intra.citec.fi> Message-ID: <1104763204.261322.59520@c13g2000cwb.googlegroups.com> Just wrote: > In article <87u0py6elt.fsf at sme.intra.citec.fi>, > Simo Melenius wrote: > > > I've sometimes replaced sys.stdout (and/or sys.stderr) to > > capture/redirect debugging information in existing code that has > > unwisely just "print"ed error and warning messages, instead of using > > sys.stderr or error logging modules. > > > > py> def with_output_to_string (func): > > ... try: > > ... sys.stdout = StringIO.StringIO () > > ... func () > > ... return sys.stdout.getvalue () > > ... finally: > > ... sys.stdout = sys.__stdout__ > > Aargh, I can't believe how widespread this idiom is :-(. See my other > reply in this thread: DON'T use sys.__stdout__. Ever. > > Just From tundra at tundraware.com Thu Jan 27 23:08:18 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 27 Jan 2005 23:08:18 EST Subject: tkinter: Can You Underline More Than 1 Char In A Menu Title In-Reply-To: References: Message-ID: Jeff Epler wrote: > On Thu, Jan 27, 2005 at 06:38:22AM -0500, Tim Daneliuk wrote: > >>Is it possible to underline more than a single character as I am doing >>with the 'underline=0' above. I tried 'underline=(0,2)' but that didn't >>work. > > > No. > > Jeff I love a clear answer ;) thanks... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From dbickett at gmail.com Tue Jan 25 23:13:35 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Tue, 25 Jan 2005 23:13:35 -0500 Subject: Help! Host is reluctant to install Python In-Reply-To: References: Message-ID: <1d6cdae30501252013212d71fe@mail.gmail.com> On phr at localhost.localdomain wrote: > Daniel Bickett writes: > > I've been trying to convince my host to install python/mod_python on > > his server for a while now, however there are a number of reasons he > > is reluctant to do so, which I will outline here: > > I'm surprised that you're getting such detailed answers from him. > Usually, low-cost web hosts want to offer a one-size-fits-all package > that requires minimal interaction with customers. If you're paying > $10 a month for hosting and a host admin has to spend 1 hour sending > you email, that probably wipes out at least 6 months of profits from > you as a customer. If you want custom service you usually have to pay > a lo tmore. I know him personally, which is part of my reluctance to ditch him entirely as most of you have suggested ;-) Suffice it to say I was able to gain access to a 2.2 installation that was already on the server, however for my intents and purposes I need a minimum of 2.3. Now I'm working on getting him to upgrade to 2.4 and install mod_python :) New quick question: As for the former, on the download page it states that the RPM distribution is sufficient for Fedora Core 3 *and similar*, and I'm curious to know if that applies to Red Had Enterprise as well. Thank you all for your answers and your time. P.S. As for your pricing question, I only pay $20 a year. His services are very affordable. You can see them all at the following link: http://www.snorland.com/webhosting/ -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From roy at panix.com Wed Jan 26 11:42:43 2005 From: roy at panix.com (Roy Smith) Date: 26 Jan 2005 11:42:43 -0500 Subject: Help With Python References: Message-ID: In article , Judi Keplar wrote: > >I am currently taking a course to learn Python and was looking for >some help. I need to write a Python statement to print a comma- >separated repetition of the word, "Spam", written 511 times ("Spam, >Spam, =85 Spam"). > >Can anybody help me get started? I am completely new to programming! Well, I'll point you in a couple of good directions. The first direction would be to approach this as a traditional procedural programming problem. You need some kind of loop that can exectute a print statement 511 times. In Python, that looks something like: for i in range(511): print "spam" Almost immediately, the question that comes to mind is where, exactly, does the loop start and stop? For example, you might expect that for i in range(5): print i would print the numbers 1 through 5, but it really prints 0 through 4. This kind of "off by one" thing is a very common common issue in writing loops in almost any programming language. It's a common enough issue that a whole class of bugs is named after it, known as "fencepost errors". So, left as an exercise for the reader (i.e. you), is to figure out if "for i in range(511)" really does the loop 511 times, or maybe 510 or 512? Next, you'll notice that the first loop I wrote prints one "spam" on each line. The way you described the problem, you want all the spams on one big long line, with commas between each one. The way you get Python to not advance to the next line is to end the print statement with a comma, like this: for i in range(511): print "spam", Notice that there's something tricky going on here; the comma doesn't get printed, it's just a way of telling the print statement, "don't go on to the next line". To really get it to print a comma, you need something like: for i in range(511): print "spam,", The first comma is inside the quoted string, so it gets printed. The second one is the one that says "don't go to the next line". You're still not quite done, but I've given you enough hints. Go play with that, see what you get, and see if you can figure out what problems you still need to fix. I said I'd point you in a couple of good directions, and the second one is to look up how the "join()" string method works. It's really cool, and solves your problem in a different way. But, first I think you should master the straight-forward way. Lastly, the really cool Pythonic way would be to get a bunch of Vikings into a restaurant and give them all breakfast menus. The only problem there is you'd have trouble handing all those Vikings in with your assignment. From kartic.krishnamurthy at gmail.com Fri Jan 21 12:27:56 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 21 Jan 2005 09:27:56 -0800 Subject: Tarfile module error In-Reply-To: References: Message-ID: <1106328476.921762.178630@c13g2000cwb.googlegroups.com> Your NewBackupFilename contains ":" which is not a valid character in a filename in Windows. You could do something like this: >>> NewBackupFilename = DirBackup + '\\' + '%s' % str(datetime.today()).replace(':', '-') + '.tar.bz2' >>> NewBackupFilename 'c:\\\\skpdc01\\\\Backups\\2005-01-21 12-26-21.373000.tar.bz2' >>> TarFileBackup = tarfile.open(NewBackupFilename, 'w:bz2') >>> # Works! I changed your DirBackup to 'C:\skpdc01\Backups' Thanks, --Kartic From wuwei23 at gmail.com Thu Jan 20 20:07:49 2005 From: wuwei23 at gmail.com (alex23) Date: 20 Jan 2005 17:07:49 -0800 Subject: iteritems() and enumerate() References: <1106206068.867004.195010@f14g2000cwb.googlegroups.com> <8bSdnaEf8cvk_XLcRVn-gg@speakeasy.net> Message-ID: <1106269669.338937.184220@c13g2000cwb.googlegroups.com> Erik Max Francis wrote: > You would be funnier if you weren't so incompetent. No, even if he was more competent, he'd still be a vicious, pointless asshole: "By the way, the pussy sex accuse us and hate us virile sex for undiscrimination and hunger for humping. But look at their ugliness, hogging with their arms and legs the moment a powerful dick or asshole walks by. If we males are assholes, they made us so. If male animals rape female animals, the females has a lot to do with it. Fuck them, and fuck them for their brainlessness." http://xahlee.org/Periodic_dosage_dir/t1/20040403_fem_fatale.html With an observational ability like that, who would *ever* listen to a word he'd say? From philippecmartin at sbcglobal.net Mon Jan 3 02:59:00 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 3 Jan 2005 08:59:00 +0100 Subject: Tkinter zoom box Message-ID: <200501030859.00110.philippecmartin@sbcglobal.net> Hi, I have the following convern: I have Tkinter applications that require a zoom box, and have had the following behavior without changing a line of code: 1) Mandrake 10.0/KDE 3.2/Python 2.3: no zoom box 2) Mandrake 10.0/KDE 3.2/Python 2.4: zoom box shows 3) Mandrake 10.1/KDE 3.3/Python 2.4: no zoom box 4) Mandrake 10.1/Gnome 2.6/Python 2.4: zoom box shows I know that sounds strange, but I am fairly certain this is what happened. Is there a way to _force_ that zoom box ? Regards, Philippe -- ********************* Philippe C. Martin SnakeCard LLC www.snakecard.com ********************* From benn at cenix-bioscience.com Thu Jan 13 07:45:29 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Thu, 13 Jan 2005 13:45:29 +0100 Subject: pyserial and com port interrupts In-Reply-To: References: Message-ID: <41E66D69.4050603@cenix-bioscience.com> engsol wrote: >Has anyone done a script that will rspond to the serial com port(s) >receive buffer interrupt, as opposed to polling and timeouts? >Win2000 is the main interest right now. >Thanks >Norm B > > Hello, I came across this problem as when I first used PySerial, I came from a java background which has the ability to register listeners to a serial comm instance and receive interrupts (although some implementations use polling behind the scenes anyway). I don't think that pyserial has this kind of thing so I used the following : def __checkSerial(self): self.__objLock.acquire() try: try: intNoChars = self.__objSerialPort.inWaiting() if (intNoChars > 0): strReceivedString = self.__objSerialPort.read(intNoChars) #or you could fire an event self.newMessage(strReceivedString) except: #put any clean up code in here. raise finally: self.__objLock.release() You can then wrap this in a thread which runs the method every x milliseconds (the code to ensure that I have all the information is elsewhere in a superclass which deals with this use case across communication implementations). However you will have to be aware that you will need to lock around groups of calls to ensure you are receiving the correct information (as above). Therefore, although threading in Python is 'easy' you would still have to think about this issue, it is unavoidable in communications I'm afraid. Even if you could receive interrupts then you will likely be receiving the interrupt on a different thread of execution than the main anyways so you'll still have threading problems and need to lock around calls. This is the problem which I usually express as '/RS232C is not really a standard, more of a rumour/'. Interestingly, if we take the 'python in threading is easy' discussion (partially due to the GIL), then for this use case we could also say that threading in VB6 is even easier than python - I'll leave you to guess why!!! Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 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 beliavsky at aol.com Sat Jan 1 19:02:05 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 1 Jan 2005 16:02:05 -0800 Subject: Approximating scattered data References: <41d72377$0$31717$a1866201@visi.com> Message-ID: <1104624125.552423.63000@z14g2000cwz.googlegroups.com> Grant Edwards wrote: >I've been looking for some way to approximate scattered 3D data >points in Python. The data doesn't seem to be amenable to >fitting functions like polymials, so I may have to use >something more like a spline surface. >However, I can't find anything usable from Python, and my >Fortram skills are pretty rusty. I tried SciPy, but it's spline >fitting module doesn't work at all for my data. I've found >mentions of a Python port NURBS toolbox, but all the links I >can find are broken. NURBS is available in Matlab and Scilab at http://www.aria.uklinux.net/nurbs.php3 , and translating to Python with Numeric/Numarray should not be too hard. If you are trying to fit z = f(x,y) without having a particular functional form in mind, you can apply a nonparametric regression technique. One of the easiest approaches to code is Nadaraya-Watson kernel regression -- see for example http://www.quantlet.com/mdstat/scripts/spm/html/spmhtmlnode24.html , equation 4.68, where a Gaussian kernel can be used for K. PyML at http://pyml.sourceforge.net/doc/tutorial/tutorial.html may implement this (I have not tried it). LIBSVM at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ has a Python interface for Support Vector Machines, a fairly popular and recent flexible regression method. From spam at nospam.org Fri Jan 28 21:09:36 2005 From: spam at nospam.org (Erik Johnson) Date: Fri, 28 Jan 2005 19:09:36 -0700 Subject: SUCCESS! References: <41f6c3f7$1@nntp.zianet.com> <41f85dd8@nntp.zianet.com> <41f97058$1@nntp.zianet.com> Message-ID: <41faee43$1@nntp.zianet.com> ----- Original Message ----- From: "Peter Otten" <__peter__ at web.de> > According to http://cnswww.cns.cwru.edu/php/chet/readline/CHANGES the > features you missed were introduced in readline 4.0 and 4.2, so version 4.3 > should be sufficient. So let me ask you again, you have both the readline > and the readline-devel package installed? If yes, and configure still > complains, it may be time to look for something entirely different... Sorry! Sorry! I made a mistake - I went and checked whether readline was installed and not readline-devel. I installed readline-devel. (Thank you for re-asking that question.) 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 And the readline module is still not configured by default: #readline readline.c -lreadline -ltermcap But... if I change the line (in Modules/Setup) above to: readline readline.c -lreadline I get a clean compile and my up-arrow is now fixed! Thank you so much for your help, Peter! :) I don't know how to look at what is in a .so file, and I'm not clear on whether /usr/lib/libreadline.a and the /usr/include/readline headers existed prior to installing readline-devel or not (I would guess not), but it would seem that version 4.3 definitely *should* be sufficient (as you pointed out). ej at sand:/usr/lib> ls *readline* libguilereadline-v-12.a libguilereadline-v-12.so.12 libreadline.so libguilereadline-v-12.la libguilereadline-v-12.so.12.3.0 libguilereadline-v-12.so libreadline.a ej at sand:/usr/lib> nm libreadline.a | grep letion_match 000008d0 t gen_completion_matches 00001c60 T rl_completion_matches 00000070 T completion_matches U rl_completion_matches ej at sand:/usr/lib> nm libreadline.a | grep input_hook 00000030 B rl_pre_input_hook ej at sand:/usr/lib> cd /usr/include/readline/ ej at sand:/usr/include/readline> ls chardefs.h keymaps.h rlconf.h rltypedefs.h history.h readline.h rlstdc.h tilde.h ej at sand:/usr/include/readline> grep input_hook * readline.h:extern rl_hook_func_t *rl_pre_input_hook; ej at sand:/usr/include/readline> grep rl_completion_matches * readline.h:extern char **rl_completion_matches PARAMS((const char *, rl_compentry_func_t *)); So, there still seems to be a misbehaviour in the configure script. I'm sure there must be other people on similar systems that would like to just type: ./configure make make install and be done with it, running v2.3.4 (or other?) with command line editing working! Looks like a bug worth reporting, yeah? Thanks again for your help! :) From ncoghlan at iinet.net.au Mon Jan 10 06:54:45 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 10 Jan 2005 21:54:45 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: References: <34cieoF489ejfU1@individual.net> Message-ID: <41E26D05.5060408@iinet.net.au> Duncan Booth wrote: > Nick Coghlan wrote: > > >>Grammar Change >>-------------- >>Current:: >> statement ::= stmt_list NEWLINE | compound_stmt >> >>New:: >> statement ::= (stmt_list NEWLINE | compound_stmt) [local_namespace] >> local_namespace ::= "with" ":" suite >> >> >>Semantics >>--------- >>The code:: >> >> with: >> >> >>translates to:: >> >>def unique_name(): >> >> >>unique_name() >> > > > Your proposed grammar change says that you need a newline after the > statement: True, and not really what I intended. However, it does highlight the fact that statement lists haven't been considered in the discussion so far. If statement lists are permitted, getting the right targets bound in the containing scope is going to be fun for things like this: a = b = 2; c = 3; print a + b with: pass (Probably not impossible though - e.g. it may be feasible to figure out all the bindings that have to happen and return an appropriate tuple from the inner scope for binding in the outer scope) It might also be somewhat confusing as to exactly which statements are covered by the local scoping. (All of them would be, but you could be forgiven for assuming it was just the last one) I think the following would work as a version of the grammar which permits local namespaces for statement lists: statement ::= (stmt_list (NEWLINE | local_namespace)) | (compound_stmt [local_namespace]) local_namespace ::= "with" ":" suite Disallowing local namespaces for statement lists would suggest something like this: statement ::= (simple_stmt (NEWLINE | ";" stmt_list NEWLINE | local_namespace) ) | (compound_stmt [local_namespace]) local_namespace ::= "with" ":" suite I'm pretty sure the permissive version is legal for the CPython parser, and I think the somewhat baroque structure I've used for the restrictive version makes it legal, too. Disallowing local namespaces for statement lists might be a good place to start, since it gives an easier target for a first implementation. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From peter at engcorp.com Thu Jan 13 20:16:04 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 20:16:04 -0500 Subject: porting C code In-Reply-To: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> References: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> Message-ID: <0NidnetRONZTgHrcRVn-oQ@powergate.ca> Lucas Raab wrote: > I have the > statement: "typedef unsigned long int word32" and later on: "word32 > b[3]" referencing the third bit of the integer. If that's really exactly what you have, then you actually have something defining an array of three unsigned long integers named "b". And even if you didn't have precisely "word32 b[3]", but merely a "b[3]" reference somewhere, it would be referencing the third element of an array called "b", which is possibly a byte, maybe a long, but definitely not a bit. Maybe showing it as code rather than inline in your text would avoid the possibility of confusion. -Peter From david at graydragon.net Thu Jan 6 16:22:26 2005 From: david at graydragon.net (David Brown) Date: Thu, 6 Jan 2005 15:22:26 -0600 Subject: Python Operating System??? Message-ID: <10trb0mgiflcj4f@corp.supernews.com> Hello. I recently came across a free operating system called Unununium (or something like that) and it was developed in Python and Assembly. Now, I have been looking for a way to make an operating system for a long long time and the only possibilities I could find were C++ and assembly. I don't mind assembly so much if I don't have to use it very often. But C++ is so complicated and errors are pretty much impossible to find in the code for me. So, I was wondering if it would be possible to find a bootloader that loads a python file at startup or something... Is there an example somewhere of a Python OS? Thanks! From jjl at pobox.com Mon Jan 3 13:32:59 2005 From: jjl at pobox.com (John J. Lee) Date: 03 Jan 2005 18:32:59 +0000 Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> <1gpqhbl.125l3evz09uefN%aleaxit@yahoo.com> Message-ID: <1xd2fjms.fsf@pobox.com> Lee Harr writes: [...] > I think it looks pretty good. The only problem I see is section 5 > where it says: > > 5. Did we miss your concern? > > Please add a comment to this page. > > > but the page is immutable. Hopefully one of the site maintainers will read this and demonstrate that it's actually readonly rather than immutable, then make it appendable ;-) John From a at a.invalid Thu Jan 6 05:08:13 2005 From: a at a.invalid (Timo Virkkala) Date: Thu, 06 Jan 2005 10:08:13 GMT Subject: Other notes In-Reply-To: <1104972047.050366.211670@f14g2000cwb.googlegroups.com> References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Andrew Dalke: >>(BTW, it needs to be 1 .. 12 not 1..12 because 1. will be interpreted >> as the floating point value "1.0".)< > Uhm, I have to fix my ignorance about parsers. > Cannot a second "." after the first tell that the first "." isn't in > the middle of a floating point number? Python uses an LL(1) parser. From Wikipedia: """ LL(1) grammars, although fairly restrictive, are very popular because the corresponding LL parsers only need to look at the next token to make their parsing decisions.""" >>>This may allow: assert 5 interval 9 == interval(5,9) >>Maybe you could give an example of when you need this in real life?< > Every time you have a function with 2 parameters, you can choose to use > it infix. But why would you want to? What advantage does this give over the standard syntax? Remember, in Python philosophy, there should be one obvious way to do it, and preferably only one. Adding a whole another way of calling functions complicates things without adding much advantage. Especially so because you suggest it is only used for binary, i.e. two-parameter functions. From hwlgw at hotmail.com Mon Jan 24 05:17:25 2005 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 24 Jan 2005 02:17:25 -0800 Subject: delay and force in Python References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Message-ID: <1106561845.160088.278420@f14g2000cwb.googlegroups.com> Just for the record, an implementation without using generators, somewhat like in Sect. 3.5 of the Wizard book, and without recursion limit problems. . . def stream_hd(s): # the head of the stream . return s[0] . . def stream_tl(s): # the tail of the stream . return s[1]() . . ## . # The low argument is required: the first element of the stream. . # You either use high= or stop_f= to define the end of the . # stream. Omit both for an infinite stream. stop_f is a function . # that takes low as argument and returns True or False. . # The next_f function takes one argument (an element of the stream, . # same type as the low argument has) . # The stop_f function takes one argument (same type as low) . # @param low object . # @param high object . # @param next_f function . # @param stop_f function . # @return list, a stream . def make_stream(low, high=None, next_f=None, stop_f=None): . if next_f is None: next_f = lambda x: x + 1 . if high is not None: # using high . if low > high: . return None . else: . return [low, lambda: make_stream( . next_f(low), high=high, next_f=next_f)] . elif stop_f is not None: # using stop_f . if low > stop_f(low): . return None . else: . return [low, lambda: make_stream( . next_f(low), next_f=next_f, stop_f=stop_f)] . else: # infinite stream . return [low, lambda: make_stream( . next_f(low), next_f=next_f)] . . ## . # iterative version of filter . # @param pred function, (stream-element) -> bool . # @param s list, a stream . # @return list, a stream . def stream_filter(pred, s): . if s is None: return [] . while True: . elem = stream_hd(s) . if pred(elem): . return [elem, lambda: stream_filter(pred, stream_tl(s))] . else: . s = stream_tl(s) . if s is None: return [] . . . if __name__ == '__main__': . . def is100some(x): return x % 100 == 0 . assert(stream_hd(stream_tl(stream_tl(stream_filter( . is100some, . make_stream(1, 11111111111111))))) == 300) . . def add_33(x): return x + 33 . assert(stream_hd(stream_tl(stream_filter( . is100some, . # stream 1,34,67,100,... . make_stream(1,999999999, next_f = add_33)))) == 3400) . . assert(stream_hd(stream_tl(stream_filter( . is100some, . # infinite stream 1,2,... . make_stream(1)))) == 200) . . def mod_20000(x): return x % 20000 == 0 . # this will need more evaluations than the recursion limit count . infinite_filter = stream_filter(mod_20000, make_stream(1)) . assert( stream_hd(stream_tl(infinite_filter)) == 40000 ) . From esj at harvee.org Tue Jan 18 17:33:26 2005 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 18 Jan 2005 17:33:26 -0500 Subject: simultaneous multiple requests to very simple database In-Reply-To: References: Message-ID: <41ED8EB6.503@harvee.org> Thomas Bartkus wrote: > "Eric S. Johansson" wrote in message > news:mailman.859.1106065617.22381.python-list at python.org... > > >>at this point, I know they will be some kind souls suggesting various >>SQL solutions. While I appreciate the idea, unfortunately I do not have >>time to puzzle out yet another component. Someday I will figure it out >>because I really liked what I see with SQL lite but unfortunately, today >>is not that day (unless they will give me their work, home and cell >>phone numbers so I can call when I am stuck. ;-) > > > > Forgive me if this reply sounds a bit glib. But I do mean it without malice. understood and taken in that spirit. > Do you seriously expect to write your own (database) solution and that this > will save you time and effort over learning an existing (SQL) solution? > > Because - > If you are seeking to "save time" on "puzzles", you are certainly going > about it the wrong way. one thing I learned a long time ago was to respect the nagging voice in the back of my head that says "there is something wrong". Right now with databases, that voice is not nagging but screaming. So I made my query to try and prove that intuition wrong. So far, that has not happened. When I look at databases, I see a bunch of very good solutions that are either overly complex or heavyweight on one hand and very nice and simple but unable to deal with concurrency on the other. two sets of point solutions that try to stretch themselves and the developers to fit other application contexts. 99.9 percent of what I do (and I suspect this could be true for others) could be satisfied by a slightly enhanced super dictionary with a record level locking. but, the database world does not fit this model. It has a great deal more complication then what is frequently necessary. If I ever find the time, I will try to build such a beast probably around Metakit. The only reason for reluctance is that I have spent too many hours tracking down concurrency problems at the OS level way to many years ago and so I do not create multithreaded applications lightly. so in conclusion, my only reason for querying was to see if I was missing a solution. So far, I have not found any work using because they add orders of magnitude more complexity than simple dbm with file locking. Obviously, the simple solution has horrible performance right now I need simplicity implementation. thanks for your commentary. ---eric From aleaxit at yahoo.com Sat Jan 22 07:00:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 13:00:36 +0100 Subject: circular iteration References: Message-ID: <1gqsjq8.11240q817nwks2N%aleaxit@yahoo.com> Simon Brunning wrote: ... > > is there a faster way to build a circular iterator in python that by doing this: > > > > c=['r','g','b','c','m','y','k'] > > > > for i in range(30): > > print c[i%len(c)] > > I don''t know if it's faster, but: > > >>> import itertools > >>> c=['r','g','b','c','m','y','k'] > >>> for i in itertools.islice(itertools.cycle(c), 30): > ... print i Whenever you're using itertools, the smart money's on "yes, it's faster";-). E.g., on a slow, old iBook...: kallisti:~ alex$ python -mtimeit -s'c="rgbcmyk"' 'for i in range(30): c[i%len(c)]' 10000 loops, best of 3: 47 usec per loop kallisti:~ alex$ python -mtimeit -s'c="rgbcmyk"; import itertools as it' 'for i in it.islice(it.cycle(c),30): i' 10000 loops, best of 3: 26.4 usec per loop Of course, if you do add back the print statements they'll take orders of magnitude more time than the cyclic access, so /F's point on premature optimization may well be appropriate. But, if you're doing something VERY speedy with each item you access, maybe roughly halving the overhead for the cyclic access itself MIGHT be measurable (maybe not; it IS but a few microseconds, after all). I like itertools' approach because it's higher-abstraction and more direct. Its blazing speed is just a trick to sell it to conservative curmudgeons who don't see abstraction as an intrinsic good -- some of those are swayed by microseconds;-) Alex From nav+posts at bandersnatch.org Thu Jan 6 10:16:05 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: Thu, 06 Jan 2005 10:16:05 -0500 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <87pt0iegga.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> eeykay at gmail.com writes: > Can somebody there to point me any good commercial applications > developed using python ? Python is used in several games, including Temple of Elemental Evil and the forthcoming Civilization 4. Humungous Games, which makes software for children, is also using Python. Sorry if games would give your boss the wrong impression... Most commercial software houses don't advertise details of their development platforms. 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 jzgoda at gazeta.usun.pl Thu Jan 6 15:54:19 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 06 Jan 2005 21:54:19 +0100 Subject: Python evolution: Unease In-Reply-To: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> Message-ID: Iwan van der Kleyn wrote: > But I see little to no efforts from the core python team to address my > needs as listed above. They seem mainly to focus on the core attributes > and syntax of the language. Very little or no efforts are taken to > improve the infrastructure around the language. > > And then I read the following sentence by Van Rossum: > > "In order to make type inferencing a little more useful, I'd like to > restrict certain forms of extreme dynamic behavior in Python" > > In the end, it's mindset which counts. And I think that mindset is going > to be determine the way foreward for Python: more features, increased > complexity, less dynamism. Lots of syntax crud, without addressing the > need to improve the infrastructure around the language. I saw this once somewhere: http://groups.google.com/groups?selm=cf38ph%242f8%241%40namru.matavnet.hu -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From jussij at zeusedit.com Sun Jan 9 01:51:45 2005 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Sun, 09 Jan 2005 17:51:45 +1100 Subject: Ranting about the state of Python IDEs for Windows References: <1105222350.906941.83130@c13g2000cwb.googlegroups.com> Message-ID: <41E0D481.1C0F@zeusedit.com> Carlos Ribeiro wrote: > Oh well. A mailing list is not the most appropriate place for > rants (a blog is better), but it's still better than keeping > it for myself. > > I'm frustrated. My search for a good IDE to support my activities Take a look at Zeus: http://www.zeusedit.com/lookmain.html > doing development for Python in the Windows environment Zeus only runs on Windows. > But it's all that I have -- a 500MHz PC with 64MB and Win98 SE. Zeus should run fine on this machine. If you added another stick of 64MB it would run better :) 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 aahz at pythoncraft.com Sat Jan 29 06:31:45 2005 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2005 06:31:45 -0500 Subject: limited python virtual machine References: <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> Message-ID: In article <1gr3mwj.1mhbjao122j7fxN%aleaxit at yahoo.com>, Alex Martelli wrote: >Steven Bethard wrote: >> >> If I could see how to go from 'object' (or 'int', 'str', 'file', etc.) >> to 'eval' or '__import__', that would help out a lot... > >>>> object.__subclasses__() >[, , , , >, , , 'module'>, , , >, , , 'site._Printer'>, , , ] > >Traipse through these, find one class that has an unbound method, get >that unbound method's func_globals, bingo. One thing my company has done is written a ``safe_eval()`` that uses a regex to disable double-underscore access. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From jjreavis at gmail.com Mon Jan 10 10:15:27 2005 From: jjreavis at gmail.com (Jeff Reavis) Date: 10 Jan 2005 07:15:27 -0800 Subject: Powerful CGI libraries for Python? In-Reply-To: References: Message-ID: <1105370127.829355.120290@c13g2000cwb.googlegroups.com> You may want to check out Spyce http://spyce.sourceforge.net/index.html It will work as cgi (or using fast cgi or mod python) and has templating, session support, active tags, etc. -jjr From danperl at rogers.com Fri Jan 28 08:22:57 2005 From: danperl at rogers.com (Dan Perl) Date: Fri, 28 Jan 2005 08:22:57 -0500 Subject: How to test that an exception is raised ? References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> Message-ID: "StepH" wrote in message news:41fa0da9$0$2018$6c56d894 at feed0.news.be.easynet.net... > But i've prob with the 1st test : test_badFile. > When I run the test, unittest say that no error is Raised. > But when I run the mps2xml module with a bad file as arg., the exception > is > well Raised. I assume you don't actually see the exception (you don't see the stack traceback printed as an output) but you just see your own message "FileError". That means that the exception was raised and caught by your try-except statement. > What i'm doing wrong ? > > It is because the exception in catched in the mps2xml module ? With the above mentioned assumption, that must be it. Once the exception is caught, it is caught and no other code invoking mps2xml.mps2xml (including the assertRaises in your test) will see the exception. Your mps2xml.mps2xml function should return a value indicating success or failure or should re-raise the exception. You need a mechanism to let invoking code know that it was successful or it failed. With a return code, you should test that and not the exception. The assert you use should work if you re-raise the exception. And BTW, it is a bad idea to use a generic "except" statement like you do. That catches ALL the exceptions and you will never know if a different exception than IOError was raised. You should catch only IOError specifically or any other exception that you may expect. You can add then an extra "except" statement catching all the other exceptions, but only if it is essential for your application to handle all exceptions gracefully instead of just exiting with a stack traceback. > Thanks for your helps. > > StepH. > > From aleaxit at yahoo.com Fri Jan 7 06:15:29 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 12:15:29 +0100 Subject: Tkinter Puzzler References: Message-ID: <1gq0pqa.1bvpnoehc2zs3N%aleaxit@yahoo.com> Tim Daneliuk wrote: > I am trying to initialize a menu in the following manner: > > for entry in [("Up", KeyUpDir), ("Back", KeyBackDir), ("Home", > KeyHomeDir), ("Startdir", KeyStartDir), ("Root", KeyRootDir)]: > > func = entry[1] > UI.ShortBtn.menu.add_command(label=entry[0], command=lambda: func(None)) > > However, at runtime, each of the menu options binds to the *last* function > named in the list (KeyStartDir). > > Explicitly loading each entry on its own line works fine: > > UI........command=lambda:KeyWHATEVERDir(None) > > Any ideas why the first form does not fly? One word: late binding. Well, two, pedantically speaking;-). The lambda you're passing as the value for 'command' is a closure: it knows it will have to look up name 'func' in the environment in which it's embedded -- but also that it's meant to do that lookup as late as possible, each time it's called. If you wanted to do the lookup just once, at the time lambda executes and created an anonymous function rather than each time said anonymous function is called, you could have expressed that...: command=lambda func=func: func(None) Here, func is a local variable (argument) of the anonymous function, and its "default value" is set ONCE, when the anon function is created. Back to your code, when your anon function is called, it looks up name 'func' in the surrounding environment... and there it finds it bound to whatever it was RE-bound to the LAST time... Point to remember: a closure looks up free-variable names in its surrounding environment *as late as possible*, i.e., when the function object is called; while default argument values are evaluated *at function creation time* (when lambda or def executes, not when the resulting function object gets called). Alex From john at grulic.org.ar Mon Jan 17 01:42:16 2005 From: john at grulic.org.ar (John Lenton) Date: Mon, 17 Jan 2005 03:42:16 -0300 Subject: fefinining % of c'm'y and k In-Reply-To: <1105941466.596034.166370@f14g2000cwb.googlegroups.com> References: <1105941466.596034.166370@f14g2000cwb.googlegroups.com> Message-ID: <20050117064216.GA28935@grulic.org.ar> On Sun, Jan 16, 2005 at 09:57:46PM -0800, moshebg at shamaut.co.il wrote: > hello > i need a program (and pleas shoe me the modol in the softwar) that : > if i have a scaned photo > i want to define out of each poligon color ,as it seems in the photo, > the cmyk > in % (percets) of the color/ > 4 exampl from poligon color orang defin the cmyk in % > like that: (example) > c: 30% > m:56% > y:78% > k: 10% > moshe > thanks if I understand you correctly, then what you want to do is to determine the amounts of each color an image has. I can think of two ways of doing this, both using PIL; one faster, img = Image.open('foo.png') dot = img.resize((1,1),1) avg = dot.getpixel((0,0)) for i in zip(dot.getbands(), avg): print "%s: %s" % i and the other, thorougher img = Image.open('foo.png') width, height = img.size numdots = width*height avg = [sum(i)/numdots for i in zip(*[img.getpixel((x,y)) for x in xrange(width) for y in xrange(height)])] for i in zip(dot.getbands(), avg): print "%s: %s" % i the first is usually pretty close to the second, but YMMV. Converting from these image-specific average values to CMYK is a non-trivial problem (impossible in the general casew); see for example http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2d0c54513c4970f7 where this issue was discussed. -- John Lenton (john at grulic.org.ar) -- Random fortune: Excellent day to have a rotten day. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From simon.brunning at gmail.com Wed Jan 26 09:48:16 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 26 Jan 2005 14:48:16 +0000 Subject: fast list lookup In-Reply-To: <3e96ebd7.0501260641.159e007f@posting.google.com> References: <3e96ebd7.0501260641.159e007f@posting.google.com> Message-ID: <8c7f10c60501260648c4a7c9a@mail.gmail.com> On Wed, 26 Jan 2005 06:45:29 -0800 (PST), Klaus Neuner wrote: > what is the fastest way to determine whether list l (with > len(l)>30000) contains a certain element? If the list isn't sorted, I doubt you'll do better than if an_element in my_list: # do whatever If the list is sorted, have a look at the bisect module. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From skip at pobox.com Sat Jan 29 08:23:54 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 29 Jan 2005 07:23:54 -0600 Subject: Who should security issues be reported to? In-Reply-To: <41FB080E.1070308@iinet.net.au> References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <41FB080E.1070308@iinet.net.au> Message-ID: <16891.36458.766674.340161@montanaro.dyndns.org> Nick> Upgrading your Python interpreter (even to a new maintenance Nick> branch release) in a production environment is usually a fairly Nick> involved exercise requiring a significant amount of testing, and Nick> the fact of the matter is, you're unlikely to do so unless there Nick> is some feature or bug-fix in a new version that you really Nick> need. (I'm still using Python 2.2.2 at work - it's entirely Nick> adequate for our needs, so there's no real pressure to upgrade on Nick> the current project. For a new project, I'd probably start with Nick> 2.4, planning to go to 2.4.1 in a couple of months time, but there Nick> aren't really any post-2.2 additions to Python that I can't handle Nick> living without). Still, if a security bug was serious enough, my guess is that someone would step up to supply patches (or Windows installers) for any of a number of versions that were affected by the bug, even 2.1 or 1.5.2. That someone might or might not be part of the core development team. That nothing like that has been done before doesn't preclude it being done in the future. Skip From steve at holdenweb.com Wed Jan 19 09:01:08 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Jan 2005 09:01:08 -0500 Subject: generator expressions: performance anomaly? In-Reply-To: References: <354esdF4fouh0U1@individual.net> Message-ID: <5PtHd.80946$Jk5.119@lakeread01> Antoon Pardon wrote: > Op 2005-01-18, Steve Holden schreef : [...] > > But you do have a point that I have a tendency to put salt on > any snail. I'll try to restrain myself a bit more in the future. > Finally! :-) I find I like you much better after this reflective response. Thanks for taking the time to read my snarking and respond to it. "A tendency to put salt on any snail" is a nice phrase I've never come across before. Is it specifically Belgian? 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 esj at harvee.org Thu Jan 13 22:23:49 2005 From: esj at harvee.org (Eric S. Johansson) Date: Thu, 13 Jan 2005 22:23:49 -0500 Subject: a ConfigParser wtf moment Message-ID: I'm not sure if this is a real problem or if I have been staring at code too long. given this code #!/usr/bin/python from ConfigParser import * configuration_file = "test.conf" substitution = {"xyzzy":"maze"} configuration = SafeConfigParser() configuration.readfp(file(configuration_file)) list = configuration.items("core") print list list = configuration.items("core",0, substitution) print list --------------- and this configuration file ----------- [core] xyzzy=little bird dwarf = greasy smoke %(xyzzy)s plugh ------------ why do I get the following results? ------------- trial backup # python test.py [('dwarf', 'greasy smoke little bird plugh'), ('xyzzy', 'little bird')] [('dwarf', 'greasy smoke maze plugh'), ('xyzzy', 'maze')] trial backup # ------------- if you're having a hard time seeing it, before the substitution, xyzzy is set to the value in the configuration file, afterwards, it is set to the value of the substitution in the code. It seems to me that substitutions should not affect any configuration file symbols of the same name. anyway to fix this problem without python diving? ---eric From ncoghlan at iinet.net.au Sun Jan 9 00:54:08 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 15:54:08 +1000 Subject: python3: 'where' keyword In-Reply-To: <7xhdlsw6ov.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <7xhdlsw6ov.fsf@ruckus.brouhaha.com> Message-ID: <41E0C700.8080604@iinet.net.au> Paul Rubin wrote: > AdSR writes: > >>>Killer app for this keyword: >>>class C(object): >>> x = property(get, set) where: >>> def get(self): >>> return "Silly property" >>> def set(self, val): >>> self.x = "Told you it was silly" >> >>Hey, this is super-elegant! > > > Heh, even further: > > z = C() where: > class C(object): > ... > > Lets you make anonymous classes and singleton objects. Here's another nice one if 'where' is added to compound statements as well: @dbc(pre, post) def foo(): pass where: def pre(): pass def post(): pass Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jimmy at retzlaff.com Tue Jan 25 03:32:16 2005 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Tue, 25 Jan 2005 00:32:16 -0800 Subject: Open Folder in Desktop Message-ID: Kamilche wrote: > Is there a command you can execute in Python that will open a window on > the desktop, such as 'My Documents'? Kind of like 'system', but for > folder names, not just programs. I'm running on Windows 2000. There are two issues here. The first is how to open a folder and the second is how to resolve "special" folders. Folders are "documents" typically associated with the explorer.exe application. To open a document with its default app (e.g., a folder), use os.startfile which is included in Python. For example: import os os.startfile(r'c:\windows') Folders like My Documents, My Pictures, etc. are special and you need to determine their actual path before you can open them. The pywin32 extensions (https://sourceforge.net/project/showfiles.php?group_id=78018) include a way to get at this: from win32com.shell import shellcon, shell path = shell.SHGetFolderPath(0, shellcon.CSIDL_MYPICTURES, 0, 0) os.startfile(path) Google for CSIDL to find the constants to use for other special folders. Jimmy From kartic.krishnamurthy at gmail.com Wed Jan 5 11:30:42 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 08:30:42 -0800 Subject: get the IP address of a host In-Reply-To: <1104941334.814311.198610@z14g2000cwz.googlegroups.com> References: <1104941334.814311.198610@z14g2000cwz.googlegroups.com> Message-ID: <1104942642.925891.43120@f14g2000cwb.googlegroups.com> or socket.gethostbyname(socket.gethostname()) From lbates at syscononline.com Fri Jan 28 09:49:49 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 28 Jan 2005 08:49:49 -0600 Subject: is extending an object considered acceptable usage? In-Reply-To: References: Message-ID: When I want to do what I think you are asking, I create an iterator in that returns a category item each time the .next method is called. That way you can write. ITEM=item() . . . for CATEGORY in ITEM: in my item class: class item: def __init__(self, ): self.CATEGORIES=[] self.next_index=0 # Index point for next method def __iter__(self): return self def next(self): # # Try to get the next route # try: CATEGORY=self.CATEGORIES[self.next_index] except: self.next_index=0 raise StopIteration # # Increment the index pointer for the next call # self.next_index+=1 return CATEGORY I had one project where these were nested 5-6 deep and the resultant code reads beautifully. Larry Bates mike wrote: > > i have an Item which belongs to a Category, so Item has: > > - item.categoryId, the database primary key of its Category > > - item.category, a reference to its Category. this null unless i need a > reference from item to its Category object, in which case i call > setCategory(category) > > sometimes i want a list of categories, and from each i want to be able > to access a list of its items. in this case is it considered acceptable > to just create a list of those items and assign it as a property of > their category? eg: > > category.items = listOfItems > > this packages everything up into a hierarchy and is more convenient to > use, especially in Cheetah templates, but requries modifying the > structure of the object, which bothers me (probably for some > subconscious java-related reason). > > the alternative might be to create a dictionary that keys the lists of > items on their category: > > items = {} > items[category.id] = listOfItems > > this feels less "controversial" to me, but requires extra objects and > house-keeping. > > > thanks - just curious if there were arguments one way or the other. From baoqiu at gmail.com Mon Jan 31 01:46:51 2005 From: baoqiu at gmail.com (Baoqiu Cui) Date: 30 Jan 2005 22:46:51 -0800 Subject: a Python bug in processing __del__ method ?? Message-ID: <1107154011.859866.23480@z14g2000cwz.googlegroups.com> Today I was playing with a small Python program using Python 2.4 on Cygwin (up-to-date version, on Windows XP), but ran into a strange error on the following small program (named bug.py): ------------------------------- #!/usr/bin/python class Person: population = 0 def __del__(self): Person.population -= 1 peter = Person() ------------------------------- The error returned is this: $ python bug.py Exception exceptions.AttributeError: "'NoneType' object has no attribute 'population'" in > ignored However, if I rename variable name 'peter' to something like 'peter1' or 'david', the error is gone. Looks to me the error only happens to variable name 'peter'. Does anyone know what is wrong? Is this a bug only on Cygwin? - Baoqiu From peter at engcorp.com Mon Jan 24 10:55:26 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jan 2005 10:55:26 -0500 Subject: Memory Usage In-Reply-To: References: Message-ID: <9-adnWKPTqfwh2jcRVn-uA@powergate.ca> rbt wrote: > Peter Hansen wrote: >> I would expect to see such behaviour, given how difficult it is >> to measure *actual* memory usage. How are you measuring it? >> Just by looking at the Mem Usage column in the Task Manager? > > That's right. I look at that column. Should I measue mem usage in some > other way? Probably, but for a start, have you noticed that even just switching to another window can drastically affect the memory apparently used by an application? For example, running the wxPython demo, clicking on a few controls and getting memory usage up to 27MB, then minimizing the window will drop it down aboiut 2MB. Restoring the window will bring the amount back to only about 4MB, at least until you click on stuff. Even then, it might climb to only about 14MB or so. This particular phenomenon might not be affecting your application, but it's an indication of how bad this measurement technique can be. Inside the Control Panel, you will find "Administrative Tools". In there is a "Performance" gadget. It's not trivial to use, and I can't give a tutorial here, but if you can manage to display the Working Set for the specific Process in which you are interested, that's probably a better way to view the information. (To be honest, I think it's actually this particular value which the "Mem Usage" field shows in the Task Manager, but at least this way you get a real-time graph and more precision, and a record of the usage.) There are also dozens of other parameters you can examine to help you track down the actual usage, or to help find out what is going if it turns out that you really are using such different amounts on the two machines. More important than any of this, however, might be making sure you have similar conditions on the two machines. Are you terminating as many other processes as you can? Making sure there is ample Physical Memory Available (see the Performance tab of Task Manager, for example)? If you have one of the machines running out of memory because of other applications running, it is quite possible that the OS will steal memory from the Python process to feed the other apps, and that can show up in the working set size. As I said, this stuff isn't exactly straightforward, so it's not necessarily surprising you are seeing this behaviour. There's probably a relatively simple explanation, however, but it might come only after a bit of exploration. -Peter From Mark.English at liffe.com Fri Jan 21 05:39:31 2005 From: Mark.English at liffe.com (Mark English) Date: Fri, 21 Jan 2005 10:39:31 -0000 Subject: Class introspection and dynamically determining function arguments Message-ID: <40E605146701DE428FAF21286A97D30917450F@wphexa02.corp.lh.int> > From: "Mark English" > > I'd like to write a Tkinter app which, given a class, pops up a > window(s) with fields for each "attribute" of that class. The > user could enter values for the attributes and on closing the > window would be returned an instance of the class. The actual > application I'm interested in writing would either have > simple type attributes (int, string, etc.), or attributes > using types already defined in a c-extension, although I'd > prefer not to restrict the functionality to these requirements. <------------------------> From: "Diez B. Roggisch" > whatfor is it planned? <------------------------> From: Nick Coghlan If this only has to work for classes created for the purpose > (rather than for an arbitrary class): <------------------------> Although I'm writing it for a specific need with a specific set of classes, I was asking here to find a more general, robust approach. So handling an arbitrary class would be preferable. > This is the only way to go, as python has no attribute declarations as static compiled languages have The classes I'm dealing with do have attributes since they're C-Extension types with attributes provided in the "tp_getset" slot. So this is one case where I can query the class for attributes without having to create an instance. Thanks for making me think of that, since looking in the class's __dict__ pretty much gives me what I want. I'm not sure that that's something I can rely on though which is exactly the sort of issue where I'd like to know if there's a right way (e.g. an existing module) to ask a class for its attributes, without poking around in __dict__ directly and doing some type checking. I guess in a way I'm asking for introspection with a greater degree of granularity than "dir". ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From jaco.smuts at clover.co.za Sat Jan 15 08:37:05 2005 From: jaco.smuts at clover.co.za (Jaco Smuts) Date: Sat, 15 Jan 2005 15:37:05 +0200 Subject: How can I get the names of the files in a directory? In-Reply-To: <20050115131023.36656.qmail@web50501.mail.yahoo.com> Message-ID: have a look at the glob module Sara Fwd Sent by: python-list-bounces+jsmuts=clover.co.za at python.org 01/15/2005 03:10 PM To python-list at python.org cc Subject How can I get the names of the files in a directory? Can you guys also help me find a module that looks in a directory and print out the names of the files in there? __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From kbk at shore.net Sat Jan 8 14:15:36 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Sat, 8 Jan 2005 14:15:36 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200501081915.j08JFaqo021328@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 267 open ( +6) / 2727 closed ( +9) / 2994 total (+15) Bugs : 798 open ( -3) / 4748 closed (+15) / 5546 total (+12) RFE : 165 open ( +0) / 140 closed ( +1) / 305 total ( +1) New / Reopened Patches ______________________ Remove witty comment in pydoc.py (2005-01-01) CLOSED http://python.org/sf/1094007 opened by Reinhold Birkenfeld Docs for file() vs open() (2005-01-01) CLOSED http://python.org/sf/1094011 opened by Reinhold Birkenfeld Improvements for shutil.copytree() (2005-01-01) CLOSED http://python.org/sf/1094015 opened by Reinhold Birkenfeld xml.dom.minidom.Node.replaceChild(obj, x, x) removes child x (2005-01-01) http://python.org/sf/1094164 opened by Felix Rabe os.py: base class _Environ on dict instead of UserDict (2005-01-02) http://python.org/sf/1094387 opened by Matthias Klose add Bunch type to collections module (2005-01-02) http://python.org/sf/1094542 opened by Steven Bethard self.button.pack() in tkinter.tex example (2005-01-03) http://python.org/sf/1094815 opened by [N/A] fixes urllib2 digest to allow arbitrary methods (2005-01-03) http://python.org/sf/1095362 opened by John Reese Argument passing from /usr/bin/idle2.3 to idle.py (2003-11-30) http://python.org/sf/851459 reopened by jafo fix for trivial flatten bug in astgen (2005-01-04) http://python.org/sf/1095541 opened by DSM exclude CVS conflict files in sdist command (2005-01-04) http://python.org/sf/1095784 opened by Wummel Fix for wm_iconbitmap to allow .ico files under Windows. (2005-01-05) http://python.org/sf/1096231 opened by John Fouhy Info Associated with Merge to AST (2005-01-07) http://python.org/sf/1097671 opened by Kurt B. Kaiser Direct framework linking for MACOSX_DEPLOYMENT_TARGET < 10.3 (2005-01-07) http://python.org/sf/1097739 opened by Bob Ippolito Encoding for Code Page 273 used by EBCDIC Germany Austria (2005-01-07) http://python.org/sf/1097797 opened by Michael Bierenfeld Patches Closed ______________ locale.getdefaultlocale does not return tuple in some OS (2004-10-21) http://python.org/sf/1051395 closed by rhettinger imghdr -- identify JPEGs in EXIF format (2003-06-08) http://python.org/sf/751031 closed by rhettinger Remove witty comment in pydoc.py (2005-01-01) http://python.org/sf/1094007 closed by rhettinger Docs for file() vs open() (2005-01-01) http://python.org/sf/1094011 closed by rhettinger Improvements for shutil.copytree() (2005-01-01) http://python.org/sf/1094015 closed by jlgijsbers a new subprocess.call which raises an error on non-zero rc (2004-11-23) http://python.org/sf/1071764 closed by astrand Argument passing from /usr/bin/idle2.3 to idle.py (2003-11-30) http://python.org/sf/851459 closed by jafo @decorators, including classes (2004-08-12) http://python.org/sf/1007991 closed by jackdied Convert glob.glob to generator-based DFS (2004-04-27) http://python.org/sf/943206 closed by jlgijsbers Make cgi.py use email instead of rfc822 or mimetools (2004-12-06) http://python.org/sf/1079734 closed by jlgijsbers New / Reopened Bugs ___________________ marshal.dumps('hello',0) "Access violation" (2005-01-03) CLOSED http://python.org/sf/1094960 opened by Mark Brophy General FAW - incorrect "most stable version" (2005-01-03) http://python.org/sf/1095328 opened by Tim Delaney Python FAQ: list.sort() out of date (2005-01-03) CLOSED http://python.org/sf/1095342 opened by Tim Delaney Bug In Python (2005-01-04) CLOSED http://python.org/sf/1095789 opened by JastheAce "Macintosh" references in the docs need to be checked. (2005-01-04) http://python.org/sf/1095802 opened by Jack Jansen The doc for DictProxy is missing (2005-01-04) http://python.org/sf/1095821 opened by Colin J. Williams Apple-installed Python fails to build extensions (2005-01-04) http://python.org/sf/1095822 opened by Jack Jansen time.tzset() not built on Solaris (2005-01-05) http://python.org/sf/1096244 opened by Gregory Bond sys.__stdout__ doco isn't discouraging enough (2005-01-05) http://python.org/sf/1096310 opened by Just van Rossum _DummyThread() objects not freed from threading._active map (2004-12-22) http://python.org/sf/1089632 reopened by saravanand Example needed in os.stat() (2005-01-06) CLOSED http://python.org/sf/1097229 opened by Facundo Batista SimpleHTTPServer sends wrong Content-Length header (2005-01-06) http://python.org/sf/1097597 opened by David Schachter urllib2 doesn't handle urls without a scheme (2005-01-07) http://python.org/sf/1097834 opened by Jack Jansen getsource and getsourcelines in the inspect module (2005-01-07) CLOSED http://python.org/sf/1098134 opened by Bj?rn Lindqvist mailbox should use email not rfc822 (2003-06-19) http://python.org/sf/756982 reopened by jlgijsbers typo in "Python Tutorial": 1. Whetting your appetite (2005-01-08) http://python.org/sf/1098497 opened by Ludootje Bugs Closed ___________ Don't define _SGAPI on IRIX (2003-04-27) http://python.org/sf/728330 closed by loewis python24.msi install error (2004-12-01) http://python.org/sf/1076500 closed by loewis garbage collector still documented as optional (2004-12-27) http://python.org/sf/1091740 closed by rhettinger marshal.dumps('hello',0) "Access violation" (2005-01-03) http://python.org/sf/1094960 closed by rhettinger General FAQ: list.sort() out of date (2005-01-04) http://python.org/sf/1095342 closed by jlgijsbers Bug In Python (2005-01-04) http://python.org/sf/1095789 closed by rhettinger test_macostools fails when running from source (2004-07-16) http://python.org/sf/992185 closed by jackjansen Sate/Save typo in Mac/scripts/BuildApplication.py (2004-12-01) http://python.org/sf/1076490 closed by jackjansen _DummyThread() objects not freed from threading._active map (2004-12-22) http://python.org/sf/1089632 closed by bcannon Example needed in os.stat() (2005-01-06) http://python.org/sf/1097229 closed by facundobatista gethostbyaddr on redhat for multiple hostnames (2004-12-14) http://python.org/sf/1085069 closed by loewis Unable to see Python binary (2004-12-10) http://python.org/sf/1082874 closed by loewis Change in signal function in the signal module (2004-12-10) http://python.org/sf/1083177 closed by akuchling test_descr fails on win2k (2004-07-12) http://python.org/sf/989337 closed by rhettinger test_imp failure (2004-07-15) http://python.org/sf/991708 closed by rhettinger getsource and getsourcelines in the inspect module (2005-01-07) http://python.org/sf/1098134 closed by jlgijsbers crash (SEGV) in Py_EndInterpreter() (2002-11-17) http://python.org/sf/639611 closed by jlgijsbers shutil.copytree copies stat of files, but not of dirs (2004-10-18) http://python.org/sf/1048878 closed by jlgijsbers shutil.copytree uses os.mkdir instead of os.mkdirs (2004-06-19) http://python.org/sf/975763 closed by jlgijsbers RFE Closed __________ optparse .error() should print options list (2004-12-22) http://python.org/sf/1089955 closed by gward From pushlinque at hotmail.com Thu Jan 13 09:43:11 2005 From: pushlinque at hotmail.com (Jane) Date: Thu, 13 Jan 2005 09:43:11 -0500 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: "Lucas Raab" wrote in message news:UsuFd.5434$KJ2.1253 at newsread3.news.atl.earthlink.net... > Jane wrote: > > wrote in message > > news:1105495569.479185.166340 at z14g2000cwz.googlegroups.com... > > > >>python.org = 194.109.137.226 > >> > >>194 + 109 + 137 + 226 = 666 > >> > >>What is this website with such a demonic name and IP address? What > >>evils are the programmers who use this language up to? > >> > > > > Some people have too much time on their hands... > > > > Jane > > > > > > Better get some ointment for that burn!! Huh??? Jane From erdewit at d-e-l-e-t-e.zonnet.nl Mon Jan 17 12:10:40 2005 From: erdewit at d-e-l-e-t-e.zonnet.nl (Ewald R. de Wit) Date: Mon, 17 Jan 2005 11:10:40 -0600 Subject: directory bug on linux; workaround? References: Message-ID: Russell E. Owen wrote: > It seems that the path was to a "fat" file partition and included a > directory name that was all uppercase. The directory was created, but > using lowercase. I'm not yet sure the version of python. > > The workaround for now is to not use fat file partitions. But I was > wondering if anyone had a better option? You can mount the FAT partition with the 'shortname' argument, i.e. put something like /dev/sda1 /usbkey auto umask=0,user,iocharset=iso8859-1,sync,kudzu,codepage=850,noauto,exec,users,shortname=winnt,check=s 0 0 in your /etc/fstab Btw, this is a general Linux problem and is not really related to Python (it also happens when working with shells or filemanagers). -- -- Ewald From lbates at syscononline.com Wed Jan 5 19:18:00 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 05 Jan 2005 18:18:00 -0600 Subject: PIL and ReportsLab error In-Reply-To: References: Message-ID: PIL doesn't support compressed TIF files. You must uncompress them prior to trying to place them. I use tiffcp utility via os.system call to uncompress TIF files, then place them into my .PDF file. Larry Bates Syscon, Inc. Jason Koch wrote: > Hello, > I am trying to produce pdf files from tiffs and I keep getting this > error. Does anyone > have any tips on this one. I am using the ReportLab package with the PIL. > > File "C:\Python23\Lib\site-packages\PIL\Image.py", line 309, in > _getdecoder > raise IOError("decoder %s not available" % decoder_name) > IOError: decoder group4 not available > > Thanks, > From remi at cherrypy.org Mon Jan 3 13:14:29 2005 From: remi at cherrypy.org (remi at cherrypy.org) Date: 3 Jan 2005 10:14:29 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <1104776069.637218.113610@f14g2000cwb.googlegroups.com> Have a look a the new CherryPy (http://www.cherrypy.org). It allows developers to build web applications in much the same way they would build any other object-oriented Python program. This might corespond to what you're looking for. Remi. From donn at drizzle.com Sun Jan 9 01:06:07 2005 From: donn at drizzle.com (Donn Cave) Date: 9 Jan 2005 00:06:07 -0600 Subject: python3: accessing the result of 'if' References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> <1105236383.521393.40680@c13g2000cwb.googlegroups.com> Message-ID: <41e0c9cf$1_2@127.0.0.1> Quoth "Carl Banks" : ... | As a compromise, howabout: | | . if m > 20 where m=something(): | . do_something_with(m) | | In this case, the m=something() is NOT an assignment statement, but | merely a syntax resembling it. The "where m=something()" is part of | the if-statement, not the if-expression. It causes m to be visisble in | the if-expression and the if-block. If m=something() binds the function return to a name "m" for use in other expressions, it sure IS an assignment. If it isn't an assignment statement, it's only inasmuch as assignment has become something other than a statement. Over whose dead body, I wonder. In case it's of any interest, here's how "where" looks with "if" in Haskell. It would take longer than you might imagine to explain what that "return" is doing there, but part of it is that every "if" must have an "else", and there is no such thing as "elif". Haskell's layout (indent) structure is more flexible than Python's, there are other ways this could look. if a > 10 then putStrLn (show a) else return () where a = 5 + 6 FYI, I suppose the closest it comes to anything like "assignment as an expression" is pattern matching - case (regexp_group "^([^:]*): (.*)" line) of Nothing -> f1 line Just [a, v] -> f2 a v -- This "unwraps" the return value of regexp_group, an imaginary -- function of type (String -> String -> Maybe [String]). The -- Maybe type has two values, Maybe a = Nothing | Just a. | It (or your suggestion) could work with a while-loop too. | | . while line where line=f.readline(): | . do_something_with(line) | | The main problem here (as some would see it) is that you can't do | something this: | | . if m > 20 where (def m(): a(); b()): The way it made sense to me, "where" introduces a block. The whole point is a private scope block. Actually kind of like the reverse of a function, where instead of binding names to input parameters, you in effect bind names to the scope for a sort of return-by-reference effect. But never mind, the point is that you get a private block, with one or more names exported to the surrounding scope in the left hand side of the where clause. What you're trying to do here seems to have almost nothing to do with that. If Python 3 is going to get assignment-as-expression, it will be because GvR accepts that as a reasonable idea. You won't bootleg it in by trying to hide it behind this "where" notion, and you're not doing "where" any good in trying to twist it this way either. Donn Cave, donn at drizzle.com From grahamd at dscpl.com.au Fri Jan 28 06:17:41 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 28 Jan 2005 03:17:41 -0800 Subject: Who should security issues be reported to? In-Reply-To: References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Message-ID: <1106911061.429966.303510@f14g2000cwb.googlegroups.com> Aahz wrote: > In article <1106863164.745581.11920 at f14g2000cwb.googlegroups.com>, > wrote: > > > >Who are the appropriate people to report security problems to in > >respect of a module included with the Python distribution? I don't > >feel it appropriate to be reporting it on general mailing lists. > > There is no generally appropriate non-public mechanism for reporting > security issues. If you really think this needs to be handled > privately, do some research to find out which core developer is most > likely to be familiar with it. Even before you do that, check > SourceForge to find out whether anyone else has reported it as a bug. I find this response a bit dissappointing frankly. Open Source people make such a big deal about having lots of people being able to look at source code and from that discover security problems, thus making it somehow making it better than proprietary source code. From what I can see, if an Open Source project is quite large with lots of people involved, it makes it very hard to try and identify who you should report something to when there is no clearly identifiable single point of contact for security related issues. Why should I have to go through hoops to try and track down who is appropriate to send it to? All you need is a single advertised email address for security issues which is forwarded onto a small group of developers who can then evaluate the issue and forward it on to the appropriate person. Such developers could probably do such evaluation in minutes, yet I have to spend a lot longer trying to research who to send it to and then potentially wait days for some obscure person mentioned in the source code who has not touched it in years to respond, if at all. Meanwhile you have a potentially severe security hole sitting there wating for someone to expliot, with the only saving grace being the low relative numbers of users who may be using it in the insecure manner and that it would be hard to identify the actual web sites which suffer the problem. I'm sorry, but this isn't really good enough. If Open Source wants to say that they are better than these proprietary companies, they need to deal with these sorts of things more professionally and establish decent channels of communications for dealing with it. And yes I have tried mailing the only people mentioned in the module in question and am still waiting for a response. From spam-trap-095 at at-andros.demon.co.uk Mon Jan 17 19:02:07 2005 From: spam-trap-095 at at-andros.demon.co.uk (Andrew McLean) Date: Tue, 18 Jan 2005 00:02:07 +0000 Subject: Fuzzy matching of postal addresses Message-ID: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> I have a problem that is suspect isn't unusual and I'm looking to see if there is any code available to help. I've Googled without success. Basically, I have two databases containing lists of postal addresses and need to look for matching addresses in the two databases. More precisely, for each address in database A I want to find a single matching address in database B. I'm 90% of the way there, in the sense that I have a simplistic approach that matches 90% of the addresses in database A. But the extra cases could be a pain to deal with! It's probably not relevant, but I'm using ZODB to store the databases. The current approach is to loop over addresses in database A. I then identify all addresses in database B that share the same postal code (typically less than 50). The database has a mapping that lets me do this efficiently. Then I look for 'good' matches. If there is exactly one I declare a success. This isn't as efficient as it could be, it's O(n^2) for each postcode, because I end up comparing all possible pairs. But it's fast enough for my application. The problem is looking for good matches. I currently normalise the addresses to ignore some irrelevant issues like case and punctuation, but there are other issues. Here are just some examples where the software didn't declare a match: 1 Brantwood, BEAMINSTER, DORSET, DT8 3SS THE BEECHES 1, BRANTWOOD, BEAMINSTER, DORSET DT8 3SS Flat 2, Bethany House, Broadwindsor Road, BEAMINSTER, DORSET, DT8 3PP 2, BETHANY HOUSE, BEAMINSTER, DORSET DT8 3PP Penthouse,Old Vicarage, 1 Clay Lane, BEAMINSTER, DORSET, DT8 3BU PENTHOUSE FLAT THE OLD VICARAGE 1, CLAY LANE, BEAMINSTER, DORSET DT8 3BU St John's Presbytery, Shortmoor, BEAMINSTER, DORSET, DT8 3EL THE PRESBYTERY, SHORTMOOR, BEAMINSTER, DORSET DT8 3EL The Pinnacles, White Sheet Hill, BEAMINSTER, DORSET, DT8 3SF PINNACLES, WHITESHEET HILL, BEAMINSTER, DORSET DT8 3SF The challenge is to fix some of the false negatives above without introducing false positives! Any pointers gratefully received. -- Andrew McLean From ptmcg at austin.rr._bogus_.com Wed Jan 12 11:04:28 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 12 Jan 2005 16:04:28 GMT Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> Message-ID: "Henrik Holm" wrote in message news:1gq9qs9.3snutr1s4mcn2N%news+0409 at henrikholm.com... > I am just starting to learn Python, mostly by going through the examples > in Dive Into Python and by playing around. > > Quite frequently, I find the need to iterate over two sequences at the > same time, and I have a bit of a hard time finding a way to do this in a > "pythonic" fashion. One example is a dot product. The straight-ahead > C-like way of doing it would be: > > def dotproduct(a, b): > psum = 0 > for i in range(len(a)): > psum += a[i]*b[i] > return psum > > However, the range(len(a)) term is awfully un-pythonic :) > The built-in function map() gives me a way of "transposing" the a list > and the b list, and now I can handle it with a list comprehension: > > def dotproduct(a, b): > return sum([x*y for x, y in map(None, a, b)]) > > My concern is one of efficiency: it seems to me that I have two loops > there: first one implied with map(...) and then the for loop -- which > seems like a waste since I feel I should be able to do the > multiplication via an argument to map. So far I have come up with an > alternative via defining a separate function: > > def dotproduct(a, b): > def prod(x,y): return x*y > return sum(map(prod, a, b)) > > I suppose I could also use a lambda here -- but is there a different, > efficient, and obvious solution that I'm overlooking? > > > Thanks, > Henrik > > -- > "On some great and glorious day the plain folks of the land will reach > in their heart's desire at last and the White House will be adorned by > a downright moron." > -H.L. Mencken (1880-1956) American Writer zip maybe? def dotproduct(a,b): return sum([x*y for x,y in zip(a,b)]) -- Paul From fredrik at pythonware.com Thu Jan 27 11:43:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 27 Jan 2005 17:43:15 +0100 Subject: On benchmarks, heaps, priority queues References: <1106835562.598569.211370@c13g2000cwb.googlegroups.com><1106842754.010427.74630@c13g2000cwb.googlegroups.com> <1106843673.755688.244160@f14g2000cwb.googlegroups.com> Message-ID: aaronwmail-usenet at yahoo.com wrote: > Hypothetical performance improvements are the root of all evil. > -- Bill Tutt (paraphrased) well, after this week, I'd say that Hypothetical performance limitations are the root of all evil. From howardrh at westerncom.net Wed Jan 19 18:58:37 2005 From: howardrh at westerncom.net (howardrh at westerncom.net) Date: 19 Jan 2005 15:58:37 -0800 Subject: Python and Excel References: Message-ID: <1106179117.094466.305960@f14g2000cwb.googlegroups.com> Please consider this reply as one vote for posting your python Excel interface/software on the Vaults of Pamassus Web Site. Located at http://www.vex.net/parnassus/ From grante at visi.com Sat Jan 1 15:26:13 2005 From: grante at visi.com (Grant Edwards) Date: 01 Jan 2005 20:26:13 GMT Subject: Python equivalent of script(1) References: <1104607982.132310.181560@c13g2000cwb.googlegroups.com> Message-ID: <41d70765$0$31695$a1866201@visi.com> On 2005-01-01, cepl at surfbest.net wrote: > Is there anything like script(1) for python interactive sessions. $ script transcript.txt Script started, file is transcript.txt $ python ... Not sure if there's a way to shut off readline... -- Grant Edwards grante Yow! But was he mature at enough last night at the visi.com lesbian masquerade? From jeremy+plusnews at jeremysanders.net Wed Jan 19 12:07:44 2005 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Wed, 19 Jan 2005 17:07:44 +0000 Subject: simultaneous multiple requests to very simple database References: Message-ID: On Tue, 18 Jan 2005 11:26:46 -0500, Eric S. Johansson wrote: > So the solutions that come to mind are some form of dictionary in shared > memory with locking semaphore scoreboard or a multithreaded process > containing a single database (Python native dictionary, metakit, gdbm??) > and have all of my processes speak to it using xmlrpc which leaves me > with the question of how to make a multithreaded server using stock > xmlrpc. Another solution might be to store the records as files in a directory, and use file locking to control access to the files (careful over NFS!). You might also consider berkeley db, which is a simple database to add to an application, (and which I believe supports locks), but I must admit I'm not a fan of the library. I assume that the bottleneck is processing the records, otherwise this all seems a bit academic. Jeremy From tbolands at yahoo.com Fri Jan 21 18:14:23 2005 From: tbolands at yahoo.com (TB) Date: 21 Jan 2005 15:14:23 -0800 Subject: default value in a list Message-ID: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Hi, Is there an elegant way to assign to a list from a list of unknown size? For example, how could you do something like: >>> a, b, c = (line.split(':')) if line could have less than three fields? Thanks, TB From godoy at ieee.org Sat Jan 15 11:32:28 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Sat, 15 Jan 2005 14:32:28 -0200 Subject: python mode indentation problem References: <1105802644.939051.229990@f14g2000cwb.googlegroups.com> Message-ID: <1489909.b1Lq4kxVjM@strongwill.g2ctech> Xah Lee, S?bado 15 Janeiro 2005 13:24, wrote: > does anyone know why the Python mode in emacs uses spaces for first > level indentation but one tab for second level? > > i'm using emacs 21.3.50.1. > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html It doesn't. It uses spaces for everything, unless told otherwise. -- Godoy. From http Sun Jan 9 23:23:02 2005 From: http (Paul Rubin) Date: 09 Jan 2005 20:23:02 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> Message-ID: <7xvfa53obd.fsf@ruckus.brouhaha.com> Arich Chanachai writes: > >Yes, compiled Lisp. There are Python compilers too.\ > > > ??? You mean like Pyrex or some such? I wouldn't exactly call these > "Python" compilers, as that kind of obscures some underlying > (critical) facts. Also psyco. And I think Pypy is currently set up to compile Python into Pyrex and then run the Pyrex results through GCC. From apardon at forel.vub.ac.be Tue Jan 18 07:42:39 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2005 12:42:39 GMT Subject: generator expressions: performance anomaly? References: <377Hd.77904$Jk5.30235@lakeread01> Message-ID: Op 2005-01-18, Steve Holden schreef : > Antoon Pardon wrote: > >> Op 2005-01-18, Nick Coghlan schreef : >> >>>Raymond Hettinger wrote: >>> >>>>[Delaney, Timothy C] >>>> >>>> >>>>>Nick's other suggestion - that genexps propagate __len__ - might >>>>>still be interesting. Of course, it would only be applicable for >>>>>unconditional genexps(i.e. no if clause). >>>> >>>>Length transparency for iterators is not as general as one would expect. I once >>>>spent a good deal of effort exploring where it made sense, and I was surprised >>>>to find that it only rarely works out. Length transparency is an unexpectedly >>>>thorny subject with many dead-ends which precludes a fully general solution such >>>>as that proposed by Nick. >>>> >>>>For a recap of my research, see the docstring for Lib/test/test_iterlen.py . >>> >>>"""The situation slightly more involved whenever an object allows length >>>mutation during iteration. """ >>> >>>Ouch. Nice understatement. >>> >>>It's rather unfortunate that we can't make use of the length information even >>>when the source *doesn't* mutate, though. I'll have to think some more to see if >>>I can come up with any concrete ideas for you to shoot down :) >> >> >> Something else I was thinking about. I think it would be nice if the >> python compilor could figure out whether a genexp in a list or tuple >> expression always generates the same list or tuple and then instead >> of generating code would generate the list or tuple in place. >> > Since it doesn't yet optimize 2+5 to a constant-folded 7 you should > realize that you are suggesting a large increase in the compiler's > analytical powers. Well I can dream, cant I? > I agree it would be nice under certain circumstances, but don't forget > that unlike list comprehensions (for which it would be even nicer) the > whole point of generator expressions is often to defer the generation of > the individual items until they are required and thereby relieve stress > on memory. > > As an edge case to demonstrate the point, what about a constant but > infinite sequence? Maybe I was not clear enough. I meant to limit it to cases such as lst = list(genexp) tpl = tuple(genexp) Since in such cases the object is build in memory any way, I don't think it would be a problem of having them prebuilt in memory, or am I missing something? -- Antoon Pardon From a at b.c Tue Jan 11 13:55:42 2005 From: a at b.c (Doug Holton) Date: Tue, 11 Jan 2005 12:55:42 -0600 Subject: Windows GUIs from Python In-Reply-To: References: Message-ID: Bob Swerdlow wrote: > Anyone have opinions about whether we will be better off using PythonNet or > wxPython for the GUI layer of our application on Windows? Our code is all > Python and is now running on Mac OS X with PyObjC and Cocoa, which works > very well. Our goal is not necessarily to move to a cross-platform > solution, but rather to create a solid Windows version that looks and feels > like a native application. All the code that interacts with the user is > factored out of our business logic, so it is a matter of find a good > view/controller library and writing a thin glue layer. And, of course, we > want to build it as efficiently and robustly as we can. I would also recommend wxPython. It runs on Macs, too, so you can at least see how it compares to your PyObjC interface and keep primarily developing on your Mac. You might also be interested in PyGUI although it doesn't have a native Windows implementation yet: http://nz.cosc.canterbury.ac.nz/~greg/python_gui/ From abpillai at gmail.com Thu Jan 6 05:21:56 2005 From: abpillai at gmail.com (Anand) Date: 6 Jan 2005 02:21:56 -0800 Subject: Contributor's List In-Reply-To: <1105006211.527899.318740@c13g2000cwb.googlegroups.com> References: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> <1105006211.527899.318740@c13g2000cwb.googlegroups.com> Message-ID: <1105006916.810877.38170@c13g2000cwb.googlegroups.com> Please direct all queries to the Cookbook editors...! Thanks -Anand From philippecmartin at sbcglobal.net Mon Jan 24 13:17:13 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 24 Jan 2005 12:17:13 -0600 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) Message-ID: <1106590633.15475.3.camel@localhost> I use "__"for private variables because I must have read on net it was the way to do so - yet this seems to have changed - thanks: http://www.network-theory.co.uk/docs/pytut/tut_77.html As far as the specific stderr reroute example - I just grabbed some of my code and forgot to get rid of that stuff Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From ola.natvig at infosense.no Mon Jan 31 10:16:19 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Mon, 31 Jan 2005 16:16:19 +0100 Subject: import directory error In-Reply-To: <41fe49b5$0$2168$8fcfb975@news.wanadoo.fr> References: <41fe49b5$0$2168$8fcfb975@news.wanadoo.fr> Message-ID: <4nu1d2-hjh.ln1@pluto.i.infosense.no> Olivier Noblanc ATOUSOFT wrote: > Hello, > > > When i want to import a .py fire from another subdirectory i make > > import inc/setupxml > > > but that make me an error message. > > A man tell me to put a dot but that doesn't work. > > Can you help me ? > > Thanks. > > > You should write import inc.setupxml this imports the module located at inc/setupxml.py It's said that it imports the setupxml *module* from the inc *package* All packages should include a __init__.py file. The import may not work unless. You will get the __init__.py file if you type import inc -- -------------------------------------- Ola Natvig infoSense AS / development From http Thu Jan 20 00:23:03 2005 From: http (Paul Rubin) Date: 19 Jan 2005 21:23:03 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> Message-ID: <7xekggbrns.fsf@ruckus.brouhaha.com> Tim Peters writes: > > Huh? [1,2,[3,4,5],[6,[[[[7]],8]]]] is a perfectly valid Python list. > > You're claiming not to know any relevant difference between Python > lists and Lisp lists? Heh. Python doesn't provide syntactic sugar for [1,[2,[3,[4,[]]]]] if that's what you mean. In Lisp you'd say (1 2 3 4). It's still a perfectly valid list in Python. Python by convention uses multi-element arrays instead of lists of conses. > > And you can break out of a containing loop from a nested loop > > with try/raise. > > Heh heh. Yes, you can. I've never seen a real Python program that > did, but there's nothing to stop you. I do that on a fairly routine basis. I won't say "often", but it's a standard technique that finds a use now and then. > What did you think the "direct" in "direct way" might have been > intended to mean? I guess you meant there's no syntax sugar for a multi-level break or a break with a label. It hasn't been that big a problem. C doesn't have it either. The need for it comes up infrequently enough that try/except is a satisfactory way to handle it. > > More troublesome is not being able to see a variable in a > > containing scope from a nested scope, unless the containing > > scope is the global one. Why bother debating lexical scope for > > years before deciding to add it, only to stop halfway? > > I'd call it 80% of the way, but suit yourself. The debates are all > easily found, if you really want to know. Well, I'd say whatever the percentage is, it started at near zero and has been slowly increasing and continues to increase. For example, [x*x for x in range(5)] doesn't create a temporary scope but (x*x for x in range(5)) does, and [x*x for x in range(5)] will apparently do so in a future version. There's a technique in numerical analysis called Richardson extrapolation, where you compute an integral by evaluating the function at n=k points, then at n=2k points, then at n=4k points, etc. and fit a curve through these approximations to estimate the limit at n=infinity. This turns out to be a good way to compute integrals. Basically by making a few better and better approximations at the answer, you can make a good estimate of the final result you'd get if you kept approximating forever. I see the same thing happening in Python. It's going through successively better approximations to get closer to a limit. Python has it harder than some other languages, because it tries to serve the needs of both throwaway scripts and large-scale development projects. The result is that feature after feature starts out with an implementation sufficient for small scripts, and then edges towards the needs of large-scale projects. But it's often predictable at the beginning what the final destination is going to be. So once we can see where it's going, why not proceed to the finish line immediately instead of bothering with the intermediate steps? From FBatista at uniFON.com.ar Thu Jan 6 10:32:45 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 6 Jan 2005 12:32:45 -0300 Subject: File Handling Problems Python I/O Message-ID: [Josh] #- able to do so without a problem, but here's the catch: The open #- statement is only working on certain files. I open a simple text file #- say file1.txt without any issues, but I change the open statement to #- another text file and it error's out stating the file #- doesn't exist. I #- know the code is correct because it worked for the other file. I have #- tried both binary and ascii modes to no avail. Any idea why this is #- happening? I am running Python 2.3.4 wxPython 2.5.3.1 and SPE as the #- IDE on Win2k. Thanks Could you please post the actual code? Also, post the result to the following: "os.listdir('.')". . 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 john at grulic.org.ar Mon Jan 17 10:15:56 2005 From: john at grulic.org.ar (John Lenton) Date: Mon, 17 Jan 2005 12:15:56 -0300 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: <20050117151556.GD3811@grulic.org.ar> On Mon, Jan 17, 2005 at 11:41:20AM +0000, Antoon Pardon wrote: > Op 2005-01-17, Steve Holden schreef : > > Antoon Pardon wrote: > > [...] > >>>"A foolish consistency is the hobgoblin of little minds". Rules are made > >>>to be broken. > >> > >> > >> Like only use immutables as dictionary keys. > >> > > Fair enough, but don;t go advising newbies to do this. > > How about something like this. > > Because of the extra precautions one has to take when > using mutables as hash keys, we advise newbies > to stick with immutable keys until they have gathered > enough knowledge and experience to adequatly weight > the pro and cons of a mutable key solution against > an immutable key solution. knowledgeable and experienced users know when to ignore the rules. -- John Lenton (john at grulic.org.ar) -- Random fortune: Una buena gran parte del arte del bien hablar consiste en saber mentir con gracia. -- Erasmo de Rotterdam. (1469-1536). -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From rootshell at gazeta.pl Thu Jan 13 08:03:44 2005 From: rootshell at gazeta.pl (rootshell at gazeta.pl) Date: Thu, 13 Jan 2005 14:03:44 +0100 Subject: Free python server. Message-ID: <001b01c4f970$5247d830$208e1d53@unqku4k1fl8nea7> Hi there. What I need is web sever, where I could put just one python script. Greetings. Rootshell. From tjreedy at udel.edu Thu Jan 6 20:09:08 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Jan 2005 20:09:08 -0500 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7x4qhw859p.fsf@ruckus.brouhaha.com><7xk6qrnbum.fsf@ruckus.brouhaha.com><41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7x652bnhx0.fsf at ruckus.brouhaha.com... > If I have a 400 gig hard drive, I don't see why I need 99.99% of it > empty instead of 99.0% after I do my OS install. Even though I currently only have 80 megs (about the minimum one can currently buy), I've about decided you are right. Having just installed a 3 CD game last night, I realize that my stinginess with disk space for more serious stuff is obsolete. (My first hard disk was 5 or 10 megs.) A gigabyte would cover Python + Wxpython + numarray + scipy + pygame + a lot of other stuff. Would it be possible, at least for Windows, to write a Python script implementing a 'virtual distribution'? IE, download Python, install it, download next package, install it, etc. -- prefereably table driven? Terry J. Reedy From peter at engcorp.com Thu Jan 20 16:10:26 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Jan 2005 16:10:26 -0500 Subject: Print to Windows default Printer In-Reply-To: References: Message-ID: <8cOdnW3_BMHfg23cRVn-3w@powergate.ca> Tim Golden wrote: > [Samantha] > | The printer is on LPT1, but I sure can't get the temp file to > | print for some > | reason. > | I am using Windows XP SP2. > | S > > i'm afraid I have to step out here (metaphorically speaking): > I'm using Win2K and have no access to XP boxes. The technique > works fine here; it may be that either they've removed the > functionality under XP, or that there's some security > context which is preventing you from accessing the port. > > Can anyone else try a "PRINT blah" or a "COPY blah LPT1:" > on XP SP2? Works fine here. That is, without having my printer on, I can see the job go into the printer control window as just another job. One does, of course, have to have the printer set up to *be* LPT1, however, and that doesn't happen by default unless you select something about "print from MSDOS programs" when you set it up, or you go into the Properties and make sure you configure it properly on the Ports tab... -Peter From ncoghlan at iinet.net.au Thu Jan 20 04:13:51 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 20 Jan 2005 19:13:51 +1000 Subject: Dictionary keys (again) (was Re: lambda) In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: <41EF764F.3000101@iinet.net.au> David Eppstein wrote: > Yes, and what should the following do? > > lst1 = [1] > lst2 = [2] > dct = {lst1: "1", lst2: "2"} > lst2[0]=1 > lst1[0]=2 > print dct[[1]] > print dct[[2]] > Provide yet another example for why mutable keys are almost guaranteed to result in suprising semantics :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From hikenboots at yahoo.com Sun Jan 2 11:36:16 2005 From: hikenboots at yahoo.com (John French) Date: Sun, 2 Jan 2005 10:36:16 -0600 Subject: Advice request for project Message-ID: I've been interested in Python for a while now but haven't had an opportunity to use / learn it. I'm tasked now with a project at work that might be my first opportunity. I have to write a ~75 concurrent user document storage app. that allows users to scan documents from locally attached scanners and save to a database for retrieval. I also need to be able to call MS Word with templates and allow the user to save the file to the database. I think I understand that I can interface MS COM for these, correct? My interest is in using FreeBSD/Postgresql/Python as a back end and a Python GUI app on the XP workstations. I'm going to end up adding some non-database functionality to the project in the future that precludes only using odbc to the database. I'll likely end up with some form of inter-user messaging being incorporated before it's over. Is it better to write one server side socket app to handle everything or start via odbc and necessary server side apps later? If anyone can tell me if this project seems appropriate to Python and offer suggestions as to an initial architecture, I'd appreciate it. I'm quite interested in the RAD aspect of the language but quite lost at the moment. (I did just sign up for the Tutor mailing list). Thanks in Advance From tjreedy at udel.edu Wed Jan 12 19:19:21 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Jan 2005 19:19:21 -0500 Subject: What strategy for random accession of records in massive FASTA file? References: Message-ID: RE: What strategy for random accession of records in massive FASTA file? "Batista, Facundo" wrote in message news:A128D751272CD411BC9200508BC2194D053C7E95 at escpl.tcp.com.ar... [If you want to keep the memory usage low, you can parse the file once and store in a list the byte position where the record starts and ends. Then access the list randomly and read each record with seek() and read(). ---------- Or if you want to access by sequence name rather than number, use a dict instead. tjr From jerf at jerf.org Mon Jan 31 22:09:37 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 31 Jan 2005 22:09:37 -0500 Subject: set, dict and other structures References: <1107214762.198058.55680@f14g2000cwb.googlegroups.com> Message-ID: On Tue, 01 Feb 2005 00:43:21 +0000, Raymond Hettinger wrote: > My guess is that there will be two issues. One is that no one > implementation of graphs seems to satisfy all users. The second is that > only a small fraction of Python users need for graph support (there is > probably a much greater demand for combinatorics, numeric/numarray, or > financial modules). If the appeal is not broad, it has little chance of > making it into the standard library. This reminded me of a group of people that were supposed to have started in on this: http://www.python.org/moin/PythonGraphApi It's too soon to call it dead, but I don't see a success pattern for it; I'd say they foundered on trying to shoot for the moon in advance, instead of starting to write code and incrementally improving it. (Hint, hint, if any of you are reading this.) Trying to create a graph library that meets any significant percentage of the needs of the people who would use it is quite non-trivial. It's not impossible, but it's a lot lot lot lot lot of work. I remember counting at least 48 distinct types of graphs when I enumerated my concerns to that project and I'm sure there are a few more dimensions that didn't make it into that list (the Wiki talks about "hierachial" graphs which adds another dimension I didn't count, for instance, and I'm sure there are more...). From xah at xahlee.org Sat Jan 22 06:57:40 2005 From: xah at xahlee.org (Xah Lee) Date: 22 Jan 2005 03:57:40 -0800 Subject: [perl-python] 20050121 file reading & writing Message-ID: <1106395060.211314.54530@f14g2000cwb.googlegroups.com> # -*- coding: utf-8 -*- # Python # to open a file and write to file # do f=open('xfile.txt','w') # this creates a file "object" and name it f. # the second argument of open can be # 'w' for write (overwrite exsiting file) # 'a' for append (ditto) # 'r' or read only # to actually print to file or read from # file, one uses methods of file # objects. e.g. # reading entire file # text = f.read() # reading the one line # line = f.realine() # reading entire file as a list, of lines # mylist = f.readlines() # to write to file, do f.write('yay, first line!\n') # when you are done, close the file f.close() # closing files saves memory and is # proper in large programs. # see # http://python.org/doc/2.3.4/tut/node9.html # or in Python terminal, # type help() then topic FILES # try to write a program that read in a # file and print it to a new file. ------------------------ # in perl, similar functionality exists. # their construct is quite varied. # example of reading in file # and print it out # (first, save this file as x.pl) open(f,") {print $line} close(f) or die "error: $!"; print "am printing myself\n"; # the above is a so called "idiom" # meaning that it is the way such is # done in a particular language, as in # English. # note, the f really should be F in Perl # by some references, but can also be # lower case f or even "f". All are not # uncommon. There is no clear reason for # why or what should be or what # is the difference. Usually it's # not worthwhile to question in # Perl. ">x.pl" would be for write to # file. The tells perl the file # object, and when Perl sees t=<> it # reads a line. (usually, but technically # depending on some predefined # variables...) The f they call "file handle". # ... see # perldoc -tf open # to begin understanding. ------------ Note: this post is from the Perl-Python a-day mailing list at http://groups.yahoo.com/group/perl-python/ to subscribe, send an email to perl-python-subscribe at yahoogroups.com if you are reading it on a web page, program examples may not run because html conversion often breaks the code. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From cybermanxu at hotmail.com Fri Jan 21 17:03:51 2005 From: cybermanxu at hotmail.com (Jinming Xu) Date: Fri, 21 Jan 2005 16:03:51 -0600 Subject: Tuple size and memory allocation for embedded Python Message-ID: Hi Folks, Python seems unstable, when allocating big memory. For example, the following C++ code creates a tuple of tuples: PyObject* arCoord = PyTuple_New(n); double d = 1.5; for(int i=0; i Message-ID: Nelson Minar writes: > Could someone help me get started using XPath or XQuery in Python? I figured this out. Thanks for the help, John! Examples below. I used this exercise as an opportunity to get something off my chest about XML and Python - it's kind of a mess! More here: http://www.nelson.monkey.org/~nelson/weblog/tech/python/xpath.html Here are my samples, in three libraries: # PyXML from xml.dom.ext.reader import Sax2 from xml import xpath doc = Sax2.FromXmlFile('foo.opml').documentElement for url in xpath.Evaluate('//@xmlUrl', doc): print url.value # libxml2 import libxml2 doc = libxml2.parseFile('foo.opml') for url in doc.xpathEval('//@xmlUrl'): print url.content # ElementTree from elementtree import ElementTree tree = ElementTree.parse("foo.opml") for outline in tree.findall("//outline"): print outline.get('xmlUrl') Please see my blog entry for more commentary http://www.nelson.monkey.org/~nelson/weblog/tech/python/xpath.html From reinhold-birkenfeld-nospam at wolke7.net Fri Jan 14 14:32:15 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 14 Jan 2005 20:32:15 +0100 Subject: Why would I get a TypeEror? In-Reply-To: References: Message-ID: <34ql1vF4dqd9pU1@individual.net> It's me wrote: > Sorry if my question was a little "lazy" and yes, I was asking about the > "lazy evaluation". :=) > > I am surprised about this (and this can be dangerous, I guess). > > If this is true, I would run into trouble real quick if I do a: > > (1/x,1.0e99)[x==0] > > and that's not good. > > Something to keep in mind. :-( Lazy evaluation: use the (x==0 and 1e99 or 1/x) form! Reinhold From kartic.krishnamurthy at gmail.com Mon Jan 24 12:19:05 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 24 Jan 2005 09:19:05 -0800 Subject: Import from database In-Reply-To: References: Message-ID: <1106587145.067483.14710@z14g2000cwz.googlegroups.com> Steve, I believe you have to put ntpath, macpath and posixpath in the module database for os.path to work. I tried it with zipimporter builtin and I got the same traceback till I added ntpath.py to my zip file. (Of course, I renamed the original ntpath to _ntpath so that the original did not get imported) Thanks, --Kartic From steven.bethard at gmail.com Sat Jan 29 18:31:06 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 29 Jan 2005 16:31:06 -0700 Subject: bound vs unbound functions In-Reply-To: <1107040729.535936.42230@c13g2000cwb.googlegroups.com> References: <1107040729.535936.42230@c13g2000cwb.googlegroups.com> Message-ID: Michael Tobis wrote: > Anyway, I'd like to dynamically add a method to an instance at > instantiation time. Something like Nearly identical question from yesterday and a series of answers: http://mail.python.org/pipermail/python-list/2005-January/263024.html Steve From cr999 at ir.hit.edu.cn Sat Jan 8 22:55:30 2005 From: cr999 at ir.hit.edu.cn (cr999) Date: Sun, 9 Jan 2005 11:55:30 +0800 Subject: Are there some resources about Python's VM and Python's implementation? Message-ID: <003701c4f5ff$283f5000$1d02a8c0@cr> I am very interested in Python's VM and also Python's implementation. I want to read the Phton's source code but i think it is very helpful if there are some resources and docuemnts about this topic. Anybody knows about this? Thanks :) Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From ncoghlan at iinet.net.au Thu Jan 27 05:15:22 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 27 Jan 2005 20:15:22 +1000 Subject: python without OO In-Reply-To: <1106798140.896125.187850@f14g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> <1106798140.896125.187850@f14g2000cwb.googlegroups.com> Message-ID: <41F8BF3A.8050402@iinet.net.au> beliavsky at aol.com wrote: > Furthermore, if in Python the algorithm for the reverse function > applies to many kinds of objects, it just needs to be coded once, > whereas a reverse method would have to provided for each class that > uses it (perhaps through inheritance). Indeed, this is why Python not only provides the list.reverse() method to reverse a list in place, but also provides the reversed() function to reverse any sequence: Py> lst = list("ABCDEFGHIJ") Py> lst.reverse() Py> print "".join(lst) JIHGFEDCBA Py> print "".join(reversed(lst)) ABCDEFGHIJ Ditto list.sort() and sorted(). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jfj at freemail.gr Thu Jan 27 21:01:29 2005 From: jfj at freemail.gr (jfj) Date: Thu, 27 Jan 2005 18:01:29 -0800 Subject: Tuple slices In-Reply-To: References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> <10vdj4s9ib19fe3@corp.supernews.com> <41F7F5CF.5040902@freemail.gr> Message-ID: <41F99CF9.2020201@freemail.gr> Nick Coghlan wrote: > > 1. Applies only if you are making large slices, or a lot of slices with > each containing at least 3 elements. > A view can also *cost* memory, when it looks at a small piece of a > large item. The view will keep the entire item alive, even though it > needs only a small piece. That is correct. > > 2. Hell no. The *elements* aren't copied, pointers to the elements are. > If you *don't* copy the pointers, then every item access through the > view involves an indirection as the index into the original sequence > gets calculated. If you have x=(1,2,...100001) y=x[:-1] then you copy 100000 pointers AND you INCREF them AND you DECREF them when y dies. The unfortunate case by (1) would be: x=(1,2,...100001) x=x[:1] > > So views *may* save memory in some applications, but are unlikely to > save time in any application (except any saving resulting from the > memory saving). > They do. If tp_dealloc of a tuple view doesn't decref the pointers. We should look for what is the most common case. Gerald -PS: the PEP for the removal ought to have a ":)" at the end. From python-url at phaseit.net Sun Jan 9 13:08:03 2005 From: python-url at phaseit.net (Josiah Carlson) Date: Sun, 09 Jan 2005 18:08:03 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 9) Message-ID: QOTW: Jim Fulton: "[What's] duck typing?" Andrew Koenig: "That's the Australian pronunciation of 'duct taping'." "I'm thinking that the I-Ching is a vast untapped resource for programming wisdom, plus it makes it funny." -- Mark Carter Nick Coghlan brings up the 'lambdas are going away in 3.0' topic, which has been discussed before: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/81e17b1d3ccba538 A user asks about a non-generator-based method for iteration using class __iter__ and next() methods: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/6336a00ad217888a Daniel Bickett asks about getting Twisted and wxPython working together, and receives both a threaded and non-threaded version: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/73f1e7758225afc3 A question about iterating over floats...be careful! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1278866159ac4429 A Boogieman asks whether Python is easily learned and what can be done with it. Quick answer: yes, and anything you are capable of doing: This Boogieman later asks about GUI toolkits: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e67b776df72eb336 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d502698b4adacd01 Erik Bethke writes Majong game after using Python for a month. Ahh, will the wonders of Python never cease? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/6d710e35007f0f32 Kamilche asks about getting warnings when not calling a function, and gets pointed to pychecker, something more of us should be using: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/dff810b7dacd247c Are people allowed to build commercial applications in Python? YES! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/aa953388db68b196 Questions about asyncore brings up a web server in asyncore from _Python Web Programming_, and a pointer to Twisted. Alternatively, one could look at the asynchat or smtpd modules in the standard library as sources of inspiration: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/81360ec06013e36d ======================================================================== 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 jepler at unpythonic.net Sun Jan 23 17:27:44 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 23 Jan 2005 16:27:44 -0600 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <200501232255.08496.francis.girard@free.fr> References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501221106.49241.francis.girard@free.fr> <200501232255.08496.francis.girard@free.fr> Message-ID: <20050123222743.GA32583@unpythonic.net> Your formulation in Python is recursive (hamming calls hamming()) and I think that's why your program gives up fairly early. Instead, use itertools.tee() [new in Python 2.4, or search the internet for an implementation that works in 2.3] to give a copy of the output sequence to each "multiply by N" function as well as one to be the return value. Here's my implementation, which matched your list early on but effortlessly reached larger values. One large value it printed was 6412351813189632 (a Python long) which indeed has only the distinct prime factors 2 and 3. (2**43 * 3**6) Jeff from itertools import tee import sys def imerge(xs, ys): x = xs.next() y = ys.next() while True: if x == y: yield x x = xs.next() y = ys.next() elif x < y: yield x x = xs.next() else: yield y y = ys.next() def hamming(): def _hamming(j, k): yield 1 hamming = generators[j] for i in hamming: yield i * k generators = [] generator = imerge(imerge(_hamming(0, 2), _hamming(1, 3)), _hamming(2, 5)) generators[:] = tee(generator, 4) return generators[3] for i in hamming(): print i, sys.stdout.flush() -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From bob.ducharme at gmail.com Wed Jan 26 17:06:24 2005 From: bob.ducharme at gmail.com (bobdc) Date: 26 Jan 2005 14:06:24 -0800 Subject: short programming projects for kids In-Reply-To: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> References: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> Message-ID: <1106777184.137556.17280@f14g2000cwb.googlegroups.com> Thanks Andr?, Adrian, Steve, Duncan, and zombiehunter for the excellent suggestions. Bob From daniel at bowettsolutions.com Wed Jan 5 14:48:52 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Wed, 05 Jan 2005 19:48:52 +0000 Subject: Python evolution: Unease In-Reply-To: References: Message-ID: <41DC44A4.8080406@bowettsolutions.com> Batista, Facundo wrote: > [John Roth] > > #- I would like to contribute some documentation to Python. > #- I've got the time, I write quite a bit, etc. I've got fairly > #- strong opinions about some things that need to be documented, > #- (such as all the new style class descriptor stuff from 2.2) > #- and I have relatively little difficulty matching the existing style. > #- > #- However, I don't > #- know TEX, Latex, CVS or Sourceforge. (The latter two are > #- on my "learn sometime soon so I can put PyFIT where it belongs" > #- list.) > > The easiest way to contribute with documentation is the following: > > 1. You found something badly documented. > 2. You write/correct the docs as you think they should be. > 3. Open a bug in SF and attach your text (just plain text if you don't > want to produce something more elaborate). > > Of course, for step 3 you need a SF account: that's only five minutes. > > . Facundo > > Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog > PyAr - Python Argentina: http://pyar.decode.com.ar/** > Contribute to where on Sourceforge??? Which domentation are we talking about in general? From martin at v.loewis.de Thu Jan 20 13:37:31 2005 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 20 Jan 2005 19:37:31 +0100 Subject: xml parsing escape characters In-Reply-To: <41eff4cf$0$6209$e4fe514c@news.xs4all.nl> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efb72d$1_2@newspeer2.tds.net> <41efe52f$0$6220$e4fe514c@news.xs4all.nl> <41efee5d$0$11622$9b622d9e@news.freenet.de> <41eff4cf$0$6209$e4fe514c@news.xs4all.nl> Message-ID: <41effa64$0$3366$9b622d9e@news.freenet.de> Irmen de Jong wrote: >> Usually, but not in this case. If you have a text that looks like >> XML, and you want to put it into an XML element, the XML file uses >> < and >. The XML parser unescapes that as < and >. However, it >> does not then consider the < and > as markup, and it shouldn't. > > > That's also what I said? You said it in response to >>> All the behaviour you are seeing is a consequence of this. You need >>> to unescape the contents of the tag to be able to treat it >>> as structured XML. In that context, I interpreted >> The unescaping is usually done for you by the xml parser that you >> use. as "The parser should have done what you want; if the parser didn't, that is is bug in the parser". > The OP probably wants to feed that to a new xml parser instance > to process it as markup. > Or perhaps the way the original XML document is constructed is > flawed. Either of these, indeed - probably the latter. Regards, Martin From mercuryprey at gmail.com Sun Jan 30 13:55:08 2005 From: mercuryprey at gmail.com (mercuryprey at gmail.com) Date: 30 Jan 2005 10:55:08 -0800 Subject: Disassembling strings and turning them into function parameters In-Reply-To: References: <1107107283.694377.286360@c13g2000cwb.googlegroups.com> Message-ID: <1107111308.052945.263600@c13g2000cwb.googlegroups.com> Hey, that's exactly what I need! Thanks for your help, the others too of course :) Didn't expect to get answers so quickly.. From rasdj at frontiernet.net Sun Jan 30 23:21:49 2005 From: rasdj at frontiernet.net (rasdj at frontiernet.net) Date: 30 Jan 2005 20:21:49 -0800 Subject: next line, new line In-Reply-To: References: <1107142942.626773.131980@c13g2000cwb.googlegroups.com> Message-ID: <1107145309.922093.295360@c13g2000cwb.googlegroups.com> Thanks Jeremy, something like this would work: try: lines = [ line.replace(",\n;", ")\n;") for line in input ] If I could figgure out how to: IF ':' in line READ next line in lines = [ line.replace(",\n;", ")\n;") for line in input ] output.write(str.join('', lines)) because there are lots of "comma newline" but the only ones I want are the ones that follow the semicolon. RasDJ From aleaxit at yahoo.com Thu Jan 27 13:29:57 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Jan 2005 19:29:57 +0100 Subject: String Fomat Conversion References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Message-ID: <1gr2aln.1a15eud1xil75nN%aleaxit@yahoo.com> Steven Bethard wrote: ... > Beware of mixing iterator methods and readline: _mixing_, yes. But -- starting the iteration after some other kind of reading (readline, or read(N), etc) -- is OK... > http://docs.python.org/lib/bltin-file-objects.html > > next( ) > ...In order to make a for loop the most efficient way of looping > over the lines of a file (a very common operation), the next() method > uses a hidden read-ahead buffer. As a consequence of using a read-ahead > buffer, combining next() with other file methods (like readline()) does > not work right. > > I haven't tested your code in particular, but this warning was enough to > make me generally avoid mixing iter methods and other methods. Yeah, I know... it's hard to explain exactly what IS a problem and what isn't -- not to mention that this IS to some extent a matter of the file object's implementation and the docs can't/don't want to constrain the implementer's future freedom, should it turn out to matter. Sigh. In the Nutshell (2nd ed), which is not normative and thus gives me a tad more freedom, I have tried to be a tiny bit more specific, taking advantage, also, of the fact that I'm now addressing the 2.3 and 2.4 implementations, only. Quoting from my current draft (pardon the XML markup...): """ interrupting such a loop prematurely (e.g., with break), or calling f.next() instead of f.readline(), leaves the file's current position at an arbitrary value. If you want to switch from using f as an iterator to calling other reading methods on f, be sure to set the file's current position to a known value by appropriately calling f.seek. """ I hope this concisely indicates that the problem (in today's current implementations) is only with switching FROM iteration TO other approaches to reading, and (if the file is seekable) there's nothing so problematic here that a good old 'seek' won't cure... Alex From tim.peters at gmail.com Fri Jan 14 19:13:13 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 14 Jan 2005 19:13:13 -0500 Subject: Why 'r' mode anyway? In-Reply-To: <41e827df$0$6219$e4fe514c@news.xs4all.nl> References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> <41e80785$0$6203$e4fe514c@news.xs4all.nl> <41e827df$0$6219$e4fe514c@news.xs4all.nl> Message-ID: <1f7befae0501141613545a30cd@mail.gmail.com> [Tim Peters] >> That differences may exist is reflected in the C >> standard, and the rules for text-mode files are more restrictive >> than most people would believe. [Irmen de Jong] > Apparently. Because I know only about the Unix <-> Windows > difference (windows converts \r\n <--> \n when using 'r' mode, > right). So it's in the line endings. That's one difference. The worse difference is that, in text mode on Windows, the first instance of chr(26) in a file is taken as meaning "that's the end of the file", no matter how many bytes may follow it. That's fine by the C standard, because everything about a text-mode file containing a chr(26) character is undefined. > Is there more obscure stuff going on on the other systems you > mentioned (Mac OS, VAX) ? I think on Mac Classic it was *just* line end differences. Native VAX has many file formats. "Record-based" file formats used to be very popular. There the OS saves meta-information in the file, such as each record contains an offset to the start of the next record, and may even contain an index structure to support random access to records quickly (for example, "a line" may be a record, and "read the last line" may go quickly). Read that in binary mode, and you'll be reading up the bits in the index and offsets too, etc. IIRC, Unix was actually quite novel at the time in insisting that all files were just raw byte streams to the OS. > (That means that the bug in Simplehttpserver that my patch > 839496 addressed, also occured on those systems? Or that > the patch may be incorrect after all??) Don't know, and (sorry) no time to dig. > While your argument about why Python doesn't use its own > platform- independent file format is sound of course, I find it often > a nuisance that platform specific things tricle trough into Python > itself and ultimately in the programs you write. I sometimes feel > that some parts of Python expose the underlying C/os > implementation a bit too much. Python never claimed write once > run anywhere (as that other language does) but it would have > been nice nevertheless ;-) > In practice it's just not possible I guess. It would be difficult at best. Python hides a lot of platform crap, but generally where it's reasonably easy to hide. It's not easy to hide native file conventions, partly because Python wouldn't play well with *other* platform software if it did. Remember that Guido worked on ABC before Python, and Python is in (small) part a reaction against the extremes of ABC. ABC was 100% platform-independent. You could read and write files from ABC. However, the only files you could read from ABC were files that were written by ABC -- and files written by ABC were essentially unusable by other software. Socket semantics were also 100% portable in ABC: it didn't have sockets, nor any way to extend the language to add them. Etc -- ABC was a self-contained universe. "Plays well with others" was a strong motivator for Python's design, and that often means playing by others' rules. From jjl at pobox.com Sat Jan 1 11:44:23 2005 From: jjl at pobox.com (John J. Lee) Date: 01 Jan 2005 16:44:23 +0000 Subject: PyQT installation References: <1104370062.562575.88620@f14g2000cwb.googlegroups.com> <1104417268.153983.71970@z14g2000cwz.googlegroups.com> <8SVAd.64014$Jk5.26087@lakeread01> <1gpo9ow.7zqmxi1rwc564N%aleaxit@yahoo.com> Message-ID: <871xd5hzfc.fsf@pobox.com> aleaxit at yahoo.com (Alex Martelli) writes: [...] > Basically: if you want it on Windows for free, forget Qt Correct. > (I hear the > cygwin people are trying to make a GPL Qt available for Win+cyg+XFree, > but I suspect trolltech ain't happy about that -- anyway, I don't think > it would be "native", X11 being still required). [...] Not correct. It's driven by KDE, and it's more ambitious than that: http://kde-cygwin.sourceforge.net/qt3-win32/roadmap.php IIRC, people have already run some KDE apps under Windows (though still needing X, so far). I wonder how TrollTech will react as (and if) it progresses. John From fredrik at pythonware.com Wed Jan 26 12:48:28 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Jan 2005 18:48:28 +0100 Subject: Subclassed dict as globals References: Message-ID: Evan Simpson wrote: > In Python 2.4 the following works: > > >>> class G(dict): > ... def __getitem__(self, k): > ... return 'K' + k > ... > >>> g = G() > >>> exec 'print x, y, z' in g > Kx Ky Kz > >>> > > ...while in Python 2.3 it fails with NameError: name 'x' is not defined. Is this an "accidental > feature", or can I count on this working in future versions of Python? it's an official addition, and it's at least to safe for it to be in all future versions of CPython 2.X. http://www.python.org/doc/2.4/whatsnew/node12.html The eval(expr, globals, locals) and execfile(filename, globals, locals) functions and the exec statement now accept any mapping type for the locals parameter. Previously this had to be a regular Python dictionary. (Contributed by Raymond Hettinger.) I don't think he added this purely by accident, but it might have been a side effect of some other optimization. ;-) > For that matter, is there a way to do this (intercept global variable accesses) > in Python 2.3? not that I'm aware of... From levub137 at wi.rr.com Sun Jan 2 15:10:39 2005 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sun, 02 Jan 2005 14:10:39 -0600 Subject: [ANN] rpncalc-1.2 RPN Calculator For Python Message-ID: The rpncalc package adds an interactive Reverse Polish Notation (RPN) interpreter to Python. This interpreter allows the use of Python as an RPN calculator. You can easily switch between the RPN interpreter and the standard Python interpreter. Home page: http://calcrpnpy.sourceforge.net/ Changes in 1.2 * Added ratfun module that provides polynomial and rational function classes. These classes support mixed arithmetic where numbers, polynomials, and rational functions can be combined in a Python expression. * Incorporate a syntax that allows entering polynomials and rational functions from the RPN interpreter. From steve at holdenweb.com Sat Jan 8 13:44:55 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 08 Jan 2005 13:44:55 -0500 Subject: The limitation of the Photon Hypothesis In-Reply-To: References: Message-ID: Steve Horsley wrote: > bill wrote: > >> Please reply to hdgbyi at public.guangzhou.gd.cn, thank you ! > > > No - I'll reply to the newsgroup, if you don't mind. > >> The limitation of the Photon Hypothesis > > > >> THE UNCERTAINTY PRINCIPLE IS UNTENABLE > > > > You cannot use classical theory to disprove quantum theory that easily. > The uncertainty is quantum in origin, and not just an artifact of > classical mechanics applied to clumsy measurement. > > You don't convince me. > > Also, I think you probably accidentally posted to the wrong newsgroup. > > Steve > > No, he deliberately posted to the wrong newsgroup. But that's because there isn't a right newsgroup for this kind of twaddle (except possibly alt.rubbish.alternate.universe). You have just marked yourself as a noob, since this hoary old favorite seems to appear about ten times a year. Welcome to Usenet! 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 ncoghlan at iinet.net.au Mon Jan 10 05:11:29 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 10 Jan 2005 20:11:29 +1000 Subject: Long strings as function parameters In-Reply-To: References: <1105288564.441842.13060@c13g2000cwb.googlegroups.com> Message-ID: <41E254D1.7010305@iinet.net.au> Jeremy Bowers wrote: > I had thought there was an obvious class in the standard library to assist > with this, but I must have been wrong. buffer is the closest current contender, but I believe it's on the outer due to some problems with its implementation. I think the intention is to eventually have a 'bytes' type, but I don't recall if that was going to be mutable or immutable. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steve at holdenweb.com Mon Jan 3 14:47:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 14:47:05 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> Message-ID: Aahz wrote: > In article , > Steve Holden wrote: > >>Aahz wrote: >> >>>In article <7xacrs230c.fsf at ruckus.brouhaha.com>, >>>Paul Rubin wrote: >>> >>>>I was pretty skeptical of Java's checked exceptions when I first used >>>>them but have been coming around about them. There's just been too >>>>many times when I wrote something in Python that crashed because some >>>>lower-level function raised an exception that the upper level hadn't >>>>been expecting, after the program had been in use for a while. I'd >>>>sure rather find out about that at compile time. >>> >>>That's funny -- Bruce Eckel talks about how he used to love checked >>>exceptions but has come to regard them as the horror that they are. >>>I've learned to just write "throws Exception" at the declaration of >>>every method. >> >>Pretty sloppy, though, no? And surely the important thing is to have a >>broad handler, not a broad specification of raisable exceptions? > > > Yes, it's sloppy, but I Don't Care. I'm trying to write usable code > while learning a damnably under-documented Java library -- and I'm *not* > a Java programmer in the first place, so I'm also fighting with the Java > environment. Eventually I'll add in some better code. The road to hell is paved with good intentions. 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 absom at myrealbox.com Thu Jan 6 09:02:33 2005 From: absom at myrealbox.com (Abhijit Soman) Date: Thu, 06 Jan 2005 19:32:33 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> Message-ID: <344u90F473li5U1@individual.net> wordsender at gmail.com wrote: > Hey guys, > > I can't figure this one out, why is this simple script giving me > problems? > > logfile=file(r'test.txt','w') > logfile.write('datetime') > test=logfile.readlines() > > When I run it I get the error message: > Traceback (most recent call last): > File "C:\Documents and Settings\Gregory\My Documents\Get New Great > Job\testfile.py", line 3, in ? > test=logfile.readlines() > IOError: [Errno 9] Bad file descriptor > > I'm running Windows XP, Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC > v.1200 32 bit (Intel)] on win32 > Any help would be greatly appricated. > > Thanks, > > Greg > As logfile is opened in write mode you cannot read it. You've to open it in read mode for reading. Greetings, Abhijit -- Everybody wants to go to heaven but nobody wants to die From klachemin at comcast.net Tue Jan 18 15:42:21 2005 From: klachemin at comcast.net (Kamilche) Date: 18 Jan 2005 12:42:21 -0800 Subject: Tkinter in thread hangs on windows but not on Linux References: Message-ID: <1106080941.235008.296640@c13g2000cwb.googlegroups.com> This example worked for me on Windows 2000, after inserting import threading from Tkinter import * import ScrolledText at the top. From cam.ac.uk at mh391.invalid Sun Jan 16 20:39:58 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 17 Jan 2005 01:39:58 +0000 Subject: List problems in C code ported to Python In-Reply-To: References: <3SDGd.22010$Z%.6947@fe1.texas.rr.com> Message-ID: Michael Hoffman wrote: > Paul McGuire wrote: >> So "A" == 'a' is true in Python, not true in C. > I think you meant: > > >>> "A" == "A" > True Er, "A" == 'A' -- Michael Hoffman From mikeb at mitre.org Tue Jan 4 13:48:47 2005 From: mikeb at mitre.org (Mike Brenner) Date: Tue, 04 Jan 2005 13:48:47 -0500 Subject: lies about OOP Message-ID: <41DAE50F.414152C8@mitre.org> > ... C++ *appears* to increase the cost of fixing defects ... Some additional points: Some languages allow direct pointer manipulation which favors certain classes of bugs. This is independent of whether the language is OO, and these are probably the most costly defects to find (hanging pointers, buffer overflows, array index busting, memory leakages, etc.). Some languages have strong type checking, which reduces some classes of bugs. This is independent of whether the language is OO. Some people like to think they are OO if they wrap every incoming piece of data in get/put methods in classes. This reduces some categories of errors at the cost of flexibility. When the input format changes, the code needs serious modification everywhere. This is also independent of whether the language is OO, and is a matter of style. While python classes permit you to wrap everything, python classes are so "thin" a wrapper that it is as if they almost aren't wrapped. A trend for style would be to use OO for the methods on stable objects (a continually decreasing breed over time) and use data-driven methods to permit handling data of very flexible input formats. This trend will permit more use of techniques like XSLT, where data structures define the transformations instead of classical code, and techniques like semantical analysis using ontologies, taxonomies, thesaurii, dictionaries, and mappings of semantics into real-world contexts. In other words, data-driven software is not top-down (problem-oriented). It is also not bottom-up (object-oriented). It is simply data-oriented, and totally driven by the input data. This trend will result in the number of lines of code going down, the cost of software going down, and the consciousness of data relationships going up. We will then see Python-D, the python Data language. While Python said: "indentation of code is everything", Python-D will say: all the relational arrows in your dataflow diagram (which IS your code) must be pointing upwards. While Python said: "simplify, reduce coupling, increase cohesion of the software, and do tricks with lambda", Python-D will say: "simplify, reduce coupling, and increase cohesion of the data, and do tricks with metadata." Mike Brenner From jtauber at jtauber.com Sat Jan 8 16:24:00 2005 From: jtauber at jtauber.com (jtauber) Date: 8 Jan 2005 13:24:00 -0800 Subject: Python Operating System??? In-Reply-To: <10trb0mgiflcj4f@corp.supernews.com> References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <1105219440.064891.199690@c13g2000cwb.googlegroups.com> My experiment, Cleese, was making progress before I got distracted by other things. The approach was a micro-kernel in C made up of the CPython bytecode interpreter with the file-related calls to libc ripped out and some bare-metal port read/writes and memory operations exposed to Python as built-in functions. Everything else could then be written in pure Python. Dave Long was able to write a VGA driver in Python and an implementation of Sokoban that used it. You could then boot your machine to Sokoban :-) I should probably get back to it at some stage. see http://cleese.sourceforge.net/ James Tauber http://jtauber.com/blog/ From tjreedy at udel.edu Sun Jan 2 17:41:32 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Jan 2005 17:41:32 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com><33q4plF410bo2U1@individual.net> <1104689464.828070.309990@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1104689464.828070.309990 at c13g2000cwb.googlegroups.com... >> 2004-I: "xundef.f", line 2: 'y' is set but never used. > 2005-W: "xundef.f", line 4: 'x' is used but never set. > 2153-W: "xundef.f", line 5, column 1: Subscript out of range. None of these are syntax errors. The first two of these would be caught by lint or pychecker (I am presuming). > One reason interpreted languages like Python are recommended to > beginners is to avoid the edit/compile/debug cycle. But I think it is > faster and less frustrating to have many errors caught in one shot. True syntax errors often result in such a cascade of bogus errors that it may often be best to fix the first reported error and then recompile. Of course, compilers vary in their recovery efforts. Terry J. Reedy From BOOGIEMANPN at YAHOO.COM Mon Jan 3 15:50:46 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Mon, 3 Jan 2005 21:50:46 +0100 Subject: How do I make Windows Application with Python ? Message-ID: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> Well that's it, how do I make Windows Application with Python ??? Is there simple way that works 100% ? How can I rework visual design done in VS 2003 to use it for my python program ? From martin at v.loewis.de Fri Jan 21 19:49:45 2005 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 22 Jan 2005 01:49:45 +0100 Subject: xml parsing escape characters In-Reply-To: <41F1420E.9090706@netvisaoXX.pt> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efedf2$0$11622$9b622d9e@news.freenet.de> <35adg4F4jgvpnU1@individual.net> <41F01A86.2040805@v.loewis.de> <41F1420E.9090706@netvisaoXX.pt> Message-ID: <41F1A329.4050908@v.loewis.de> Luis P. Mendes wrote: > From your experience, do you think that if this wrong XML code could be > meant to be read only by somekind of Microsoft parser, the error will > not occur? This is very unlikely. MSXML would never do this incorrectly. Regards, Martin From mahs at telcopartners.com Fri Jan 21 23:11:59 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 21 Jan 2005 20:11:59 -0800 Subject: pure python code to do modular-arithmetic unit conversions? In-Reply-To: References: Message-ID: Dan Stromberg wrote: > Is there already a pure python module that can do modular-arithmetic unit > conversions, like converting a huge number of seconds into months, > weeks... or a bandwidth measure into megabits/s or gigabits/s or > megabytes/s or gigabytes/s, whatever's the most useful (ala df -h)? > > Thanks! > Take a look at: http://home.tiscali.be/be052320/Unum_tutorial.html From the intro: "Unum stands for 'unit-numbers'. It is a Python module that allows to define and manipulate true quantities, i.e. numbers with units such as 60 seconds, 500 watts, 42 miles-per-hour, 100 kg per square meter, 14400 bits per second, 30 dollars etc. The module validates unit consistency in arithmetic expressions; it provides also automatic conversion and output formatting." Michael From roy at panix.com Sun Jan 2 13:09:27 2005 From: roy at panix.com (Roy Smith) Date: Sun, 02 Jan 2005 13:09:27 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: claird at lairds.us (Cameron Laird) wrote: > Let me add a cautionary note, though: Big Companies, > including Oracle, Software AG, IBM, Cisco, and so on, have > adopted Tcl over and over. All of them still rely on Tcl > for crucial products. All of them also have employees who > sincerely wonder, "Tcl? Isn't that dead?" A lot of people laugh at Tcl, but it's really a very useful tool. In my last job, we did a major component of our product (SNMP-based network management package) in Tcl, probably on the order of 10 kloc. It has its limitations, but it's very easy to learn, very easy to embed and extend, and reasonably fast. It certainly blows away shell scripting. Around here, AOL/Moviephone has been trolling for years for Tcl people; I guess that counts as a big company. From fredrik at pythonware.com Wed Jan 26 12:07:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Jan 2005 18:07:39 +0100 Subject: string.atoi and string.atol broken? References: <0ttev01qgb9k6a9f34g185lhohkn2p3evq@4ax.com> <4mffv0dqtj0dpjtsqn7lcf46ndc4ei9bc5@4ax.com> Message-ID: Christos TZOTZIOY Georgiou wrote: > You're messing with the time machine again, right? no, it was a subversion pilot error, this time. but now that you remind me, I have to say that this http://mail.python.org/pipermail/python-list/2005-February/030720.html is a bit scary. I wonder from where I was posting that? > [1] Ska vi dela femtio-femtio? Jag kan t?nka mig 60-40 om du st?r f?r det praktiska. From rNOSPAMon at flownet.com Sun Jan 2 15:15:46 2005 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 02 Jan 2005 12:15:46 -0800 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > In article , > Roy Smith wrote: > >In article , > > Ron Garret wrote: > >> In article <1104657461.868175.252380 at c13g2000cwb.googlegroups.com>, > >> "Erik Bethke" wrote: > >>> > >>> I have NEVER experienced this kind of programming joy. > >> > >> Just wait until you discover Lisp! > > Taking this more seriously than it deserves, I've tried poking at Lisp a > couple of times -- each time, I walk away shaking my head in disgust. > Lisp just ain't as *READABLE* as Python. Readability is in the eye of the beholder, but this is not the place to argue this. But this topic does bring up a legitimate question: I have a bunch of code that generates HTML using PRINT statements. I need to convert all this code to return strings rather than actually printing them (so I can use the results to populate templates). In Lisp I could do this: (with-output-to-string (s) (let ( (*standard-output* s) ) (call-html-generating-code) s)) Is there an equivalent Python trick to capture a function call's output as a string? Thanks, rg From fuzzyman at gmail.com Tue Jan 25 07:58:52 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2005 04:58:52 -0800 Subject: snakespell and myspell Message-ID: <1106657932.301181.150050@z14g2000cwz.googlegroups.com> I'm looking to implement a plugin spell checker. I'm probably going to go with PyEnchant, as it looks to be the most promising currently maintained spell checker. I just wondered if anyone knew what happened to snakespell and myspell. Both seem to have dissapeared from the net. People have reported good results from both - and it seems a shame to lose them. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From claird at lairds.us Sun Jan 2 13:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Sun, 02 Jan 2005 18:08:04 GMT Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: In article <41d7def6$0$74273$ed2619ec at ptn-nntp-reader03.plus.net>, Mark Carter wrote: . [tale of *very* typical experience with non-software engineers] . . >use something like Python. I didn't get a reaction from that at the >time, but no doubt they'll be telling me that I'll have to make Excel >work through the internet, or something. I do that, by the way--work with Excel through the 'Net. I use Python, of course. From http Thu Jan 13 13:49:12 2005 From: http (Paul Rubin) Date: 13 Jan 2005 10:49:12 -0800 Subject: sorted (WAS: lambda) References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <7x7jmh1eek.fsf@ruckus.brouhaha.com> Message-ID: <7xpt09xizb.fsf@ruckus.brouhaha.com> Steven Bethard writes: > Note that sorted is a builtin function, not a method of a list > object. Oh, same difference. I thought it was a method because I'm not using 2.4 yet. The result is the same, other than that having it as a function instead of a method is another inconsistency to remember. From mahs at telcopartners.com Tue Jan 25 14:06:56 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 25 Jan 2005 11:06:56 -0800 Subject: Classical FP problem in python : Hamming problem In-Reply-To: References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> Message-ID: Nick Craig-Wood wrote: > Steven Bethard wrote: > >> Nick Craig-Wood wrote: >> >>>Thinking about this some more leads me to believe a general purpose >>>imerge taking any number of arguments will look neater, eg >>> >>>def imerge(*generators): >>> values = [ g.next() for g in generators ] >>> while True: >>> x = min(values) >>> yield x >>> for i in range(len(values)): >>> if values[i] == x: >>> values[i] = generators[i].next() >>> >> >> This kinda looks like it dies after the first generator is exhausted, >> but I'm not certain. > > > Yes it will stop iterating then (rather like zip() on lists of unequal > size). Not sure what the specification should be! It works for the > hamming problem though. > > >>>>list(imerge(iter([1, 2]), iter([1, 2, 3]), iter([1, 2, 3, 4]))) > > [1, 2] > > >>An alternate version that doesn't search for 'i': >> >> py> def imerge(*iterables): >> ... iters = [iter(i) for i in iterables] >> ... values = [i.next() for i in iters] >> ... while iters: >> ... x, i = min((val, i) for i, val in enumerate(values)) >> ... yield x >> ... try: >> ... values[i] = iters[i].next() >> ... except StopIteration: >> ... del iters[i] >> ... del values[i] >> ... >> py> list(imerge([1, 4, 7], [2, 5, 8], [3, 6, 9])) >> [1, 2, 3, 4, 5, 6, 7, 8, 9] >> py> list(imerge([3, 6, 9], [1, 4, 7], [2, 5, 8])) >> [1, 2, 3, 4, 5, 6, 7, 8, 9] >> py> list(imerge([1, 4, 7], [3, 6, 9], [2, 5, 8])) >> [1, 2, 3, 4, 5, 6, 7, 8, 9] > > > This isn't quite right... > > >>>>list(imerge([1, 2, 3], [1, 2, 3], [1, 2, 3])) > > [1, 1, 1, 2, 2, 2, 3, 3, 3] > > This should produce > [1, 2, 3] > > So I'm afraid the searching *is* necessary - you've got to find all > the generators with the min value and move them on. > Here's a dict-based implementation: cute, but slow, at least for a small number of iterators >>> def imerge(*iterables): ... 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 >>> list(imerge([1, 2, 3, 6], [1, 2, 3, 7], [1, 2, 3, 4, 5])) [1, 2, 3, 4, 5, 6, 7] >>> Michael From drjonfox at gmail.com Tue Jan 18 07:19:04 2005 From: drjonfox at gmail.com (drjonfox at gmail.com) Date: 18 Jan 2005 04:19:04 -0800 Subject: Central New Jersey PIG Meeting -- Python Interest Group In Princeton PIG/IP In-Reply-To: References: <1105976215.038859.72730@z14g2000cwz.googlegroups.com> Message-ID: <1106050744.772501.178230@f14g2000cwb.googlegroups.com> Yes Jay. PIG/IP meetings are publicly open with no RSVP necessary. Most of the folks coming are LUG/IP members, as I am and the location is the same as LUG/IP meetings. We haven't formalized the group's affiliation yet. -- Jon From aleaxit at yahoo.com Tue Jan 18 16:21:40 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 18 Jan 2005 22:21:40 +0100 Subject: what would you like to see in a 2nd edition Nutshell? References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> <1gpkxzx.fu7ild1r7602uN%aleaxit@yahoo.com> <200412301319.10987.drlinux@columbus.rr.com> <1105952686.436008.132990@z14g2000cwz.googlegroups.com> Message-ID: <1gqlus1.18qfs1r1r467xeN%aleaxit@yahoo.com> Steven Chan wrote: > I completely agree. I'm also waiting for an advanced Python/project > management book that helps folks out with large-scale projects. I won't schedule that project until the Nutshell 2nd ed is substantially done... and I'm not _promising_ I'll schedule it right afterwards;-). > And, for the 2nd edition, may I suggest: > - coverage of OptionParser module, which is more advanced than the > getopt module that you discuss on page 141. I assume you mean optparse -- that's the module; OptionParser is a class within that module. Yep, covering that is in the plan. > - better Mac OS X application building coverage. Tell us how to build > double-clickable applications. Python in a Nutshell is a book about *cross-platform* Python. There is practically no *WINDOWS*-specific coverage -- 80% of the market or whatever -- it would be absurd if there was platform-specific coverage for a (wonderful) system that has less than 1/10th as much volume (and much as I may be rooting for the mac mini to revolutionize the market, I suspect it will only make a relatively small, incremental difference). I *WISH* I could write a book about Python on the Mac -- ever since I got my iBook, over a year ago, it's been my love and joy, and as soon as I had to change a desktop machine I got myself a dual processor G5 PowerMac too. However, when I proposed that idea to O'Reilly, their reaction was a firm no -- it's too narrow a market, they think (and, being the premier publisher for both the Mac AND Python, they should know, if anybody does). I don't know if this perception of O'Reilly can be changed. If it ever does change, I sure hope they'll call me first, to do that book...!!! > I wish I could ask for wxPython coverage (the whole chapter on tkinter > is useless to me), but I won't start a flame war here. As long as Tkinter is distributed with standard Python and not deprecated, it's unlikely that a reference work about Python can just quietly ignore it. If standard Python changed in this respect, I would of course take that into account in the next following edition!-) Alex From nick at craig-wood.com Thu Jan 13 11:30:03 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 13 Jan 2005 16:30:03 GMT Subject: Debian says "Warning! you are running an untested version of Python." on 2.3 References: Message-ID: Gerhard Haering wrote: > ROFL. Are you using testing, sid or experimental? I expect overzealous > patching from Debian developers, but this is the worst I've heard > of. I would have thought that is unlikely given the way packages move (unmodified) from unstable -> testing (and eventually) -> stable. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From fredrik at pythonware.com Mon Jan 24 07:34:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 13:34:07 +0100 Subject: finding name of instances created References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> <1106397218.724722.172660@c13g2000cwb.googlegroups.com> <41F4DEDE.6070003@iinet.net.au> Message-ID: Nick Coghlan wrote: > Incidentally, this discussion made me realise the real reason why using a lambda to create a named > function is evil: > > Py> def f(): pass > ... > Py> f.func_name > 'f' > Py> f = lambda: None > Py> f.func_name > '' > > I think I've heard that explanation before, but it never really clicked. that's nothing you cannot fix, though: >>> f = lambda: None >>> f.func_name = "f" >>> f.func_name 'f' (only works in 2.4 and later, from what I can tell) From siona at chiark.greenend.org.uk Mon Jan 24 10:05:16 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 24 Jan 2005 15:05:16 +0000 (GMT) Subject: What is print? A function? References: Message-ID: <48h*RouFq@news.chiark.greenend.org.uk> Michael Hoffman wrote: >Frans Englich wrote: >> Nah, I don't think it's a function, but rather a builtin "statement". But it's >> possible to invoke it as an function; print( "test" ) works fine. >That is not invoking it as a function. The parentheses are only for >ordering the expression on the right > >You can do this too: > > >>> print("abc"),("def"),("ghi") >abc def ghi And for further enlightenment: .>>> print("abc", "def", "ghi") ('abc', 'def', 'ghi') -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From duncan-news at grisby.org Wed Jan 5 06:05:49 2005 From: duncan-news at grisby.org (Duncan Grisby) Date: Wed, 05 Jan 2005 12:05:49 +0100 Subject: Looking for CORBA (omniORB) examples References: <1104875968.342963.181970@z14g2000cwz.googlegroups.com> Message-ID: <35964$41dbca0d$5160480d$13218@nf1.news-service.com> In article <1104875968.342963.181970 at z14g2000cwz.googlegroups.com>, wrote: >can we script CORBA objects/events with python. my search for simple >examples has not yielded any results. any help appreciated. There are some simple examples in the omniORBpy distribution. There are a few more examples in this presentation I gave: http://www.grisby.org/presentations/py10code.html Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From stewart.midwinter at gmail.com Wed Jan 26 16:36:11 2005 From: stewart.midwinter at gmail.com (stewart.midwinter at gmail.com) Date: 26 Jan 2005 13:36:11 -0800 Subject: subprocess.Popen() redirecting to TKinter or WXPython textwidget??? In-Reply-To: <41f80b1b$0$148$3a628fcd@reader1.nntp.hccnet.nl> References: <41f80b1b$0$148$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <1106775371.049857.36360@z14g2000cwz.googlegroups.com> Ivo, my initial thought would be, you need to know how much text you will get back from popen. My Python reference has the following example: import os dir = os.popen('ls -al', 'r') while (1): line = dir.readline() if line: print line, else: break that example shows how to capture the process output in a file-type object, then bring it into a string with readline(). in your app, you could create a Tkinter stringVar, say myOutput, for the process output. In your Tkinter widget, you could then set a textvariable=myOutput. also use the wait_variable and watch options (hope I recall these correctly, don't have my Tkinter ref. at hand) to detect when there's been a change to the contents of the StringVar and update the contents of the label. Hope this helps, if not, write back. cheers S From simon.brunning at gmail.com Mon Jan 24 11:22:11 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 24 Jan 2005 16:22:11 +0000 Subject: Python 2.1 - 2.4 differences In-Reply-To: References: Message-ID: <8c7f10c605012408222153e13d@mail.gmail.com> On Mon, 24 Jan 2005 17:13:44 +0100, BOOGIEMAN wrote: > I found some e-book about Python 2.1, I want to print it but just to check > first if sintax of Python 2.1 is same as 2.4 ? Pretty musch the same, but naturally, some things have changed. See these documents for the major changes, by release: * http://www.python.org/doc/2.2.3/whatsnew/ * http://www.python.org/doc/2.3/whatsnew/ * http://www.python.org/doc/2.4/whatsnew/ -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From xah at xahlee.org Mon Jan 24 09:54:16 2005 From: xah at xahlee.org (Xah Lee) Date: 24 Jan 2005 06:54:16 -0800 Subject: [perl-python] 20050124 classes & objects Message-ID: <1106578456.705117.74220@c13g2000cwb.googlegroups.com> ? # -*- coding: utf-8 -*- ? # Python ? ? # in Python, one can define a boxed set ? # of data and functions, which are ? # traditionally known as "class". ? ? # in the following, we define a set of data ? # and functions as a class, and name it xxx ? class xxx: ? "a class extempore! (^_^)" ? i=1 # i'm a piece of data ? def okaydokey(self): return "okaydokey" ? def square(self,a): return a**a ? ? # in the following, ? # we create an object, of the class xxx. ? # also known as "instantiate a class". ? x = xxx() ? ? # data or functions defined in a class ? # are called the class's attributes or ? # methods. ? # to use them, append a dot and ? # their name after the object's name. ? print 'value of attribute i is:', x.i ? print "3 squared is:", x.square(3) ? print "okaydokey called:", x.okaydokey() ? ? # in the definition of function inside a ? # class, the first parameter "self" is ? # necessary. (you'll know why when you need to) ? ? # the first line in the class definition ? # is the class's documentation. It can ? # be accessed thru the __doc__ ? # attribute. ? print "xxx's doc string is:", x.__doc__ ? ? # one can change data inside the class ? x.i = 400 ? ? # one can also add new data to the class ? x.j=4 ? print x.j ? ? # or even override a method ? x.square = 333 ? # (the following line will no longer work) ? # print "3 squared is:", x.square(3) ? ? # in Python, one must be careful not to ? # overwrite data or methods defined in a ? # class. ---------------------- for a obfuscated treatment with a few extra info, see http://python.org/doc/2.3.4/tut/node11.html in Python terminal, type help() then topic CLASSES to read about existing datatypes as classes, and classes in Python try to write a class with one data of integer and two functions, one increases it by 1, one decreases it by 1. note: inside a class definition, to refer to data inside itself use self. e.g. self.i ------------------------------------------ Perl does not support classes or objects in the so-called "Object Oriented" programing. However, a complete set of emulations of OO style of programing have been done, resulting in modules and books and many documentations and tutorials. here is a quote from perldoc perlobj First you need to understand what references are in Perl. See perlref for that. Second, if you still find the following reference work too complicated, a tutorial on object-oriented programming in Perl can be found in perltoot and perltooc. it goes on and sayz: If you're still with us, then here are three very simple definitions that you should find reassuring. 1. An object is simply a reference that happens to know which class it belongs to. 2. A class is simply a package that happens to provide methods to deal with object references. 3. A method is simply a subroutine that expects an object reference (or a package name, for class methods) as the first argument. Good luck. Note: this post is from the Perl-Python a-day mailing list at http://groups.yahoo.com/group/perl-python/ to subscribe, send an email to perl-python-subscribe @ yahoogroups.com if you are reading it on a web page, program examples may not run because html conversion often breaks the code. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From merkosh at hadiko.de Fri Jan 28 17:39:45 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 28 Jan 2005 23:39:45 +0100 Subject: example needed: sip + Qt References: <39688.82.68.80.137.1106920041.squirrel@82.68.80.137> Message-ID: Friday 28 January 2005 23:18 pm Uwe Mayer wrote: > Traceback (most recent call last): > File "", line 1, in ? > ImportError: ./hello.so: undefined symbol: _ZTV5Hello > > $ c++filt _ZTV5Hello > vtable for Hello > > The compilation did not give any warnings or error messages. Any ideas? $ ldd -d hello.so libqt-mt.so.3 => /usr/lib/libqt-mt.so.3 (0x40057000) libXext.so.6 => /usr/X11R6/lib/libXext.so.6 (0x4190c000) libX11.so.6 => /usr/X11R6/lib/libX11.so.6 (0x4154e000) libpthread.so.0 => /lib/tls/libpthread.so.0 (0x41173000) libstdc++.so.5 => /usr/lib/libstdc++.so.5 (0x40743000) libm.so.6 => /lib/tls/libm.so.6 (0x4114f000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x407fd000) libc.so.6 => /lib/tls/libc.so.6 (0x41019000) libfontconfig.so.1 => /usr/lib/libfontconfig.so.1 (0x418d8000) libaudio.so.2 => /usr/lib/libaudio.so.2 (0x40807000) libXt.so.6 => /usr/X11R6/lib/libXt.so.6 (0x4191c000) libpng12.so.0 => /usr/lib/libpng12.so.0 (0x4081c000) libz.so.1 => /usr/lib/libz.so.1 (0x41856000) libXrender.so.1 => /usr/lib/libXrender.so.1 (0x41749000) libXrandr.so.2 => /usr/X11R6/lib/libXrandr.so.2 (0x40842000) libXcursor.so.1 => /usr/lib/libXcursor.so.1 (0x41734000) libXft.so.2 => /usr/lib/libXft.so.2 (0x416e1000) libfreetype.so.6 => /usr/lib/libfreetype.so.6 (0x42487000) libSM.so.6 => /usr/X11R6/lib/libSM.so.6 (0x42583000) libICE.so.6 => /usr/X11R6/lib/libICE.so.6 (0x4256a000) libdl.so.2 => /lib/tls/libdl.so.2 (0x41184000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x80000000) libexpat.so.1 => /usr/lib/libexpat.so.1 (0x40847000) undefined symbol: _ZTV5Hello (./hello.so) undefined symbol: _ZNK5Hello9classNameEv (./hello.so) undefined symbol: _ZN5Hello7qt_castEPKc (./hello.so) undefined symbol: _ZN5Hello9qt_invokeEiP8QUObject (./hello.so) undefined symbol: _ZN5Hello7qt_emitEiP8QUObject (./hello.so) undefined symbol: _ZN5Hello11qt_propertyEiiP8QVariant (./hello.so) undefined symbol: _ZTI5Hello (./hello.so) undefined symbol: _Py_NoneStruct (./hello.so) undefined symbol: PyCObject_Type (./hello.so) Uwe From xah at xahlee.org Thu Jan 20 02:50:12 2005 From: xah at xahlee.org (Xah Lee) Date: 19 Jan 2005 23:50:12 -0800 Subject: [perl-python] 20050120 find functions in modules Message-ID: <1106207412.251279.279670@f14g2000cwb.googlegroups.com> ? # -*- coding: utf-8 -*- ? # Python ? ? # once a module is loaded ? # import mymodule ? # one can find all the names it ? # export with dir() ? ? import sys ? print dir(sys) ? ? # without argument it gives the names ? # you've defined ? print dir() ? ? # to find a list of built-in names ? # import the module __builtin__ ? # and use dir on it. ? import __builtin__ ? print dir(__builtin__) ? ? # see ? # http://python.org/doc/2.3.4/tut/node8.html ? ? ---------------- ? # in Perl, Perl experts can achieve ? # similar functionality by, for example: ? ? use Data::Dumper ('Dumper'); ? print Dumper \%Data::Dumper::; ? ? # it has to do with understanding the inner ? # mechanisms of Perl's module system. ? ? --------------- ? ? Note: this post is from the Perl-Python ? a-day mailing list at ? http://groups.yahoo.com/group/perl-python/ ? to subscribe, send an email to ? perl-python-subscribe @ yahoogroups.com if ? you are reading it on a web page, ? program examples may not run because ? html conversion often breaks the code. ? ? Xah ? xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html From samantha7395 at hotmail.com Thu Jan 20 11:59:45 2005 From: samantha7395 at hotmail.com (Samantha) Date: Thu, 20 Jan 2005 08:59:45 -0800 Subject: Print to Windows default Printer References: Message-ID: Thanks Tim, That is exactly what I want to do. How do I map the printer to LPT1? S "Tim Golden" wrote in message news:mailman.931.1106211699.22381.python-list at python.org... > [Samantha] > | Thanks Tim. I didn't realize it would be so difficult. > | S > > Strictly, if all you want to do is print text and you > have mapped LPTx: to some printer (local or network) > then the venerable "PRINT " or "COPY LPTx:" > may well be what you want. You can issue these via > an os.system call from within Python, and if that serves > the purpose, well... > > > > import os > > f = open ("temp.txt", "w") > f.write ("""I must go down to the sea again, > To the lonely sea and the sky. > And all I ask is a tall ship > And a star to steer her by. > """) > f.close () > > os.system ("print temp.txt") > > > > 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 Sonny.Baillargeon at bmonb.com Tue Jan 4 13:16:51 2005 From: Sonny.Baillargeon at bmonb.com (Baillargeon, Sonny) Date: Tue, 4 Jan 2005 13:16:51 -0500 Subject: Pexpect getting a defuct process Message-ID: <453D335C35136F4B8163C281D58BBD884D0E75@NBNUNYCEXCH1.nesbittburns.ca> Nothing...I know that's the default answer but considering I control the environment, I can assure you that nothing changed. -----Original Message----- From: Jorge Luiz Godoy Filho [mailto:godoy at ieee.org] Sent: Tuesday, January 04, 2005 12:06 PM To: python-list at python.org Subject: Re: Pexpect getting a defuct process Baillargeon, Sonny, Ter?a 04 Janeiro 2005 14:42, wrote: > This used to work before but now I get a defunct process after it runs. > Any ideas? "before" what? What has changed in your environment to make it stop working? -- Godoy. **************************************************************************** This e-mail and any attachments may contain confidential and privileged information. If you are not the intended recipient, please notify the sender immediately by return e-mail, delete this e-mail and destroy any copies. Any dissemination or use of this information by a person other than the intended recipient is unauthorized and may be illegal. Unless otherwise stated, opinions expressed in this e-mail are those of the author and are not endorsed by the author's employer. From claird at lairds.us Sat Jan 15 09:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Sat, 15 Jan 2005 14:08:03 GMT Subject: Why 'r' mode anyway? References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> <41e827df$0$6219$e4fe514c@news.xs4all.nl> Message-ID: In article , Tim Peters wrote: . . . >reading up the bits in the index and offsets too, etc. IIRC, Unix was >actually quite novel at the time in insisting that all files were just >raw byte streams to the OS. Not just "novel", but "puzzling" and even "controversial". It was far from clear that the Unix way could be successful. . . . >but generally where it's reasonably easy to hide. It's not easy to >hide native file conventions, partly because Python wouldn't play well >with *other* platform software if it did. > >Remember that Guido worked on ABC before Python, and Python is in >(small) part a reaction against the extremes of ABC. ABC was 100% >platform-independent. You could read and write files from ABC. >However, the only files you could read from ABC were files that were >written by ABC -- and files written by ABC were essentially unusable >by other software. Socket semantics were also 100% portable in ABC: >it didn't have sockets, nor any way to extend the language to add >them. Etc -- ABC was a self-contained universe. "Plays well with >others" was a strong motivator for Python's design, and that often >means playing by others' rules. At a slightly different level, that--not playing well enough with others--is what held Smalltalk back. Again, a lot of this stuff wasn't obvious at the time, even as late as 1990. I think we understand better now that languages are secondary, in that good developers can be productive with all sorts of syntaxes and semantics; as a practical matter, daily struggles have to do with the libraries or how the languages access what is outside themselves. From ncoghlan at iinet.net.au Mon Jan 31 06:38:34 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 31 Jan 2005 21:38:34 +1000 Subject: Nested scopes and class variables In-Reply-To: <1107161922.285810.8510@f14g2000cwb.googlegroups.com> References: <1107161922.285810.8510@f14g2000cwb.googlegroups.com> Message-ID: <41FE18BA.2010506@iinet.net.au> wittempj at hotmail.com wrote: > To me it seems you should do it something like this: > -def f(x): > - class C(object): > - def __init__(self, x): > - self.x = x # here you set the attribute for class C > - c = C(x) # instantiate a C object > - print c.x > > -f(5) > That does something different - in this case, x is an instance variable, not a class variable. You do raise an interesting questions though: Py> def f(x): ... class C(object): ... x = None ... def __init__(self): ... if C.x is None: ... C.x = x ... C() ... print C.x ... Py> x = 5 Py> f(6) 6 So, the real problem here is the interaction between the ability to write " = " in a class definition with the reference on the RHS being resolved in the global namespace and nested scopes (since that first lookup does NOT respect nested scopes). Functions don't have the problem, since they don't allow that initial lookup to be made from the outer scope. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From rittersporn at gmail.com Sat Jan 8 08:13:51 2005 From: rittersporn at gmail.com (rittersporn at gmail.com) Date: 8 Jan 2005 05:13:51 -0800 Subject: Pre/Postconditions with decorators References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> <34814fF43bm4cU1@individual.net> Message-ID: <1105190031.287227.319360@c13g2000cwb.googlegroups.com> Thank you very much. It is really a very elegant piece of code :-) Eiffel (language) has both type checking and design by contract. Python lacks both. Your module tackles type checking, I tried to execute arbitrary code before and after function execution to realize runtime assertions. I wonder if this should be separated in a Python "checker"-module. Both are part of the interface "contract". Ciao From golux at comcast.net Sat Jan 8 02:33:18 2005 From: golux at comcast.net (Stephen Waterbury) Date: Sat, 08 Jan 2005 02:33:18 -0500 Subject: Software archeology (was Re: Developing Commercial Applications in Python) In-Reply-To: References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <41DF8CBE.8080506@comcast.net> Aahz wrote: > In article , > Stephen Waterbury wrote: > >>Aahz wrote: >> >>>In article , >>>Stephen Waterbury wrote: >>> >>>>Also see Python Success Stories: http://pythonology.org/success >>>> >>>>A notable example is Verity's search engine -- see >>>>http://python.oreilly.com/news/PythonSS.pdf >>> >>>Actually, your statement is slightly inaccurate. The Verity search >>>engine is more than fifteen years old in its core technology; it was >>>started as a LISP project at IIRC MIT. (At one point I was much amused >>>to look at the C source code and find car() and cdr() functions.) As of >>>my last information, Python isn't used at all in or with the Verity >>>search engine. What you're referring to is the Verity Ultraseek engine, >>>originally written and owned by Infoseek before getting transferred to >>>Verity through a series of dot-bomb transactions. The Ultraseek engine >>>doesn't use Python, but Python is used to control the engine, and I think >>>much of the spider is written in Python. >> >>Actually, Aahz didn't add anything useful that wasn't explained better >>in the article itself, pointing to which was the purpose of my post, >>but he is correct: Python was *not* used to write the Verity search >>engine ... how the hell do these stupid rumors get started anyhow?? ;). >>Just read the article, dammit! :) > > You're quite correct that I added little useful information, but seeing > as I used to work at Verity, I couldn't resist adding some hopefully > interesting and/or amusing trivia. Especially the LISP bit. Well GEEZ, you should've mentioned that you used to work there! All the trivia *were* amusing ... sorry if I harshed! :) Cheers, Steve From steve at holdenweb.com Wed Jan 19 15:21:52 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Jan 2005 15:21:52 -0500 Subject: a question In-Reply-To: <1106165238.353672.272980@f14g2000cwb.googlegroups.com> References: <3YvHd.80953$Jk5.28602@lakeread01> <6kwHd.48934$w62.45338@bgtnsc05-news.ops.worldnet.att.net> <1106165238.353672.272980@f14g2000cwb.googlegroups.com> Message-ID: <7ozHd.80963$Jk5.43195@lakeread01> Will Stuyvesant wrote: > Andrew Koenig wrote: > >>how about writing this instead? >> >> ('this is a ' >> 'long string') > > > Yes, nice. And to make that possible we have to write > ('one-string-item',) instead of ('one-string-item') if we want a tuple > with one string inside. Sometimes that feels like a wart to me, but > now I know it, sometimes not. > That has very little to do with tuples. You could just as easily write 'this is a '\ 'long string' It's the dangling comma that's required to specify a tuple: >>> 1, (1,) >>> 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 marklists at mceahern.com Sat Jan 1 15:21:42 2005 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 01 Jan 2005 14:21:42 -0600 Subject: Looping using iterators with fractional values In-Reply-To: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> References: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> Message-ID: <41D70656.6000505@mceahern.com> drife wrote: > Hello, > > Making the transition from Perl to Python, and have a > question about constructing a loop that uses an iterator > of type float. How does one do this in Python? > > Use a generator: >>> def iterfloat(start, stop, inc): ... f = start ... while f <= stop: ... yield f ... f += inc ... >>> for x in iterfloat(0.25, 2.25, 0.25): ... print '%9.2f' % x ... 0.25 0.50 0.75 1.00 1.25 1.50 1.75 2.00 2.25 >>> From bulba at bulba.com Tue Jan 4 12:54:40 2005 From: bulba at bulba.com (Bulba!) Date: Tue, 04 Jan 2005 18:54:40 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Message-ID: On Mon, 3 Jan 2005 00:08:25 +0100, aleaxit at yahoo.com (Alex Martelli) wrote: >> True. I have a bit of interest in economics, so I've seen e.g. >> this example - why is it that foreign branches of companies >> tend to cluster themselves in one city or country (e.g. >It's not just _foreign_ companies -- regional clustering of all kinds of >business activities is a much more widespread phenomenon. First, even though I disagree with you in places, thanks for this reply - it enhanced my knowledge of the topic in some places. Re the foreign/domestic companies: I have observed this what I call "irrational clustering" esp. re foreign companies here. >Exogenous is fine if you're looking at the decision a single firm, the >N+1 - th to set up shop in (say) a city, faces, given decisions already >taken by other N firms in the same sector. >The firm's production processes have inputs and outputs, coming from >other firms and (generally, with the exception of the last "layer" of >retailers etc) going to other firms. Say that the main potential buyers >for your firm's products are firms X, Y and Z, whose locations all >"happen to be" (that's the "exogenous" part) in the Q quarter of town. >So, all your competitors have their locations in or near Q, too. Where >are you going to set up your location? Rents are higher in Q than >somewhere out in the boondocks -- but being in Q has obvious advantages: >your salespeople will be very well-placed to shuttle between X, Y, Z and >your offices, often with your designers along so they can impress the >buyers or get their specs for competitive bidding, etc, etc. What you wrote regards especially strong the industries you pointed at: fashion, jewellery, esp. I think in those industries those factors may be decisive. When this street is renown in the city to have "good jewellers" located there, the choice for a new jeweller in this city is almost like this: get located there or die. However, I'd argue that industries with those kinds of dependencies are actually pretty rare. >At some >points, the competition for rents in quarter Q will start driving some >experimenters elsewhere, but they may not necessarily thrive in those >other locations. If, whatever industry you're in, you can strongly >benefit from working closely with customers, then quarter Q will be >where many firms making the same products end up (supply-side >clustering). >Now consider a new company Z set up to compete with X, Y and Z. Where >will THEY set up shop? Quarter Q has the strong advantage of offering >many experienced suppliers nearby -- and in many industries there are >benefits in working closely with suppliers, too (even just to easily >have them compete hard for your business...). I grant that this model is neat and intuitive - but I'd argue it is not very adequate to real world. Read on. >So, there are easily >appreciated exogenous models to explain demand-side clustering, too. >That's how you end up with a Holliwood, a Silicon Valley, a Milan (for >high-quality fashion and industrial design), even, say, on a lesser >scale, a Valenza Po or an Arezzo for jewelry. Ancient European cities >offer a zillion examples, with streets and quarters named after the >trades or professions that were most clustered there -- of course, there >are many other auxiliary factors related to the fact that people often >_like_ to associate with others of the same trade (according to Adam >Smith, generally to plot some damage to the general public;-), but >supply-side and demand-side, at least for a simpler exogenous model, are >plenty. >Say that it's the 18th century (after the corporations' power to stop >"foreign" competition from nearby towns had basically waned), you're a >hat-maker from Firenze, and for whatever reason you need to move >yourself and your business to Bologna. If all the best hat-makers' >workshops and shops are clustered around Piazza dell'Orologio, where are >YOU going to set up shop? Rents in that piazza are high, BUT - that's >where people who want to buy new hats will come strolling to look at the >displays, compare prices, and generally shop. That will only be true if the hats from Piazza dell'Orologio are much better than elsewhere. If the quality and prices of products converged, the gain for the customers to go there isn't high. And the prices for customers have to be higher, as the high rents drive some suppliers out, so the supply of hats is lower, ergo customer prices are higher. >That's close to where >felt-makers are, since they sell to other hat-makers. Should your >business soon flourish, so you'll need to hire a worker, that's where >you can soon meet all the local workers, relaxing with a glass of wine >at the local osteria after work, and start getting acquainted with >everybody, etc, etc... That is true in the model. However, I don't find it very true in practice in a lot of industries: - "physical proximity" in this city very often means navigating through jammed roads, so the transportation costs in terms of time and money may very well increase rather than decrease by locating "in a cluster", even though physical distance may be smaller. physical distance != temporal distance & a cost of getting there. - since everything is more expensive, so is labor; even if you pay this worker a little bit less elsewhere, he might find it more attractive to commute shortly to work and have lower costs of living in a different area, so this very well may work as a motivation to relocate - few large businesses nowadays have customers neatly clustered in one location, they tend to sell countrywide or worldwide; so the premium for getting into this expensive place is low and the costs are high - production nowadays tends to be geographically distributed as well - communication costs and transportation costs are DRAMATICALLY lower nowadays than they used to be (today it costs 1/80 [one eightieth] to transport a kg of mass using an aircraft in comparison to what it cost in 1930s; ditto for telecommunication). Consider real world examples: Microsoft in Redmond or Boeing in Seattle. Microsoft needs quite a lot of programmers. It would be rather hard to find enough programmers born and educated in Redmond, wouldn't it? Boeing: Seattle?! Why Seattle? Doesn't Boeing sell most of its new aircrafts in Washington? AFAIK, in Europe Boeing does much of its production in cooperation with Alena in Italy. From this viewpoint it really doesn't matter much if Boeing is located in Seattle or anywhere else in America really, does it? Right here (Poland), most of the foreign corporations set up their call centers in Warsaw, which is totally ridiculous given how expensive that city is. Oh I can understand setting up a warehouse by HP there because it's close to its biggest customers. But I really see no good reason behind HP call center being located in Warsaw, too, AFAIK (or at least that's the city code when I have to call them sometimes). Most of the successful domestic companies I have observed here have started and still operate in some God-forgotten provincial towns, where land and labor is cheap and when it comes to highly skilled professionals, you have to "import" some or all of them from elsewhere anyway, because not even a big city is likely to have precisely all the kinds of ultra-specialized professionals that you may need. And there's less crime, and shuttling kids to school isn't a nightmare, and the costs of living are lower. Plus there's less of other things to do, so your workers tend to focus more on work. :-) >Risk avoidance is quite a secondary issue here (except if you introduce >in your model an aspect of imperfect-information, in which case, >following on the decisions made by locals who may be presumed to have >better information than you is an excellent strategy). Nor is there any >"agency problem" (managers acting for their interests and against the >interest of owners), not a _hint_ of it, in fact -- the hatmaker acting >on his own behalf is perfectly rational and obviously has no agency >problem!). I find no justification in most of foreign companies setting up their call centers in a ridiculously overpriced capital city - so from my viewpoint the risk avoidance is the only explanation that is left. Not all corporations do that: in this country Coca-Cola has made their big "green field" investment almost in the middle of nowhere in this country. GM, Volkswagen, FIAT, and most of other carmakers have made similar decisions. Doesn't seem like those were bad business decisions for them. The cluster I've seen - an IT "corporate area" in Dublin, Ireland - was specifically created not due to "natural clustering", but due to govt policy of tax breaks and preparing good infrastructure in this place rather than some inter-business and inter-customer dependencies, since e.g. Microsoft (where the company sent me for training) neither is able to get all the workers it needs just from this city, nor it sells mostly to local customers, but it sells all over Europe. To me, the issue of manager having to face their superiors asking him a question - "why on Earth have you decided to locate our branch in the middle of nowhere in this country? Why not in capital city? Can't you look at the map? Read some stats how many inhabitants this city has and what is the income level there?" is overwhelming: it would take long time to explain for this manager who e.g. may have already got his hands dirty in this industry in that country to know that say, there's little revenue increase to be gained in locating the facility in capital city, the needed workers are actually hard to find there, etc. To me, this is much like decision whether do much of development in Python or MS VS / VB. "But everybody's using VisualStudio / VB" is a simple and compelling argument: "so many people can't be wrong", while explanations that going Python may actually be better decision in this context requires long and complex explanations and managers oft can not even be bothered to read executive summaries. I feel econ models frequently are elegantly designed abstractions of elegantly designed problems; the problem is how close those are to the real-world problems. At the end of the day, it's "human action" that gets all of that implemented. I've seen too much resources going down the drain in completely idiotic projects and decisions to believe managers are rational beings. ;o) -- Real world is perfectly indifferent to lies that are the foundation of leftist "thinking". From ncoghlan at iinet.net.au Tue Jan 25 22:49:51 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 13:49:51 +1000 Subject: Can't load bytecode with execfile ? In-Reply-To: References: Message-ID: <41F7135F.3000000@iinet.net.au> Bo Jacobsen wrote: > I have a number of files compiled to bytecode using py_compile.compile(). > The .pyc files can be invoked by python directly ($python file.pyc), but > "loading" them by execfile just throws an exception ? Py> help(execfile) Help on built-in function execfile in module __builtin__: execfile(...) execfile(filename[, globals[, locals]]) Read and execute a Python _SCRIPT_ from a file. The globals and locals are dictionaries, defaulting to the current globals and locals. If only globals is given, locals defaults to it. (Emphasis Added) Execfile doesn't go through the "is it bytecode?" check that the import machinery or the -m command line switch use. It tries to interpret anything you give it as Python source code - which is why you get a syntax error when you try to use it on compiled bytecode. Allowing it to handle compiled bytecode might make a reasonable feature request, though. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From erikbethke at gmail.com Wed Jan 19 10:54:21 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 19 Jan 2005 07:54:21 -0800 Subject: ElementTree cannot parse UTF-8 Unicode? Message-ID: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> Hello All, I am getting an error of not well-formed at the beginning of the Korean text in the second example. I am doing something wrong with how I am encoding my Korean? Do I need more of a wrapper about it than simple quotes? Is there some sort of XML syntax for indicating a Unicode string, or does the Elementree library just not support reading of Unicode? here is my test snippet: from elementtree import ElementTree vocabXML = ElementTree.parse('test2.xml').getroot() where I have two data files: this one works: this one fails: From bj_666 at gmx.net Sat Jan 8 15:48:25 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 08 Jan 2005 21:48:25 +0100 Subject: escape string for command line References: Message-ID: In , Ksenia Marasanova wrote: > I have a simple ecard creation script on a website, where user can add > text to a graphic. I use ImageMagick for it: > > # template_file => path to image template file > # new_file => path to generated file > # text => user input > command = '''convert %s -font OfficinaSanITC-BookOS -pointsize 12 > -fill "#8C2F48" -draw "gravity north text 0,26 '%s'" %s''' % ( > template_file, text, new_file) > system(command) > > I was wondering, is there a general way to escape the string entered > by the user, to prevent code injection into command line? Take a look at the "string-escape" encoding: >>> evil = "'; rm -rf /;" >>> command = "echo '%s'" >>> print command % evil.encode('string-escape') echo '\'; rm -rf /;' > Will it > always be safe, even when binary data is submitted through POST? Don't know if it's always safe. Unprintable bytes like 0x00 will be escaped as '\x00'. Ciao, Marc 'BlackJack' Rintsch From roy at panix.com Mon Jan 3 15:38:15 2005 From: roy at panix.com (Roy Smith) Date: 3 Jan 2005 15:38:15 -0500 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: Stephen Waterbury wrote: >> Shaw-PTI (www.pti-us.com) uses Python in their software. > >... but the "Python Powered" logo is conspicuous by its >absence from their site. Too bad that some commercial >exploiters of Python don't advertise that fact more often. Companies use all sorts of technologies to produce their products. I have no idea who Shaw-PTI is or what they do, but I'm sure they also use other languages, and web servers, and operating systems, and telephones and office furniture and pencil sharpeners. They're all just tools. You don't expect a company to waste space on their web site advertising which brand of pencil sharpener they use, so why would you expect they would do so for a programming language? Sometimes you see web sites with "Powered by IBM" or "Powered by Sun" or whatever. I'm sure behind every one of those is a deal cut with the supplier to promote their name in return for some favorable terms on a contract. From ptmcg at austin.rr._bogus_.com Mon Jan 10 12:00:18 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 10 Jan 2005 17:00:18 GMT Subject: Writing huge Sets() to disk References: Message-ID: "Martin MOKREJ?" wrote in message news:mailman.448.1105373471.22381.python-list at python.org... > Hi, > I have sets.Set() objects having up to 20E20 items, > each is composed of up to 20 characters. Keeping > them in memory on !GB machine put's me quickly into swap. > I don't want to use dictionary approach, as I don't see a sense > to store None as a value. The items in a set are unique. > > How can I write them efficiently to disk? To be more exact, > I have 20 sets. _set1 has 1E20 keys of size 1 character. > > alphabet = ('G', 'A', 'V', 'L', 'I', 'P', 'S', 'T', 'C', 'M', 'A', 'Q', 'F', 'Y', 'W', 'K', 'R', 'H', 'D', 'E') > for aa1 in alphabet: > # l = [aa1] > #_set1.add(aa1) > for aa2 in alphabet: > # l.append(aa2) > #_set2.add(''.join(l)) > [cut] > > The reason I went for sets instead of lists is the speed, > availability of unique, common and other methods. > What would you propose as an elegant solution? > Actually, even those nested for loops take ages. :( > M. _set1 only has 19 keys of size 1 character - 'A' is duplicated. Assuming you replace 'A' with another character (say 'Z'), then here is what you get: _set1 - 20 elements (20**1) _set2 - 400 elements (20**2) _set3 - 8000 elements (20**3) ... _set20 - 20**20 ~ 10 ^ (1.301*20) or 1E26 If you have no duplicates in your alphabet, then you wont need to use sets, every combination will be unique. In this case, just use a generator. Here's a recursive generator approach that may save you a bunch of nested editing (set maxDepth as high as you dare): alphabet = ('G', 'A', 'V', 'L', 'I', 'P', 'S', 'T', 'C', 'M', 'Z', 'Q', 'F', 'Y', 'W', 'K', 'R', 'H', 'D', 'E') maxDepth = 3 def genNextCombo(root=list(),depth=1): for a in alphabet: thisRoot = root + [a] yield "".join( thisRoot ) if depth < maxDepth: for c in genNextCombo(thisRoot, depth+1): yield c for c in genNextCombo(): print c # or write to file, or whatever -- Paul From jeff at ccvcorp.com Tue Jan 25 20:08:17 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 25 Jan 2005 17:08:17 -0800 Subject: Help! Host is reluctant to install Python In-Reply-To: References: Message-ID: <10vdr0kksufnp7c@corp.supernews.com> Daniel Bickett wrote: > I've been trying to convince my host to install python/mod_python on > his server for a while now, however there are a number of reasons he > is reluctant to do so, which I will outline here: > > 1. His major reason is optimization. He uses Zend's optimization of > PHP as an example, and he has stated that python is rather resource > consuming. This depends, as all things, on what's being done with it -- it's certainly possible to write resource-hogging Python apps, but it's possible to do that in any language. And I'm not aware of Python being particularly worse in this regard than any other web-scripting language. I suspect this translates to "I'm avoiding anything that I don't already know". > And, in light of point #1, I suggested that if there wasn't any > optimization immediately available, he could just enable it for my > account (thus lessening potential resource consumption at any given > time), to which he retorted "Do /you/ know how to do that?", and I > must say, he has me cornered ;-) I don't know how to do that offhand... but then, I don't expect people to pay me for web-hosting expertise. I would expect, from the little that I *do* know of Apache configuration, that it wouldn't be too difficult to allow Python CGIs to run out of only one specific directory, that being within your webspace. If you're paying for this service, then I'd agree with everyone else that you should be paying for a different service. There's plenty of webhosts around who *will* do Python. If this is a friend, then point him to the Python Success Stories (http://www.pythonology.com/success) and suggest that if there's that many Python web apps around, it can't be too horrible on resources/management, and that he shouldn't be so afraid to try something new... Jeff Shannon Technician/Programmer Credit International From fumanchu at amor.org Mon Jan 31 12:21:10 2005 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 31 Jan 2005 09:21:10 -0800 Subject: variable declaration Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33982FA@exchange.hqamor.amorhq.net> 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". You are an exceptional person, Alex. ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org From tzot at sil-tec.gr Wed Jan 26 11:45:19 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 26 Jan 2005 18:45:19 +0200 Subject: string.atoi and string.atol broken? References: <0ttev01qgb9k6a9f34g185lhohkn2p3evq@4ax.com> Message-ID: <4mffv0dqtj0dpjtsqn7lcf46ndc4ei9bc5@4ax.com> On Wed, 26 Jan 2005 13:23:42 +0100, rumours say that "Fredrik Lundh" might have written: >Christos TZOTZIOY Georgiou wrote: > >>>the function's named "atoi", not "atoitoa". >> >> [Fredrik] [0] >cool. can I have a copy of your script? I hereby declare my script in perpetual alpha-testing stage, and therefore won't be making it public, since I intend to make money out of this [1] collecting all translations in a book called "The effbot's guide to pythonology" [2]. >reminds me that I have a few patches in the inqueue. I wonder >what this one does? ;-) >hmm ;-) guess I can tune that later ;-) and what about that other >patch? ;-) let's see ;-) patch, checkout, reload File "effbot.py", line 29238 > <<<<<<< .mine > ^ >IndentationError: expected an indented block You're messing with the time machine again, right? Your patch is probably for nightly build 20071202032501 . At the moment, most of the script logic (and bugs :) is concentrated in line 2: what_to_print = raw_input("Translation of /F's single line reply? ") [0] got it right this time [1] Ska vi dela femtio-femtio? [2] which book will help you improve your own python use, hopefully :) -- 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 danb_83 at yahoo.com Sun Jan 16 12:33:59 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 16 Jan 2005 09:33:59 -0800 Subject: why are some types immutable? In-Reply-To: References: Message-ID: <1105896839.966379.220890@z14g2000cwz.googlegroups.com> Roy Smith wrote: > Torsten Mohr wrote: > > reading the documentation (and also from a hint from this NG) > > i know now that there are some types that are not mutable. > > > > But why is it this way? > > > > From an overhead point of view i think it is not optimal, > > for example for a large string it could be much faster to > > have it changed in place, not generating a new one for > > every step in a change. > > There has been a huge amount written about immutable types recently. A > search of the Google news archives should turn up tons of articles. > > But, in a nutshell, the biggest reason for immutable types (tuples and > strings) is that this lets they be dictionary keys. If you want to know > why dictionary keys have to be immutable, More precisely, dictionary keys can't be mutable in any way that affects the result of the hash function or the == or != operators. From PPNTWIMBXFFC at spammotel.com Fri Jan 7 03:48:11 2005 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Fri, 07 Jan 2005 09:48:11 +0100 Subject: Apple creator on Python Message-ID: One of the "creators" of Apple has written a book and mentions Python in the interview: http://www.macdevcenter.com/pub/a/mac/2005/01/04/hertzfeld.html After writing around 20 stories, I shifted gears and worked on the web software to publish them, writing a simple authoring system in Python, which I love to program in. From aahz at pythoncraft.com Mon Jan 31 19:08:30 2005 From: aahz at pythoncraft.com (Aahz) Date: 31 Jan 2005 19:08:30 -0500 Subject: Want to meet any of these people? They are registered for PyCon References: Message-ID: In article , Steve Holden wrote: > >Sorry you can't make it to Python. My even-naiver way of approaching the >problem was to use the sort utility built into Cygwin, thereby avoiding >writing any code at all. That's cheating! ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. 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 From steven.bethard at gmail.com Fri Jan 7 18:49:01 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 16:49:01 -0700 Subject: switching an instance variable between a property and a normal value In-Reply-To: References: Message-ID: Robert Brewer wrote: > Steven Bethard wrote: > >>I'm playing around with a mapping type that uses setdefault >>as suggested >>in http://www.python.org/moin/Python3_2e0Suggestions. The >>default value >>for a missing key is either a simple value, or a value >>generated from a >>function. If it's generated from the function, it should be >>generated >>new each time so that, for example, if the default is an empty list, >>d[1] and d[2] don't access the same list. This is why 'c.x is c.x' >>should be False if I'm using the function. >> >>The best option I guess is to rewrite this with a >>_getdefault() function instead of a property: >> >>But I was hoping to avoid having two separate attributes (self._value >>and self._func) when only one should have a value at any given time. > > > It seems to me like you were using the property as a glorified flag. > Just use a flag. > > ftypes = ('BuiltinFunctionType', 'BuiltinMethodType', > 'FunctionType', 'GeneratorType', 'LambdaType', > 'MethodType', 'UnboundMethodType',) > > class D(dict): > def __init__(self): > self._default = None > self._call_default = False > def __getitem__(self, key): > if not key in self: > if self._call_default: > self[key] = self._default() > else: > self[key] = self._default > return dict.__getitem__(self, key) > def setdefaultvalue(self, value): > self._default = value > self._call_default = isinstance(value, ftypes) > > ...or: > > def setdefaultvalue(self, value, call_callables=True): > self._default = value > self._call_default = callable(value) and call_callables Well, the right solution using a flag for the particular behavior I was looking for would have to look something like: class D(dict): def __init__(self): self._default = None self._call = False def __getitem__(self, key): if not key in self: if self._call: func, args, kwds = self._default self[key] = func(*args, **kwds) else: self[key] = self._default return dict.__getitem__(self, key) def setdefault(self, value, call=False, *args, **kwds): if call: self._default = value, args, kwds else: self._default = value self._call = call where I also accept *args and **kwds when the default value is to be called. It's certainly doable with a flag, but note that I have to check the flag every time in both __getitem__ and setdefault. It'd minimize redundancy a bit if I only had to check it in one place. Guess I could do something like: class D(dict): def __init__(self): self._default = None self._call_default = False def __getitem__(self, key): if not key in self: self[key] = self._default() return dict.__getitem__(self, key) def setdefault(self, value, call=False, *args, **kwds): if call: def caller(): return value(*args, **kwds) else: def caller(): return value self._default = caller Then I only have to test call when setdefault is called. Not sure I like this any better though... Steve P.S. The reason I had two functions, setdefaultvalue and setdefaultfunction has to do with argument parsing for setdefaultfunction. Note that def setdefault(self, value, call=False, *args, **kwds): ... means that you can't call functions with keyword arguments 'value' or 'call'. That means I have to rewrite this function as something like def setdefault(*args, **kwds): self = args[0] value = args[1] call = ??? ... The problem is, if 'call' is a keyword argument, I don't know whether it was intended as one of the function arguments or as an argument to setdefault. If setdefaultvalue and setdefaultfunction are two separate methods, I don't run into this problem. From martin at v.loewis.de Sun Jan 16 06:46:06 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 16 Jan 2005 12:46:06 +0100 Subject: mutable string? In-Reply-To: References: Message-ID: <41ea53ff$0$25939$9b622d9e@news.freenet.de> Torsten Mohr wrote: > is there some string class that i can change in place, > like perls strings? array.array is mutable. You can use the 'c' code if you want an array of characters. > Is it possible to do some regex replacement functions > that would even change its length? You can't use re.sub array, but you can use re.search, and you can perform slice assigment. > Can i append to this string? Yes. > Is there some wrapper for C++ STL string class (if that > would make sense)? It would be possible, but I cannot see why one would want to do that. Regards, Martin From macrocosm at fastmail.fm Sat Jan 8 13:27:48 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Sat, 08 Jan 2005 13:27:48 -0500 Subject: Python Operating System??? In-Reply-To: References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> Message-ID: <41E02624.90602@fastmail.fm> Peter Hansen wrote: > Paul Rubin wrote: > >> When Unix was first written, people thought implementing an OS in C >> was ludicrous. Everyone knew OS's had to be written in assembler. > > > Actually, when Unix was first written that belief was entirely > correct, and OSes *did* have to be written in assembler. *nods* > > That is, pure C did not have the capability to handle all > that was required. I recall it taking a good decade before it > became *common* to find C compilers with, for example, @interrupt > support to let the compiler generate code that properly saved > all registers and used RTI instead of RTS (or whatever it might > have been called one one's particular flavour of CPU). If my memory serves me, you are entirely correct. > > Now, once you added a few tiny interrupt handlers, and some context > switching (stack manipulation) routines, pretty much everything else > *could* be done in C, but that doesn't invalidate the point. *nods* > > I think it's safe to say that none of pure C, pure Lisp, or pure Python > are really capable of being used as the *sole* language to build > an operating system. *nods* > > It's also safe to say that this is a largely irrelevant point. > It would probably only be of academic interest to try to do > something like that. Any practical attempt would not think more > than twice of resorting to a little "glue" in assembler or in > the form of "canned" byte sequences built by hand and stuck > into the appropriate places in memory... > > -Peter Indeed indeed. Once must remain focused and ask oneself what he/she is attempting to achieve. In all likelihood, a little asm/c/python glue work won't hurt the objective, especially given that doing otherwise would entail a very _low level_ reworking of Python that would take as much and likely more effort and skill than to resort to asm/c when Python falls incapable. One could do a Python-Lisp OS w/ Lisp used for the Python incapable areas, but you would near entirely loose the benefits of Lisp in that respect--- it would have to be so low-level, could you call it Lisp? (A question someone else here posed in this thread.) - Arich From rkern at ucsd.edu Thu Jan 6 21:12:23 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 06 Jan 2005 18:12:23 -0800 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <16859.16548.249527.30210@montanaro.dyndns.org> <864d37090501050117761a32e6@mail.gmail.com> Message-ID: Bulba! wrote: > On Wed, 05 Jan 2005 17:25:08 -0800, Robert Kern > wrote: >>I still think numarray is a good start for this. It handles more than >>just numbers. And RecArray (an array that has different types in each >>column, as you seem to require) can be subclassed to add these methods >>to it. > > > I have downloaded it, playing with it and like it. I esp. like things > like: > > >>>>print a + a > > [2 4 6] > > or > > >>>>b.getshape() > > (4,3) > > Very Pythonic. :-) > > However, not all things are generic enough like I meant. That > is not to criticize, but merely to point out that the library is for > obvious reasons slanted towards numerical work, so e.g. while the > following works: > > .>>> from numarray import transpose > .>>> transpose([[1,2],[3,4]]) > array([[1, 3], > [2, 4]]) > > ...this doesn't: > > >>>>transpose([('phone1', 12345), ('phone2', 67890)]) > > Traceback (most recent call last): > File "", line 1, in ? > [....] > TypeError: Expecting a python numeric type, got something else. > > Why would someone want to do such a thing: suppose he > wants 'phone1' and 'phone2' and number records sequenced > horizontally instead vertically, while when he read that from > a file, such was the file structure. It's a boneheaded example, > but you get the idea. http://stsdas.stsci.edu/numarray/numarray-1.1.html/module-numarray.objects.html In [1]: from numarray import objects, transpose In [2]: a = objects.array([['phone1', 12345], ['phone2', 67890]]) In [3]: a Out[3]: ObjectArray([['phone1', 12345], ['phone2', 67890]]) In [4]: transpose(a) Out[4]: ObjectArray([['phone1', 'phone2'], [12345, 67890]]) Note the use of lists. Using tuples makes the constructor think you want a vector of tuple objects. -- 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 tim.peters at gmail.com Sun Jan 30 17:57:37 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 30 Jan 2005 17:57:37 -0500 Subject: pickle, cPickle, & HIGHEST_PROTOCOL In-Reply-To: <1107124050.160083.129630@f14g2000cwb.googlegroups.com> References: <1107124050.160083.129630@f14g2000cwb.googlegroups.com> Message-ID: <1f7befae0501301457b8e7216@mail.gmail.com> [A.B., Khalid] > I wonder if someone can explain what is wrong here. I am pickling a > list of dictionaries (see code attached) and unpickling it back using > the HIGHEST_PROTOCOL of pickle and cPickle. ... > ... on Win98. Pickles are binary data. Therefore you should open pickle files in binary mode on all platforms, and must open them in binary mode on Windows. That is, replace your lines: f = file('pkl_' + fn, 'w') f = file('pkl_' + fn, 'r') with: f = file('pkl_' + fn, 'wb') f = file('pkl_' + fn, 'rb') It's true that you can get away with opening pickle files in text mode on Windows if you stick to the default pickle protocol (0), although in that case your pickle files won't be portable across platforms. For that reason, don't try to be clever: always use binary-mode files to store pickles, regardless of pickle protocol in use. From cookedm+news at physics.mcmaster.ca Mon Jan 10 22:53:05 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 10 Jan 2005 22:53:05 -0500 Subject: why not datetime.strptime() ? References: Message-ID: Joshua Spoerri writes: > Skip Montanaro pobox.com> writes: >> josh> Shouldn't datetime have strptime? >> If someone wants to get their feet wet with extension module >> programming >> this might be a good place to start. Mostly, I think nobody who has >> needed/wanted it so far has the round tuits available to spend on the >> task. > > OK, it was pretty straightforward. Thanks for the direction. > > To whom should I send the patch (attached)? Submit it to the patch tracker on sourceforge. But first, some constructive criticism: > --- Modules/datetimemodule.c.orig 2003-10-20 10:34:46.000000000 -0400 > +++ Modules/datetimemodule.c 2005-01-10 20:58:38.884823296 -0500 > @@ -3774,6 +3774,32 @@ > return result; > } > > +/* Return new datetime from time.strptime(). */ > +static PyObject * > +datetime_strptime(PyObject *cls, PyObject *args) > +{ > + PyObject *result = NULL, *obj, *module; > + const char *string, *format; > + > + if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format)) > + return NULL; > + if ((module = PyImport_ImportModule("time")) == NULL) > + return NULL; > + obj = PyObject_CallMethod(module, "strptime", "ss", string, format); > + Py_DECREF(module); You don't check for errors: an exception being thrown by PyObject_CallMethod will return obj == NULL. If there's a module in sys.path called time that overrides the stdlib time, things will fail, and you should be able to catch that. > + result = PyObject_CallFunction(cls, "iiiiiii", > + PyInt_AsLong(PySequence_GetItem(obj, 0)), > + PyInt_AsLong(PySequence_GetItem(obj, 1)), > + PyInt_AsLong(PySequence_GetItem(obj, 2)), > + PyInt_AsLong(PySequence_GetItem(obj, 3)), > + PyInt_AsLong(PySequence_GetItem(obj, 4)), > + PyInt_AsLong(PySequence_GetItem(obj, 5)), > + PyInt_AsLong(PySequence_GetItem(obj, 6))); Are you positive those PySequence_GetItem calls will succeed? That they will return Python integers? > + Py_DECREF(obj); > + return result; > +} > + > /* Return new datetime from date/datetime and time arguments. */ > static PyObject * > datetime_combine(PyObject *cls, PyObject *args, PyObject *kw) > @@ -4385,6 +4411,11 @@ > PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " > "(like time.time()).")}, > > + {"strptime", (PyCFunction)datetime_strptime, > + METH_VARARGS | METH_CLASS, > + PyDoc_STR("strptime -> new datetime parsed from a string" > + "(like time.strptime()).")}, > + > {"combine", (PyCFunction)datetime_combine, > METH_VARARGS | METH_KEYWORDS | METH_CLASS, > PyDoc_STR("date, time -> datetime with same date and time fields")}, It probably would help to add some documentation to add to the datetime module documentation. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From mark at freelance-developer.com Sat Jan 1 16:03:08 2005 From: mark at freelance-developer.com (Mark Nenadov) Date: Sat, 01 Jan 2005 16:03:08 -0500 Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> Message-ID: What can you do with Python? Just about anything your heart desires. How hard is Python to learn? I'd say it is near the top of the barrel when it comes to being easy to learn. I'd certainly say that for the most part, you will learn Python much faster than you would learn C#. Can you make a full-screen game with it? Yes, most certainly--providing you have the skill/knowledge to program a full-screen game. But then again that is rarely a matter of having the right programming language, but rather a matter of having the right libraries. -- ~Mark Nenadov On Sat, 01 Jan 2005 21:57:32 +0100, BOOGIEMAN wrote: > Beginners question, but really what can you do with it ? > How hard is Python to learn compared with other languages > (let's say C#). Can you make fullscreen game with it (for example) ? > I've looked at http://www.python.org but nothing concrete there From danperl at rogers.com Fri Jan 28 16:50:39 2005 From: danperl at rogers.com (Dan Perl) Date: Fri, 28 Jan 2005 16:50:39 -0500 Subject: How to test that an exception is raised ? References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> <41fa400b$0$2029$6c56d894@feed0.news.be.easynet.net> <41faa68f$0$17406$4d4efb8e@read.news.be.uu.net> Message-ID: "StepH" wrote in message news:41faa68f$0$17406$4d4efb8e at read.news.be.uu.net... > So why the assertRaises function in unittest ? My goal is to test if an > exception is well raised when a bad filename is passed to the mps2xml > function. It is for functions in which the exception is raised and not caught. You can use the exception mechanism to let the code invoking your function know that something "exceptional" has happened. It means that you "throw" that exception to the invoking code which has to catch it. Maybe the terminology is poorly chosen, but assertRaises does not check whether an exception is raised inside the function but only that an exception is raised (or "thrown", as described by other languages) from inside the function to outside. A function does not "throw" an exception if the exception is caught inside the function. Is that clearer now? In java for instance, functions are actually declared to "throw" an exception if any operation inside the function may throw that exception and the exception is not caught inside the function. If you implement a function A that invokes another function B and B throws an exception of type C, then you must catch the exception C in A or you have to declare A that it "throws C". Hope this helps. Dan From cwilbur at mithril.chromatico.net Sun Jan 9 22:49:30 2005 From: cwilbur at mithril.chromatico.net (Charlton Wilbur) Date: Mon, 10 Jan 2005 03:49:30 GMT Subject: a new Perl/Python a day References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: <87r7ku3pwq.fsf@mithril.chromatico.net> >>>>> "XL" == Xah Lee writes: XL> i'll cross post to comp.lang.perl.misc and comp.lang.python. XL> If you spot mistakes, feel free to correct or discourse here. Error #1: crossposting to those two groups. (Error #2 is implying that you're a Perl expert, but someone else already pointed that out.) Charlton -- cwilbur at chromatico dot net cwilbur at mac dot com From macrocosm at fastmail.fm Thu Jan 6 21:08:06 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Thu, 06 Jan 2005 21:08:06 -0500 Subject: Python Operating System??? In-Reply-To: <0WlDd.8830$5R.1182@newssvr21.news.prodigy.com> References: <10trb0mgiflcj4f@corp.supernews.com> <0WlDd.8830$5R.1182@newssvr21.news.prodigy.com> Message-ID: <41DDEF06.8020506@fastmail.fm> Roose wrote: >What exactly do you mean by an operating system? > >If you don't want to program in C/C++ then you're going to have a hard time. >I don't want to be too discouraging, but with that attitude I doubt you >would get very far. > > Indeed, this is very true. >It sounds like you want to make more of an OS shell -- no? You can >implement a shell on top of any OS and probably do it in a language like >Python. > > He should just build around a linux core or use OS kit (if he is serious/determined). >But if it is going to be a complete OS in pure Python, uh, it won't be! >You'll have to do a lot of stuff in C, at the least interface with the >hardware. > > > > He could use something like O' caml or Oz no? I might be confused, but I understood them to be C/C++ comparable in terms of power and in that they both compile vs. VMs and interpreters (for O' caml this is optional I think). Or what about D? From max at alcyone.com Sun Jan 23 18:46:02 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 23 Jan 2005 15:46:02 -0800 Subject: [perl-python] 20050121 file reading & writing In-Reply-To: References: <1106395060.211314.54530@f14g2000cwb.googlegroups.com> Message-ID: Bob Smith wrote: > To do this efficiently on a large file (dozens or hundreds of megs), you > should use the 'sizehint' parameter so as not to use too much memory: > > sizehint = 0 > mylist = f.readlines(sizehint) It doesn't make any difference. .readlines reads the entire file into memory at once. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Can I lay with you / As your wife -- India Arie From daniel at bowettsolutions.com Wed Jan 26 17:16:57 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Wed, 26 Jan 2005 22:16:57 +0000 Subject: MySQLdb executemany In-Reply-To: References: Message-ID: Daniel Bowett wrote: > I seem to have found a bug/limitation of executemany in MySQLdb. > > I am inserting 3100 records into a database. It works fine and adds them > in about 1 second. > > I went back to the program today and realised i'd missed a field so > added it to the insert statement. This seems to break it if I try to add > all the records in one go. Through trial and error I have realised the > limit is 2786 records in one go. Any more than that I get two different > errors on the executemany statement: > > "MySQL server has gone away" - This occurs if I try to add all 3100 > records in one go. > > "Lost Connection to MySQL server during query" - This happens if I am > near the 2786 threshold. > > Is there a known limit with this function??? > UPDATE ------ The maximum packet size in mysql by default is 1MB. Hence why I was hitting ths problem. http://dev.mysql.com/doc/mysql/en/packet-too-large.html From rkern at ucsd.edu Thu Jan 13 19:41:45 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 13 Jan 2005 16:41:45 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <10ue4s49jl8s6d7@corp.supernews.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> <1105632841.461042.68310@c13g2000cwb.googlegroups.com> <10udfj4c4rgkvcc@corp.supernews.com> <1105651353.769879.229690@f14g2000cwb.googlegroups.com> <10ue4s49jl8s6d7@corp.supernews.com> Message-ID: Jeff Shannon wrote: > (Plus, if this format might be used for RNA sequences as well as DNA > sequences, you've got at least a fifth base to represent, which means > you need at least three bits per base, which means only two bases per > byte (or else base-encodings split across byte-boundaries).... That gets > ugly real fast.) Not to mention all the IUPAC symbols for incompletely specified bases (e.g. R = A or G). http://www.chem.qmul.ac.uk/iubmb/misc/naseq.html -- 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 ola.natvig at infosense.no Tue Jan 4 05:44:04 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Tue, 04 Jan 2005 11:44:04 +0100 Subject: How do I make Windows Application with Python ? In-Reply-To: <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> Message-ID: BOOGIEMAN wrote: > On Mon, 03 Jan 2005 17:19:22 -0500, Peter Hansen wrote: > > >>What do you mean by "Windows Applications"? I'm running >>Python on Windows XP, so every program I write with >>Python is a "Windows application" by my definition. Obviously >>you are using a different one. >> >>(And if you just mean "it has a GUI", then my answer is >>"I use wxPython with Python". There is also Tkinter, and >>other options. Please ask a more specific, detailed question >>to get useful answers.) > > > Well, I programmed a little in MS Visual Studio 2003, and there you have > Console apllication and Windows application (among others). Windows one is > with buttons and other gadgets. So, I want to make applications that > doesn't open console to display result, I want to display it into the > message box. Also, I want to use that application on the computers where > Python isn't installed if you are familliar with the .NET framework you can use the beta release og Python.NET to create your GUI. It gives you access to the Windows Forms controlls in the .NET framework -- -------------------------------------- Ola Natvig infoSense AS / development From asda at sdarta.com Wed Jan 5 23:55:36 2005 From: asda at sdarta.com (worzel) Date: Thu, 6 Jan 2005 12:55:36 +0800 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dca575$0$14347$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <1104985449.245498.215940@z14g2000cwz.googlegroups.com> Message-ID: <41dcc4c7$0$14331$5a62ac22@per-qv1-newsreader-01.iinet.net.au> re: YOU'LL SEE IT'S ADDICTIVE Yes, I know! I am hooked already! Its such a breeze after doing so much Java programming. I just download Jython - the possibilities with this seem incredible. Unlike you, I learned Coldfusion after learning Java first (about 1996). For the sake of a couple of jobs I got on and then some training work as a Macromedia Instructor, it was okay for a while. But, the work dried up, and then the training became in very low demand, so I find myself looking for a new 'second language' - Python is it! (Its in danger of becoming my 'first language' as I am enjoying it so much!) "Luis M. Gonzalez" wrote in message news:1104985449.245498.215940 at z14g2000cwz.googlegroups.com... >> by the way, does anybody want to buy any coldfusion books :) > > I have Sam's Teach Yourself Coldfusion by Charles Mohnike, which I > bought in 2001. > By this time I used to think that I was learning rocket science the > easy way, and thinking about learning php or asp was really scary... > these codes looked very complex for my uninitiated eyes. > However, It was good for grasping the logic of interacting with a > database through sql and making my website dynamic. > Soon I realized that finding a cheap CF hosting wasn't easy at all, and > I started to read about php. > Php is also for web development, but it gave me the basic knowledge to > understand programming. > However, I wanted to learn a more general purpose language and I don't > remember how, I landed in pythonland. > > Let me tell you that I could learn python basics in just a few hours. > Once I got the interpreter running, I couldn't stop! > Just get one of the many tutorial available on the web and start > playing. YOU'LL SEE IT'S ADDICTIVE. > > If you want to start from zero, I suggest Josh Cogliati's beginner > tutorial. > Another good introduction is A Byte of Python (google this), or any of > the ones quoted in Python's web site. > > Learning Python is a good book too (especially the second edition). > Enjoy! > From km at mrna.tn.nic.in Thu Jan 20 05:10:06 2005 From: km at mrna.tn.nic.in (km) Date: Thu, 20 Jan 2005 15:40:06 +0530 Subject: inbuilt function buffer() Message-ID: <20050120101006.GA1496@mrna.tn.nic.in> Hi all, I which context is the inbuilt function buffer() used ? regards, KM From bokr at oz.net Tue Jan 11 05:25:59 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 11 Jan 2005 10:25:59 GMT Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <1105381339.922714.23200@c13g2000cwb.googlegroups.com> <1oFEd.71967$Jk5.45632@lakeread01> Message-ID: <41e39978.557378407@news.oz.net> On Mon, 10 Jan 2005 21:15:50 -0500, Tim Peters wrote: >... > >[Anna] >>> BTW - I am *quite* happy with the proposal for "where:" syntax - I >>> think it handles the problems I have with lambda quite handily. > >[Steve Holden] >> Whereas I find it to be an excrescence, proving (I suppose) that one >> man's meat is another person's poison, or something. > >I've been waiting for someone to mention this, but looks like nobody >will, so I'm elected. Modern functional languages generally have two >forms of local-name definition, following common mathematical >conventions. "where" was discussed here. The other is "let/in", and Well, I did say it reminded me of some kind of weird let ;-) http://groups-beta.google.com/groups?q=%20Reminds%20me%20of%20some%20kind%20of%20weird%20let&hl=en&lr=&sa=N&tab=wg >seems a more natural fit to Python's spelling of block structure: > > let: > suite > in: > suite > >There's no restriction to expressions here. I suppose that, like the >body of a class, the `let` suite is executed starting with a >conceptually empty local namespace, and whatever the suite binds to a >local name becomes a temporary binding in the `in` suite (like >whatever a class body binds to local names becomes the initial value >of the class __dict__). So, e.g., > > i = i1 = 3 > let: > i1 = i+1 > from math import sqrt > in: > print i1, sqrt(i1) > print i1, > print sqrt(i1) > >would print > > 4 2 > 3 > >and then blow up with a NameError. > >LIke it or not, it doesn't seem as strained as trying to pile more >gimmicks on Python expressions. I could get to like it ;-) Hm, a little extension to this could provide a new way to populate closure variables, and also (never mind, one thing at a time ;-) #1: If you gave your 'let' above a list of 'externs' that can be rebound from within the let. E.g., let(sqrt): the effect in your example would be to eliminate the NameError you mention. The compiler would make an entry for sqrt in the enclosing namespace, and generate code to bind/rebind if assigned from within the let. This would be an interesting way to create closure bindings: let(foo): preset = 'another way to make closure vairables' in: def foo(): return preset ... print foo() #2: Making the in: suite callable as a light weight function with no arguments. An optional binding name after in would bind like def and create a persistent named callable instead of just an implicitly called anonymous suite. Then you could define the same effective foo by let: preset = 'another way to make closure vairables' in foo: return preset # return now legal ... print foo() The combination would work like: let(rebindable): factor = 10 in bar: rebindable *= factor rebindable = 2 bar() print rebindable # => 20 rebindable += 5 bar() print rebindable # => 250 You can see this could be used nicely in case functionality, with a dict of named in-functions. What do you think? Regards, Bengt Richter From http Fri Jan 7 07:39:44 2005 From: http (Paul Rubin) Date: 07 Jan 2005 04:39:44 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> <1gq0odo.1x1uyr2kgdgiyN%aleaxit@yahoo.com> Message-ID: <7xu0ptjtv3.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > Paul Rubin wrote: > > Really, I just want to buy a new > > computer, turn it on, and have everything there. That's generally > > impossible without running satanware from Redmond > > The princes of insufficient light from Cupertino will in fact be very > happy to sell you such computers, I actually do sometimes advise nontechnical people to buy those things and run the installed software since GNU/Linux is really not there yet with a number of types of apps, and is more of a maintenance headache. But if I bought one myself, I'd feel oblige to reformat the hard drive to get rid of the darkware (= no source) just like I do with a PC. I've played with that notion at different times since the hardware is actually rather nice. > and _their_ definition of "everything" > includes a bit more than the Redmonders' (e.g., Python is there, perl is > there, gcc is there, so is Apache, a good development GUI-based IDE, Oh cool, you mean emacs/gud/gdb. > emacs, a solid firewall, a _usable_ Terminal/commandline program to run > bash or tcsh on, ...), Yes, shell mode in Emacs works fine, I haven't had much need to use anything else. Xterm also works. > though it's no doubt still missing many pieces > that you or I might want as parts of *our* "everything" (gvim rather > than just vim, I'm not sure what the difference is supposed to be... I remember someone explaining "you can't spell vile without vi". > GUI/IDEs for Python, I remember there was a gud interface for Python but it didn't work pretty well. There's also IDLE which is pretty crude and flaky. I think I'll just wait for Pypy deployment before worrying about this situation too much. Is there something else I can download? > Python add-ons such as numarray, > gmpy, ctypes, ...) -- all of those you still have to download and > install, just as you would for the satanware. That's unfortunate, that stuff should be included with Python. From ncoghlan at iinet.net.au Tue Jan 25 08:53:26 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 25 Jan 2005 23:53:26 +1000 Subject: delay and force in Python In-Reply-To: References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> <41EE6658.8000409@iinet.net.au> Message-ID: <41F64F56.3080107@iinet.net.au> Peter Otten wrote: > Nick Coghlan wrote: > > >>>Py> print islice((x for x in xrange(1, 996) if x % 2 == 0), 1, 2).next() >>>4 >> >>Wouldn't it be nice if this could be spelt: >> >>print (x for x in xrange(1, 996) if x % 2 == 0)[2] >> >>Well, I just put a patch on SF to enable exactly that: >>http://www.python.org/sf/1108272 > > > I like it. Of course you always have to bear in mind that one giant leap for > a list could be _many_ small steps for an iterator. Indeed. The main cases I am thinking of involve picking off the first few items of an iterator (either to use them, or to throw them away before using the rest). And if an app actually *needs* random access, there's a reason lists still exist ;) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steven.bethard at gmail.com Wed Jan 19 12:17:00 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 19 Jan 2005 10:17:00 -0700 Subject: Dictionary keys (again) (was Re: lambda) In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Nick Coghlan wrote: > For a 'mutable key' to make sense, the following: > > lst = [] > dct = {l: "Hi!"} > print dct[[]] > print dct[lst] > lst.append(1) > print dct[[1]] > print dct[lst] > > Should print: > Hi > Hi > Hi > Hi And here's an implementation that does so: py> class sillydict(dict): ... def __getitem__(self, key): ... items = self.items() ... self.clear() ... self.update(items) ... return super(sillydict, self).__getitem__(key) ... py> class sillylist(list): ... def __hash__(self): ... return hash(tuple(self)) ... py> lst = sillylist([]) py> dct = sillydict({lst: "Hi!"}) py> print dct[sillylist([])] Hi! py> print dct[lst] Hi! py> lst.append(1) py> print dct[sillylist([1])] Hi! py> print dct[lst] Hi! Of course, as noted by the classes themselves, they're silly. ;) But as long as you don't mind rehashing the dict each time the dict is accessed ;) you can get sane behavior even in the presence of mutable keys. Steve From spamerom at niet.com Sat Jan 8 10:06:30 2005 From: spamerom at niet.com (JZ) Date: Sat, 8 Jan 2005 16:06:30 +0100 Subject: The best way to do web apps with Python? References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <12tz3aez24pv4.i8nqbs9uqlg1$.dlg@40tude.net> Dnia Sat, 8 Jan 2005 21:11:49 +0800, worzel napisa?(a): > What is the best way to web developemnt with Python? Hmm. :) I prefer http://cherrypy.org + http://cheetahtemplate.org/. Very easy to learn and develop, yet powerfull. > Is there anything close to PHP style in-page script > placement that can create and use other Python objects? Check http://spyce.sourceforge.net or http://nick.borko.org/pse -- JZ ICQ: 6712522 http://zabiello.om From premshree.pillai at gmail.com Sat Jan 22 02:43:49 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Sat, 22 Jan 2005 13:13:49 +0530 Subject: Event details changed: Bangalore Python January Meetup In-Reply-To: <20050121171306.16111.qmail@web40729.mail.yahoo.com> References: <8548c5f3050121084976c0ac8a@mail.gmail.com> <20050121171306.16111.qmail@web40729.mail.yahoo.com> Message-ID: On Fri, 21 Jan 2005 09:13:06 -0800 (PST), Swaroop C H wrote: > > Read Anand's email!! Especially the part about 'well-known Python community > members' ... ha ha, I can't stop laughing ;) :) Hey, in case I forget (I have a terrible memory), message me! :) > > --- Anand Pillai wrote: > > > Yes. I am quite happy with the response that we received. I also noted that > > four members joined the group today which is quite an achievement :-). > > The membership has reached 20 in less than a month, 21 days to be > > exact, i.e about one member joining every day on an average. That is > > quite a tremendous response which I did not expect to get initially > > :-). I guess that the timing was somehow spot on perhaps. > > > > It is encouraging for the group that two well-known Python community > > members namely yourself and Premshree are part of it. I got Prem's > > RSVP > > a few hours back. Bernhardt, the german guy called me up and said he > > is not coming since he has to attend Mysore LUG meeting in the > > weekend. Also I don't see Pradeep (btbytes) saying yes. Is he going to > > come? > > > > That makes about 8 confirmed attendees. Let us hope that we get some > > more unexpected turn out tomorrow. > > > > See ya at Ebony. > > > > -Anand > > > > On Fri, 21 Jan 2005 08:09:34 -0800 (PST), Swaroop C H > > wrote: > > > Hello Anand, > > > > > > Looks like around 10 people are coming. Good response :) > > > > > > http://www.swaroopch.info/archives/2005/01/21/python-meetup-in-bangalore-tomorrow/ > > > > > > See you tomorrow evening. > > > > > > Regards, > > > Swaroop > > > > > > --- Anand Pillai wrote: > > > > > > > As you requested, below is a copy of the email you just sent. > > > > Had you *not* requested a copy, based on the audience of the > > > > email you selected, you *still* would have received the email. > > > > ----------------------------------------------------------------- > > > > > > > > Your Organizer, Anand Pillai, sent the following message to > > > > some members of Bangalore Python Meetup Group: > > > > > > > > I have booked a table for 8 at the Ebony Restaurant, Barton > > > > Center tomorrow at 7:30 pm. This requires a small change in the > > > > meeting timing. Please arrive by 7:15 - 7:30 pm at Barton > > > > Center and go directly to Ebony on the top floor. > > > > > > > > Barton Center is a prominent building on M.G Road a few yards > > > > after Higgin Bothams & Indian Coffee House, when you walk from > > > > the Brigade road end towards Cubbon Park end. It has a fast > > > > food joint at the entrance , which is busy most of the time. In > > > > case you come early, please wait there. However do remember to > > > > walk up towards Ebony by about 7:15 - 7:30 pm. Ask the hotel > > > > staff for the tables reserved by Anand Pillai. > > > > > > > > In case you get stuck or confused, call the number 9886483821 > > > > for directions. > > > > > > > > If less than five people turn out by 8:00 pm the meeting will > > > > be cancelled. > > > > > > > > Hope to see all of you at Ebony tomorrow! > > > > > > > > -Anand > > > > > > > > P.S: The "official" mail is below. > > > > -==============================================- > > > > > > > > I've updated this event. For more details, see the full listing: > > > > http://python.meetup.com/158/events/3974233/" > > > > > > > > If the change affects your plans to attend, please take a > > > > moment to update your RSVP. (You can RSVP 'No' or 'Maybe' as > > > > well as 'Yes'.)" > > > > > > > > You can always get in touch with me through the 'Contact > > > > Organizer' feature on the Meetup.com website: > > > > http://python.meetup.com/158/suggestion/" > > > > ----------------------------------------------------------------- > > > > > > > > To visit Bangalore Python Meetup Group, go here: > > > > http://python.meetup.com/158/ > > > > > > > > Did this email end up in your spam/junk/bulk folder? Add > > > > info at meetup.com to your address book to ensure that you receive > > > > all future messages in your Inbox. > > > > > > > > ----------------------------------------------------------------- > > > > HOW TO UNSUBSCRIBE > > > > You received this message because you registered this email > > > > address at Meetup.com. > > > > > > > > To remove yourself from individual Meetup Groups and their > > > > related emails, click the link below and select 'Remove > > > > yourself' under the name of the appropriate Group: > > > > http://www.meetup.com/account/ > > > > > > > > To unsubscribe from ALL your Meetup Groups and the Meetup.com > > > > service as a whole, click here: > > > > http://www.meetup.com/account/remove/ > > > > ----------------------------------------------------------------- > > > > > > > > > > > > > > > > > ===== > > > Swaroop C H > > > Blog: http://www.swaroopch.info > > > Book: http://www.byteofpython.info > > > > > > > > > -- > > Anand B Pillai, > > Techical Specialist, > > SETLabs, INFOSYS Technologies, > > Electronics City, > > Hosur Road, Bangalore - 560100. > > > > > ===== > Swaroop C H > Blog: http://www.swaroopch.info > Book: http://www.byteofpython.info > -- Premshree Pillai http://www.livejournal.com/~premshree From craig at postnewspapers.com.au Fri Jan 28 08:24:48 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 28 Jan 2005 21:24:48 +0800 Subject: example needed: sip + Qt In-Reply-To: References: Message-ID: <1106918688.3941.51.camel@albert.localnet> On Fri, 2005-01-28 at 13:30 +0100, Uwe Mayer wrote: > Hi, > > can someone provide me with a running example for subclassing QWidget (or > something similarly simple) in C++ and then creating SIP (4.x+) bindings > for in for Python (2.3+)? Out of curiosity, would this be for an extension module used in an embedded Python interpreter, or for plain extension module for use with a standalone interpreter? I'm afraid I can't help you with your specific problem, though I'll be interested to hear if anybody here does know. If you don't have any luck here, try the PyQt/PyKDE list (and search its archives first). -- Craig Ringer From sp1d3rx at gmail.com Wed Jan 26 18:16:36 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 26 Jan 2005 15:16:36 -0800 Subject: exclude binary files from os.walk In-Reply-To: References: <41f8167b$0$8648$a1866201@visi.com> Message-ID: <1106781396.336126.319540@f14g2000cwb.googlegroups.com> you might want to look up the 'isascii' function... i.e. - can be represented using just 7-bits. From http Sat Jan 22 23:08:56 2005 From: http (Paul Rubin) Date: 22 Jan 2005 20:08:56 -0800 Subject: [OT] XML design intent ... further musings References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> <41F2C840.2050304@comcast.net> Message-ID: <7xhdl8pz1j.fsf@ruckus.brouhaha.com> Stephen Waterbury writes: > I should note that I have to deal with XML a lot, but always > kicking and screaming (though much less now because of Fredrik's > Elementtree package ;). Thanks, Fredrik and Peter, for the > references. ;) I love this old rant about XML: http://groups-beta.google.com/group/comp.lang.lisp/msg/9a30c508201627ee From jeff at ccvcorp.com Tue Jan 25 19:46:54 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 25 Jan 2005 16:46:54 -0800 Subject: Browsing text ; Python the right tool? In-Reply-To: References: Message-ID: <10vdpohm549g44a@corp.supernews.com> Paul Kooistra wrote: > 1. Does anybody now of a generic tool (not necessarily Python based) > that does the job I've outlined? > 2. If not, is there some framework or widget in Python I can adapt to > do what I want? Not that I know of, but... > 3. If not, should I consider building all this just from scratch in > Python - which would probably mean not only learning Python, but some > other GUI related modules? This should be pretty easy. If each record is CRLF terminated, then you can get one record at a time simply by iterating over the file ("for line in open('myfile.dat'): ..."). You can have a dictionary of classes or factory functions, one for each record type, keyed off of the 2-character identifier. Each class/factory would know the layout of that record type, and return a(n) instance/dictionary with fields separated out into attributes/items. The trickiest part would be in displaying the data; you could potentially use COM to insert it into a Word or Excel document, or code your own GUI in Python. The former would be pretty easy if you're happy with fairly simple formatting; the latter would require a bit more effort, but if you used one of Python's RAD tools (Boa Constructor, or maybe PythonCard, as examples) you'd be able to get very nice results. Jeff Shannon Technician/Programmer Credit International From aahz at pythoncraft.com Fri Jan 28 16:24:30 2005 From: aahz at pythoncraft.com (Aahz) Date: 28 Jan 2005 16:24:30 -0500 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Message-ID: In article , Tim Peters wrote: >[grahamd at dscpl.com.au] >> >> Who are the appropriate people to report security problems to >> in respect of a module included with the Python distribution? >> I don't feel it appropriate to be reporting it on general mailing >> lists. > >The Python project has no non-public resources for this. Filing a bug >report on SourceForge is the usual approach. If you must, you could >send email directly to Guido . He may or may >not have time to follow up on it; public disclosure is the norm in >this project. Be forewarned that despite that he currently works for >a security startup, his threshold for "security panic" is very high. You mean s/despite/because/ don't you? ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From rm at rm.net Sat Jan 22 14:31:34 2005 From: rm at rm.net (rm) Date: Sat, 22 Jan 2005 20:31:34 +0100 Subject: What YAML engine do you use? In-Reply-To: <46ednYMe9-q4Om_cRVn-tQ@comcast.com> References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> Message-ID: <35fo4iF4maov2U1@individual.net> Doug Holton wrote: > What do you expect? YAML is designed for humans to use, XML is not. > YAML also hasn't had the backing and huge community behind it like XML. > XML sucks for people to have to write in, but is straightforward to > parse. The consequence is hordes of invalid XML files, leading to > necessary hacks like the mark pilgrim's universal rss parser. YAML > flips the problem around, making it harder perhaps to implement a > universal parser, but better for the end-user who has to actually use > it. More people need to work on improving the YAML spec and > implementing better YAML parsers. We've got too many XML parsers as it is. 100% right on, stuff (like this)? should be easy on the users, and if possible, on the developers, not the other way around. But developers come second. Now, I didn't check the specs, they might be difficult, they might be incorrect, maybe their stated goal is not reached with this implementation of their idea. But I'd love to see a generic, pythonic data format. bye, rm From mmokrejs at ribosome.natur.cuni.cz Mon Jan 17 08:14:24 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-2?Q?Martin_MOKREJ=A9?=) Date: Mon, 17 Jan 2005 14:14:24 +0100 Subject: Writing huge Sets() to disk In-Reply-To: References: Message-ID: <41EBBA30.10303@ribosome.natur.cuni.cz> Steve Holden wrote: > Martin MOKREJ? wrote: > >> Hi, >> could someone tell me what all does and what all doesn't copy >> references in python. I have found my script after reaching some >> state and taking say 600MB, pushes it's internal dictionaries >> to hard disk. The for loop consumes another 300MB (as gathered >> by vmstat) to push the data to dictionaries, then releases >> little bit less than 300MB and the program start to fill-up >> again it's internal dictionaries, when "full" will do the >> flush again ... >> >> The point here is, that this code takes a lot of extra memory. >> I believe it's the references problem, and I remeber complains >> of frineds facing same problem. I'm a newbie, yes, but don't >> have this problem with Perl. OK, I want to improve my Pyhton >> knowledge ... :-)) >> > Right ho! In fact I suspect you are still quite new to programming as a > whole, for reasons that may become clear as we proceed. > >> >> >> >> def push_to_disk(self): >> _dict_on_disk_tuple = (None, self._dict_on_disk1, >> self._dict_on_disk2, self._dict_on_disk3, self._dict_on_disk4, >> self._dict_on_disk5, self._dict_on_disk6, self._dict_on_disk7, >> self._dict_on_disk8, self._dict_on_disk9, self._dict_on_disk10, >> self._dict_on_disk11, self._dict_on_disk12, self._dict_on_disk13, >> self._dict_on_disk14, self._dict_on_disk15, self._dict_on_disk16, >> self._dict_on_disk17, self._dict_on_disk18, self._dict_on_disk19, >> self._dict_on_disk20) The None above is there just as I didn't want to evaluate all the time something like "x+1": for x in _dict_on_disk_tuple: key = .... newdict[x+1][key] = ... This None doesn't hurt me, then x contains exactly the value I need several times in the loop ... > > > It's a bit unfortunate that all those instance variables are global to > the method, as it means we can't clearly see what you intend them to do. > However ... > > Whenever I see such code, it makes me suspect that the approach to the > problem could be more subtle. It appears you have decided to partition > your data into twenty chunks somehow. The algorithm is clearly not coded > in a way that would make it easy to modify the number of chunks. No, it's not, but that's not the speed problem, really. ;) > > [Hint: by "easy" I mean modifying a statement that reads > > chunks = 20 > > to read > > chunks = 40 > > for example]. To avoid this, we might use (say) a list of temp edicts, > for example (the length of this could easily then be parameterized as > mentioned. So where (my psychic powers tell me) your __init__() method > currently contains > > self._dict_on_disk1 = something() > self._dict_on_disk2 = something() > ... > self._dict_on_disk20 = something() Almost. They are bsddb dictionary files. > > I would have written > > self._disk_dicts = [] > for i in range(20): > self._disk_dicts.append(something) > > Than again, I probably have an advantage over you. I'm such a crappy > typist I can guarantee I'd make at least six mistakes doing it your way :-) Originally I had this, I just to get of one small list. ;) > >> _size = 0 > > > What with all these leading underscores I presume it must be VERY > important to keep these object's instance variables private. Do you have > a particular reason for that, or just general Perl-induced paranoia? :-) See below. ;) > >> # >> # sizes of these tmpdicts range from 10-10000 entries for each! >> for _tmpdict in (self._tmpdict1, self._tmpdict2, >> self._tmpdict3, self._tmpdict4, self._tmpdict5, self._tmpdict6, >> self._tmpdict7, self._tmpdict8, self._tmpdict9, self._tmpdict10, >> self._tmpdict11, self._tmpdict12, self._tmpdict13, self._tmpdict14, >> self._tmpdict15, self._tmpdict16, self._tmpdict17, self._tmpdict18, >> self._tmpdict19, self._tmpdict20): >> _size += 1 >> if _tmpdict: >> _dict_on_disk = _dict_on_disk_tuple[_size] >> for _word, _value in _tmpdict.iteritems(): >> try: >> _string = _dict_on_disk[_word] >> # I discard _a and _b, maybe _string.find(' ') >> combined with slice would do better? >> _abs_count, _a, _b, _expected_freq = >> _string.split() >> _abs_count = int(_abs_count).__add__(_value) >> _t = (str(_abs_count), '0', '0', '0') >> except KeyError: >> _t = (str(_value), '0', '0', '0') >> >> # this writes a copy to the dict, right? >> _dict_on_disk[_word] = ' '.join(_t) >> >> # >> # clear the temporary dictionaries in ourself >> # I think this works as expected and really does release memory >> # >> for _tmpdict in (self._tmpdict1, self._tmpdict2, >> self._tmpdict3, self._tmpdict4, self._tmpdict5, self._tmpdict6, >> self._tmpdict7, self._tmpdict8, self._tmpdict9, self._tmpdict10, >> self._tmpdict11, self._tmpdict12, self._tmpdict13, self._tmpdict14, >> self._tmpdict15, self._tmpdict16, self._tmpdict17, self._tmpdict18, >> self._tmpdict19, self._tmpdict20): >> _tmpdict.clear() >> > There you go again with that huge tuple. You just like typing, don't > you? You already wrote that one out just above. Couldn't you have > assigned it to a local variable? Well, in this case I was looking what's slow, and wanted to avoid one slice on a referenced tuple. ;) > > By the way, remind me again of the reason for the leading None in the > _dict_on_disk_tuple, would you? I was told to code this way - to make it clear that they are internal/local to the function/method. Is it wrong or just too long? ;-) > > The crucial misunderstanding here might be the meaning of "release > memory". While clearing the dictionary will indeed remove references to > the objects formerly contained therein, and thus (possibly) render those > items subject to garbage collection, that *won't* make the working set > (i.e. virtual memory pages allocated to your process's data storage) any > smaller. The garbage collector doesn't return memory to the operating > system, it merely aggregates it for use in storing new Python objects. Well, it would be fine, but I thought python returns that immediately. >> The above routine doesn't release of the memory back when it >> exits. >> > And your evidence for this assertion is ...? Well, the swapspace reserved grows during that posted loop. Tell me, there were about 5 local variable in that loop. Their contents while the loop iterates get constantly updated, so they shouldn't need more and more space, right? But they do! It's 300MB. it seems to me like the variable always points to a new value, but the old value still persists in the memory not only the the source tmpdictionary, but also somewhere else as it used to be referenced by that local variable. I'd say those 300MB account for those references. Most of the space is returned to the system (really, swap get's freed) when the loop get to the point where the dictionaries are cleared. More or less same behaviour I see of course even without swap, it just happened to me to be easily visible with the swap problem. > >> >> See, the loop takes 25 minutes already, and it's prolonging >> as the program is in about 1/3 or 1/4 of the total input. >> The rest of my code is fast in contrast to this (below 1 minute). >> >> -rw------- 1 mmokrejs users 257376256 Jan 17 11:38 diskdict12.db >> -rw------- 1 mmokrejs users 267157504 Jan 17 11:35 diskdict11.db >> -rw------- 1 mmokrejs users 266534912 Jan 17 11:28 diskdict10.db >> -rw------- 1 mmokrejs users 253149184 Jan 17 11:21 diskdict9.db >> -rw------- 1 mmokrejs users 250232832 Jan 17 11:14 diskdict8.db >> -rw------- 1 mmokrejs users 246349824 Jan 17 11:07 diskdict7.db >> -rw------- 1 mmokrejs users 199999488 Jan 17 11:02 diskdict6.db >> -rw------- 1 mmokrejs users 66584576 Jan 17 10:59 diskdict5.db >> -rw------- 1 mmokrejs users 5750784 Jan 17 10:57 diskdict4.db >> -rw------- 1 mmokrejs users 311296 Jan 17 10:57 diskdict3.db >> -rw------- 1 mmokrejs users 295895040 Jan 17 10:56 diskdict20.db >> -rw------- 1 mmokrejs users 293634048 Jan 17 10:49 diskdict19.db >> -rw------- 1 mmokrejs users 299892736 Jan 17 10:43 diskdict18.db >> -rw------- 1 mmokrejs users 272334848 Jan 17 10:36 diskdict17.db >> -rw------- 1 mmokrejs users 274825216 Jan 17 10:30 diskdict16.db >> -rw------- 1 mmokrejs users 273104896 Jan 17 10:23 diskdict15.db >> -rw------- 1 mmokrejs users 272678912 Jan 17 10:18 diskdict14.db >> -rw------- 1 mmokrejs users 260407296 Jan 17 10:13 diskdict13.db >> >> Some spoke about mmaped files. Could I take advantage of that >> with bsddb module or bsddb? >> > No. I'll ask in a different way? How do you update huge files, when it has to happen say thousand times? > >> Is gdbm better in some ways? Recently you have said dictionary >> operations are fast ... Once more. I want to turn of locking support. >> I can make the values as strings of fixed size, if mmap() would be >> available. The number of keys doesn't grow much in time, mostly >> there are only updates. >> > Also (possibly because I come late to this thread) I don't really > understand your caching strategy. I presume at some stage you look in > one of the twenty temp dicts, and if you don;t find something you read > it back in form disk? I parse some input file, get one list containing mixed-in words of sizes 1 to 20. The *cache* here means once it get's some amount of data in the list, the list is converted to dictionary in memory, as there are many repeated items in th list. Then, I copy the contents of that temporary dictionary to those dictionaries located on disk (the code moving the contents of temporary dictionaries to those on disk is the one posted). > > This whole thing seems a little disorganized. Perhaps if you started > with a small dataset your testing and development work would proceed > more quickly, and you'd be less intimidated by the clear need to > refactor your code. I did and the bottlenecks where in the code. Now the bottleneck is constantly re-writing almost 20 files of filesizes about 200MB and up. OK. I think I'll do it another way. I'll just generate words of one size per each loop, flush the results to disk, and loop back. With this scenario, I'll read 20 times the input, which seems to be less expensive then having 20 huge dictionaries on disk constantly updated. Possibly I won't be able to keep the dictionary in memory and flush it just once to disk, as the size might be about gigabyte ...? Don't know, probably will have to keep the *cache* method mentioned above, and update the files several times. This is the part I can refactor, but I'll overwrite those huge files maybe only 20x or 200x instead of 20000 times. Still, I'll search for a way to update them efficiently. Maybe even mmaped plaintextfiles would be updated more efficiently than this .db file. Hmm, will probably have to keep in memory position of the fixed-sized value in such a file. Thanks for help! Martin From invalidemail at aerojockey.com Tue Jan 11 06:06:48 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 11 Jan 2005 03:06:48 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <1105381339.922714.23200@c13g2000cwb.googlegroups.com> <1oFEd.71967$Jk5.45632@lakeread01> Message-ID: <1105441608.304627.271340@f14g2000cwb.googlegroups.com> Tim Peters wrote: > ... > > [Anna] > >> BTW - I am *quite* happy with the proposal for "where:" syntax - I > >> think it handles the problems I have with lambda quite handily. > > [Steve Holden] > > Whereas I find it to be an excrescence, proving (I suppose) that one > > man's meat is another person's poison, or something. > > I've been waiting for someone to mention this, but looks like nobody > will, so I'm elected. Modern functional languages generally have two > forms of local-name definition, following common mathematical > conventions. "where" was discussed here. The other is "let/in", and > seems a more natural fit to Python's spelling of block structure: > > let: > suite > in: > suite Ah. During that discussion, I did kind of suggest this (spelling it where...do) as an alternative to where (thinking I was clever). Only no one seemed to take notice, probably because I suggested something more poignant at the same time. Now I see why I liked the idea so much; it was exactly like let forms. > There's no restriction to expressions here. I suppose that, like the > body of a class, the `let` suite is executed starting with a > conceptually empty local namespace, and whatever the suite binds to a > local name becomes a temporary binding in the `in` suite (like > whatever a class body binds to local names becomes the initial value > of the class __dict__). So, e.g., > > i = i1 = 3 > let: > i1 = i+1 > from math import sqrt > in: > print i1, sqrt(i1) > print i1, > print sqrt(i1) > > would print > > 4 2 > 3 > > and then blow up with a NameError. > > LIke it or not, it doesn't seem as strained as trying to pile more > gimmicks on Python expressions. Indeed. -- CARL BANKS From apardon at forel.vub.ac.be Tue Jan 18 08:28:00 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2005 13:28:00 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-18, Nick Coghlan schreef : > Antoon Pardon wrote: >> More specific the Decimal class is mutable and usable as dict key. > > It's *meant* to be immutable though. The fact that we used __slots__ instead of > __setattr__ to implement the immutability, so you *can* overwrite the slot > variables if you really want to is merely an artifact of the current Python > implementation. > > The limited mutability bug will disappear in Python 2.5, so it's not a good > example of a 'mutable' dict key (especially given that the only way to mutate it > is to modify private variables directly). > > And, as I've stated previously, if the issue of sane mutable keys in > dictionaries and sets really bugs you so much - implement identity_dict and > identity_set in C and lobby for their inclusion in the collections module. I'm not bugged by its absence in Python. I'm bugged by the attitude about them. But anyway I'm thinking about implementing a safe dictionary that will copy whenever it would otherwise allow the risk of mutating a key. > On the more general point of "don't use mutable objects with non-identity based > comparisons as dictionary keys", try teaching students for a while (or listen to > those who have): What kind of students? I have implemented a hash table when I was a student and its implementation allowed the use of 'mutable' objects as a key without a problem. It simply always made copies when appropiate and didn't allow external access to the keys. So although the key objects were 'mutable' there was no way a user could accidently mutate a key. So don't use a mutable as a dictionary key isn't so much a dictionary limitation in general but a specific limitation of the python implementation. And yes I understand, the current implenatation is the result of the fact that the same dictionaries are used internally for variables in scopes and attributes in objects and the fact that no copies are involved gives a boost to performance. But it could be argued that providing these same dictionaries with those semantics to the users was a premature optimisation. > When stating useful general principles, it is never, ever worth it to get into > the quibbly little details about exceptions to the principle. If students ask, > admit that they exist, but point out that the exceptions are rare, and not worth > worrying about at that point in their learning. But don't use mutable keys is not a general principle. It is a principle introduced by the limitations of the python implementations. I don't like it when a good rule of thumb because of implementation limitations is sold as a general principle. -- Antoon Pardon From fredrik at pythonware.com Fri Jan 14 05:35:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 14 Jan 2005 11:35:07 +0100 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com><7xsm559heo.fsf@ruckus.brouhaha.com><7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: Antoon Pardon wrote: >> no, expressions CAN BE USED as statements. that doesn't mean >> that they ARE statements, unless you're applying belgian logic. > > No I am applying set logic. Any string that is in the set of > valid expressions is also in the set of valid statements. since you're arguing that one concept is identical to another concept, that operation has to work in both directions. > Like any animal that is in the set of dogs is also in the > set of mamals. and all mammals are dogs? it this a language problem? do you have problems parsing the statements you reply to? even when someone explictly says "Given that we are having this discussion in the context of", you chose to ignore that context. what's wrong with you? From flamesrock at gmail.com Sat Jan 1 20:24:39 2005 From: flamesrock at gmail.com (flamesrock) Date: 1 Jan 2005 17:24:39 -0800 Subject: Confusion About Classes In-Reply-To: References: <1104194131.792545.140560@z14g2000cwz.googlegroups.com> <1104213408.450534.205270@z14g2000cwz.googlegroups.com> <1104370779.827348.205400@c13g2000cwb.googlegroups.com> <1104388925.645630.168900@c13g2000cwb.googlegroups.com> Message-ID: <1104629079.456741.116020@z14g2000cwz.googlegroups.com> Well, I took a short excursion into xml for a different part of the program, but the class is now finished!! (source below) I have a few more questions for you guys. 1)If I set self.serverConfig = file(os.path.join('configuration','score.conf'), 'w') and then go self.serverConfig.close(), is there a way to open it in read mode without calling the filename directly? Like self.serverConfig.open('r') -which doesn't work BTW- instead of open(os.path.join('configuration','score.conf'), 'r')? Using open(self.ServerConfig, 'r') doesn't seem to work either. 2) A problem arose when converting the encoded file back into a string for decoding; the \n's seemed to have dissapeared so it returned an error when I tried to decode. Is there a way to stop python from disposing of those those characters before writing to file? 3) Is there way to retrieve the timestamp of a file via ftp? >>There are NAMES, thats why there are NAMESPACES. >>A name is just a reference or 'handle' to an object, because..... >>everything in python is an OBJECT,(except for names, they are just >>names). And >>That being said, understanding this part of Python can aid enormously in >>working with the language. If you'd like to think of it in C terms, >>basically every 'name' in Python is a pointer to a PyObject, and 'names' >>(as pointers) are always passed by value -- that is, you get a copy of >>the pointer, but not a copy of the object. Ahhhhh...now *that* makes sense. So dynamically typed variables aren't variables at all...but just another term for pointers? cool, I like that. And thanks for the examples, guys. Its coming together and I'm starting to actually 'get it' :) So name mangling basically follows the rules of private and public in Java? (I have limited experience in java so don't quote me on that.) (Google groups isn't displaying the spaces correctly, so I added four *'s = 1 four space indentation..) import ftplib, ezPyCrypto, ConfigParser import traceback, sys, os #------------------------------------------------------------------------------- class create_server: ****'''Create a create_server object whenever a new server is to be added to ****the SCORE network.''' ****def __init__(self, absCFGpath, domain, servername, master_ftpUSER, ****master_ftpPASS, score_ftpUSER='anonymous', score_ftpPASS='anonymous', ****scorecontact='admin at simcitysphere.com', maxusers='unlimited', httpport='80', ****ftpport='21', passivemode=True): ********self.domain = domain ********self.httpport = httpport ********self.ftpport = ftpport ********self.servername = servername ********self.maxusers = maxusers ********self.scorecontact = scorecontact ********try: ************self.serverConfig = file(os.path.join('configuration','score.conf'), 'w') ********except: ************os.mkdir('configuration') ************self.serverConfig = file(os.path.join('configuration','score.conf'), 'w') ********self.absCFGpath = absCFGpath ********self.master_ftpUSER = master_ftpUSER ********self.master_ftpPASS = master_ftpPASS ********self.score_ftpUSER = score_ftpUSER ********self.score_ftpPASS = score_ftpPASS ********self.passivemode = passivemode ********self.parser = ConfigParser.ConfigParser() #------------------------------------------------------------------------------- ****def createUniversalConfig(self): ********'''Creates the SCORE servers main configuration file.''' ********self.parser.add_section('score') ********self.parser.set('score', 'domain', self.domain) ********self.parser.set('score', 'servername', self.servername) ********self.parser.set('score', 'httpport', self.httpport) ********self.parser.set('score', 'ftpport', self.ftpport) ********self.parser.set('score', 'maxusers', self.maxusers) ********self.parser.set('score', 'scorecontact', self.scorecontact) ********self.parser.write(self.serverConfig) ********self.serverConfig.close() ********return open(os.path.join('configuration','score.conf'), 'r') #------------------------------------------------------------------------------- ****def editUniversalConfig(self, section, key, value): ********'''edit the SCORE servers main configuration file.''' ********self.serverConfig = open(os.path.join('configuration','score.conf'), 'w') ********self.parser.set(section, key, value) ********self.serverConfig.close #------------------------------------------------------------------------------- ****def createUSERfile(self): ********'''Creates an encrypted ascii public ftp password file that clients use ********to decode after logging in''' ********crypt = ezPyCrypto.key() ********userFile = file(os.path.join('configuration','uFile.enc'), 'w') ********userFile.write(crypt.encStringToAscii(self.score_ftpUSER)) ********userFile.close() ********userFile = open(os.path.join('configuration','uFile.enc'), 'r') ********return userFile #------------------------------------------------------------------------------- ****def createPASSfile(self): ********'''Creates an encrypted ascii public ftp password file that clients use ********to decode after logging in''' ********crypt = ezPyCrypto.key() ********passFile = file(os.path.join('configuration','pFile.enc'), 'w') ********passFile.write(crypt.encStringToAscii(self.score_ftpPASS)) ********passFile.close() ********passFile = open(os.path.join('configuration','pFile.enc'), 'r') ********return passFile #------------------------------------------------------------------------------- ****def uploadConfigs(self): ********'''Uploads the universal config/ftpuser/pass files to the correct directories on the site''' ********##print "Files:", sys.argv[1:] relic.. ********print "Logging in..." ********ftp = ftplib.FTP() ********ftp.set_pasv(self.passivemode) #true if passive, false if active ********ftp.connect(self.domain, self.ftpport) ********print ftp.getwelcome() ********try: ************try: ****************ftp.login(self.master_ftpUSER, self.master_ftpPASS) ****************ftp.cwd(self.absCFGpath) #*the SCORE root directory ****************print "Currently in:", ftp.pwd() ****************print "Uploading..." ****************sConfig = self.createUniversalConfig() ****************uFile = self.createUSERfile() ****************pFile = self.createPASSfile() ****************ftp.storlines('STOR score.conf', sConfig) ****************try: ********************ftp.cwd(self.absCFGpath + '/files') ****************except ftplib.error_perm: #*if dir doesn't exist ********************ftp.mkd('files') ********************ftp.cwd(self.absCFGpath + '/files') #change to config directory ****************ftp.storlines('STOR uFile.enc', uFile) ****************ftp.storlines('STOR pFile.enc', pFile) ****************sConfig.close() ****************uFile.close() ****************pFile.close() ****************print "OK" ****************print "Files:" ****************print ftp.retrlines('LIST') ************finally: ****************print "Quitting..." ************ftp.quit() ********except: ************traceback.print_exc() #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- -thanks, flamesrock From vze4rx4y at verizon.net Mon Jan 17 07:56:39 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Mon, 17 Jan 2005 12:56:39 GMT Subject: generator expressions: performance anomaly? References: Message-ID: [Delaney, Timothy C] > Nick's other suggestion - that genexps propagate __len__ - might > still be interesting. Of course, it would only be applicable for > unconditional genexps(i.e. no if clause). Length transparency for iterators is not as general as one would expect. I once spent a good deal of effort exploring where it made sense, and I was surprised to find that it only rarely works out. Length transparency is an unexpectedly thorny subject with many dead-ends which precludes a fully general solution such as that proposed by Nick. For a recap of my research, see the docstring for Lib/test/test_iterlen.py . Raymond Hettinger From gsakkis at rutgers.edu Tue Jan 25 10:14:11 2005 From: gsakkis at rutgers.edu (gsakkis at rutgers.edu) Date: 25 Jan 2005 07:14:11 -0800 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net><35lbvdF4k3ss4U1@individual.net> Message-ID: <1106666051.334641.70740@z14g2000cwz.googlegroups.com> Terry Reedy wrote: > "George Sakkis" wrote in message > news:35lbvdF4k3ss4U1 at individual.net... > > Actually my initial motivation was not a huge tuple I had to slice many > > times. It was something much > > less extraordinarily unlikely, a recursive function with a sequence > > parameter: > > > > def foo(sequence): > > # base_case > > # do_stuff() > > combine(foo(sequence[:n]), > > foo(sequence[n:])) > > > > Having each slice be a view of the original sequence instead of a fresh > > copy would be a Good Thing > > Why? To save time? memory? Either would require more that a few bytes per > slice. If they are, you can probably use virtual slices as follows. > > def foo(sequence): > def _foo(seq, start, stop) > # base_case > # do_stuff() > combine(_foo(seq, start, n), _foo(seq, n, stop)) > _foo(sequence, 0, len(sequence) > > In other words, if you don't really want slices copied out of the sequence, > then don't slice! Just use 2 ints to indicate the working region or view. > Both this and using a nested function with additional params are standard > techniques. This also works when the seq is mutable and you want changes > to the 'slice' to change the original, as in quicksort. > > Terry J. Reedy I would say these are standard *C/C++* techniques; slicing simplifies things and thus seems more 'pythonic' to me. George From sharidas at zeomega.com Sat Jan 15 08:23:26 2005 From: sharidas at zeomega.com (Satchidanand Haridas) Date: Sat, 15 Jan 2005 18:53:26 +0530 Subject: How can I get the names of the files in a directory? In-Reply-To: <20050115131023.36656.qmail@web50501.mail.yahoo.com> References: <20050115131023.36656.qmail@web50501.mail.yahoo.com> Message-ID: <41E9194E.7080803@zeomega.com> Hi, try the 'listdir' function in the 'os' module. Also check the 'walk' function. regards, 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 Sara Fwd wrote: >Can you guys also help me find a module that looks in >a directory and print out the names of the files in there? > > > >__________________________________ >Do you Yahoo!? >Yahoo! Mail - Helps protect you from nasty viruses. >http://promotions.yahoo.com/new_mail > > From jdhunter at ace.bsd.uchicago.edu Fri Jan 21 16:00:08 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 21 Jan 2005 15:00:08 -0600 Subject: Graph and Table implementation In-Reply-To: (Jan Rienyer Gadil's message of "Fri, 21 Jan 2005 17:26:25 +0800") References: Message-ID: >>>>> "Jan" == Jan Rienyer Gadil writes: Jan> could anyone please help me! what and how is the best Jan> implementation of creating a table based on data coming from Jan> the serial port ? and also how would i be able to create Jan> graphs (2D) based on these data? Jan> opinions and suggestion are most highly welcome. thanks. matplotlib can handle most kinds of 2D plots -- it even has a table command for including simple tabular data in your graph http://matplotlib.sourceforge.net/screenshots.html#table_demo so for heavy duty tables you'll probably want to use a GUI widget. JDH From bulba at bulba.com Sun Jan 9 13:58:22 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 09 Jan 2005 19:58:22 +0100 Subject: Speed revisited References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> Message-ID: On Sat, 08 Jan 2005 17:57:30 -0700, Steven Bethard wrote: >Note that Python lists are implemented basically as arrays, which means >that deleting an item from anywhere but the end of the list is O(n) >because all items in the list must be moved down to fill the hole. Ouch... -- I have come to kick ass, chew bubble gum and do the following: from __future__ import py3k And it doesn't work. From davorss at gmail.com Wed Jan 26 00:22:31 2005 From: davorss at gmail.com (Davor) Date: 25 Jan 2005 21:22:31 -0800 Subject: python without OO In-Reply-To: <1106710590.312881.222520@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> Message-ID: <1106716951.060290.253010@z14g2000cwz.googlegroups.com> M.E.Farmer, first to clarify few things - I'm neither manager nor professionally involved in code development - I'm just embarking on a small project that I would like to attract some programmers to later on and make it a nice open-source system. Based on my previous experience with few SMALL projects, I would like to avoid object orientation as much as possible. The reason is that I always ended up working with people who were without much experience, same as me, but they were all so influenced by OO propaganda that it was impossible to reason with them and to go with as simple solution as possible (not saying that OO solution is necessarily more complex than a structured one IN ALL CASES - but in any single case I've seen so far it was). So every single time I was wasting time trying to explain why not to go with cool OO way as opposed to simple un-cool structured solution. So, if the application was feasible to develop in C or C++, the solution would be easy - just choose C and avoid all OO mess - of course would have slightly more problems with C's looser type-checking but in my experience it's far less problem then troubles that happen when one starts going crazy with C++ generic classes, multiple inheritance, deep inheritance trees, etc.. The nature of the application that I'm planning on is perfectly suited to a good high-level scripting language, and python looked very attractive so I decided to take look at it, but then i realized it has all this OO stuff that I got scared off immediately :-) - luckily some of these other guys including yourself mentioned that there are not that many issues with Python's OO stuff as there is with Java's of C++ (seems I'm not the only one with Java&C++ OO traumas :-)) - so I'm encouraged to proceed with Python. > It seems you are telling me that : > 1) You do not understand most programming concepts not really - I rather want to prevent incorporation of anything that is not really needed in the code... > 2) You are not willing to learn. more that I like to reject anything that is not obviously substantiated and that many people seem to have problems with... > 3) You might not have the skill set to manage developers maybe not good management approach but I would always opt for "not giving them the tools I don't want them to use" over "giving them tools I don't want them to use and then forbidding them to use these tools" - especially if they are not getting paid for what they are building :-) > Stop telling your programmers how to program! Seriously NOW. > If you managed a group of doctors would you tell them that they could > only use techniques that *YOU* understood, even if the were STANDARD > and well known by others? This sounds like one of those ideas preached by agile community - I say set up the rules and conventions as much as you can (in a *non-intrusive* way) if you are a manager... Exactly the group of professionals you mentioned in your example is support for what I am claiming. In fact in that profession everything is exactly about the rules, precise techniques, and exact processes that have to be done and when they have to be used. If anything gets done outside of recommended practices they are legally responsible for. For example, if a person has to undergo sinus surgery and the endoscopic version is sufficient (simple, non-intrusive, internal incision) and a doctor decides to do the traditional surgery with external cutting - I guess everyone would be pissed off - especially the patient :-).. Also, yes, I have read GOF book... but I never found it a big deal - no one ever had to document structured patterns - which definitely exist - but seem to be obvious enough that there is no need to write a book about them... Thanks for your feedback! Davor From merkosh at hadiko.de Fri Jan 21 14:44:02 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 21 Jan 2005 20:44:02 +0100 Subject: make install with python Message-ID: Hi, I am writing a Python application and use the GNU auto-tools to compile what needs compilation (i.e. Qt's .ui files). However, I don't know how to write an automake file that installs the main file (lmc.py) and some library files (i.e. ClassA.py, ClassB.py) into the appropriate directories. Any tips there? Thanks Uwe From ewanon at gmail.com Thu Jan 6 23:24:24 2005 From: ewanon at gmail.com (EW) Date: 6 Jan 2005 20:24:24 -0800 Subject: Problem remotely shutting down a windows computer with python In-Reply-To: <1104848654.965978.63000@z14g2000cwz.googlegroups.com> References: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> <1104848654.965978.63000@z14g2000cwz.googlegroups.com> Message-ID: <1105071864.183918.72410@f14g2000cwb.googlegroups.com> This does exactly what I needed! Thanks! Not sure what Windows Management Instrumentation is, but I'll look into it now. Eric From __peter__ at web.de Fri Jan 21 10:36:28 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Jan 2005 16:36:28 +0100 Subject: need help on generator... References: <63b5e209.0501210558.686f5c10@posting.google.com> Message-ID: Joh wrote: > i'm trying to understand how i could build following consecutive sets > from a root one using generator : > > l = [1,2,3,4] > > would like to produce : > > [1,2], [2,3], [3,4], [1,2,3], [2,3,4] > > but unfortunately can not, i guess i can do it by using sub generator > and maybe enumerate, please if you help could you explain a bit the > trick ? looks like this sub generator thing mess me up. Here is an (untested) variant that accepts any iterable while trying to remain memory-efficient. This makes it necessary to shuffle the order of the output a bit. from itertools import tee, islice def gen(iterable, start, end): it = iter(iterable) while True: it, a = tee(it) a = tuple(islice(a, end-1)) for sz in xrange(start, len(a)+1): yield a[:sz] it.next() if __name__ == "__main__": print list(gen(range(1, 5), 2, 4)) # prints: # [(1, 2), (1, 2, 3), (2, 3), (2, 3, 4), (3, 4)] Peter From skip at pobox.com Tue Jan 4 20:19:32 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Jan 2005 19:19:32 -0600 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> Message-ID: <16859.16548.249527.30210@montanaro.dyndns.org> Terry> Numarray has a record array type. If there is not one publicly Terry> available, perhaps you could write a CSV file to record-array Terry> slurper and contribute it to the Recipes site or maybe even the Terry> CSV module. -1 on putting such a beast into the CSV module, especially if, as it seems, it would rely on something outside the core. Skip From segphault at sbcglobal.net Mon Jan 24 08:19:45 2005 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 24 Jan 2005 13:19:45 GMT Subject: finding name of instances created References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> Message-ID: On Fri, 21 Jan 2005 16:13:19 -0800, Andr? wrote: > Short version of what I am looking for: > > Given a class "public_class" which is instantiated a few times e.g. > > a = public_class() > b = public_class() > c = public_class() > > I would like to find out the name of the instances so that I could > create a list of them e.g. > ['a', 'b', 'c'] > A working solution: class A: pass a = A() b = A() c = A() [x for x,y in locals().items() if hasattr(y,"__class__") and y.__class__ == A] That said, you probably dont want to do it. I doubt that it will work consistently. BTW, based on my understanding of the other stuff you said, this is probably not the best way to do whatever it is you are trying to do. --SegPhault From erikbethke at gmail.com Wed Jan 19 06:45:41 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 19 Jan 2005 03:45:41 -0800 Subject: wxPython and PyGame - do they play well together? In-Reply-To: <1106039039.627729.62990@f14g2000cwb.googlegroups.com> References: <1106026599.092269.292170@c13g2000cwb.googlegroups.com> <1106039039.627729.62990@f14g2000cwb.googlegroups.com> Message-ID: <1106135141.121584.327370@c13g2000cwb.googlegroups.com> After a touch more of exploration... actually from the wxPython demo's startup tips lead me over to the wxPython Wiki.... Here I found this gem: http://wiki.wxpython.org./index.cgi/IntegratingPyGame Awesome. There is in fact some very tricky timing of the import statement for pygame -Erik From ncoghlan at iinet.net.au Fri Jan 7 11:00:50 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 02:00:50 +1000 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Message-ID: <41DEB232.1000007@iinet.net.au> Jacek Generowicz wrote: > [*] Funnily enough, getting them to understand that "lambda x: fn(x)" > is just a very silly way of writing "fn", can be quite a struggle > at times ... but that's probably a consequence of the context in > which lambda is introduced. If you genuinely taught them that, you may have done them a disservice: Py> def f(x): ... print x ... Py> f1 = f Py> f2 = lambda x: f(x) Py> f1("hi") hi Py> f2("hi") hi Py> def f(x): ... print x * 2 ... Py> f1("hi") hi Py> f2("hi") hihi Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From davorss at gmail.com Tue Jan 25 18:33:11 2005 From: davorss at gmail.com (Davor) Date: Tue, 25 Jan 2005 18:33:11 -0500 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: > On the other hand, this does beggar for a reason to bother with Python at > all. It seems you could be happy doing BASH scripts for Linux or DOS batch > files for Windows. Both are "nice&simple" scripting languages free of > object oriented contamination. not really, what I need that Python has and bash&dos don't is: 1. portability (interpreter runs quite a bit architectures) 2. good basic library (already there) 3. modules for structuring the application (objects unnecessary) 4. high-level data structures (dictionaries & lists) 5. no strong static type checking 6. very nice syntax so initially I was hoping this is all what Python is about, but when I started looking into it it has a huge amount of additional (mainly OO) stuff which makes it in my view quite bloated now... anyhow, I guess I'll have to constrain what can be included in the code through different policies rather than language limitations... Thanks Davor From jjl at pobox.com Mon Jan 3 13:11:06 2005 From: jjl at pobox.com (John J. Lee) Date: 03 Jan 2005 18:11:06 +0000 Subject: using HTTP Digest auth with arbitrary HTTP methods? References: Message-ID: John Reese writes: > In comp.lang.python, [I] wrote: [...] > I instead copied it (to urllib3.py) and made the following changes: > a. in AbstractDigestAuthHandler.get_authorization, call > req.get_method() instead of req.has_data() and 'POST' or 'GET' > (python has a ternary operator, who knew) (Re ternary operator: Everybody who read this list at certain times in the past is painfully aware of that fact, and of precisely why it's not quite true, and of all the syntax alternatives for real ternary conditionals that will never be part of Python ;-) > b. in AbstractHTTPHandler.do_open, call req.get_method instead of the > hard-coded if-logic which is the same as that in req.get_method > > Both of these seem like bugs in urllib2. Yup, bugs both. > Then I overrode urllib2.Request and made it possibly to set the method, > and then passed an instance of my custom Request class (the one that > shouldn't have to exist, since Request should allow method to be set > explicitly) to OpenerDirector.open(). > > I'd like to see these changes make it into the standard library -- after > being vetted by whoever's in charge of urllib2. Anybody know who I > should talk to? Nobody is really in charge: just go ahead and submit a patch. Drop me an email when you do, and I'll try to review it. The only reason urllib2 doesn't already do arbitrary HTTP methods is that nobody has spent the time to think carefully if a .set_method() really is the right way to do it, then followed through with the work needed to get a patch applied. As always, a precondition for change is that somebody thinks something through carefully, writes tests, documentation, patch and submits all three to the SF patch tracker with a brief explanation like the one you give above. BTW, Greg Stein started work on adding the stuff you need at the httplib level (as module httpx). He seems too busy to finish it, but see modules httpx and davlib (one or both are in the Python CVS sandbox). He thinks httplib is a better place for DAV than urllib2, and he should know. But go ahead and fix urllib2 anyway... :-) John From snail at objmedia.demon.co.uk Wed Jan 26 08:59:24 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Wed, 26 Jan 2005 13:59:24 +0000 Subject: is there better 32 clock() timing? References: <41f61372.1768192005@news.oz.net> <41f63d79.1778950866@news.oz.net> <41f746c3.1846865602@news.oz.net> Message-ID: In message <41f746c3.1846865602 at news.oz.net>, Bengt Richter writes >>QueryPerformanceCounter is 47 times slower to call than clock() on my >>1Ghz Athlon. >That really makes me wonder. Perhaps the Athlon handles RDTSC by way of >an illegal instruction trap and faking the pentium instruction? No. Athlon implements it correctly- if it didn't you'd end up in the debugger with an illegal instruction trap - you don't. Also my stats below show that Athlon's RDTSC is faster than Pentium's which I doubt you'd get if you were faking things. Taking it further - the test to see if a processor supports RDTSC is to wrap it in an exception handler and execute the instruction - if it doesn't you end up in the __except part of the SEH handler. QueryPerformanceCounter and RDTSC are not the same thing. QueryPerformanceCounter talks to hardware to get its results. I imagine that differences in performance for QueryPerformanceCounter are down to how the HAL talks to the hardware and can't be blamed on the processor or manufacturer. clock() gets its info from the OS at (I imagine) the same granularity as the NT scheduler. Some systems schedule at 10ms/11ms others at about 6ms or 7ms. I think this is to do with single/dual processors - unsure as I don't have a dual processor box. If you call GetThreadTimes() you will find values returned that match the approx clock() values - which is why I think they are related. I've just run some tests using the same old program. QPC is QueryPerformanceCounter. QPF is QueryPerformanceFrequency. I've included the QPC/QPF column to show the timings in seconds. 1Ghz Athlon, Windows XP, SP2 1,000,000 iterations QPC QPC/QPF (seconds) QueryPerformanceCounter 7156984 5.998233 GetThreadTimes 503277 0.421794 RDTSC 103430 0.086684 clock() 148909 0.124800 QPC QPC/QPF (seconds) 850Mhz Pentium III, W2K. 1,000,000 iterations QueryPerformanceCounter 5652161 1.579017 GetThreadTimes 3608976 1.008222 RDTSC 842950 0.235491 clock() 699840 0.195511 The results surprise me - Pentium III clock() takes less time to execute than Pentium III RDTSC! It surprises me that the 850Mhz Pentium III QPC is faster than the 1Ghz Athlon QPC, but whichever way you slice it, QPC is massively slower than RDTSC or clock(). Also surprising is the W2K GetThreadTimes is so slow compared to the Athlon GetThreadTimes(). >of the timer chip that drives the old 55ms clock that came from IBM >using cheap TV crystal based oscillators instead of defining an >OS-implementer-friendly time base, I think. The frequency was nominally >1193182 hz I believe. Obviously the OS didn't get interrupted that often, >but if you divide by 2**16, you get the traditional OS tick of ~55ms: I though that was the Windows 9x way of doing things. You get the 49 day wrap around with this one I think. >you can't expect to control ignition of a racing engine reliably with >an ordinary windows based program ;-) ...and Schumacher is in the lead, oh look! The Ferrari has blue screened. The new regulations to reduce speeds in F1 are working, that has really slowed him down... Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From kosh at aesaeion.com Wed Jan 26 21:32:38 2005 From: kosh at aesaeion.com (kosh) Date: Wed, 26 Jan 2005 19:32:38 -0700 Subject: 20050126 find replace strings in file In-Reply-To: References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> Message-ID: <200501261932.38770.kosh@aesaeion.com> On Wednesday 26 January 2005 7:13 pm, Tad McClellan wrote: > [ Followup set ] > > Dan Perl wrote: > > I can't imagine why or how, but there are > > actually 26 members in the perl-python Yahoo! group who have registered > > to get these bogus lessons sent to them daily! > > There is one born every minute. > Nah it is daily humor. Just think of it like a joke list. :) From snail at objmedia.demon.co.uk Fri Jan 7 08:47:18 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Fri, 7 Jan 2005 13:47:18 +0000 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <1105056774.393244.199250@f14g2000cwb.googlegroups.com> Message-ID: In message , Christopher Koppler writes >Still, Java feels like C++ done right, while being more wrong >:-[ Couldn't disagree more. Just about anything you want to do that is low-level, is impossible in Java. Anyway this is off-topic. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From steven.bethard at gmail.com Wed Jan 12 19:49:43 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 17:49:43 -0700 Subject: dict.updated In-Reply-To: <5GiFd.8571$Vj3.3354@newssvr17.news.prodigy.com> References: <5GiFd.8571$Vj3.3354@newssvr17.news.prodigy.com> Message-ID: Rick Morrison wrote: > I could live with creating a new dict, sure (although it seems wasteful). I > realize that something like this probably doesn't stand a chance of ever > making it into the std library for what might be called "philosophical" > reasons. I just want it for me (my personal philosophy runs more to the > pragmatic -- well at least for coding). > > I suppose the in-place version would be more along the lines of: > > >>>>def updated(d, updates): > > ... d.update(updates) > ... return d > ... > >>>>[updated(d, {'c':3}) for d in [{'a':1, 'b':2}, {'x':10, 'y':'11'}]] > > [{'a': 1, 'c': 3, 'b': 2}, {'y': '11', 'x': 10, 'c': 3}] > > But I'd like to put the "updated" method on the "dict" object, which is what > I can't seem to figure out. > Yeah I know that's "bad", but to my mind so is polluting the global > namespace with the "updated" function. You could do something like: py> class dict(dict): ... def updated(self, *args, **kwds): ... self.update(*args, **kwds) ... return self ... py> [d.updated(c=3) for d in [dict(a=1, b=2), dict(x=10, y=11)]] [{'a': 1, 'c': 3, 'b': 2}, {'y': 11, 'x': 10, 'c': 3}] It'd mean you'd have to create all your dicts with the dict constructor instead of {} though. Steve From marc.poulhies at NO-SP4Mepfl.ch Mon Jan 31 11:41:30 2005 From: marc.poulhies at NO-SP4Mepfl.ch (=?iso-8859-1?Q?Marc_Poulhi=E8s?=) Date: Mon, 31 Jan 2005 17:41:30 +0100 Subject: Using HTTPSConnection and verifying server's CRT References: <41fe5357@epflnews.epfl.ch> Message-ID: <41fe5fb7@epflnews.epfl.ch> ngps at netmemetic.com (Ng Pheng Siong) writes: Hi, > According to Marc Poulhi?s : >> I tried to see if the M2Crypto has this possibility, but from my tests >> and from what I can find on the website, it seems not :/ > > How did you test and where on the website does it say not? I did things like this: con = M2Crypto.httpslib.HTTPSConnection("some_secure_server") con.request("GET" , "/") I tried to play with optional parameters (strict, debuglevel, etc) to see if it was saying that it will not check server's CRT or some other debug message dealing with server's certificate, but it is always returning the webpage without saying anything :) I did not say that M2C's doc stated clearly that this was not possible (that's why I wrote "seems"), but I couldn't find something stating it was possible (I tried google, API docs). >> Can someone confirm me this is not possible or point me to something >> that could help me? > > 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. ;-) Ok, sorry for that. Maybe that with more readings I could have spotted this. I'll try that tomorrow and give my code if I have something working! > M2Crypto even does client certs. Since Apr 2000, according to the very last > blog entry on the ZServerSSL page. Yes, I did try this and have my client authenticated to the server. Thanks for this quick and clear answer ;) Marc From binux.lists at gmail.com Mon Jan 10 00:55:32 2005 From: binux.lists at gmail.com (Binu K S) Date: Mon, 10 Jan 2005 11:25:32 +0530 Subject: Datetime module In-Reply-To: <1105335972.454019.46450@c13g2000cwb.googlegroups.com> References: <1105335972.454019.46450@c13g2000cwb.googlegroups.com> Message-ID: <2b7d8b42050109215523001bc0@mail.gmail.com> The time module will do. >>> import time >>> time.ctime() 'Mon Jan 10 11:17:54 2005' Use strftime if you need to format the time differently. >>> time.strftime("%Y-%m-%d %H:%m:%S",time.localtime()) '2005-01-10 11:01:45' On 9 Jan 2005 21:46:12 -0800, rublind at gmail.com wrote: > I am writing a script that acts as an AIM bot [using twisted.IM's base > scripts] and I want to add a logging feature. I got it to log who sends > what to whom, but what I want to add is the date and time that the > message was sent (or recieved by the bot), I tried to look at datetime > on my own, and I couldn't get anything to work. > Anyone know a simple way to get the current date and/or time? > > Thanks! > > -- > http://mail.python.org/mailman/listinfo/python-list > From http Sun Jan 9 10:04:46 2005 From: http (Paul Rubin) Date: 09 Jan 2005 07:04:46 -0800 Subject: Python3: on removing map, reduce, filter References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> Message-ID: <7x4qhqr6cx.fsf@ruckus.brouhaha.com> Andrey Tatarinov writes: > anyway list comprehensions are just syntaxic sugar for > >>> for var in list: > >>> smth = ... > >>> res.append(smth) > > (is that correct?) I would expect lc's to work more like map does. From steven.bethard at gmail.com Sun Jan 23 15:46:04 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 23 Jan 2005 13:46:04 -0700 Subject: What is print? A function? In-Reply-To: References: Message-ID: Frans Englich wrote: > The reason I thinks about this is I need to implement a debug print for my > program; very simple, a function/print statement that conditionally prints > its message whether a bool is true. Not overly complex. Sounds like you want to override sys.stdout: py> class ConditionalWriter(object): ... def __init__(self, outfile, cond=True): ... self.outfile = outfile ... self.cond = cond ... def write(self, text): ... if self.cond: ... self.outfile.write(text) ... ... py> import sys py> writer = ConditionalWriter(sys.stdout) py> sys.stdout = writer py> print "hi!" hi! py> writer.cond = False py> print "hi!" py> writer.cond = True py> print "hi!" hi! You probably want to restore sys.stdout when you're done too: py> sys.stdout = writer.outfile py> writer.cond = False py> print "hi!" hi! That said, you probably _really_ want the logging module: http://docs.python.org/lib/module-logging.html Steve From apardon at forel.vub.ac.be Wed Jan 12 03:07:52 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 Jan 2005 08:07:52 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: Op 2005-01-12, It's me schreef : > > "Robert Kern" wrote in message > news:cs1mp9$sg9$1 at news1.ucsd.edu... >> >> That's *it*. > > So, how would you overload an operator to do: > > With native complex support: > > def twice(a): > return 2*a > > print twice(3+4j), twice(2), twice("abc") > > Let's presume for a moment that complex is *not* a native data type in > Python. How would we implement the above - cleanly? I suppose in the same way as (graphic) points and vectors can be implemented cleanly. A few years back I had written a Vector class in python, just to get an understanding of how things worked. It worked without a problem with your twice function. >>> Vec(1.0,2.0) Vector[1.0, 2.0] >>> def twice(a): ... return 2 * a ... >>> twice(Vec(1.0,2.0)) Vector[2.0, 4.0] >>> I suppose what can be done with a vector class could have been done with a complex class should complex numbers not have been native to python. -- Antoon Pardon From jeff at ccvcorp.com Fri Jan 21 20:04:11 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 21 Jan 2005 17:04:11 -0800 Subject: default value in a list In-Reply-To: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: <10v39ald6em3u6f@corp.supernews.com> TB wrote: > Hi, > > Is there an elegant way to assign to a list from a list of unknown > size? For example, how could you do something like: > > >>>> a, b, c = (line.split(':')) > > if line could have less than three fields? (Note that you're actually assigning to a group of local variables, via tuple unpacking, not assigning to a list...) One could also do something like this: >>> l = "a:b:c".split(':') >>> a, b, c, d, e = l + ([None] * (5 - len(l))) >>> print (a, b, c, d, e) ('a', 'b', 'c', None, None) >>> Personally, though, I can't help but think that, if you're not certain how many fields are in a string, then splitting it into independent variables (rather than, say, a list or dict) *cannot* be an elegant solution. If the fields deserve independent names, then they must have a definite (and distinct) meaning; if they have a distinct meaning (as opposed to being a series of similar items, in which case you should keep them in a list), then which field is it that's missing? Are you sure it's *always* the last fields? This feels to me like the wrong solution to any problem. Hm, speaking of fields makes me think of classes. >>> class LineObj: ... def __init__(self, a=None, b=None, c=None, d=None, e=None): ... self.a = a ... self.b = b ... self.c = c ... self.d = d ... self.e = e ... >>> l = "a:b:c".split(':') >>> o = LineObj(*l) >>> o.__dict__ {'a': 'a', 'c': 'c', 'b': 'b', 'e': None, 'd': None} >>> This is a bit more likely to be meaningful, in that there's almost certainly some logical connection between the fields of the line you're splitting and keeping them as a class demonstrates that connection, but it still seems a bit smelly to me. Jeff Shannon Technician/Programmer Credit International From claudio.grondi at freenet.de Fri Jan 21 03:11:36 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 21 Jan 2005 08:11:36 -0000 Subject: DevX: "Processing EDI Documents into XML with Python" Message-ID: <35c0hcF4jnr7pU1@individual.net> "You don't have to rely on expensive and proprietary EDI conversion software to parse, validate, and translate EDI X12 data to and from XML; you can build your own translator with any modern programming language, such as Python." by Jeremy Jones http://www.devx.com/enterprise/Article/26854 Excerpt: "Python is an object-oriented, byte-compiled language with a clean syntax, clear and consistent philosophy, and a strong user community. These attributes (both of the language and the community) make it possible to quickly write working, maintainable code, which in turn makes Python an excellent choice for nearly any programming task. Processing any "flavor" of EDI is no exception." Hi, just wanted to share with you, that the last issue of the DevX newsletter comes with a Python related article as first item in the list of subjects. Claudio From harold.fellermann at upf.edu Mon Jan 10 11:45:28 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Mon, 10 Jan 2005 17:45:28 +0100 Subject: syntax error in eval() Message-ID: <08965366-6327-11D9-B3E0-003065FB7B26@upf.edu> Hi all, I am trying to dynamically add class attributes at runtime using the function eval(), i.e. I want to do something like >>> class X : pass ... >>> X.attr = 5 but without knowing either the attributes name nor its value. However, I encounter a syntax error I cannot understand: Python 2.4 (#1, Dec 30 2004, 08:00:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> class X : pass ... >>> attrname = "attr" >>> eval("X.%s = val" % attrname , {"X":X, "val":5}) Traceback (most recent call last): File "", line 1, in ? File "", line 1 X.attr = val ^ SyntaxError: invalid syntax Does anyone have a clue what might be wrong? Thanks in advance. - harold - -- "I know what I believe. I will continue to articulate what I believe and what I believe - I believe what I believe is right." -- George W. Bushman From apardon at forel.vub.ac.be Tue Jan 18 02:57:18 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2005 07:57:18 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-17, Steve Holden schreef : > Antoon Pardon wrote: > > Mostly, though, I was trying to say that I found your nitpicking > insistence on terminological exactitude, even when giving advice to > those new to the language, both inappropriate and tedious in the extreme. I think it is appropiate because not all new to the language are new to programming and even newbees have a right to know how it really is. Otherwise after some time you get experienced users who don't know the fact. In this case for example there are a number of people who flat out assert that muatble dict keys in pyhthon is impossible. -- Antoon Pardon From steve at holdenweb.com Sun Jan 2 09:20:36 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Jan 2005 09:20:36 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> Message-ID: Aahz wrote: > In article <7xacrs230c.fsf at ruckus.brouhaha.com>, > Paul Rubin wrote: > >>I was pretty skeptical of Java's checked exceptions when I first used >>them but have been coming around about them. There's just been too >>many times when I wrote something in Python that crashed because some >>lower-level function raised an exception that the upper level hadn't >>been expecting, after the program had been in use for a while. I'd >>sure rather find out about that at compile time. > > > That's funny -- Bruce Eckel talks about how he used to love checked > exceptions but has come to regard them as the horror that they are. > I've learned to just write "throws Exception" at the declaration of > every method. Pretty sloppy, though, no? And surely the important thing is to have a broad handler, not a broad specification of raisable exceptions? 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 michael at stroeder.com Fri Jan 14 04:19:33 2005 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 14 Jan 2005 10:19:33 +0100 Subject: python connect to db2 In-Reply-To: References: <1105689253.3167.0.camel@linux.tister.com> Message-ID: <5efkb2-co4.ln1@nb2.stroeder.com> yuzx wrote: > > i try to connect to db2 use python,i find it on > python-db2 doc: > > $ python > >>> import DB2 > >>> conn = DB2.connect(dsn='sample', uid='db2inst1', pwd='ibmdb2') > >>> curs = conn.cursor() > > but i don't know about dsn, It's the host name. In a former project (using module DB2 together with 'IBM DB2 Connect' to access OS/390 database via TCP/IP) I had to invoke a special catalog db2 script before being able to use the host name. Ciao, Michael. From Scott.Daniels at Acm.Org Sat Jan 15 16:47:55 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 15 Jan 2005 13:47:55 -0800 Subject: interpret 4 byte as 32-bit float (IEEE-754) In-Reply-To: <41E97907.9070709@web.de> References: <34t1p2F4foiplU1@individual.net> <41e952b9$1@nntp0.pdx.net> <41E96302.4020003@web.de> <41e964bc$1@nntp0.pdx.net> <41E97907.9070709@web.de> Message-ID: <41e98c50$1@nntp0.pdx.net> G.Franzkowiak wrote: > Scott David Daniels schrieb: >> If you really want to do this kind of byte fiddling: >> http://members.dsl-only.net/~daniels/block.html >> Then: >> from block import Block, View >> b = Block(4) # enough space for one float (more is fine) >> iv = View('i', b) # getting to it as an integer >> fv = View('f', b) # same memory as floating point >> iv[0] = 0x3F8CCCCD # Here is a sample just using the integer >> print fv[0] >> On an Intel/Amd/Generic "PC" machine, you should get 1.1 > > That's good :-)) > I'm missing the makefile ;-) > I'm using the other world... right There's a lot more than one other world. distlib is your friend. There is no makefile. If you are not on a windows box, get the source, extract the files from the zip, and run: python setup.py install -Scott David Daniels Scott.Daniels at Acm.Org From ng01.spamguard at icewater.org Mon Jan 24 22:44:04 2005 From: ng01.spamguard at icewater.org (mike) Date: Mon, 24 Jan 2005 22:44:04 -0500 Subject: is extending an object considered acceptable usage? Message-ID: i have an Item which belongs to a Category, so Item has: - item.categoryId, the database primary key of its Category - item.category, a reference to its Category. this null unless i need a reference from item to its Category object, in which case i call setCategory(category) sometimes i want a list of categories, and from each i want to be able to access a list of its items. in this case is it considered acceptable to just create a list of those items and assign it as a property of their category? eg: category.items = listOfItems this packages everything up into a hierarchy and is more convenient to use, especially in Cheetah templates, but requries modifying the structure of the object, which bothers me (probably for some subconscious java-related reason). the alternative might be to create a dictionary that keys the lists of items on their category: items = {} items[category.id] = listOfItems this feels less "controversial" to me, but requires extra objects and house-keeping. thanks - just curious if there were arguments one way or the other. From uche at ogbuji.net Thu Jan 27 22:19:25 2005 From: uche at ogbuji.net (Uche Ogbuji) Date: 27 Jan 2005 19:19:25 -0800 Subject: Clarification on XML parsing & namespaces (xml.dom.minidom) In-Reply-To: <41f5eb4b$0$10526$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41f5eb4b$0$10526$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1106882365.827371.59940@f14g2000cwb.googlegroups.com> Greg Wogan-Browne wrote: > I am having some trouble figuring out what is going on here - is this a > bug, or correct behaviour? Basically, when I create an XML document with > a namespace using xml.dom.minidom.parse() or parseString(), the > namespace exists as an xmlns attribute in the DOM (fair enough, as it's > in the original source document). However, if I use the DOM > implementation to create an identical document with a namespace, the > xmlns attribute is not present. > > This mainly affects me when I go to print out the document again using > Document.toxml(), as the xmlns attribute is not printed for documents I > create dynamically, and therefore XSLT does not kick in (I'm using an > external processor). > > Any thoughts on this would be appreciated. Should I file a bug on pyxml? It's odd behavior, but I think it's a stretch to call it a bug. You problem is that you're mixing namespaced documents with the non-namespace DOM API. That means trouble and such odd quirks every time. Use getAttributeNS, createElementNS, setAttributeNS, etc. rather than getAttribute, createElement, setAttribute, etc. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://4Suite.org http://fourthought.com Use CSS to display XML - http://www.ibm.com/developerworks/edu/x-dw-x-xmlcss-i.html Introducing the Amara XML Toolkit - http://www.xml.com/pub/a/2005/01/19/amara.html Be humble, not imperial (in design) - http://www.adtmag.com/article.asp?id=10286UBL 1.0 - http://www-106.ibm.com/developerworks/xml/library/x-think28.html Manage XML collections with XAPI - http://www-106.ibm.com/developerworks/xml/library/x-xapi.html Default and error handling in XSLT lookup tables - http://www.ibm.com/developerworks/xml/library/x-tiplook.html Packaging XSLT lookup tables as EXSLT functions - http://www.ibm.com/developerworks/xml/library/x-tiplook2.html From jeff at ccvcorp.com Tue Jan 4 19:10:22 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 04 Jan 2005 16:10:22 -0800 Subject: Lambda as declarative idiom In-Reply-To: References: Message-ID: <10tmbqt2u4hmg91@corp.supernews.com> Robert Brewer wrote: > Michael Spencer wrote: > >>I believe that this "possibility to postpone" divides into >>two related but separate concepts: controlling the moment >>of evaluation, and assembling the arguments required at >>that moment. They are both species of 'eval', but >>managing arguments is more specialized, because it includes >>possibly renaming parameters, assigning default values, >>processing positional and keyword arguments, and, perhaps >>in the future dealing with argument types. > > Yes, but the "moment of evaluation" is more complex than just > "postponing". In a declarative construct, you probably also want global > variables to be bound early, so that the expression does not depend upon > *any* free variables. Ditto for closures. A more realistic example: > > term = input("Enter the amount to add") > e = expr(x): x + term > > ...MUCH code passes, maybe even a new process or thread... > > d = a + e(3) I see this as simply a combination of both of the aforementioned concepts -- argument control plus moment-of-evaluation control. Jeff Shannon Technician/Programmer Credit International From dial#####$#$#NOSPAM####$$##$tone at gmail.com Thu Jan 6 10:25:23 2005 From: dial#####$#$#NOSPAM####$$##$tone at gmail.com (Valentino Volonghi aka) Date: Thu, 6 Jan 2005 16:25:23 +0100 Subject: Nevow Tutorial and sample app References: <1105016703.493588.308570@z14g2000cwz.googlegroups.com> Message-ID: <1gpz6lc.i8e84x16qg22N%dial#####$#$#NOSPAM####$$##$tone@gmail.com> wrote: > Can any one redirect me to a good nevow tutorial and/or a an appliction > that is niether too big nor too small and can be help in learning > nevow. Nevow tutorial with the distrubution is too simple and it You should probably look at all the examples in the latest svn release. I've made some changes on the way examples directory work and now you can run all the examples by just running: twistd -noy examples.tac It will create a local webserver at http://localhost:8080/ with an index of all the examples (in difficulty order) with colored browseable source code and the live example. Plus you can access each sample application's (like the blog engine or the interactive chat server, or the pastebin) source code. Examples should scale well from very simple and basic hello world to very sophisticated ones like the blog engine which uses also xmlrpc and smtp protocols, or live pages like chatola. -- Valentino Volonghi aka Dialtone Now Running MacOSX 10.3.7 Blog: http://vvolonghi.blogspot.com http://weever.berlios.de From qvx3000 at yahoo.com Fri Jan 28 18:03:34 2005 From: qvx3000 at yahoo.com (Qvx) Date: 28 Jan 2005 15:03:34 -0800 Subject: Daylight savings and getmtime Message-ID: <8b2d5523.0501281503.253269@posting.google.com> Hello, I'we written a simple web deployment program which scans for the changes made to local copy of web site. Changed files are than packaged into a zip file and deployed to web server. Now here's the catch. Changes are computed using (1) log file from the last deployment and (2) local file system. Log file contains datestamps (integers) returned from os.path.getmtime(f) function at the time of last deployment. So i'm comparing two getmtime() values. The problem is when Daylight saving kicks in: suddenly all local files are reported as older than they were at the time of deployment. How do I compensate for this? Thanks, Tvrtko For those curious, here is the script. I apologize for Croatian comments and literals and missing private libraries, but I think the code is self-explanatory. ______________ # -*- coding: windows-1250 -*- from os.path import getmtime, join from os import walk, rename from zipfile import ZipFile, ZIP_DEFLATED from sets import Set from StringIO import StringIO from ftplib import FTP from qvx.io import adapt_stdout, unadapt_stdout from qvx.composite import Dot from qvx.compositeutil import read_composite import sys import time class DeploymentError(Exception): pass class Deployer: def __init__ (self, cfg_file): self.reset(cfg_file) def reset (self, cfg_file): self.read_cfg(cfg_file) self.local_files = [] self.remote_files = [] self.new_files = [] self.deleted_files = [] self.newer_files = [] self.older_files = [] self.www_all_time = None self.old_deployed = False def read_cfg (self, cfg_file): tree = read_composite(cfg_file) self.cfg = Dot(tree).DEPLOYMENT def prepare_file_lists (self): # Sastavi popis _datoteka_ u DIR direktoriju. # Izostavi datoteke iz _notes direktorija self.local_files = [] for root, dirs, files in walk(self.cfg.DIR): filtered = [join(root, f).replace('\\', '/') for f in files if f not in self.cfg.SKIP_FILES] self.local_files.extend(filtered) for skip_dir in self.cfg.SKIP_DIRS.split(','): if skip_dir.strip() in dirs: dirs.remove(skip_dir) # Sastavi popis datoteka na serveru # Koristi se sa informacijama od zadnjeg deploymenta # Popis se nalazi u www_all.txt datoteci self.remote_files = [] remote_stamps = {} zip = ZipFile(self.cfg.FILE, 'r') for line in zip.read('www_all.txt').split('\n'): name, stamp = line.split('\t') remote_stamps[name] = int(stamp) self.remote_files.append(name) self.www_all_time = zip.getinfo('www_all.txt').date_time # Deployment nije obavljen ako nije zapisan log self.old_deployed = 'deployment.log' in zip.namelist() zip.close() # Rastavi datoteke u tri kategorije: nove, obrisane i iste lset = Set(self.local_files) rset = Set(self.remote_files) self.new_files = list(lset - rset) self.deleted_files = list(rset - lset) common_files = list(lset & rset) # Pogledaj ?to se promijenilo u zajedničkim datotekama self.newer_files = [] self.older_files = [] for name in common_files: remotetime = remote_stamps[name] localtime = getmtime(name) #+ 3600 # Ako je razlika unutar sekunde, zanemari if abs(remotetime-localtime) > int(self.cfg.IGNORE_SEC): if remotetime > localtime: self.older_files.append(name) elif localtime > remotetime: self.newer_files.append(name) def need_redeployment (self): return not self.old_deployed def check_changes (self): # Ne bi trebalo biti starijih if self.older_files: raise DeploymentError('Ne smije biti starijih datoteka!') if not (self.new_files or self.deleted_files or self.newer_files): raise DeploymentError('Nema promjena!') def make_deployment_file (self): # Uključi potrebne datoteke deployment = ZipFile('new_'+self.cfg.FILE, 'w', ZIP_DEFLATED) for name in self.new_files + self.newer_files: deployment.write(name) # Uključi popis svih datoteka all_files = '\n'.join([f+'\t'+str(getmtime(f)) for f in self.local_files]) deployment.writestr('www_all.txt', all_files) # Uključi popis datoteka za obrisati for_delete = '\n'.join(self.deleted_files) if for_delete: deployment.writestr('www_delete.txt', for_delete) deployment.close() print '\nNapravljena je nova deployment datoteka.' # Preimenuj deployment datoteke timestr = '%04d-%02d-%02d_%02d-%02d-%02d' % self.www_all_time old_deployment = self.cfg.FILE.replace('.zip', '_'+timestr+'.zip') rename(self.cfg.FILE, old_deployment) rename('new_'+self.cfg.FILE, self.cfg.FILE) print 'Stara deployment datoteka se sada zove', old_deployment def exec_ftp (self, silent, logtext, func, *arg): try: self.ftp_log = self.ftp_log + '\n\n' + logtext self.ftp_log = self.ftp_log + '\n' + func(*arg) return 'OK' except Exception, e: self.ftp_log = self.ftp_log + '\n' + str(e) if not silent: raise DeploymentError(str(e)) return 'ERROR' def deploy_ftp (self): self.ftp_log = '' # Spoji se na FTP server print '\nSpajam se na ftp server %s ...' % (self.cfg.SERVER,), try: ftp = FTP(self.cfg.SERVER) print 'OK' except Exception, e: print 'ERROR' raise DeploymentError('Ne mogu se spojiti na FTP server: '+str(e)) # Logiraj se print 'Logiram se kao %s ... ' % (self.cfg.USER,), print self.exec_ftp(False, 'LOGIN', ftp.login, self.cfg.USER, self.cfg.PASSWORD) # Kopiraj datoteke deployment = ZipFile(self.cfg.FILE, 'r') deployment_files = [n for n in deployment.namelist() if n not in ['www_all.txt', 'www_delete.txt', 'deployment.log']] if deployment_files: print '?aljem datoteke:' for name in deployment_files: bytes = deployment.read(name) fp = StringIO(bytes) print ' ', name, len(bytes), ' bytes ...', print self.exec_ftp(True, 'STORBIN '+name, ftp.storbinary, 'STOR '+name, fp) fp.close() # Obri?i datoteke if 'www_delete.txt' in deployment.namelist(): deleted_files = deployment.read('www_delete.txt').split('\n') print 'Bri?em datoteke:' for name in deleted_files: print ' ', name, '...', print self.exec_ftp(True, 'DEL '+name, ftp.delete, name) deployment.close() # Bye bye print 'Zavr?avam s radom ...', print self.exec_ftp(True, 'BYE', ftp.quit) # Ispi?i FTP log print '\nFTP log:' print '-'*20, print self.ftp_log def write_log (self, text): # Zapi?i deployment log deployment = ZipFile(self.cfg.FILE, 'a', ZIP_DEFLATED) deployment.writestr('deployment.log', text) deployment.close() def run_interactively (self): # Adaptiraj stdout: mijenja kodnu stranicu u cp852 radi ispisa # hrvatskih grafema, također logira sve poruke ofa = adapt_stdout('cp852', True) try: try: # Analiziraj datoteke self.prepare_file_lists() print '*'*5, 'Obrisani', '*'*5, self.deleted_files print '*'*5, 'Novi ', '*'*5, self.new_files print '*'*5, 'Noviji ', '*'*5, self.newer_files print '*'*5, 'Stariji ', '*'*5, self.older_files if self.need_redeployment(): # Pitaj korisnika da li ?eli poslati od prije pripremljeni deployment na server yn = raw_input('\nOd prije pripremljeni deployment nije obavljen.\n>>> Da li ?elite taj deployment poslati na server? [y/N]: ') if yn.lower().strip() == 'y': self.deploy_ftp() self.write_log(''.join(ofa._log)) else: self.check_changes() # Pitaj korisnika da li ?eli napraviti deployment datoteku yn = raw_input('\n>>> Da li ?elite pripremiti deployment? [y/N]: ') if yn.lower().strip() == 'y': desc = raw_input('\n>>> Upi?ite kratki opis: ') print '\nOpis:', desc self.make_deployment_file() # Pitaj korisnika da li ?eli poslati deployment na server yn = raw_input('\n>>> Da li ?elite poslati deployment na server? [y/N]: ') if yn.lower().strip() == 'y': self.deploy_ftp() self.write_log(''.join(ofa._log)) except DeploymentError, e: print str(e) finally: # Vrati stari stdout unadapt_stdout(ofa) if __name__ == '__main__': deployer = Deployer('hpk.ini') deployer.run_interactively() x = raw_input('\n[Pritisnite Enter ...] ') sys.exit(0) From mt at 3planes.com Mon Jan 31 18:23:55 2005 From: mt at 3planes.com (Michael Tobis) Date: 31 Jan 2005 15:23:55 -0800 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1107188359.375703.110590@f14g2000cwb.googlegroups.com> <1gr9lyc.1rrm543162uefN%aleaxit@yahoo.com> Message-ID: <1107213835.138613.117620@c13g2000cwb.googlegroups.com> This is definitely a wart: ... z = 42.3 ... ... def f(): ... if False: ... global z ... z = -666 ... ... f() ... print z From http Tue Jan 11 11:49:52 2005 From: http (Paul Rubin) Date: 11 Jan 2005 08:49:52 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> Message-ID: <7xu0pndi6n.fsf@ruckus.brouhaha.com> Alexander Schremmer <2004b at usenet.alexanderweb.de> writes: > > I need to set up a wiki for a small group. I've played with MoinMoin > > a little bit and it's reasonably straightforward to set up, but > > limited in capabilities and uses BogusMarkupConventions. > > At which point do you see limitations? It doesn't have features that MW has, like user pages, lists of incoming links to wiki pages, automatic discussion links for every wiki page, automatic update notification for specific pages of your choice, support for managing image uploads and embedding them into wiki pages, etc. etc. > And what of the markup don't you like? The BogusMixedCaseLinkNames. I'd rather have ordinary words with spaces between them, like we use in ordinary writing. > > In the larger world, though, there's currently One True wiki package, > > namely Mediawiki (used by Wikipedia). > > It is just very famous because of Wikipedia IMHO. Well, it's gotten a lot more development attention because of that same Wikipedia. > Having a DBMS backend is good in your opinion? It has some severe > disadvantages like not easy to scale (you would need to setup DBMS > replication), two potential points of failure, more complex setup, bigger > memory requirements, etc. I didn't say that it was good, in fact I was listing it as a disadvantage there. I think for a small wiki like I was discussing, it's just an extra administrative hassle. For a large wiki though, MoinMoin's approach is completely unworkable and MoinMoin's documentation actually says so. First of all MoinMoin uses a separate subdirectory for every page, and all those subdirs are in a flat top level directory, so if you have 100,000 wiki pages, the top level directory has that many subdirs. Most file systems are not built to handle such large directories with any reasonable speed. (Also, every revision has its own file in the subdir. Lots of Wikipedia pages have thousands of revisions). Second, DBMS's have indexes and transactions, that make it simple to have features like "what links here". Yes you could do something like that in MoinMoin with additional files, but then you'd have to update multiple files when you commit a change, which can leave stuff inconsistent if there's a crash partway through the update (I wonder just how crash-resilient MoinMoin is right now, even). The DBMS can also handle stuff like replication automatically. > If you really want to use the wiki for content, you have to agree on > a markup style. You could use an independent one (like > RestructuredText) and hope that MediaWiki supports it (MoinMoin > does). Or you end up writing complex migration scripts just for the > markup. I looked at RestructuredText once and hated it. WikiMedia's markup language has bogosities just like anything else, but for the most part it's not too bad. Anyway, lots more people are used to it than any other Wiki markup language, just because of Wikipedia's popularity. > > Is anyone here actually running Mediawiki who can say just how > > big a hassle it is? > > A few months I tried to install it. I got it running. But I did not like > the necessary complex administration tasks. I'm not too surprised. That's why MoinMoin was the first one I tried. > > The other one will be public and is planned grow to medium size (a few > > thousand active users) > > There are even MoinMoin sites that are as big as that. Maybe you should > rethink your kind of prejudice and re-evaluate MoinMoin. I don't doubt there are MoinMoin sites that size, but with that large a user base, I want something nicer looking than those StupidMixedCasePageNames. From itsme at yahoo.com Mon Jan 3 14:53:59 2005 From: itsme at yahoo.com (It's me) Date: Mon, 03 Jan 2005 19:53:59 GMT Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: Well, now that they are API based, they can easily add any script language they so wish through SWIG (www.swig.org). Maybe not LISP. SNOBOL would be the right thing to do. (*NOT*) "Richards Noah (IFR LIT MET)" wrote in message news:crc699$l24$1 at athen03.muc.infineon.com... > > > > It was actually developed in Fortran some 35 years ago. Then migrated to > > F77. Then added a C/C++ layer to sit ontop. Then converted to API > based. > > Then added a Python layer on top. > > > > The only thing unfortunate is that they went with MFC on the newest > version. > > Yuck! > > > > Hahaha, sounds like a party to me. And they didn't even throw in a layer of > Lisp for good effort? Too bad, if you ask me :) > > From daranrife at yahoo.com Fri Jan 28 19:16:00 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 16:16:00 -0800 Subject: LinearAlgebra incredibly slow for eigenvalue problems In-Reply-To: <1106957598.136667.45430@z14g2000cwz.googlegroups.com> References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> <1106952951.834888.65430@f14g2000cwb.googlegroups.com> <1106957598.136667.45430@z14g2000cwz.googlegroups.com> Message-ID: <1106957760.485860.104760@f14g2000cwb.googlegroups.com> David, One more thing. I checked to see if the SciPy libraries had dependencies on ATLAS. They do not, however, the eigenvector calculation is still much faster than Numeric? This is very strange. Daran From fu.limin.tao at gmail.com Thu Jan 27 17:42:51 2005 From: fu.limin.tao at gmail.com (Limin Fu) Date: Thu, 27 Jan 2005 23:42:51 +0100 Subject: ANN: Tao Scripting Language 0.8.5 beta released! In-Reply-To: <397cc8578b5e9adf0e31f18ffa556593@gmail.com> References: <397cc8578b5e9adf0e31f18ffa556593@gmail.com> Message-ID: I only looked at languages which are more often used in bioinformatics, at that time I didn't heard about Lua. I knew it about 2 or 3 months after I began to implement Tao. For Io, this is my first time to hear about it :) Cheers, Limin On Thu, 27 Jan 2005 23:02:45 +0100, PA wrote: > > On Jan 27, 2005, at 22:54, Limin Fu wrote: > > > I found that, a language with simple syntax, convenient text > > processing functionality, powerful numeric computation capability, and > > simple C/C++ interfaces would be very useful > > You bet. > > Have you looked at Lua? > > http://www.lua.org/about.html > > Or perhaps Io? > > http://www.iolanguage.com/About/ > > Cheers > > -- > PA, Onnay Equitursay > http://alt.textdrive.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Homepage for Tao Language: http://taoscript.sourceforge.net Tao Language project at sourceforge.net: http://sourceforge.net/projects/taoscript From zyqnews at 163.net Sat Jan 29 22:10:33 2005 From: zyqnews at 163.net (zyqnews at 163.net) Date: 29 Jan 2005 19:10:33 -0800 Subject: nedd help on using Installer Message-ID: <1107054633.283242.43930@f14g2000cwb.googlegroups.com> hello: I am using Install to create a standalone program for linux. What I has done is : [Installer]$cd source/linux [linux]$python Make.py [linux]$make [Installer]$cd ../../ [Installer]$python Configure.py [Installer]$python Makespec.py hello.py [Installer]$python Build.py hello Traceback (most recent call last): File "Build.py", line 823, in ? build(sys.argv[1]) File "Build.py", line 25, in build rthooks = eval(open(os.path.join(HOMEPATH, 'rthooks.dat'), 'r').read()) File "", line 1 { ^ SyntaxError: invalid syntax What is this? What is wrong? Please help me. Thanks From newsgroups at jhrothjr.com Mon Jan 3 12:32:13 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 3 Jan 2005 11:32:13 -0600 Subject: How can engineers not understand source-code control? (was: The Industry choice) References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> <41d8417e$0$14596$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: <10tj0cqfkor680c@news.supernews.com> > In article <41d8417e$0$14596$ed2619ec at ptn-nntp-reader01.plus.net>, > Mark Carter wrote: > . > . > . >>Don't start me! Dammit, too late ... ... >>Honestly, I thought (real) engineers were supposed to be clever. You might want to read this: http://alistair.cockburn.us/crystal/articles/teoseatsoecg/theendofsoftwareengineering.htm His thesis is very simple: engineering took a wrong turn after WW II, and the people who coined the term "software engineering" didn't have a clue. Of course, he puts it a bit more diplomatically, but he's got the data to demonstrate that software engineering is an oxymoron. John Roth From jeff at ccvcorp.com Thu Jan 13 14:40:52 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 13 Jan 2005 11:40:52 -0800 Subject: finding/replacing a long binary pattern in a .bin file In-Reply-To: <41e6293f.725257715@news.oz.net> References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> <41e6293f.725257715@news.oz.net> Message-ID: <10udjc3fmnhro9d@corp.supernews.com> Bengt Richter wrote: > BTW, I'm sure you could write a generator that would take a file name > and oldbinstring and newbinstring as arguments, and read and yield nice > os-file-system-friendly disk-sector-multiple chunks, so you could write > > fout = open('mynewbinfile', 'wb') > for buf in updated_file_stream('myoldbinfile','rb', oldbinstring, newbinstring): > fout.write(buf) > fout.close() What happens when the bytes to be replaced are broken across a block boundary? ISTM that neither half would be recognized.... I believe that this requires either reading the entire file into memory, to scan all at once, or else conditionally matching an arbitrary fragment of the end of a block against the beginning of the oldbinstring... Given that the file in question is only a few tens of kbytes, I'd think that doing it in one gulp is simpler. (For a large file, chunking it might be necessary, though...) Jeff Shannon Technician/Programmer Credit International From steve at holdenweb.com Mon Jan 10 19:54:04 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Jan 2005 19:54:04 -0500 Subject: python3: 'where' keyword In-Reply-To: <7xllb1jsdz.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> <1105355380.040837.189270@c13g2000cwb.googlegroups.com> <7xis65a5w6.fsf@ruckus.brouhaha.com> <1105357839.696387.309900@c13g2000cwb.googlegroups.com> <7xr7kt314a.fsf@ruckus.brouhaha.com> <1105364925.848973.73080@c13g2000cwb.googlegroups.com> <7xllb1jsdz.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Carl Banks" writes: > >>When I asked you to do this, it was just a rhetorical way to tell you >>that I didn't intend to play this game. It's plain as day you're >>trying to get me to admit something. I'm not falling for it. >> >>If you have a point to make, why don't you just make it? > > > You asked me to compare the notion of macros with the Zen list. I did > so. I didn't see any serious conflict, and reported that finding. > Now you've changed your mind and you say you didn't really want me to > make that comparison after all. > Well I for one disagreed with many of your estimates of the zen's applicability to macros, but I just couldn't be arsed saying so. > An amazing amount of the headaches that both newbies and experienced > users have with Python, could be solved by macros. That's why there's > been an active interest in macros for quite a while. It's not clear > what the best way to do design them is, but their existence can have a > profound effect on how best to do these ad-hoc syntax extensions like > "where". Arbitrary limitations that are fairly harmless without > macros become a more serious pain in the neck if we have macros. > This is not a justifiable assertion, IMHO, and if you think that newbies will have their lives made easier by the addition of ad hoc syntax extensions then you and I come from a different world (and I suspect the walls might be considerably harder in mine than in yours). > So, we shouldn't consider these topics separately from each other. > They are likely to end up being deeply related. I don't really understand why, if macros are so great (and you are reading the words of one who was using macros back in the days of Strachey's GPM) why somebody doesn't produce a really useful set of (say) M4 macros to prove how much they'd improve Python. Now that's something that would be a bit less ignorable than this apparently interminable thread. regards Steve PS: Your continued use of the NOSPAM.invalid domain is becoming much more irritating than your opinions on macros in Python. Using a bogus URL is piling crap on top of more crap. -- 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 davidf at sjsoft.com Fri Jan 7 01:31:08 2005 From: davidf at sjsoft.com (David Fraser) Date: Fri, 07 Jan 2005 08:31:08 +0200 Subject: Python evolution: Unease In-Reply-To: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> References: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Carlos Ribeiro wrote: > ... > >>wish I could simply plug & play DBAPI modules in a totally seamlessly >>way. Anyone who tried know how far are we of this dream. > > > If you manage to get there, you'll start fighting against the different > dialects of SQL supported by the various back-ends, as is well known by > anybody who tried, say, ODBC or ADO, which do manage good plug&play of > their components but still can't solve the real hard one:-( I've found I can get by nicely by just supporting stock standard bottom end SQL and not using any database-specific features. Just requires a little wrapper code for some functions David From pythongnome at hotmail.com Sun Jan 9 16:36:08 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Sun, 09 Jan 2005 21:36:08 GMT Subject: Old Paranoia Game in Python In-Reply-To: References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> Message-ID: Aahz wrote: > In article <5JcEd.1988$KJ2.907 at newsread3.news.atl.earthlink.net>, > Lucas Raab wrote: > >>Sean P. Kane wrote: >> >>>I ported the old (and long since removed) game from the bsd-game pacakge >>>called, Paranoia, based on the old Paranoia role playing game from C to >>>Python as a simple exercise in learning the language and pure late night >>>boredom. Anyways, here it is for anyone looking for a few minutes of >>>nostalgia. I may get around to posting this at >>>http://homepage.mac.com/spkane/ or http://www.spkane.org/, but for now >>>here it is. Improvements or corrections, welcome. >> >> >> >>>Equipment: Red Reflec Armour, Laser Pistol, Laser Barrel (red), >>> Notebook & Stylus, Knife, Com Unit 1, Jump suit, >>> Secret Illuminati Eye-In-The-Pyramid(tm) Decoder ring, >>> Utility Belt & Pouches >>>=============================================================================== >> >> >> >>The Illuminati really have infiltrated our society. > > > Stay alert! > Trust no one! > Keep your laser handy! Well, I really meant "Secret Illuminati Eye-In-The-Pyramid(tm) Decoder ring", but if you wanted to go in another direction... From http Mon Jan 10 19:21:56 2005 From: http (Paul Rubin) Date: 10 Jan 2005 16:21:56 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> <7xu0ppyjjg.fsf@ruckus.brouhaha.com> <9yzEd.9081$wZ2.6859@newssvr13.news.prodigy.com> Message-ID: <7xr7ksrf17.fsf@ruckus.brouhaha.com> "Roose" writes: > Well, then of course you know I have to say: An OS does not run inside a > browser. There's a sentence I never thought I'd utter in my lifetime. > > So that is an irrelevant example, since it obviously isn't a task scheduler > in the context of this thread. Huh? I'm just baffled why you think writing a scheduler in an OS is harder than writing one in an application. You have some means of doing a coroutine switch in one situation, and some means of doing a hardware context switch in the other. Aside from that the methods are about the same. Why do you think there's anything difficult about doing this stuff in Python, given the ability to call low level routines for some hardware operations as needed? From kbk at shore.net Sun Jan 16 14:24:37 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Sun, 16 Jan 2005 14:24:37 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200501161924.j0GJObqo029011@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 272 open ( +5) / 2737 closed (+10) / 3009 total (+15) Bugs : 793 open ( -5) / 4777 closed (+29) / 5570 total (+24) RFE : 165 open ( +0) / 141 closed ( +1) / 306 total ( +1) New / Reopened Patches ______________________ Enhance tracebacks and stack traces with vars (2005-01-08) http://python.org/sf/1098732 opened by Skip Montanaro Single-line option to pygettext.py (2005-01-09) http://python.org/sf/1098749 opened by Martin Blais improved smtp connect debugging (2005-01-11) CLOSED http://python.org/sf/1100140 opened by Wummel Log gc times when DEBUG_STATS set (2005-01-11) http://python.org/sf/1100294 opened by Skip Montanaro deepcopying listlike and dictlike objects (2005-01-12) http://python.org/sf/1100562 opened by Bj?rn Lindqvist ast-branch: fix for coredump from new import grammar (2005-01-11) http://python.org/sf/1100563 opened by logistix datetime.strptime constructor added (2005-01-12) http://python.org/sf/1100942 opened by Josh Feed style codec API (2005-01-12) http://python.org/sf/1101097 opened by Walter D?rwald Patch for potential buffer overrun in tokenizer.c (2005-01-13) http://python.org/sf/1101726 opened by Greg Chapman ast-branch: hacks so asdl_c.py generates compilable code (2005-01-14) http://python.org/sf/1102710 opened by logistix Fix for 926423: socket timeouts + Ctrl-C don't play nice (2005-01-15) http://python.org/sf/1102879 opened by Irmen de Jong Boxing up PyDECREF correctly (2005-01-15) CLOSED http://python.org/sf/1103046 opened by Norbert Nemec AF_NETLINK sockets basic support (2005-01-15) http://python.org/sf/1103116 opened by Philippe Biondi Adding the missing socket.recvall() method (2005-01-16) http://python.org/sf/1103213 opened by Irmen de Jong tarfile.py: fix for bug #1100429 (2005-01-16) http://python.org/sf/1103407 opened by Lars Gust?bel Patches Closed ______________ pydoc data descriptor unification (2004-04-17) http://python.org/sf/936774 closed by jlgijsbers xml.dom missing API docs (bugs 1010196, 1013525) (2004-10-21) http://python.org/sf/1051321 closed by jlgijsbers Fix for bug 1017546 (2004-08-27) http://python.org/sf/1017550 closed by jlgijsbers fixes urllib2 digest to allow arbitrary methods (2005-01-04) http://python.org/sf/1095362 closed by jlgijsbers Bug fix 548176: urlparse('http://foo?blah') errs (2003-03-30) http://python.org/sf/712317 closed by jlgijsbers bug fix 702858: deepcopying reflexive objects (2003-03-22) http://python.org/sf/707900 closed by jlgijsbers minor codeop fixes (2003-05-15) http://python.org/sf/737999 closed by jlgijsbers SimpleHTTPServer reports wrong content-length for text files (2003-11-10) http://python.org/sf/839496 closed by jlgijsbers improved smtp connect debugging (2005-01-11) http://python.org/sf/1100140 closed by jlgijsbers Boxing up PyDECREF correctly (2005-01-15) http://python.org/sf/1103046 closed by rhettinger New / Reopened Bugs ___________________ socket.setdefaulttimeout() breaks smtplib.starttls() (2005-01-08) http://python.org/sf/1098618 opened by Matthew Cowles set objects cannot be marshalled (2005-01-09) CLOSED http://python.org/sf/1098985 opened by Gregory H. Ball codec readline() splits lines apart (2005-01-09) CLOSED http://python.org/sf/1098990 opened by Irmen de Jong Optik OptionParse important undocumented option (2005-01-10) http://python.org/sf/1099324 opened by ncouture refman doesn't know about universal newlines (2005-01-10) http://python.org/sf/1099363 opened by Jack Jansen raw_input() displays wrong unicode prompt (2005-01-10) http://python.org/sf/1099364 opened by Petr Prikryl tempfile files not types.FileType (2005-01-10) CLOSED http://python.org/sf/1099516 opened by Frans van Nieuwenhoven copy.deepcopy barfs when copying a class derived from dict (2005-01-10) http://python.org/sf/1099746 opened by Doug Winter Cross-site scripting on BaseHTTPServer (2005-01-11) http://python.org/sf/1100201 opened by Paul Johnston Scripts started with CGIHTTPServer: missing cgi environment (2005-01-11) http://python.org/sf/1100235 opened by pacote Frame does not receive configure event on move (2005-01-11) http://python.org/sf/1100366 opened by Anand Kameswaran Wrong "type()" syntax in docs (2005-01-11) http://python.org/sf/1100368 opened by Facundo Batista TarFile iteration can break (on Windows) if file has links (2005-01-11) http://python.org/sf/1100429 opened by Greg Chapman Python Interpreter shell is crashed (2005-01-12) http://python.org/sf/1100673 opened by abhishek test_fcntl fails on netbsd2 (2005-01-12) http://python.org/sf/1101233 opened by Mike Howard test_shutil fails on NetBSD 2.0 (2005-01-12) CLOSED http://python.org/sf/1101236 opened by Mike Howard dict subclass breaks cPickle noload() (2005-01-13) http://python.org/sf/1101399 opened by Neil Schemenauer popen3 on windows loses environment variables (2005-01-13) http://python.org/sf/1101667 opened by June Kim popen4/cygwin ssh hangs (2005-01-13) http://python.org/sf/1101756 opened by Ph.E % operator bug (2005-01-14) CLOSED http://python.org/sf/1102141 opened by ChrisF rfc822 Deprecated since release 2.3? (2005-01-14) http://python.org/sf/1102469 opened by Wai Yip Tung pickle files should be opened in binary mode (2005-01-15) http://python.org/sf/1102649 opened by John Machin Incorrect RFC 2231 decoding (2005-01-15) http://python.org/sf/1102973 opened by Barry A. Warsaw raw_input problem with readline and UTF8 (2005-01-15) http://python.org/sf/1103023 opened by Casey Crabb send/recv SEGMENT_SIZE should be used more in socketmodule (2005-01-16) http://python.org/sf/1103350 opened by Irmen de Jong Bugs Closed ___________ typo in "Python Tutorial": 1. Whetting your appetite (2005-01-08) http://python.org/sf/1098497 closed by jlgijsbers xml.dom documentation omits hasAttribute, hasAttributeNS (2004-08-16) http://python.org/sf/1010196 closed by jlgijsbers xml.dom documentation omits createDocument, ...DocumentType (2004-08-21) http://python.org/sf/1013525 closed by jlgijsbers Documentation of DOMImplmentation lacking (2004-07-15) http://python.org/sf/991805 closed by jlgijsbers wrong documentation for popen2 (2004-01-29) http://python.org/sf/886619 closed by jlgijsbers test_inspect.py fails to clean up upon failure (2004-08-27) http://python.org/sf/1017546 closed by jlgijsbers weird/buggy inspect.getsource behavious (2003-07-11) http://python.org/sf/769569 closed by jlgijsbers SimpleHTTPServer sends wrong Content-Length header (2005-01-07) http://python.org/sf/1097597 closed by jlgijsbers urllib2: improper capitalization of headers (2004-07-19) http://python.org/sf/994101 closed by jlgijsbers urlparse doesn't handle host?bla (2002-04-24) http://python.org/sf/548176 closed by jlgijsbers set objects cannot be marshalled (2005-01-09) http://python.org/sf/1098985 closed by rhettinger codec readline() splits lines apart (2005-01-09) http://python.org/sf/1098990 closed by doerwalter tempfile files not types.FileType (2005-01-10) http://python.org/sf/1099516 closed by rhettinger for lin in file: file.tell() tells wrong (2002-11-29) http://python.org/sf/645594 closed by facundobatista Py_Main() does not perform to spec (2003-01-21) http://python.org/sf/672035 closed by facundobatista Incorrect permissions set in lib-dynload. (2003-02-04) http://python.org/sf/680379 closed by facundobatista Apple-installed Python fails to build extensions (2005-01-04) http://python.org/sf/1095822 closed by jackjansen test_shutil fails on NetBSD 2.0 (2005-01-12) http://python.org/sf/1101236 closed by jlgijsbers CSV reader does not parse Mac line endings (2003-08-16) http://python.org/sf/789519 closed by andrewmcnamara Bugs in _csv module - lineterminator (2004-11-24) http://python.org/sf/1072404 closed by andrewmcnamara % operator bug (2005-01-14) http://python.org/sf/1102141 closed by rhettinger test_atexit fails in directories with spaces (2003-03-18) http://python.org/sf/705792 closed by facundobatista SEEK_{SET,CUR,END} missing in 2.2.2 (2003-03-29) http://python.org/sf/711830 closed by loewis CGIHTTPServer cannot manage cgi in sub directories (2003-07-28) http://python.org/sf/778804 closed by facundobatista double symlinking corrupts sys.path[0] (2003-08-24) http://python.org/sf/794291 closed by facundobatista popen3 under threads reports different stderr results (2003-12-09) http://python.org/sf/856706 closed by facundobatista Signals discard one level of exception handling (2003-07-15) http://python.org/sf/771429 closed by facundobatista build does not respect --prefix (2002-10-27) http://python.org/sf/629345 closed by facundobatista urllib2 proxyhandle won't work. (2001-11-30) http://python.org/sf/487471 closed by facundobatista RFE Closed __________ popen does not like filenames with spaces (2003-07-20) http://python.org/sf/774546 closed by rhettinger From elephantum at dezcom.mephi.ru Sun Jan 9 05:51:49 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 13:51:49 +0300 Subject: python3: accessing the result of 'if' In-Reply-To: <1105236383.521393.40680@c13g2000cwb.googlegroups.com> References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> <1105236383.521393.40680@c13g2000cwb.googlegroups.com> Message-ID: <34cgm6F468o4tU1@individual.net> Carl Banks wrote: > As a compromise, howabout: > > . if m > 20 where m=something(): > . do_something_with(m) That's good, but first idea was about 'where' block that contains any expressions, that we need, for example function definition. the syntax you proposed has same problems as 'lambda'. > The main problem here (as some would see it) is that you can't do > something this: > > . if m > 20 where (def m(): a(); b()): exactly From maxm at mxm.dk Fri Jan 7 17:31:54 2005 From: maxm at mxm.dk (Max M) Date: Fri, 07 Jan 2005 23:31:54 +0100 Subject: Returning same type as self for arithmetic in subclasses Message-ID: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> # -*- coding: latin-1 -*- """ I subclass datetime and timedelta >>> dt = myDatetime(1970,1,1) >>> type(dt) >>> td = myTimedelta(hours=1) >>> type(td) But when I do arithmetic with these classes, they return datetime and timedelta, where I want them to return myDatetime and myTimedelta >>> new_time = dt + td >>> new_time datetime.datetime(1970, 1, 1, 1, 0) >>> type(new_time) So I wondered if there was a simlpler way to coerce the result into my desired types rather than overwriting the __add__, __sub__ etc. methods? """ from datetime import datetime, timedelta class myDatetime(datetime): pass class myTimedelta(timedelta): pass if __name__ == "__main__": import os.path, doctest, dtime # import and test this file doctest.testmod(dtime) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From skip at pobox.com Mon Jan 31 14:55:36 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 31 Jan 2005 13:55:36 -0600 Subject: [ANN] Spike Asset Manager release 0.13 In-Reply-To: <1107196878.026930.154270@c13g2000cwb.googlegroups.com> References: <1107196878.026930.154270@c13g2000cwb.googlegroups.com> Message-ID: <16894.36152.345508.583247@montanaro.dyndns.org> Matt> Spike Asset Manager (SAM) is an open-source cross-platform Matt> framework written in python for probing a system for components Matt> and reporting them. Matt, That's a pretty generic description. Pardon my ignorance, but what's the advantage over, for example, "rpm -aq | grep httpd"? -- Skip Montanaro skip at mojam.com http://www.mojam.com/ From rbt at athop1.ath.vt.edu Mon Jan 10 13:42:05 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 10 Jan 2005 13:42:05 -0500 Subject: ftplib with unknown file names In-Reply-To: References: Message-ID: Jeremy Jones wrote: > rbt wrote: > >> How can I use ftplib to retrieve files when I do not know their names? >> I can do this to get a listing of the directory's contents: >> >> ftp_server.retrlines('LIST') >> >> >> The output from this goes to the console and I can't figure out how to >> turn that into something I can use to actually get the files (like a >> list of file names). I read a bit about the callback function that can >> be passed to retrlines but I couldn't figure out how to use it. >> >> Any help is appreciated. >> >> Thanks! > > > .nlst(argument) will return a list of file names. Here are > the docs for the nlst command: > > http://www.python.org/doc/current/lib/ftp-objects.html > > > HTH, > > Jeremy Jones Very good Jeremy! Thank you for pointing that out. It works great. From mt at 3planes.com Sun Jan 30 12:10:22 2005 From: mt at 3planes.com (Michael Tobis) Date: 30 Jan 2005 09:10:22 -0800 Subject: Coding style article with interesting section on white space In-Reply-To: <1107059169.510996.262480@z14g2000cwz.googlegroups.com> References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> Message-ID: <1107105022.827941.114510@c13g2000cwb.googlegroups.com> beliavsky at aol.com wrote: > Michael Tobis wrote: > > (unwisely taking the bait...) > > > > If you like your language to look like this > > http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html > > then more power to you. > > Thanks for pointing out that interesting article on Fortran 90 bugs. > How long would a comparable C++ list be? Even Python has gotchas, for > example the difference between deep and shallow copies. The reply "C++ is even worse", while debatable either way, seems to be a common response from Fortran defenders. It misses the point. What the scientific community needs, whether they know it or not, is high-performance Python if that's possible, or something as close to it as possible. Specifically, something with serious introspective power and economy of expression. > > I prefer my languages to be portable, terse and expressive. > > Fortran programmers are generally happy with the portability of the > language. Until they try to port something...? Honestly, I can't imagine where anyone would get this impression. Now, about the terseness and expressiveness? > For scientific computation, consider the case of Numeric > and Numarray. I'm not happy with these, because they either make temporary arrays with wild abandon, or enforce an unnatural style of expression. I could see how they would be useful to others but they are awkward in long-time spatially coarse finite difference/finite volume/spectral calculations, which is the problem space I care about. As for non-coarse (finite element) integrations (where rectangular decompositions do not suffice) it seems to me that using Fortran is sheer madness, even though there are real pointers now. I do not suggest that Python is currently competitive with C++ or Fortran. I simply agree with http://www.fortranstatement.com that something new ought to be designed, that a backward compatible Fortran2003 cannot possibly be it, and that attention to fortran diverts resources from teh osrt of genuine progress that ought to be possible. > The recent "Pystone Benchmark" message says that Python is only 75% as > fast on Linux as on Windows. Fortran programs do not suffer this > performance hit and are in this respect more portable. In theory, as > has been mentioned, one could use a faster compiler to compile CPython > on Linux, but AFAIK this has not yet been done. Without disagreeing with Alex Martelli's response to this, I find it nonsensical on other grounds. Performance portability has nothing to do with what I'm talking about. The answer belies the attitude that programmers are there to put in time and expend effort, because the only resource worth considering is production cycles on a big machine. This attitude explains why working with Fortran is so unpleasant an experience for anyone who has been exposed to other languages. An alternative attitude is that the amount of human effort put into solving a problem is a relevant factor. In this view, "portability" is actually about build effort, not runtime performance. Perhaps the Fortran community finds this idea surprising? Getting a python package working usually amounts to an install command to the OS and an import command to the interpreter. Then you can get down to work. Getting a Fortran package working involves not only an endless dance with obscure compiler flags and library links, but then a set of workarounds for codes that produce expected results on one compiler and compile failures or even different results on another. The day when project cost was dominated by machine time as opposed to programmer time is coming to a close. Fortran is a meaningful solution only to the extent that programmer time is not just secondary but actually negligible as a cost. The assumption that portability is somehow about performance belies total lack of concern for the programmer as a resource, and therefore to the time-to-solution of any new class of scientific problem. The result of this habit of thought (entirely appropriate to 1955) is that in an environment where fortran is expected, new problems are interpreted as changes to old problems, and the packages become vast and bloated. Since most of these legacy codes in practice predate any concept of design-for-test, they are also almost certainly wrong, in the sense that they are unlikely to implement the mathematics they purport to implement. Usually they are "close enough" for some purposes, but it's impossible to delimit what purposes are inside or outside the range of application. > Nobody is stopping Python developers from working on projects like > Psyco. They aren't helping either, for the most part. Psyco aside, institutions that ought to be supporting development of high-performance high-expressiveness scientific languages are not doing so. Institutions with a Fortran legacy base are confused between maintaining the existing investment and expanding it. The former is frequently a mistake already, but the latter is a mistake almost always. This mistake drives investment of effort in inefficient directions, where efficiency is about design and build cost-to-solution rather than runtime cost-of-execution. > So uninterested in interoperability is the Fortran standards committee > that they added interoperability with C in Fortran 2003 standard. Er, replaced the modest C interoperability they lost in F90, right? The codes I care about aren't new ones. So now I have to hack into the code and redeclare all my arrays, right? So that they'll have a defined structure? And hope that doesn't break some other assumptions? Except that I have to await someone actually releasing an F03 compiler, right? Thanks. It turns out that I need a compiler, not a specification, unfortunately. Even so, I understood that there was some resistance to even this level of interoperability, because it breaks the Fortran no-convention convention. C-interop vapor-mode will require, (oh horror!) a specification for which bytes represent what. Now each vendor will have to try to patch that back in to their idiosyncratic representation. They'll probably get it mostly right, eventually. > > Python fundamentally respects the programmer. > > What does that mean? > If you don't know by now, don't mess with it. mt From apardon at forel.vub.ac.be Thu Jan 13 08:33:02 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 13:33:02 GMT Subject: Unclear On Class Variables References: Message-ID: Op 2005-01-13, harold fellermann schreef : > Hi Tim, > > If you have > > class Foo(object) : > x = 0 > y = 1 > > foo = Foo() > > foo.x # reads either instance or class attribute (class in this case) > > foo.x = val # sets an instance attribute (because foo is instance not > class) > > Foo.x = val # sets a class attribute > foo.__class.__x = val # does the same > > this might be sometimes confusing. IMHO, the following is especially > nasty: > > >>> foo = Foo() > >>> foo.x += 1 > >>> > >>> print foo.x > 1 > >>> print Foo.x > 0 > > although the += operator looks like an inplace add it isn't. > it is just syntactic sugar for foo.x = foo.x + 1. Except is x belongs to a mutable class that implements the += operator as an inplace add. Try the same but with x = [2] and foo.x += [3] -- Antoon Pardon From sara_fwd at yahoo.com Sat Jan 15 08:10:23 2005 From: sara_fwd at yahoo.com (Sara Fwd) Date: Sat, 15 Jan 2005 05:10:23 -0800 (PST) Subject: How can I get the names of the files in a directory? Message-ID: <20050115131023.36656.qmail@web50501.mail.yahoo.com> Can you guys also help me find a module that looks in a directory and print out the names of the files in there? __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail From f.geiger at vol.at Sat Jan 29 03:24:56 2005 From: f.geiger at vol.at (F. GEIGER) Date: Sat, 29 Jan 2005 09:24:56 +0100 Subject: boa constructor & mysql References: <2005012900090816807%mikybNO@SPAMinterfreeit> Message-ID: Look at the wx demos. Another idea: Use a virtual list control. In the OnGetItemText() you could do the appropriate SQL query. Workedpretty well for me. HTH Franz GEIGER "Michele" schrieb im Newsbeitrag news:2005012900090816807%mikybNO at SPAMinterfreeit... > I've search a lot to found how visualize a mysql table in a gui (wxpython). > I think to use wxgrid to visualize this table...but I don't know how... > > Anyone help me? > > Thanks a lot for the patience. > > Michele > From douardda at free.fr Sat Jan 29 13:29:41 2005 From: douardda at free.fr (David Douard) Date: Sat, 29 Jan 2005 19:29:41 +0100 Subject: Independence of programs! References: Message-ID: <41fbd33a$0$28942$636a15ce@news.free.fr> blade8472 wrote: > > Hey all, hope all is fine, I have a question; I am new in python > programming, I write the programs to a text doc then I run them with > the interpreter, so I wanna know whether I can save the programs as > exe so that they can be run independently on other PCs without the > python interpreter. > hope you help me, thanks alot! If you are under Microsoft Windows (which I guess, according your question), you may use py2exe ( http://starship.python.net/crew/theller/py2exe/ ). It will do all the required stuff for you to have a standalone executable. David From dwyoon at TpuruninfoD.TcoD.Tkr Wed Jan 5 01:36:30 2005 From: dwyoon at TpuruninfoD.TcoD.Tkr (Daewon YOON) Date: Wed, 05 Jan 2005 15:36:30 +0900 Subject: % operation Message-ID: ==== Python 1.5.2 (#1, Jul 5 2001, 03:02:19) [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> x=9 >>> y=4 >>> x%y 1 >>> for z in range(44): ... z%9 File "", line 2 z%9 ^ SyntaxError: invalid syntax ==== What's wrong with the above operation and how can I get the correct modulo result with Python? -- ZOO-< From morphex at gmail.com Thu Jan 13 13:45:25 2005 From: morphex at gmail.com (morphex) Date: 13 Jan 2005 10:45:25 -0800 Subject: Creating text on images In-Reply-To: References: <1105591796.422252.190990@f14g2000cwb.googlegroups.com> Message-ID: <1105641925.111934.53400@c13g2000cwb.googlegroups.com> Yes, something like that. I was a bit confused when it came to using truetype fonts, but that was straightforward enough (just pass font objects to the text method). :) From hans at zephyrfalcon.org Tue Jan 4 11:46:21 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 04 Jan 2005 11:46:21 -0500 Subject: Python evolution: Unease In-Reply-To: <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Iwan van der Kleyn wrote: > > >>to be determine the way foreward for Python: more features, increased >>complexity, less dynamism. Lots of syntax crud, without addressing the > > > As a student of human nature, I'm _really_ curious as to how one could > possibly read the key document: > http://www.python.org/peps/pep-3000.html > and think in consequence of "more features, increased complexity". > > Also, you keep talking about "the core python team" on the basis, it > would appear, of reading one document by Guido. Have you bothered doing > a MINIMUM of homework, such as, looking at > http://www.amk.ca/diary/archives/cat_python.html > and specifically AMK's entry for September 30? I'm trying to understand > whether you completely missed doing the most elementary amount of > background searching before venting on the group, or if you did find and > read the obvious documents and somehow STILL manage to completely ignore > their contents or read them as saying exactly the opposite of what they > _do_ say... Optimistic documents about a cleaner and smaller language (and an improved stdlib) are all well and good, but if you look what has actually been happening to Python over the last few years, then the OP's worries don't seem so far-fetched. "More features, increased complexity, less dynamism" pretty much sums it up. Guido's posts about optional static typing seem to suggest that this development will continue in the same vein. (He may just be putting his thoughts on paper, but it's the BDFL, so what is one supposed to think?) I for one will NOT welcome our new static typing overlords. ;-) -- Hans Nowak http://zephyrfalcon.org/ From steve at holdenweb.com Fri Jan 14 11:03:36 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 11:03:36 -0500 Subject: import problems *newbie* In-Reply-To: <41e7959b$0$385$636a15ce@news.free.fr> References: <1105682316.601321.118820@f14g2000cwb.googlegroups.com> <41e7959b$0$385$636a15ce@news.free.fr> Message-ID: <41E7ED58.80908@holdenweb.com> F. Petitjean wrote: > Le 13 Jan 2005 21:58:36 -0800, mike kreiner a ?crit : > >>I am having trouble importing a module I created. I'm running PythonWin >>on Windows XP if that helps. I saved my module in a folder called >>my_scripts in the site-packages directory. I edited the python path to >>include the my_scripts folder (it now reads >>C:\Python23\Lib;C:\Python23\DLLs;C:\Python23\Lib\lib-tk;C:\Python23\Lib\site-packages\my_scripts). > > Not a very godd idea to mess with the python path > Furthermore it should not be necessary! >>When I try to import the module, I get this error: >> >> >>>>>from PolyDraw import * >> >>Traceback (most recent call last): >>File "", line 1, in ? >>ImportError: No module named PolyDraw >> OK, have your modifications to the path worked? Try adding import sys print sys.path before the import statement to verify what Python is actually using as the path. >>When I select Browse PythonPath from the tools menu, I'm able to locate >>my module, PolyDraw.py. >> >>The problem goes away if I open PolyDraw.py from PythonWin, which I'm >>assuming is because opening the module makes my_scripts the current >>working directory. This is just a quick workaround, but I'd like to >>know how to fix the problem. Thanks. > > A quick fix is to promote your my_scripts folder to be a python package, > by creating a python module (file) named __init__.py right in the > package directory. The content of __init__.py can be for instance The __init__.py can actually be completely empty, but surely then you'd have to import the module by from my_scripts import PolyDraw which is a little less convenient. It would be easier (and also easier than modifying the PYTHONPATH) just to create a .pth file (say C:\Python23\Lib\site-packages\my.pth) containing the single line my_scripts and that should ensure that the directory really *is* on your path. The *name* of the .pth file is irrelevant, and you can actually have several lines naming different directories (whose paths can be absolute, or relative to the directory containing the .pth file). Obviously you should check that the path's setting is correct using the technique allowed above. > #!/usr/bin/env python > # -*- coding: Latin-1 -*- > """ > my_scripts package containing miscellaneous modules > PolyDraw > .... > """ > __author__ = 'mike kreiner' > > To import from this package the syntax is > from my_scripts import PolyDraw > Let's not recommend this as a way around the problem - let's find out what the problem actually *is* and fix it ;-) 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 steve at holdenweb.com Wed Jan 26 09:13:22 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 26 Jan 2005 09:13:22 -0500 Subject: PyCon: Early Bird Deadline two days away [really]! Message-ID: Pythonistas: If you have been putting off your registration, stop putting it off! Last year the early bird deadline was extended because we were a little late getting the program together. This year the program was published two weeks in advance of the deadline for early bird registrations, which is JANUARY 28 (and it's already January 26). So, don't delay: save yourself $75 and register by midnight Friday. Which time zone, you ask. Why wait and find out - it only takes a couple of minutes to register. http://www.python.org/pycon/2005/register.html regards Steve Holden Chairman, PyCON DC 2005 -- PyCon DC 2005: The third Python Community Conference http://www.pycon.org/ http://www.python.org/pycon/ The scoop on Python implementations and applications From sjmachin at lexicon.net Sun Jan 9 18:43:15 2005 From: sjmachin at lexicon.net (John Machin) Date: 9 Jan 2005 15:43:15 -0800 Subject: Python3: on removing map, reduce, filter In-Reply-To: <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> Message-ID: <1105314195.310792.163170@c13g2000cwb.googlegroups.com> Steven Bethard wrote: > Note that list comprehensions are also C-implemented, AFAIK. Rather strange meaning attached to "C-implemented". The implementation generates the code that would have been generated had you written out the loop yourself, with a speed boost (compared with the fastest DIY approach) from using a special-purpose opcode LIST_APPEND. See below. >>> def afunc(n): ... return [x*x for x in xrange(n)] ... >>> afunc(3) [0, 1, 4] >>> import dis >>> dis.dis(afunc) 2 0 BUILD_LIST 0 3 DUP_TOP 4 STORE_FAST 1 (_[1]) 7 LOAD_GLOBAL 1 (xrange) 10 LOAD_FAST 0 (n) 13 CALL_FUNCTION 1 16 GET_ITER >> 17 FOR_ITER 17 (to 37) 20 STORE_FAST 2 (x) 23 LOAD_FAST 1 (_[1]) 26 LOAD_FAST 2 (x) 29 LOAD_FAST 2 (x) 32 BINARY_MULTIPLY 33 LIST_APPEND 34 JUMP_ABSOLUTE 17 >> 37 DELETE_FAST 1 (_[1]) 40 RETURN_VALUE >>> def bfunc(n): ... blist=[]; blapp=blist.append ... for x in xrange(n): ... blapp(x*x) ... return blist ... >>> bfunc(3) [0, 1, 4] >>> dis.dis(bfunc) 2 0 BUILD_LIST 0 3 STORE_FAST 3 (blist) 6 LOAD_FAST 3 (blist) 9 LOAD_ATTR 1 (append) 12 STORE_FAST 2 (blapp) 3 15 SETUP_LOOP 34 (to 52) 18 LOAD_GLOBAL 3 (xrange) 21 LOAD_FAST 0 (n) 24 CALL_FUNCTION 1 27 GET_ITER >> 28 FOR_ITER 20 (to 51) 31 STORE_FAST 1 (x) 4 34 LOAD_FAST 2 (blapp) 37 LOAD_FAST 1 (x) 40 LOAD_FAST 1 (x) 43 BINARY_MULTIPLY 44 CALL_FUNCTION 1 47 POP_TOP 48 JUMP_ABSOLUTE 28 >> 51 POP_BLOCK 5 >> 52 LOAD_FAST 3 (blist) 55 RETURN_VALUE >>> From philippecmartin at sbcglobal.net Sun Jan 30 10:19:22 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Sun, 30 Jan 2005 09:19:22 -0600 Subject: naive doc question Message-ID: <1107098362.7164.1.camel@localhost> Gabriel B. wrote: > Is it just me that can't find a full reference in the docs? > > I wanted a list of all the methods of dict for example... where can i > find it? > > Thanks, and sorry if this question is just dumb, i really can't find > it Also if you are using mozilla or firefox, I suggest you try this documentation sidebar: http://projects.edgewall.com/python-sidebar/ Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From http Mon Jan 10 05:17:24 2005 From: http (Paul Rubin) Date: 10 Jan 2005 02:17:24 -0800 Subject: Python serial data aquisition References: <41e1b833$1_3@omega.dimensional.com> Message-ID: <7x4qhpeggb.fsf@ruckus.brouhaha.com> fccoelho at gmail.com (Flavio codeco coelho) writes: > I'll put your Ideas to the test ASAP, meanwhile, could you point me to > references to these bit operations in Python? I am new to this stuff, > and might need to do more of this to support other hardware... > > I havent been able to find anything about this on the python > documentation.. ord(ch) turns a character into an integer, i.e. ord('a') = 97, etc. You can use the << (left shift), >> (right shift), | (logical or), and & (logical and) operations just like in C. So for your diagram |-------------bits(1-8)-----------| Byte1: x x x n1 n2 n3 n4 n5 Byte2: x n6 n7 n8 n9 n10 n11 n12 assuming n1 is the high order bit, you'd just say value = ((ord(byte1) & 0x1f) << 7) | (ord(byte2) & 0x3f) or something like that. From Danielnord15 at yahoo.se Sun Jan 2 06:47:49 2005 From: Danielnord15 at yahoo.se (Svennglenn) Date: 2 Jan 2005 03:47:49 -0800 Subject: Problems programming with Tkinter Message-ID: <1104666469.813371.204280@c13g2000cwb.googlegroups.com> Hi ! I'm trying to create a graphical program using Tkinter. The program is supposed to save a string the user defines as a filename. I've made it work with the the first button in the program that's named "Spara ett v?rde i en str?ng till ett filnamn", that's swedish for "Save a value in a string as a file name". The button "Skriv ett v?rde till filen" (swedish for "Write a value to the file") But, i want the program to open a new dialogue when i press the button "Visa ruta" and in that dialogue will be a field where you can enter a value directly in the program, but a can't get it to work because is don't know how i shall do to open a new dialogue window in the program? Is there someone who can help me with my problem? Here's the sourcecode for my program: from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.hi_there = Button(frame, text="Spara ett v?rde i en str?ng till ett filnamn", command=self.say_hi) self.hi_there.pack(side=LEFT) self.skriv_varde = Button(frame, text="Skriv ett v?rde till filen", command=self.skriv_varde) self.skriv_varde.pack(side=LEFT) self.visa_ruta = Button(frame, text="Visa ruta", command=self.visa_ruta) self.visa_ruta.pack(side=LEFT) def say_hi(self): print "Sparar fil" S = "filen.fil" output = open(S, 'w') print "Filen sparad" def skriv_varde(self): print "Skriver v?rde till filen" myfile = open('filen.fil', 'w') myfile.write('Ny mening') myfile.close() print "V?rdet till filen skrivet" def visa_ruta(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() app = App(root) root.mainloop() From m-le-van-kiem at bordeaux-port.fr Thu Jan 13 09:49:33 2005 From: m-le-van-kiem at bordeaux-port.fr (Michel LE VAN KIEM) Date: Thu, 13 Jan 2005 15:49:33 +0100 Subject: How to install pyparallel Message-ID: <41e689fc$0$15700$626a14ce@news.free.fr> Hi everybody ! I'm trying to install the pyparallel module for my Python 2.3.4 (runs on a FC3) but I do have some troubles. When I import the parallel module, python shows the following message : >>> import parallel /usr/lib/python2.3/site-packages/parallel/parallelppdev.py:32: FutureWarning: x<>> p=parallel.Parallel() ppdev0: failed to register device ! ... IOError: [No such device or address] Some help would be appreciated. Michel From premshree.pillai at gmail.com Tue Jan 4 11:32:35 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Tue, 4 Jan 2005 22:02:35 +0530 Subject: Cookbook 2nd ed Credits (was Re: The Industry choice) In-Reply-To: <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> Message-ID: Do contributors of less than 5 recipes get a copy too? :-? Btw, is there a comprehensive list of ALL contributors put up anywhere? On Tue, 4 Jan 2005 17:15:53 +0100, Alex Martelli wrote: > wrote: > > > But then I have THREE published recipes!! > > Does that mean that I get three free copies of the cookbook ? ;-) > > ...ti piacerebbe eh...?-) Sorry, "one each", even though you have > _five_ credits. For the curious, here's the roster of most credited > contributors (remember, significant comments we merged into other's > recipes also count!-)...: > > 1: 42 u'Alex Martelli' > 2: 26 u'Raymond Hettinger' > 3: 25 u'Luther Blissett' > 4: 22 u'Peter Cogolo' > 5: 10 u'John Nielsen' > 6: 10 u'Anna Martelli Ravenscroft' > 7: 8 u'J\x9frgen Hermann' > 8: 7 u'Scott David Daniels' > 9: 7 u'Chris Perkins' > 10: 6 u'S\x8ebastien Keim' > 11: 6 u'Paul Prescod' > 12: 6 u'Noah Spurrier' > 13: 6 u'Jeff Bauer' > 14: 6 u'Holger Krekel' > 15: 6 u'Danny Yoo' > 16: 6 u'Brent Burley' > 17: 5 u'Paul Moore' > 18: 5 u'Michele Simionato' > 19: 5 u'Mark Nenadov' > 20: 5 u'David Eppstein' > 21: 5 u'Brian Quinlan' > > If you wished to count only _authored_ recipes (but that's a bit > misleading, since in several recipes-as-published there is a merge of > two or three separately submitted and accepted recipes, and here I'm > counting only the first-listed-author per published-recipe...): > > 1: 25 u'Luther Blissett' > 2: 21 u'Alex Martelli' > 3: 9 u'John Nielsen' > 4: 8 u'Raymond Hettinger' > 5: 8 u'J\x9frgen Hermann' > 6: 6 u'S\x8ebastien Keim' > 7: 6 u'Peter Cogolo' > 8: 6 u'Anna Martelli Ravenscroft' > 9: 5 u'Scott David Daniels' > 10: 5 u'Paul Prescod' > 11: 5 u'Michele Simionato' > 12: 5 u'Mark Nenadov' > 13: 5 u'Jeff Bauer' > 14: 5 u'Brent Burley' > > ...but each still gets ONE free copy...!-) > > Alex > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From pythongnome at hotmail.com Sat Jan 15 13:36:16 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Sat, 15 Jan 2005 18:36:16 GMT Subject: porting C code In-Reply-To: References: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> <0NidnetRONZTgHrcRVn-oQ@powergate.ca> Message-ID: Peter Hansen wrote: > Lucas Raab wrote: > >> Sorry, the third "byte" is what I meant. > > > Fair enough. Note, however, that as someone pointed out, > it's actually the *fourth* of something, and it would not > necessarily be a byte. In fact, in your case, it's not: > >> typedef unsigned long int word32 ; >> void mu(word32 *a) >> { >> int i ; >> word32 b[3] ; > > > This defines an array of *3* long (32-bit) integers. > >> b[0] = b[1] = b[2] = 0 ; > > > Each of these is just indexing into that array, starting > as Python does with an index origin of zero. > >> The "a[#]" and "b[#]" are the parts that are giving me trouble. > > > Between the clarifications you've got and Duncan's post, > you shouldn't have much more trouble now. :-) > > -Peter Thanks. From eino at iki.fi Tue Jan 11 10:12:39 2005 From: eino at iki.fi (=?ISO-8859-1?Q?Eino_M=E4kitalo?=) Date: Tue, 11 Jan 2005 17:12:39 +0200 Subject: Python 2.4 and os.open question? In-Reply-To: References: <41e3e670$0$20038$39db0f71@news.song.fi> Message-ID: <41e3ece8$0$25434$39db0f71@news.song.fi> Antoon Pardon wrote: > Why? What is it about the exclusive flag that > makes you like to use it? Ok. Thanks, I misunderstood the meaning of flag. What I' like to do is to open file and keep it exclusive locked for me. Apparently this flag is not for me. Eino M?kitalo From dbickett at gmail.com Sun Jan 23 14:24:50 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 23 Jan 2005 14:24:50 -0500 Subject: OT: problems mirroring python-list to c.l.py? In-Reply-To: <20050123190637.GA4820@grulic.org.ar> References: <1d6cdae305012310535980e82d@mail.gmail.com> <20050123190637.GA4820@grulic.org.ar> Message-ID: <1d6cdae305012311245658711c@mail.gmail.com> John Lenton wrote: > > On Sun, Jan 23, 2005 at 01:53:52PM -0500, Daniel Bickett wrote: > > > > > > Is there a reason that Google Groups isn't mirroring python-list > > > exactly like it used to, or is it simply a conspiracy I'm not in on? > > > > You should not ask this kind of question in a public forum, > > and *you* should know better than to go around flapping your mouth > like that. Now I'm further confused, because I don't know what you quoted, but it isn't on the mailing list and it isn't on c.l.py :) Maybe I should give up trying to figure these things out. You didn't include a name at the beginning of your citation... Who had the audacity to take my joke seriously? ;-) Daniel Bickett From sifu at isohypse.org Fri Jan 21 23:18:22 2005 From: sifu at isohypse.org (Siegmund Fuehringer) Date: Sat, 22 Jan 2005 12:18:22 +0800 Subject: list unpack trick? In-Reply-To: References: Message-ID: <20050122041822.GA8007@m.0xx0.net> On Fri, Jan 21, 2005 at 08:02:38PM -0800, aurora wrote: > I find that I use some list unpacking construct very often: > > name, value = s.split('=',1) > > So that 'a=1' unpack as name='a' and value='1' and 'a=b=c' unpack as > name='a' and value='b=c'. > > The only issue is when s does not contain the character '=', let's say it > is 'xyz', the result list has a len of 1 and the unpacking would fail. Is > there some really handy trick to pack the result list into len of 2 so > that it unpack as name='xyz' and value=''? what about: s.find( '=' )!=-1 and s.split( '=', 1 ) or [s,''] bye bye - sifu From mensanator at aol.com Sun Jan 9 19:52:46 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 9 Jan 2005 16:52:46 -0800 Subject: Old Paranoia Game in Python In-Reply-To: References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> Message-ID: <1105318366.966577.107460@c13g2000cwb.googlegroups.com> Aahz wrote: > Trust the computer, the computer is your friend. However, the computer isn't a fuckin' mind reader. If you're going to post source code on the usenet, don't have lines longer than 72 characters. Otherwise you'll find your code has wrapped lines. This not only causes syntax errors in your choose and print statements but also fucks up the formatting of of printed paragraphs. Stupid human. From fumanchu at amor.org Fri Jan 21 02:08:35 2005 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 20 Jan 2005 23:08:35 -0800 Subject: Dejavu 1.3, a Python ORM Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339823A@exchange.hqamor.amorhq.net> The Dejavu Object-Relational Mapper (version 1.3) is now available and in the public domain. Get it at svn://casadeamor.com/dejavu/trunk or http://www.aminus.org/rbre/python/. Dejavu is an Object-Relational Mapper for Python applications. It is designed to provide the "Model" third of an MVC application. Dejavu avoids making decisions in the framework which are better left to developers, and avoids forcing developers to make decisions which are better left to deployers. In particular, deployers are allowed to mix and match storage mechanisms, including how and when to cache objects in memory, making it easier for deployers to tune applications to their particular environment. Dejavu provides: MODELING LAYER 1. A base Unit class for persisting objects to storage. 2. A base Unit Property class for persistent object attributes. 3. ID Sequencers. 4. Associations between Unit classes. 5. Unit Engines, Rules, and Collections. 6. Aggregation and analysis tools. APPLICATION LAYER 1. Expressions: pure Python Unit queries. This is perhaps the most appealing feature of Dejavu. However, since it uses bytecode hacks, Dejavu only runs on CPython. 2. Sandboxes, which serve as Identity Maps and per-connection caches. Unit objects are "memorized" and "recalled" from a Sandbox, using Expressions. 3. An Arena class for application-level data. STORAGE LAYER 1. A base StorageManager class and specification. Unlike many ORMs, Dejavu does not require you to have complete control of the back end. 2. Specific StorageManagers for: a. Microsoft SQL Server/MSDE via ADO. b. Microsoft Access (Jet) via ADO. c. PostgreSQL. d. MySQL. e. SQLite. f. ODBC databases (not complete, and probably never will be). g. Shelve to dbm. Major changes from 1.2: 1. Support for PostgreSQL, MySQL, and SQLite. 2. New db module which abstracts common DB StorageManager code. 3. Full support for decimal and fixedpoint. 4. zoo_fixture.py brings common tests to all StorageManagers. Dejavu welcomes your use and feedback as an application developer. Dejavu also welcomes framework developers. New code for additional Storage Managers, analysis tools, or other portions will be gladly reviewed for inclusion in future releases. Drop me an email if you feel so inclined. Robert Brewer MIS Amor Ministries fumanchu at amor.org From ricardo.b at zmail.pt Tue Jan 18 17:45:48 2005 From: ricardo.b at zmail.pt (Ricardo Bugalho) Date: Tue, 18 Jan 2005 22:45:48 +0000 Subject: simultaneous multiple requests to very simple database References: Message-ID: On Tue, 18 Jan 2005 17:33:26 -0500, Eric S. Johansson wrote: > When I look at databases, I see a bunch of very good solutions that are > either overly complex or heavyweight on one hand and very nice and simple > but unable to deal with concurrency on the other. two sets of point > solutions that try to stretch themselves and the developers to fit other > application contexts. > Have you considerded SQLite/pySQLite ? -- Ricardo From __peter__ at web.de Wed Jan 26 06:26:59 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Jan 2005 12:26:59 +0100 Subject: string.atoi and string.atol broken? References: <1106700417.482871.45140@z14g2000cwz.googlegroups.com> Message-ID: Christos TZOTZIOY Georgiou wrote: > On Wed, 26 Jan 2005 08:58:45 +0100, rumours say that Peter Otten > <__peter__ at web.de> might have written: > >>By the way, does anyone know the Greek name for 36? > > triakontahexadecimal would be a nice compromise of greek and the > "hexadecimal" convention of having six before ten -- "???" ("hexi") is > six, "????" ("deka") is ten, "?????????" ("triakonta") is thirty. I > think in ancient Greek sometimes units came before tens, just like in > German (another similarity is the verb in the end of the sentence, as > Mark Twain also noted sometime in a humourous article AFAIR.) > > In current Greek hexadecimal is "????????????" ("dekaexadikon"). The Latin part escaped me. Now we need unicode names in Python, and the fun can really begin. I had you in mind with my question, thank you. Peter From gabriel.barros at gmail.com Sun Jan 23 21:00:52 2005 From: gabriel.barros at gmail.com (Gabriel B.) Date: Mon, 24 Jan 2005 00:00:52 -0200 Subject: python newt under win32 Message-ID: <5175a81c05012318003ff66a46@mail.gmail.com> Anyone has any info if there's something similar to Newt lib for win32? Thanks Gabriel From devries at idolstarastronomer.com Mon Jan 31 10:49:29 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: Mon, 31 Jan 2005 10:49:29 -0500 Subject: how to find number of processors in python In-Reply-To: <822e8fe0.0501302113.4716c2ba@posting.google.com> References: <822e8fe0.0501302113.4716c2ba@posting.google.com> Message-ID: <20050131154928.GA10363@miyu.cjas.org> "/usr/sbin/psrinfo -p" will print the number of physical processors on the system, though it does not indocate if they are on- or off-line. You could also write an extension which gets processor information using the sys/processor library. Example code is available in the "p_online" man page. Chris From harold.fellermann at upf.edu Tue Jan 11 05:46:37 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 11 Jan 2005 11:46:37 +0100 Subject: here document In-Reply-To: References: Message-ID: <1166F26E-63BE-11D9-B3E0-003065FB7B26@upf.edu> On 11.01.2005, at 11:34, Nader Emami wrote: > Would somebody help me how i can write the 'here document' in > Python script please? I have a csh script in which a program > is invoked with some argument in the form of here document: > > /bin/exe.x << End_Here > CategorY = GRIB > etc. > End_Here > > I translate this script to Python and i don't know how can I > do this! f = open("/bin/exe.x","w") print >>f , """CategoryY = GRIB etc. """ -- What if nothing exists and everything is an illusion? In this case I definitely overpayed my new carpet! -- Woody Allen From danperl at rogers.com Sun Jan 23 10:24:20 2005 From: danperl at rogers.com (Dan Perl) Date: Sun, 23 Jan 2005 10:24:20 -0500 Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: "Xah Lee" wrote in message news:1106472508.591411.40140 at c13g2000cwb.googlegroups.com... > the beginning two paragraphs should be deleted. Nobody gives a shit > except a few smug academicians where the author wrote it for pleasing > himself. For 99% of readers, it is incomprehensible and irrelevant. > > the first paragraph of 9.1 "A Word About Terminology" is epitome of > masturbation. The entire 9.1 is not necessary. > > Large part of 9.2 "Python Scopes and Name Spaces" is again > masturbatory. This is a perfect description for your own postings. Why don't you follow your own advice? From philippecmartin at sbcglobal.net Wed Jan 5 05:14:02 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Wed, 05 Jan 2005 11:14:02 +0100 Subject: smtp question Message-ID: <1104920042.7006.30.camel@localhost> Hi, I am testing the smtp module and have the following question: in the code below (taken from net sample) prior to adding the "Subject:" field, the email client found the "From" and the "To". Without the "Subject:" field on I get this: Email client = Evolution: the "From" field is blank Email client = KMail: the "To" field is blank Any clue ? Thanks and regards, Philippe ********************** import smtplib def prompt(prompt): return raw_input(prompt).strip() fromaddr = prompt("From: ") toaddrs = prompt("To: ").split() print "Enter message, end with ^D (Unix) or ^Z (Windows):" # Add the From: and To: headers at the start! msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs))) while 1: try: line = raw_input() except EOFError: break if not line: break msg = msg + line print "Message length is " + repr(len(msg)) server = smtplib.SMTP('smtp.sbcglobal.yahoo.com') server.set_debuglevel(1) server.login ('xxxxx','yyyyyyy') server.sendmail(fromaddr, toaddrs, 'Subject:from python\n\n'+msg) server.quit() -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From http Sat Jan 22 07:40:25 2005 From: http (Paul Rubin) Date: 22 Jan 2005 04:40:25 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <1gqsayh.th49i518ixczeN%aleaxit@yahoo.com> Message-ID: <7xpszxljra.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > If it changed the semantics of for-loops in general, that would be quite > inconvenient to me -- once in a while I do rely on Python's semantics > (maintaining the loop control variable after a break; I don't recall if > I ever used the fact that the variable is also maintained upon normal > termination). Some languages let you say things like: for (var x = 0; x < 10; x++) do_something(x); and that limits the scope of x to the for loop. That seems like a reasonable way to offer for-loops that don't leak. > (musing...): I think the reason there's no real use case for using a > listcomp's control variable afterwards is connected to this distinction: > listcomps have no `break'... Of course you can still break out of listcomps: class oops: pass def f(x): if x*x % 11 == 3: raise oops return x*x try: lcomp = [f(x) for x in range(10)] except oops: pass print x prints "5" From sara_fwd at yahoo.com Tue Jan 25 12:52:14 2005 From: sara_fwd at yahoo.com (Sara Fwd) Date: Tue, 25 Jan 2005 09:52:14 -0800 (PST) Subject: module for 'po' files Message-ID: <20050125175214.61327.qmail@web50507.mail.yahoo.com> Hi all Is there a module for processing & handling '.po' files in python? __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From ptmcg at austin.rr._bogus_.com Sun Jan 9 18:38:10 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 09 Jan 2005 23:38:10 GMT Subject: pyparsing: how to negate a grammar References: <1105229039.136595.180640@c13g2000cwb.googlegroups.com> <1105280829.930207.169770@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1105280829.930207.169770 at c13g2000cwb.googlegroups.com... > Hi Paul, > > I am trying to extract HTTP response codes from a HTTP page send from > a web server. Below is my test program. The program just hangs. > > Thanks, > Khoa > ################################################## > > Khoa - Thanks for supplying a little more information to go on. The problem you are struggling with has to do with pyparsing's handling or non-handling of whitespace, which I'll admit takes some getting used to. In general, pyparsing works its way through the input string, matching input characters against the defined pattern. This gets a little tricky when dealing with whitespace (which includes '\n' characters). In particular, restOfLine will read up to the next '\n', but will not go past it - AND restOfLine will match an empty string. So if you have a grammar that includes repetition, such as OneOrMore(restOfLine), this will read up to the next '\n', and then just keep matching forever. This is just about the case you have in your code, ZeroOrMore(BodyLine), in which BodyLine is BodyLine = Group(nonHTTP + restOfLine) You need to include something to consume the terminating '\n', which is the purpose of the LineEnd() class. Change BodyLine to BodyLine = Group(nonHTTP + restOfLine + LineEnd()) and this will break the infinite looping that occurs at the end of the first body line. (If you like, use LineEnd.suppress(), to keep the '\n' tokens from getting included with your other parsed data.) Now there is one more problem - another infinite loop at the end of the string. By similar reasoning, it is resolved by changing nonHTTP = ~Literal("HTTP/1.1") to nonHTTP = ~Literal("HTTP/1.1") + ~StringEnd() After making those two changes, your program runs to completion on my system. Usually, when someone has some problems with this kind of "line-sensitive" parsing, I recommend that they consider using pyparsing in a different manner, or use some other technique. For instance, you might use pyparsing's scanString generator to match on the HTTP lines, as in for toks,start,end in StatusLine.scanString(data): print toks,toks[0].StatusCode, toks[0].ReasonPhrase print start,end which gives [['HTTP/1.1', '200', ' OK']] 200 OK 0 15 [['HTTP/1.1', '400', ' Bad request']] 400 Bad request 66 90 [['HTTP/1.1', '500', ' Bad request']] 500 Bad request 142 166 If you need the intervening body text, you can use the start and end values to extract it in slices from the input data string. Or, since your data is reasonably well-formed, you could just use readlines, or data.split('\n'), and find the HTTP lines using startswith(). While this is a brute force approach, it will run certainly many times faster than pyparsing. In any event, best of luck using pyparsing, and write back if you have other questions. -- Paul From pas at demail.svp Tue Jan 18 15:32:10 2005 From: pas at demail.svp (arN) Date: Tue, 18 Jan 2005 21:32:10 +0100 Subject: Window capture using WM_PRINT and Python Message-ID: <41ed7017$0$23339$7a628cd7@news.club-internet.fr> Hi ! I'm a Java developper and I wish to make a capture of an offscreen window (on WinXP). It's not possible in Java, so I use a python script and WM_PRINT, but it doesn't seem to work. Could someone have a look at my script and give me any advise ? TIA -- Arnaud my python script : python snap.py GraphicalContext_handle image_handle -------------------------------------------------------------------------------------------------- snap.py : " import win32api, win32con, sys win32api.SendMessage(sys.argv[2], win32con.WM_PAINT, sys.argv[3], 0) win32api.SendMessage(sys.argv[2], win32con.WM_PRINT, sys.argv[3], win32con.PRF_CHILDREN | win32con.PRF_CLIENT | win32con.PRF_OWNED) " ------------------------------------------------------------------------------------------------ snippet from Snapshot.java : " public static Image snapshot(Composite bean) { GC gc = new GC(bean); final Image image = new Image (null, bean.getBounds().width, bean.getBounds().height); String commmand = "python snap.py " + gc.handle + " " + image.handle; Runtime rt = Runtime.getRuntime(); try { Process p = rt.exec(command); } catch (.....) gc.dispose(); return image; } " From steve at holdenweb.com Wed Jan 19 16:46:32 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Jan 2005 16:46:32 -0500 Subject: Zen of Python In-Reply-To: References: Message-ID: Peter Hansen wrote: > Timothy Fitz wrote: > >> While I agree that the Zen of Python is an amazingly concise list of >> truisms, I do not see any meaning in: >> >> Flat is better than nested. >> [incrdeibly secret PSU facts blurted out] > > And with that out of the way, one is left with "there's a balance > along the flat/nested dimension which is appropriate to any > given situation, so nest with moderation and only when necessary". > They'd probably been talking to Antoon Pardon :-) > But that didn't fit in the list so they went with the shorter version... > 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 aahz at pythoncraft.com Tue Jan 25 23:45:57 2005 From: aahz at pythoncraft.com (Aahz) Date: 25 Jan 2005 23:45:57 -0500 Subject: re Insanity References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> Message-ID: In article <4ln9c2-0mh1.ln1 at eskimo.tundraware.com>, Tim Daneliuk wrote: > >Given an arbitrary string, I want to find each individual instance of >text in the form: "[PROMPT:optional text]" > >I tried this: > > y=re.compile(r'\[PROMPT:.*\]') > >Which works fine when the text is exactly "[PROMPT:whatever]" but >does not match on: > > "something [PROMPT:foo] something [PROMPT:bar] something ..." > >The overall goal is to identify the beginning and end of each [PROMPT...] >string in the line. > >Ideas anyone? Yeah, read the Friedl book. (Okay, so that's not gonna help right now, but trust me, if you're going to write lots of regexes, READ THAT BOOK.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From richie at entrian.com Tue Jan 11 12:15:48 2005 From: richie at entrian.com (Richie Hindle) Date: Tue, 11 Jan 2005 17:15:48 +0000 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: <7xu0pndi6n.fsf@ruckus.brouhaha.com> References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> Message-ID: <9128u0pnvb9vm8630mk99k89l4e7oes5r9@4ax.com> [Paul] > [MoinMoin] doesn't have [...] automatic update notification for > specific pages of your choice Yes it does. See http://entrian.com/sbwiki for example - register there and you'll see in your preferences "Subscribed wiki pages (one regex per line)" > The BogusMixedCaseLinkNames. I'd rather have ordinary words with > spaces between them, like we use in ordinary writing. MoinMoin has an option to display WikiWords with spaces between them (albeit still capitalised), again in the user preferences. I'm not saying that MoinMoin is better than MediaWiki, just that it really does have some of the features you say it doesn't (perhaps you've been looking at an old version). -- Richie Hindle richie at entrian.com From irmen at -nospam-remove-this-xs4all.nl Sat Jan 15 23:06:47 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 16 Jan 2005 05:06:47 +0100 Subject: there's a socket.sendall(), so why no socket.recvall()? In-Reply-To: <41e03ccc$0$6208$e4fe514c@news.xs4all.nl> References: <41e03ccc$0$6208$e4fe514c@news.xs4all.nl> Message-ID: <41e9e854$0$6212$e4fe514c@news.xs4all.nl> Irmen de Jong wrote: >>> Subject says it all; >>> there's a socket.sendall(), so why no socket.recvall()? [...] > I may even write a patch for socketmodule.c right now :-D And here it is: the missing socket.recvall(). http://www.python.org/sf/1103213 --Irmen From gregor.jan at NOSPAM.quick.cz Thu Jan 27 07:53:45 2005 From: gregor.jan at NOSPAM.quick.cz (Jan Gregor) Date: Thu, 27 Jan 2005 13:53:45 +0100 Subject: redirect of standard output of jython to JTextArea In-Reply-To: References: Message-ID: problem solved. in class: sys.stdout = StdOutRedirector(self) class StdOutRedirector: def __init__(self, console): self.console = console def write(self, data): #print >> sys.stderr, ">>%s<<" % data if data != '\n': # This is a sucky hack. Fix printResult self.console.textArea.append(data) Jan Jan Gregor wrote: > Hello > > I want to redirect output of jython's functions print and println to > JTextArea component. Is it possible ? > > I tried this (swingConsole.textArea is instance): > > In my class > > self.printStream= MyPrintStream(System.out) > System.setOut(self.printStream) > > ---------------------------------------------------- > class MyPrintStream (PrintStream): > > def println (str): > swingConsole.textArea.append(str) > > def print (str): > swingConsole.textArea.append(str) > > > Output is still directed to standard output. > > > Thanks for help, > Jan From ksenia.marasanova at gmail.com Fri Jan 7 14:59:33 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Fri, 7 Jan 2005 21:59:33 +0200 Subject: escape string for command line Message-ID: <130df19305010711593b514714@mail.gmail.com> Hi, I have a simple ecard creation script on a website, where user can add text to a graphic. I use ImageMagick for it: # template_file => path to image template file # new_file => path to generated file # text => user input command = '''convert %s -font OfficinaSanITC-BookOS -pointsize 12 -fill "#8C2F48" -draw "gravity north text 0,26 '%s'" %s''' % ( template_file, text, new_file) system(command) I was wondering, is there a general way to escape the string entered by the user, to prevent code injection into command line? Will it always be safe, even when binary data is submitted through POST? Or maybe some stable Python interface for ImageMagick that takes care of it :) Thanks in advance, -- Ksenia From martinnitram at excite.com Wed Jan 19 01:12:39 2005 From: martinnitram at excite.com (martinnitram at excite.com) Date: 18 Jan 2005 22:12:39 -0800 Subject: safest way to kill a thread In-Reply-To: References: <1106106497.429643.307440@f14g2000cwb.googlegroups.com> Message-ID: <1106115159.200989.60870@c13g2000cwb.googlegroups.com> limodou wrote: >Using Thread's method setDaemon() before you call the start() method. >Just like : >t.setDaemon(True) >t.start() thank for fast reply. from python.org doc, said that setDaemon() function as "The entire Python program exits when no active non-daemon threads are left." is it mean that when the main program exit (normally/abnormally), all threads created will also exit? Thank again. From xah at xahlee.org Sun Jan 16 09:45:53 2005 From: xah at xahlee.org (Xah Lee) Date: 16 Jan 2005 06:45:53 -0800 Subject: [perl-python] 20050116 defining a function Message-ID: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> ? # the following is a example of defining ? # a function in Python. ? ? def fib(n): ? """This prints n terms of a sequence ? where each term is the sum of previous two, ? starting with terms 1 and 1.""" ? result=[];a=1;b=1 ? for i in range(n): ? result.append(b) ? a,b=b,a+b; ? result.insert(0,1) ? del result[-1] ? return result ? ? print fib(6) ? ? # note the use of .insert to insert 1 at ? # the beginning of a list, and ?del ? # result[-1]? to remove the last element ? # in a list. Also, the string ? # immediately following the function ? # definition is the function's ? # documentation. ? ? # the unusual syntax of a.insert() is ? # what's known as Object Oriented syntax style. ? ? # try writing a factorial function. ? ? ------------------- ? # the equivalent perl version is this: ? ? =pod ? ? fib(n) prints n terms of a sequence where each ? term is the sum of previous two, ? starting with terms 1 and 1. ? ? =cut ? ? use strict; ? my @result; ? my ($a, $b); ? ? sub fib($) { ? my $n= @_[0]; ? @result=();$a=1;$b=1; ? for my $i (1..$n){ ? push @result, $b; ? ($a,$b)=($b,$a+$b); ? } ? unshift @result, 1; ? pop @result; ? return @result; ? } ? ? use Data::Dumper; ? print Dumper [fib(5)]; ? ? # the =pod and =cut ? # is perl's way of demarking inline ? # documentation called POD. ? # see ?perldoc -t perlpod? ? # note: the empty line around it ? # is necessary, at least in perl version ? # 5.6 up to ~2002. ? ? # the ?use strict;? is to make perl's ? # loose syntax stricter by enforcement. ? # Its use is encouraged by ? # perl gurus, but not all standard ? # packages use it. ? ? # the ?my? are used to declare variables. ? # necessary under ?use strict;? ? # see ?perldoc -t strict? ? ? # the $ in fib($) is there to declare ? # that fib has a parameter of one scalar. ? # Its use is however optional and uncommon. ? # it is used for clarity but ? # has also met with controversy by ? # perl gurus as being unperl. ? # see ?perldoc perlsub? for ref. ? ? # the @_[0] is the first element of the ? # array @_. The @_ array is a predefined ? # array, holding arguments to subroutines. ? # see ?perldoc -t perlvar? ? ? # see ? # perldoc -tf unshift ? # perldoc -tf pop ? ? # the last line, [fib(5)], is basically ? # to make it a memory address of a copy of ? # the list returned by fib(5), so that ? # Dumper can print it. ? # see ?perldoc -t perldata? or perlref ? # for unix-styled technicalities. ? ? Xah ? xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html From forall2see_2000 at yahoo.com Mon Jan 3 08:58:02 2005 From: forall2see_2000 at yahoo.com (forall2see_2000 at yahoo.com) Date: Mon, 03 Jan 05 13:58:02 GMT Subject: website hosting Message-ID: <0501031358025172@news.usenetmonster.com> here is the place that I host my websites with . If your still looking for a good host check out http://frontpage-web-hosting.org From steve at ferg.org Fri Jan 7 16:15:29 2005 From: steve at ferg.org (Steve) Date: 7 Jan 2005 13:15:29 -0800 Subject: Tkinter: using a Listbox In-Reply-To: References: Message-ID: <1105132529.319205.311720@z14g2000cwz.googlegroups.com> > #Listbox > self.listbox = Listbox(self.selectFrame) > self.listbox.insert(END, "a list entry") > for item in ["A","B","C"]: > self.listbox.insert(END, item) Don't forget to pack the listbox. You may find this useful... http://www.ferg.org/thinking_in_tkinter/index.html From news at outbacklinux.com Mon Jan 24 07:06:13 2005 From: news at outbacklinux.com (Adrian Casey) Date: Mon, 24 Jan 2005 21:36:13 +0930 Subject: short programming projects for kids References: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> Message-ID: <41f4e4b5@duster.adelaide.on.net> Andr? Roberge wrote: > bobdc wrote: >> I will be teaching an "Introduction to Programming" class to some >> middle school aged children and will be using Python, obviously. Does >> anyone have suggestions for simple little programs to create and >> analyze with them after I get past turtle graphics? >> >> Turtle graphics will be plenty for the first session, and I will leave >> time to ask them what they'd like to do in later sessions, but I was >> curious if anyone on the list has experience picking pedagogical >> programming examples appropriate for twelve-year-olds' attention spans. >> thanks, >> >> Bob >> > While it is not python per se, I suggest you have a look at GvR > (Guido van Robot) (The app is written in Python but is too complicated > for beginners). It is hosted on sourceforge (gvr.sourceforge.net). > It is a very interesting way (imho) to learn about programming, in > a pythonic way. > > (somewhat shameless plug follows:) > A 'more advanced version' of GvR which uses the full Python syntax > is RUR-PLE (rur-ple.sourceforge.net). The version currently hosted > there does NOT work under Linux (untested on Mac). > It uses wxPython 2.4 and will not work with 2.5. > An updated release that will work under both Linux and Windows, > and under both wxPython 2.4 and 2.5 will come out very soon, I hope. > > I'm working on it :-) I have two kids (ages 11 and 13) and plan to use > rur-ple to teach them about programming. Note that, even though > I plan it to be suitable for motivated children (with some guidance), > the end product (to be finished in a year?) is planned to be suitable > for a complete first-year university computer science. > > Andre Roberge I started teaching my 11 year old first of all by doing silly stuff like -: for i in range(10): print "Silly me!" Moving on to more useful stuff like times tables (which they have to learn anyway). After times tables, I plan to work on a simple number guessing game where the computer picks a random number between 1 and 100 and asks the user to take a guess. This will help demonstrate many basic programming concepts. Not sure how to introduce graphics though as so much is relatively abstract. Adrian. From mike at hobbshouse.org Fri Jan 7 11:40:30 2005 From: mike at hobbshouse.org (Michael Hobbs) Date: Fri, 07 Jan 2005 16:40:30 -0000 Subject: Getting rid of "self." References: <740c3aec05010705393048a374@mail.gmail.com> Message-ID: <10tteru3bh91j48@corp.supernews.com> Nick Coghlan wrote: > > Wait for Python 3k when this will work: > > class c: > def __init__(self): > with self: > .x = 1 > .y = 2 > .hi = "Hi there!" Python is looking more like JavaScript every day... From bokr at oz.net Sat Jan 22 05:42:57 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 22 Jan 2005 10:42:57 GMT Subject: Class introspection and dynamically determining function arguments References: <41f18d10.1471646806@news.oz.net> Message-ID: <41f2212f.1509565800@news.oz.net> On Fri, 21 Jan 2005 20:23:58 -0500, "Mike C. Fletcher" wrote: > >>On Thu, 20 Jan 2005 11:24:12 -0000, "Mark English" wrote: >> >> >> >>>I'd like to write a Tkinter app which, given a class, pops up a >>>window(s) with fields for each "attribute" of that class. The user could >>>enter values for the attributes and on closing the window would be >>>returned an instance of the class. The actual application I'm interested >>>in writing would either have simple type attributes (int, string, etc.), >>>or attributes using types already defined in a c-extension, although I'd >>>prefer not to restrict the functionality to these requirements. >>> >>> >Hmm, I missed the original post, but I'll jump in anyway: > > This sounds a heck of a lot like a property-editing system. When > creating a property-modeled system, the best approach is normally to > use something that actually models the properties, rather than > trying to guess at the metadata involved by poking around in an > arbitrarily structured object. I agree that "poking around in an arbitrarily structured object" is not a likely road to satisfaction, but sometimes the arbitrary can be taken out an something pretty simple can be done ;-) OTOH, I probably should have mentioned that there are ways to view these kinds of problems from a longer perspective. E.g., I googled for "model view controller" and found a nice wiki page at http://wact.sourceforge.net/index.php/ModelViewController that may be worth reading for the OP, just for ideas. There is interesting discussion of many MVC-related issues, but I don't know anything about the associated project. > > My BasicProperty system allows for this kind of interaction > (property-sheets) using wxPython (rather than Tkinter) when using > wxoo. You declare classes as having a set of data-properties (which > can have defaults or not, constraints or not, restricted data-types > or not, friendly names or not, documentation or not). Normally you > create these classes as subclasses of a class that knows how to > automatically assign __init__ parameters to properties, and knows > how to tell (e.g.) wxoo about the properties of the class. Does the BasicProperty base class effectively register itself as an observer of subclass properties and automatically update widgets etc., a la Delphi data-driven visual components? I've thought of doing a light-weight form extension class that would use a text (maybe CSV) definition to control contruction, and easy programmatic manipulation by python of the definition parameters, like a stripped-down version of the text view of Delphi forms. It could also be done via Tkinter, to prototype it. It would be interesting to allow dragging widgets and edges around in Tkinter and round-trip the parameter changes automatically into the text representation. A little (well, ok, a fair amount ;-) further and you'd have a drag-n-drop GUI design tool. But don't hold your breath ;-) > > Those same property classes also allow for editing properties of > database rows in PyTable, but that isn't likely relevant to your > case. We've also used them internally to create a rather large > web-based property-editing mechanism (applied to such databases), > but again, not really relevant to the case at hand. Who knows, the OP may only be revealing his concerns about a small part of his great tapestry ;-) > >Anyway, if you aren't interested in BasicProperty for this task; another >project on which I work, PyDispatcher provides fairly robust mechanism >(called robustApply) for providing a set of possible arguments and using >inspect to pick out which names match the parameters for a function in >order to pass them in to the function/method/callable object. That >said, doing this for __init__'s with attribute values from an object's >dictionary doesn't really seem like the proper way to approach the problem. Sounds like a workaround for parameter passing that maybe should have been keyword-based? Regards, Bengt Richter From sylvain.thenault at nospam.logilab.fr Tue Jan 18 11:03:09 2005 From: sylvain.thenault at nospam.logilab.fr (Sylvain Thenault) Date: Tue, 18 Jan 2005 17:03:09 +0100 Subject: MemoryError with parser.suite and wrong encoding declaration References: Message-ID: On Tue, 18 Jan 2005 16:16:32 +0100, Thomas Heller wrote: > Sylvain Thenault writes: > >> Hi there ! >> I've noticed the following problem with python >= 2.3 (actually 2.3.4 >> and 2.4): >> >> syt at musca:test$ python >> Python 2.3.4 (#2, Sep 24 2004, 08:39:09) [GCC 3.3.4 (Debian 1:3.3.4-12)] >> on linux2 Type "help", "copyright", "credits" or "license" for more >> information. >>>>> import parser >>>>> parser.suite('# -*- coding: IBO-8859-1 -*-') >> Traceback (most recent call last): >> File "", line 1, in ? >> MemoryError >>>>> parser.suite('# -*- coding: ISO-8859-1 -*-') >> >> >> Shouldn't parser.suite just ignore the wrong encoding declaration, or at >> least raise a more appropriate exception. IMHO the first solution would >> be better, since that's the behaviour of the (C) python interpreter. > > Ignore the wrong declaration? All Python's that I have (on windows, at > least) raise a SyntaxError: > > File "x.py", line 1 > SyntaxError: 'unknown encoding: IBO-8859-1' hum, right (with python >= 2.3 which is the first release using those declaration...). I was sure to have checked this but I've obviously missed something. Maybe the fact that being able to parse it anyway is the solution I wish has driven me to write this ;) I would like this behaviour so that pylint can check a module with a wrong encoding declaration anyway. But at least, SyntaxError would be better than MemoryError. > See also: > > http://www.python.org/sf/979739 thanks -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From ncoghlan at iinet.net.au Sat Jan 15 11:27:00 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 16 Jan 2005 02:27:00 +1000 Subject: How to del item of a list in loop? In-Reply-To: <34s7omF4emdsaU1@individual.net> References: <34rvjqF4f6l70U1@individual.net> <34s7omF4emdsaU1@individual.net> Message-ID: <41E94454.3010309@iinet.net.au> Reinhold Birkenfeld wrote: > Addition: In Py2.4, I can't find a problem with > > for i in reversed(lst) Some poking around suggests it's fine - and it avoids copying the list. Don't delete anything earlier in the list than the current element though (which list.remove() will do quite happily when data is duplicated). However, there will still be data movement costs when deleting elements from the middle of the list. In addition, remove() itself has to do a linear search for the value being removed. An off-place solution based on a list comprehension is usually going to be your best performer - it's an O(n) operation, based on the size of the original list. The in-place mechanisms can turn out to be O(n**2) due to worst-case memory movement effects (lists don't allow gaps, so deleting items will usually trigger data movement). I think this is about the best you can do for an in-place version: for i, x in enumerate(reversed(lst)): if x == 2: del lst[-i] The effbot's version is still going to be faster though: lst = [x for x in lst if x != 2] Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From anthony.briggs at gmail.com Wed Jan 12 13:33:13 2005 From: anthony.briggs at gmail.com (Anthony) Date: Wed, 12 Jan 2005 13:33:13 -0500 Subject: counting items In-Reply-To: References: Message-ID: <532716200501121033c8597db@mail.gmail.com> On Wed, 12 Jan 2005 17:42:50 GMT, It's me wrote: > Okay, I give up. > > What's the best way to count number of items in a list? How long is a piece of string? There are many different ways, which give you different trade offs. > For instance, > > a=[[1,2,4],4,5,[2,3]] > > I want to know how many items are there in a (answer should be 7 - I don't > want it to be 4) > > I tried: > > b=len([x for y in a for x in y]) > > That doesn't work because you would get an iteration over non-sequence. And is very unreadable. > I tried: > > g=lambda x: (1,len(x))[isinstance(x,(list,tuple,dict))] > b=sum(lambda(x) for x in a) > > and that didn't work because I get a TypeError from the len function (don't > know why) Because you're trying to get the length of an integer, which is what's failing. If you know that the list nesting is only one deep, you can do something like: === #!/usr/local/bin/python compoundList = [[1,2,4],4,5,[2,3]] listLengths = [len(item) for item in compoundList if type(item) not in [int,long,str,float]] print listLengths compoundLength = len(compoundList) - len(listLengths) + sum(listLengths) print compoundLength === If the nesting is 2 deep or more, then the next two options that I would explore would be: 1. Have a look in the standard library. I'm pretty sure that there are list-manipulation libraries that'll do what you want (not sure on names, though). 2. Write a function to do what you want. Some sort of recursive thing should be pretty easy to write. Of course it depends on how fast you need to go, but that should give you a good first approximation. Anthony -- ----------------------------------------------------- HyPEraCtiVE? HeY, WhO aRE YoU cALliNg HypERaCtIve?! aNthONy.BrIGgS at gmAiL.CoM ----------------------------------------------------- From peter at engcorp.com Sun Jan 9 14:59:53 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 14:59:53 -0500 Subject: windows mem leak In-Reply-To: References: <41XDd.70234$Jk5.40626@lakeread01> <41E06C18.6050407@hotmail.com> Message-ID: Roel Schroeven wrote: >> Peter Hansen wrote: >>> How have >>> you proven that it is not *that* program which is at fault?) > > It would surprise me: even if it consumes much CPU-time, memory and > other resources, each instances returns all resources when it exits. I agree with that statement, but you assume that the program *is* exiting. And your initial analysis with "fake_nmap" suggests that, at least to the extent of having leftover cmd.exe's kicking around, maybe it is not. -Peter From gilles.no.lenfant.spam at ingeniweb.com Thu Jan 27 07:57:02 2005 From: gilles.no.lenfant.spam at ingeniweb.com (Gilles Lenfant) Date: Thu, 27 Jan 2005 13:57:02 +0100 Subject: how to pass attribute name via sys.argv In-Reply-To: <41f8e31a$1@idnews.unizh.ch> References: <41f8e31a$1@idnews.unizh.ch> Message-ID: Felix Hebeler a ?crit : > Hi all, > I am doing some Python scripting for a while, but I'm not too deep into > it yet. So I have a problem I can't solve. > > I need to call an object attribute: > > value = object.attrName[0] > > the problem is, that the attribute name can only be specified at runtime. > > So what I have is something like > > >>> attrName = sys.argv[1] > >>> attrName > 'cellsize' > > and I need to pass it on so I can call > > value = object.cellsize[0] > > > Can this be done using Python? > > Thanks for any hints > > Cheers > Felix The builtin "setattr" is your friend. "object" is now a reserved (builtin) name, use "objekt" instead. class Foo(object): pass objekt = Foo() attrName = sys.argv[1] values = ['foo', 'bar', 'whatever'] setattr(objekt, attrName, values) HTH -- Gilles From michel.levankiem at free.fr Thu Jan 13 15:58:37 2005 From: michel.levankiem at free.fr (Michel LE VAN KIEM) Date: Thu, 13 Jan 2005 21:58:37 +0100 Subject: How to install pyparallel In-Reply-To: References: <41e689fc$0$15700$626a14ce@news.free.fr> Message-ID: <41e6e0fa$0$11935$636a15ce@news.free.fr> The ppdev module is loaded and the lp module is unloaded, but I still have the error message. I used 'lsmod | grep ppdev' to check it. Is it necessary to plug the parallel cable ? Peter Hansen a ?crit : > Michel LE VAN KIEM wrote: > >> >> I'm trying to install the pyparallel module for my Python 2.3.4 (runs >> on a FC3) but I do have some troubles. >> >> >>> p=parallel.Parallel() >> ppdev0: failed to register device ! >> ... >> IOError: [No such device or address] >> >> Some help would be appreciated. > > > Did you read the notes in the parallelppydev.py file's > Parallel class? I suspect they may be of some help... > > (I don't see any other significant documentation of > pyParallel, so I'm not sure where else one would look > for assistance.) > > Also, perhaps one of these threads would be of help: > http://groups.google.ca/groups?q=parallel+ppdev0+failed+to+register+device > > -Peter From tconnors at no.spam.accepted.here-astro.swin.edu.au Wed Jan 12 00:45:08 2005 From: tconnors at no.spam.accepted.here-astro.swin.edu.au (TimC) Date: Wed, 12 Jan 2005 05:45:08 GMT Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: On Wed, 12 Jan 2005 at 02:06 GMT, humblythegreatest at usa.com (aka Bruce) was almost, but not quite, entirely unlike tea: > python.org = 194.109.137.226 > > 194 + 109 + 137 + 226 = 666 > > What is this website with such a demonic name and IP address? What > evils are the programmers who use this language up to? Writing code that has to be indented *exactly* or it just won't work. I bet they all use eVIl VI too. -- TimC -- http://astronomy.swin.edu.au/staff/tconnors/ A new verb was accidently created during a discussion about KDE 3 and Debian. It was said that KDE 3 will sid soon. -- Debian Weekly News Jan 14,2003 From xah at xahlee.org Tue Jan 25 11:13:34 2005 From: xah at xahlee.org (Xah Lee) Date: 25 Jan 2005 08:13:34 -0800 Subject: [perl-python] 20050125 standard modules Message-ID: <1106669614.666772.17750@z14g2000cwz.googlegroups.com> # -*- coding: utf-8 -*- # Python # some venture into standard modules import os # print all names exported by the module print dir(os) # print the module's online manual print help(os) # the above is also available in # interactive mode in Python terminal # example of using a function print 'current dir is:', os.getcwd() # this prints a list of existing modules print help('modules') # referecnce # http://python.org/doc/2.3.4/tut/node12.html # in Python terminal, type help() then # modules # to get a list # then a module name to see its doc. # take a gander of its richness and # suitability -------------------------- in perl, i don't think there is one way to list available modules. one can write a program to find out. Start by use Data::Dumper; print Dumper \@INC; to see where is the standard modules located, then search for *.pm files to get an idea. ------------------------- Note: this post is from the Perl-Python a-day mailing list at http://groups.yahoo.com/group/perl-python/ to subscribe, send an email to perl-python-subscribe @ yahoogroups.com if you are reading it on a web page, program examples may not run because html conversion often breaks the code. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From bob_smith_17280 at hotmail.com Sat Jan 8 20:45:12 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sat, 08 Jan 2005 20:45:12 -0500 Subject: Windows XP Installation In-Reply-To: References: Message-ID: Smitsky wrote: > Hi. I am a newbie to Python. I am running Win XP and want to know what the > best course is for installing Python on my system. Could someone kindly > direct me to some related resources? Thanks in advance, Steve > > It's really easy on Windows. Just download the install package and click on it. It only takes one, maybe two minutes top. It's safe to just accept the default settings. Good luck. From simonwittber at gmail.com Tue Jan 11 20:49:50 2005 From: simonwittber at gmail.com (Simon Wittber) Date: Wed, 12 Jan 2005 09:49:50 +0800 Subject: Game programming in Python In-Reply-To: References: Message-ID: <4e4a11f8050111174931abc62e@mail.gmail.com> > I'm looking for any books or on-line resources on game programming > using Python. Does anyone have any advice? Hi Baza, If I you are as I assume, a programmer just starting out with game programming, the best suggestion I can give is head over to pygame.org, and after downloading and installing the library (also install PyOpenGL if you can), go through the tutorials listed at http://www.pygame.org/docs/ . You will also find the pygame mailing list very helpfu, and, if you are so inclined, the IRC #pygame channel on freenode.net Sw. From jerf at jerf.org Fri Jan 21 08:49:30 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 21 Jan 2005 08:49:30 -0500 Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: On Fri, 21 Jan 2005 03:08:50 -0800, Xah Lee wrote: > i've started to read python tutorial recently. > http://python.org/doc/2.3.4/tut/tut.html > > Here are some quick critique: You don't have the respect points for anyone to give a damn. Step one would be demonstrating that you understand the language enough to have a valid opinion, which we're all still waiting on. From peter at monicol.co.uk Mon Jan 10 14:24:14 2005 From: peter at monicol.co.uk (Peter Mott) Date: Mon, 10 Jan 2005 19:24:14 -0000 Subject: Uploading files Message-ID: <41e2d6d7$0$23059$bed64819@news.gradwell.net> If you upload a file using the cgi module is there anyway to discover the file name that the user submitted as well as the file data? I've googled till I squint but I can't find anything. Peter From bdesth.quelquechose at free.quelquepart.fr Mon Jan 10 15:49:39 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 10 Jan 2005 21:49:39 +0100 Subject: tuples vs lists In-Reply-To: References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dfe2a6$0$22729$636a15ce@news.free.fr> Message-ID: <41e2e8cf$0$5744$626a14ce@news.free.fr> Antoon Pardon a ?crit : > Op 2005-01-08, Bruno Desthuilliers schreef : > >>worzel a ?crit : >> >>>I get what the difference is between a tuple and a list, but why would I >>>ever care about the tuple's immuutability? >> >>Because, from a purely pratical POV, only an immutable object can be >>used as kay in a dict. s/kay/key/ > This is not true. Chapter and verse, please ? > >>So you can use tuples for 'composed key'. > > lists can be so used too. Just provide a hash. Please show us an example, and let's see how useful and handy this is from a "purely practical POV" ?-) Bruno From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 11:11:09 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-2?Q?Martin_MOKREJ=A9?=) Date: Mon, 10 Jan 2005 17:11:09 +0100 Subject: Writing huge Sets() to disk Message-ID: <41E2A91D.7080006@ribosome.natur.cuni.cz> Hi, I have sets.Set() objects having up to 20E20 items, each is composed of up to 20 characters. Keeping them in memory on !GB machine put's me quickly into swap. I don't want to use dictionary approach, as I don't see a sense to store None as a value. The items in a set are unique. How can I write them efficiently to disk? To be more exact, I have 20 sets. _set1 has 1E20 keys of size 1 character. alphabet = ('G', 'A', 'V', 'L', 'I', 'P', 'S', 'T', 'C', 'M', 'A', 'Q', 'F', 'Y', 'W', 'K', 'R', 'H', 'D', 'E') for aa1 in alphabet: # l = [aa1] #_set1.add(aa1) for aa2 in alphabet: # l.append(aa2) #_set2.add(''.join(l)) [cut] The reason I went for sets instead of lists is the speed, availability of unique, common and other methods. What would you propose as an elegant solution? Actually, even those nested for loops take ages. :( M. From hans at zephyrfalcon.org Sat Jan 1 14:24:14 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sat, 01 Jan 2005 14:24:14 -0500 Subject: The Industry choice In-Reply-To: <41d6ee45$1_2@127.0.0.1> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <41d6ee45$1_2@127.0.0.1> Message-ID: Donn Cave wrote: > Quoth Hans Nowak : > | Paul Rubin wrote: > | > |> You should write unit tests either way, but in Python you're relying > |> on the tests to find stuff that the compiler finds for you with Java. > | > | As I wrote on my weblog a while ago, I suspect that this effect is > | largely psychological. You jump through hoops, declaring types all over > | the place, checking exceptions, working around the language's > | limitations, etc. So when your code compiles, it *feels* safer. Like > | you're at least part of the way towards ensuring correctness. All that > | work must be good for *something*, right? Never mind that when writing > | unit tests for a dynamic language, you don't check for these things at > | all. How often do you explicitly check types in Python unit tests? > | IMHO, when using a dynamic language, you don't need most of the checks > | that Java, C# and their ilk force upon you. > > I have been fooling around with strongly, statically typed languages > for a couple of years, in my spare time - Objective CAML, Haskell, > O'Haskell. This is a little different experience than what you two > are talking about - I don't think Java, C# and their ilk are quite as > rigorous, nor do they use type inference - but as much as it would > probably gag an FP enthusiast to say this, the basic idea is the same. > > I can only believe that if you think the benefit of static typing is > psychological, either something is very different between the way you > and I write programs, or you're not doing it right. I do think it makes more sense in functional languages like the ones you mention... that's one of the reasons I am trying to learn OCaml. I don't think the type systems in OCaml, Haskell etc can quite be compared to what's used in Java, C#, C++ or Delphi. So far, I am getting the impression that the type system in OCaml is actually there to help you, rather than something that gets in your way. I concur that in my OCaml experiments so far, errors pointed out by the compiler made a lot more sense, because they pointed to actual problems, rather than being a case of "you didn't declare this method as public static final". Of course, it helps that, like Python, said languages (OCaml, Haskell) are higher-level than Java/C#/etc, so you can express things concisely and clearly. That might be one of the reasons why static, strong typing in VHLLs has a much higher "return on investment" than it has in lower-level languages, where you have to write acres of code just to get something done (availability of libraries notwithstanding). -- Hans Nowak http://zephyrfalcon.org/ From tim.peters at gmail.com Mon Jan 10 21:23:35 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 10 Jan 2005 21:23:35 -0500 Subject: Writing huge Sets() to disk In-Reply-To: References: Message-ID: <1f7befae05011018234684d84b@mail.gmail.com> [Istvan Albert] > #- I think that you need to first understand how dictionaries work. > #- The time needed to insert a key is independent of > #- the number of values in the dictionary. [Batista, Facundo] > Are you sure? > > I think that is true while the hashes don't collide. If you have collisions, > time starts to depend of element quantity. But I'm not sure > > Tim sure can enlighten us. I can only point the way to enlightenment -- you have to contemplate your own navel (or Guido's, but he's kind of shy that way). What Istvan Albert said is close enough in context. The *expected* (mean) number of collisions in a Python dict probe is less than 1, regardless of dict size. That assumes the collision distribution is no worse than random. It's possible that all dict keys hash to the same table slot, and then each insertion is O(len(dict)). It's possible to contrive such cases even if the hash function is a good one. But it's not going to happen by accident (and, when it does , open a bug report -- we'll improve the key type's hash function then). From petite.abeille at gmail.com Wed Jan 26 14:47:35 2005 From: petite.abeille at gmail.com (PA) Date: Wed, 26 Jan 2005 20:47:35 +0100 Subject: python without OO In-Reply-To: <200501262039.23260.francis.girard@free.fr> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <10vdt2bpr0m84db@corp.supernews.com> <200501262039.23260.francis.girard@free.fr> Message-ID: <1993411a01509c62cae1715b62fe16f5@gmail.com> On Jan 26, 2005, at 20:39, Francis Girard wrote: > When I think that comapnies > pay big money for these kind of monsters after having seen a few ppt > slides > about it, it makes me shiver. Right... but... since when does an implementation language of any sort save a project from its own doom? Project fails for many reasons but seldomly because one language is "better" or "worst" than another one. Cheers -- PA http://alt.textdrive.com/ From adamc at linuxmail.org Fri Jan 7 04:49:02 2005 From: adamc at linuxmail.org (adamc) Date: Fri, 07 Jan 2005 03:49:02 -0600 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> <7xpt0h66yf.fsf@ruckus.brouhaha.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 2005-01-07, Paul Rubin wrote: > Roman Suzi writes: >> I do not like the idea of having stubs. Once I had an experience working with >> CPAN (I tried to install SpamAssassin and it required some specific modules.) >> "Magic" install shell, provided by Perl, upgraded half the Perl distro, >> including newer version of Perl! >> >> So, I do like Python distutils better. it is not a major problem to >> install something even if it required something else. Of course, >> this depends on the package authors. > > But distutils don't help the problem that the module requires stuff > that's missing. That's what happened with the thing I downloaded last > week, that needed wxPython. I don't understand why the author felt he > had to use wxPython instead of tkinter, since it wasn't a really fancy > gui, but after already-described hassles trying to instead wxPython, I > just used the application's command line interface instead, which > worked fine. But if wxPython is so much better, maybe it's time for > Python to include it. > > I want to start using Audacity pretty soon, which I think really does > depend on wxPython, so I'm going to have to deal with this wxPython > installation problem which is definitely not completely trivial. What > a pain. > I've not experienced problems installing wxPython on Debian (unstable). It just *works* out of the box with apt-get. Perhaps this is more of a problem with the package maintainers? Adam - -- http://www.monkeez.org PGP key: 7111B833 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.5 (GNU/Linux) iD8DBQFB3lgd9F0IVXERuDMRAu49AJ4lBRrF10nHLtBK9NBVuznOnfJH/QCgx0vV Oqk8Vx/nASKJXvakVEYtHII= =kThY -----END PGP SIGNATURE----- From http Wed Jan 5 13:45:11 2005 From: http (Paul Rubin) Date: 05 Jan 2005 10:45:11 -0800 Subject: Securing a future for anonymous functions in Python References: <7x3bxnewmx.fsf@ruckus.brouhaha.com> Message-ID: <7xd5wjiuko.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > Do you consider generator expressions or list comprehensions deficient > because they don't allow several statements in the body of the for > loop? I don't see what it would mean to do otherwise. From newsgroups at jhrothjr.com Fri Jan 7 11:39:07 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 7 Jan 2005 10:39:07 -0600 Subject: Getting rid of "self." References: Message-ID: <10tteq0ahi8t2ff@news.supernews.com> "BJ?rn Lindqvist" wrote in message news:mailman.293.1105105152.22381.python-list at python.org... I think it would be cool if you could refer to instance variables without prefixing with "self." I know noone else thinks like me so Python will never be changed, but maybe you can already do it with Python today? ... It works! exec(magic()) does the needed hi = self.hi. Not so impressive in this case but much cooler when there is more instance variables around. But the solution is very ugly because you have to write exec(magic()) in every method. So I'm asking here if someone knows a better way, maybe using decorators or metaclasses or other black magic? [response] Having to specify the instance explicitly is something that Python needs because it isn't a statically typed language. In a statically typed language, all variables are pre-declared, so the compiler knows where they all are. Python's compiler knows about local variables. It doesn't know where any other variables are, so it has to search. Including the instance as one of the method parameters means that the search splits right at the front: either it starts looking up the instance, or it goes up the definition chain (usually empty) to the module namespace and then the builtins. Eliminating "self" would mean it would have to either search the instance before the module and builtins, or search the module and builtins before the instance. This is both a performance issue and a maintenance issue because of the increased possibility of one shadowing the other. This is distinct from the issue of how to spell "self". As another responder has already said, you can spell it any way you want; it's simply whatever you choose to call the first paramteter to the method. Going the other way, the word "self" could become a keyword, removing the necessity of specifying it among the method parameters. While I like the idea, there's enough dislike of the notion that it's not going to happen. John Roth -- mvh Bj?rn From carribeiro at gmail.com Wed Jan 5 04:17:13 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 5 Jan 2005 07:17:13 -0200 Subject: Python evolution: Unease In-Reply-To: <16859.16548.249527.30210@montanaro.dyndns.org> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <16859.16548.249527.30210@montanaro.dyndns.org> Message-ID: <864d37090501050117761a32e6@mail.gmail.com> On Tue, 4 Jan 2005 19:19:32 -0600, Skip Montanaro wrote: > > Terry> Numarray has a record array type. If there is not one publicly > Terry> available, perhaps you could write a CSV file to record-array > Terry> slurper and contribute it to the Recipes site or maybe even the > Terry> CSV module. > > -1 on putting such a beast into the CSV module, especially if, as it seems, > it would rely on something outside the core. Although I see your point, in the long term it will be required. Assuming that Numarray will, at some point in the future, be included in the stdlib... why not give these people some help, easing the integration? A recipe, or some code that can be provisionally included in Numarray itself (as a submodule), and then later migrated to the CSV module... it does make sense in the long run. -- 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 nav+posts at bandersnatch.org Tue Jan 11 07:53:03 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: Tue, 11 Jan 2005 07:53:03 -0500 Subject: Ranting about the state of Python IDEs for Windows References: <1105222350.906941.83130@c13g2000cwb.googlegroups.com> Message-ID: <878y70dt5c.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> "AkioIto" writes: > Look at http://www.pspad.com/en/index.html. Thanks for the tip, looks perfect for the flash memory toolkit, since it can just run from the directory it was unpacked into. 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 bokr at oz.net Thu Jan 20 04:59:29 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 20 Jan 2005 09:59:29 GMT Subject: list item's position References: Message-ID: <41ef7697.1334881407@news.oz.net> On Wed, 19 Jan 2005 22:04:44 -0500, Bob Smith wrote: >Hi, > >I have a Python list. I can't figure out how to find an element's >numeric value (0,1,2,3...) in the list. Here's an example of what I'm doing: > >for bar in bars: > if 'str_1' in bar and 'str_2' in bar: > print bar > >This finds the right bar, but not its list position. The reason I need >to find its value is so I can remove every element in the list before it >so that the bar I found somewhere in the list becomes element 0... does >that make sense? > sneaky (python 2.4) one-liner (not tested beyond what you see, and not recommended as the best self-documenting version ;-) >>> bars = [ ... 'zero', ... 'one', ... 'str_1 and str_2 both in line two', ... 'three', ... 'four', ... 'str_1 and str_2 both in line five', ... 'last line'] >>> newbar=bars[sum(iter(('str_1' not in bar or 'str_2' not in bar for bar in bars).next, 0)):] >>> for s in newbar: print repr(s) ... 'str_1 and str_2 both in line two' 'three' 'four' 'str_1 and str_2 both in line five' 'last line' Alternatively: >>> newbar=bars[[i for i,v in enumerate(bars) if 'str_1' in v and 'str_2' in v][0]:] >>> for s in newbar: print repr(s) ... 'str_1 and str_2 both in line two' 'three' 'four' 'str_1 and str_2 both in line five' 'last line' Alternatively: >>> newbar = list(dropwhile(lambda x: 'str_1' not in x or 'str_2' not in x, bars)) >>> for s in newbar: print repr(s) ... 'str_1 and str_2 both in line two' 'three' 'four' 'str_1 and str_2 both in line five' 'last line' Regards, Bengt Richter From duncan.booth at invalid.invalid Sat Jan 22 06:17:09 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Jan 2005 11:17:09 GMT Subject: re Insanity References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> Message-ID: Tim Daneliuk wrote: > > I tried this: > > y=re.compile(r'\[PROMPT:.*\]') > > Which works fine when the text is exactly "[PROMPT:whatever]" but > does not match on: > > "something [PROMPT:foo] something [PROMPT:bar] something ..." > > The overall goal is to identify the beginning and end of each [PROMPT...] > string in the line. > The answer sort of depends on exactly what can be in your optional text: >>> import re >>> s = "something [PROMPT:foo] something [PROMPT:bar] something ..." >>> y=re.compile(r'\[PROMPT:.*\]') >>> y.findall(s) ['[PROMPT:foo] something [PROMPT:bar]'] >>> y=re.compile(r'\[PROMPT:.*?\]') >>> y.findall(s) ['[PROMPT:foo]', '[PROMPT:bar]'] >>> y=re.compile(r'\[PROMPT:[^]]*\]') >>> y.findall(s) ['[PROMPT:foo]', '[PROMPT:bar]'] >>> .* will match as long a string as possible. .*? will match as short a string as possible. By default this won't match any newlines. [^]]* will match as long a string that doesn't contain ']' as possible. This will match newlines. From fredrik at pythonware.com Mon Jan 17 03:42:21 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Jan 2005 09:42:21 +0100 Subject: why are some types immutable? References: Message-ID: Roy Smith wrote: > But, in a nutshell, the biggest reason for immutable types (tuples and > strings) is that this lets they be dictionary keys. if you think that's the biggest reason, you haven't spent enough time working on high-performance Python code and extensions (there's a reason why some languages adopt a "you can only assign to a variable once" approach). From newsgroups at jhrothjr.com Tue Jan 18 18:39:32 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 18 Jan 2005 17:39:32 -0600 Subject: Fuzzy matching of postal addresses References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> <$aq2IQPQ8X7BFwRy@at-andros.demon.co.uk> Message-ID: <10ur7ikcr3avdd4@news.supernews.com> "Andrew McLean" wrote in message news:$aq2IQPQ8X7BFwRy at at-andros.demon.co.uk... > Thanks for all the suggestions. There were some really useful pointers. > > A few random points: > > 1. Spending money is not an option, this is a 'volunteer' project. I'll > try out some of the ideas over the weekend. > > 2. Someone commented that the data was suspiciously good quality. The data > sources are both ones that you might expect to be authoritative. If you > use as a metric, having a correctly formatted and valid postcode, in one > database 100% the records do in the other 99.96% do. > > 3. I've already noticed duplicate addresses in one of the databases. > > 4. You need to be careful doing an endswith search. It was actually my > first approach to the house name issue. The problem is you end up matching > "12 Acacia Avenue, ..." with "2 Acacia Avenue, ...". > > I am tempted to try an approach based on splitting the address into a > sequence of normalised tokens. Then work with a metric based on the > differences between the sequences. The simple case would look at deleting > tokens and perhaps concatenating tokens to make a match. It's been a while since I did this stuff. The trick in dealing with address normalization is to parse the string backwards, and try to slot the pieces into the general pattern. In your case, the postal code, district (is that what it's called in the UK?) and city seem to be fine, it's when you get to the street (with or without house number), building name and flat or room number that there's a difficulty. We always had a list of keywords that could be trusted to be delimiters. In your examples, "the" should be pretty reliable in indicating a building name. Of course, that might have some trouble with Tottering on the Brink. John Roth > > -- > Andrew McLean From peter at somewhere.com Mon Jan 17 07:27:05 2005 From: peter at somewhere.com (Peter Maas) Date: Mon, 17 Jan 2005 13:27:05 +0100 Subject: (objects as) mutable dictionary keys In-Reply-To: References: Message-ID: Antoon Pardon schrieb: > Dictionary lookup with mutable types like lists is a source of > unpleasant surprises for the programmer and therefore impossible in > Python. > > > It is not impossible in Python. It may be discouraged but it is not > impossible since I have already done so. Wouldn't this raise a TypeError? Or did you wrap them with an object? -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From klapotec at chello.at Mon Jan 3 15:52:16 2005 From: klapotec at chello.at (Christopher Koppler) Date: Mon, 03 Jan 2005 20:52:16 GMT Subject: Bad Interpreter References: <1104783849.754892.47560@c13g2000cwb.googlegroups.com> Message-ID: On Mon, 03 Jan 2005 12:24:09 -0800, RajaSrinivasan wrote: > I have seen some previous messages about such a problem. I have this > problem but it is not clear what the solution really was. > > I am running FC2, python 2.3.3 > > the script i have sock.py runs if i say something like : > > python sock.py > > but ./sock.py results in a :bad interpreter error > how do i troubleshoot something like this? > Check the first line of your script - it should set the path to the Python interpreter. It should look something like this: #!/usr/bin/python or #!/usr/bin/env python which doesn't explicitly set the path to the interpreter, but checks the environment variable called python for that path. If your python executable lives somewhere the first line or the environment variable doesn't point to, you'll need to correct that. -- Christopher OutOfSigError From tim.peters at gmail.com Wed Jan 19 22:53:41 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 19 Jan 2005 22:53:41 -0500 Subject: Zen of Python In-Reply-To: <972ec5bd0501191641166972b0@mail.gmail.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> Message-ID: <1f7befae050119195356a64150@mail.gmail.com> [Carl Banks] >> The gist of "Flat is better than nested" is "be as nested as >> you have to be, no more," because being too nested is just a >> mess. [Timothy Fitz] > Which I agree with, and which makes sense. However your > "gist" is a different meaning. It's not that "Flat is better than > nested" it's that "Too flat is bad and too flat is nested so be as < nested (or as flat) as you have to be and no more." Perhaps Tim > Peters is far too concise for my feeble mind Always happy to help a fellow Tim, but I don't claim to understand the 20 Pythonic Theses, I just claim to have channelled them from Guido's inscrutable Python-mind. If you _were_ to ask me (and it's not something I recommend in general), I'd say your reading "X is better than Y" as "X is always good, and no matter how much; Y is always evil, and no matter how little" is unreasonably literal. For example, most would agree that full is better than hungry, but few would take that as meaning one should always be stuffing one's face. And I happen to know that Guido believes full is better than hungry, yet simultaneously sometimes refrains from eating until he's actually hungry. Or consider "accurate is better than vague". Go ahead: just _try_ to be 100% accurate! For that matter, just try to be 100% flat. Or 100% beautiful, 100% simple, or 100% sparse. If you were to ask for examples in Python, well, they're all over the place, and often in what's _not_ there. Guido is on record as saying that Python's original simple 3-level scope rules (local, global, builtin) were in part a reaction against the horrid abuses of deeply nested Pascal programs he had to wrestle with. Lexical scoping was added only after years of debate -- and it's still usually better to wrap state in objects (you can pass 'em around then, add useful methods to them, display them, mutate 'em, ...). Or note that you can't define a module inside another module, that Python's basic list type is a flat vector instead of a recursively-defined S-expression, and that there's no direct way to break out of a containing loop from a nested loop. Python encourages flatness of various kinds in all these (and other) ways. But that's just what I think -- nobody knows why Guido believes what he does, least of all Guido. Thanks to my remarkable channelling power, at least we know *what* he believes! I think he was grateful to find that out too . there's-just-no-disputing-divine-revelation-ly y'rs - tim From dmarcusanu at yahoo.com Mon Jan 31 21:13:00 2005 From: dmarcusanu at yahoo.com (Dana Marcusanu) Date: Mon, 31 Jan 2005 18:13:00 -0800 (PST) Subject: getting data from a port in use Message-ID: <20050201021301.4434.qmail@web52907.mail.yahoo.com> Hi to all, 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. I don't know what else I can try. Any suggestions will be welcome. import socket, select, os PORT = 2005 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((socket.gethostname(), PORT)) s.listen(1) work_socket, addr = s.accept() data = s.recv(1024) print data s.close() Thank you, Dana __________________________________ Do you Yahoo!? Meet the all-new My Yahoo! - Try it today! http://my.yahoo.com From steven.bethard at gmail.com Fri Jan 14 16:58:40 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 14 Jan 2005 14:58:40 -0700 Subject: Why would I get a TypeEror? In-Reply-To: References: <34ql1vF4dqd9pU1@individual.net> Message-ID: It's me wrote: > Say again??? Please stop top-posting -- it makes it hard to reply in context. > "Reinhold Birkenfeld" wrote... >>It's me wrote: >>>If this is true, I would run into trouble real quick if I do a: >>> >>>(1/x,1.0e99)[x==0] >> >>Lazy evaluation: use the (x==0 and 1e99 or 1/x) form! If you want short-circuting behavior, where only one of the two branches gets executed, you should use Python's short-circuiting boolean operators. For example, (x == 0 and 1.0e99 or 1/x) says something like: Check if x == 0. If so, check if 1.0e99 is non-zero. It is, so return it. If x != 0, see if 1/x is non-zero. It is, so return it. Note that if you're not comfortable with short-circuiting behavior, you can also code this using lazy evaluation: (lambda: 1/x, lambda: 1.0e99)[x==0]() This says something like: Create two functions, one to produce 1/x and one to produce 1.0e99. Select one of these functions depending on whether or not x==0 Invoke the chosen function. HTH, Steve From http Thu Jan 6 19:29:34 2005 From: http (Paul Rubin) Date: 06 Jan 2005 16:29:34 -0800 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <344l83F45rstqU1@individual.net> Message-ID: <7xzmzmaxox.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > > Which I find again wrong: suppose this developer used GPL-ed > > library A, developed patches B and C. He provided you with > > the source code of publicly available library A and a patch > > C, but he doesn't want to release patch B. > > Then he does not have to. As I understand the GPL, as long as he does not > release (distribute) the patch in any form (in particular, binary), then > the GPL has no effect. I think the hypothesis is that the developer distributed the patched library. The GPL then requires distributing source for all the patches. From benn at cenix-bioscience.com Thu Jan 13 07:49:56 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Thu, 13 Jan 2005 13:49:56 +0100 Subject: pyserial and com port interrupts In-Reply-To: <41E66D69.4050603@cenix-bioscience.com> References: <41E66D69.4050603@cenix-bioscience.com> Message-ID: <41E66E74.8070205@cenix-bioscience.com> Neil Benn wrote: > engsol wrote: > >> Has anyone done a script that will rspond to the serial com port(s) >> receive buffer interrupt, as opposed to polling and timeouts? Win2000 >> is the main interest right now. >> Thanks >> Norm B >> >> > Hello, > > I came across this problem as when I first used PySerial, I > came from a java background which has the ability to register > listeners to a serial comm instance and receive interrupts (although > some implementations use polling behind the scenes anyway). I don't > think that pyserial has this kind of thing so I used the following : Tabs got screwed up here is teh code again : def __checkSerial(self): self.__objLock.acquire() try: try: intNoChars = self.__objSerialPort.inWaiting() if (intNoChars > 0): strReceivedString = self.__objSerialPort.read(intNoChars) self.newMessage(strReceivedString) except: raise finally: self.__objLock.release() Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 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 cabrera at wrc.xerox.com Mon Jan 31 21:58:47 2005 From: cabrera at wrc.xerox.com (jose isaias cabrera) Date: Mon, 31 Jan 2005 21:58:47 -0500 Subject: Java Integer.ParseInt translation to python References: <1107217651.764967.258100@z14g2000cwz.googlegroups.com> Message-ID: <007701c50809$f59e3040$d6b8850d@jicman> thanks everyone...! ----- Original Message ----- From: "ech0" Newsgroups: comp.lang.python To: Sent: Monday, January 31, 2005 7:27 PM Subject: Re: Java Integer.ParseInt translation to python > buffer[0] = int(string,16) & 0xff > > that should work > > -- > http://mail.python.org/mailman/listinfo/python-list > From dbickett at gmail.com Sun Jan 30 23:22:57 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 30 Jan 2005 23:22:57 -0500 Subject: gmail access with python! In-Reply-To: References: Message-ID: <1d6cdae30501302022d198e25@mail.gmail.com> On Jeremy Bowers wrote: > Can you expand on that for us non-GMail users? A login is required to view > that page. I apologize, I wasn't aware :) It simply outlines all of the credentials to use gmail with pop3, I'll list it all here: Incoming server: pop.gmail.com Outgoing server: smtp.gmail.com Be sure to include @gmail.com for your username. For the incoming server (the topic at hand, if I'm not mistaken,) It instructs you to use an SSL connection and port 995, so that is sure to change some things. I believe that's all. -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From aleaxit at yahoo.com Sat Jan 29 03:54:27 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 29 Jan 2005 09:54:27 +0100 Subject: Pystone benchmark: Win vs. Linux (again) References: <7xhdl0ll3t.fsf@ruckus.brouhaha.com> Message-ID: <1gr59wv.9tx8a21g2kdv9N%aleaxit@yahoo.com> Paul Rubin wrote: > Franco Fiorese writes: > > * Windows XP Pro: 16566.7 pystones/second > > * Linux (kernel 2.6.9 NPTL): 12346.2 pystones/second > > > > I have repeated the test, on Linux, also with other distributions and > > kernel but a relevant difference still exists with Windows offering a > > better performance. > > > > Is there any way, that you know, to get better performance under Linux? > > I hate to say this but the Windows C compiler may be beating GCC in > output code. Doing anything about it may require a lot of careful > profiling and tuning. ...or (just as hypothetically) purchasing some commercial compiler might help, under the assumption that the optimization and code generation of the compiler are the issues here. I have nothing but hearsay to go on, but IBM's compiler for PPC chips, and Intel's compiler for Intel chips, appear to claim that they have excellent code generation, for example. Alex From bokr at oz.net Fri Jan 14 02:10:57 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 14 Jan 2005 07:10:57 GMT Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> <39ednWfqlrgB6HvcRVn-iA@powergate.ca> <41e6f606.777680996@news.oz.net> Message-ID: <41e76278.805442965@news.oz.net> On Thu, 13 Jan 2005 17:43:01 -0600, Jeff Epler wrote: > >--LQksG6bCIzRHxTLp >Content-Type: text/plain; charset=us-ascii >Content-Disposition: inline >Content-Transfer-Encoding: quoted-printable > >On Thu, Jan 13, 2005 at 11:04:21PM +0000, Bengt Richter wrote: >> One way to do it consistently is to have a sign digit as the first >> digit after the x, which is either 0 or base-1 -- e.g., +3 and -3 would be >>=20 >> 2x011 2x101 >> 8x03 8x75 >> 16x03 16xfd >> 10x03 10x97 > >=2E.. so that 0x8 and 16x8 would be different? So that 2x1 and 2x01 would >be different? I guess I didn't make the encoding clear enough, sorry ;-/ 16x8 would be illegal as a literal, since the first digit after x is not 0 or f (base-1) 0x8 would be spelled 16x08 in x format. 2x1 _could_ be allowed as a degenerate form of the general negative format for -1, where any number of leading base-1 "sign digits" compute to the same value. Hence 2x1 == 1*2**0 - 2**1 == -1 2x11 == 1*2**0 + 1*2**1 - 2**2 == 1 + 2 -4 == -1 2x111 == 1*2**0 + 1*2**1 + 1*2**2 - 2**4 == 1 + 2 + 4 - 8 == -1 16f == 15*16**0 - 16**1 = 15 -16 == -1 16ff == 15*6**0 + 15*16**1 - 16**2 = 15 + 240 - 256 == -1 etc. Although IMO it will be more consistent to require a leading "sign digit" even if redundant. The one exception would be zero, since 00 doesn't look too cool in company with a collection of other numbers if output minimally without their (known) base prefixes, e.g., -2,-1,0,1,2 => 110 11 0 01 010 Of course these numbers can be output in constant width with leading pads of 0 or base-1 digit according to sign, e.g., 1110 1111 0000 0001 0010 for the same set width 4. That would be format '%04.2b' and if you wanted the literal-making prefix, '2x%04.2b' would produce legal fixed width literals 2x1110 2x1111 etc. Regards, Bengt Richter From steven.bethard at gmail.com Wed Jan 12 17:35:31 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 15:35:31 -0700 Subject: list and generators (WAS: counting items) In-Reply-To: <1105567784.297529.246800@c13g2000cwb.googlegroups.com> References: <1105559439.538736.87370@z14g2000cwz.googlegroups.com> <1105567784.297529.246800@c13g2000cwb.googlegroups.com> Message-ID: Michael Hartl wrote: > That's cool! Of course, walk returns a generator, so using a list > comprehension to turn it into a list seems natural, but I didn't > realize that list() does the same thing (and neither, apparently, did > the original implementor) -- although, with a little reflection, it > obviously must! Yup. Also worth noting is that if you want the scoping rules of generator expression, but need a list instead, you can just call list with the generator expression: py> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined py> [pow(x, 7, 23) for x in range(10)] [0, 1, 13, 2, 8, 17, 3, 5, 12, 4] py> x 9 py> del x py> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined py> list(pow(x, 7, 23) for x in xrange(10)) [0, 1, 13, 2, 8, 17, 3, 5, 12, 4] py> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined Note that with the generator expression, 'x' doesn't get leaked to the enclosing scope. Steve From paul at subsignal.org Thu Jan 27 18:49:36 2005 From: paul at subsignal.org (paul koelle) Date: Fri, 28 Jan 2005 00:49:36 +0100 Subject: Transparent (redirecting) proxy with BaseHTTPServer In-Reply-To: References: <35sfdaF4hka1hU1@individual.net> Message-ID: <35t9huF4rt829U1@individual.net> Thanks, aurora ;), aurora wrote: > If you actually want the IP, resolve the host header would give you that. I' m only interested in the hostname. > > The second form of HTTP request without the host part is for > compatability of pre-HTTP/1.1 standard. All modern web browser should > send the Host header. How safe is the assumtion that the Host header will be there? Is it part of the HTTP/1.1 spec? And does it mean all "pre 1.1" clients will fail? Hmm, maybe I should look on the wire whats really happening... thanks again Paul From jalil at feghhi.com Sun Jan 30 14:17:08 2005 From: jalil at feghhi.com (jalil at feghhi.com) Date: 30 Jan 2005 11:17:08 -0800 Subject: Exception from bsddb module Message-ID: <1107112627.990210.95160@z14g2000cwz.googlegroups.com> I am using Python 2.4 and get this exception when running my mod_python application. This used to work in my older environment. Any ideas on how I can debug this issue? -Jalil Mod_python error: "PythonHandler mod_python.psp" Traceback (most recent call last): File "/usr/local/lib/python2.4/site-packages/mod_python/apache.py", line 299, in HandlerDispatch result = object(req) File "/usr/local/lib/python2.4/site-packages/mod_python/psp.py", line 297, in handler p.run() File "/usr/local/lib/python2.4/site-packages/mod_python/psp.py", line 191, in run session = Session.Session(req) File "/usr/local/lib/python2.4/site-packages/mod_python/Session.py", line 389, in Session timeout=timeout, lock=lock) File "/usr/local/lib/python2.4/site-packages/mod_python/Session.py", line 294, in __init__ timeout=timeout, lock=lock) File "/usr/local/lib/python2.4/site-packages/mod_python/Session.py", line 124, in __init__ if self.load(): File "/usr/local/lib/python2.4/site-packages/mod_python/Session.py", line 185, in load dict = self.do_load() File "/usr/local/lib/python2.4/site-packages/mod_python/Session.py", line 315, in do_load dbm = self._get_dbm() File "/usr/local/lib/python2.4/site-packages/mod_python/Session.py", line 302, in _get_dbm result = self._dbmtype.open(self._dbmfile, 'c') File "/usr/local/lib/python2.4/anydbm.py", line 83, in open return mod.open(file, flag, mode) File "/usr/local/lib/python2.4/dbhash.py", line 16, in open return bsddb.hashopen(file, flag, mode) File "/usr/local/lib/python2.4/bsddb/__init__.py", line 285, in hashopen e = _openDBEnv() File "/usr/local/lib/python2.4/bsddb/__init__.py", line 339, in _openDBEnv e.open('.', db.DB_PRIVATE | db.DB_CREATE | db.DB_THREAD | db.DB_INIT_LOCK | db.DB_INIT_MPOOL) DBError: (153777744, 'Unknown error 153777744') From reinhold-birkenfeld-nospam at wolke7.net Tue Jan 11 11:53:03 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 11 Jan 2005 17:53:03 +0100 Subject: tuples vs lists In-Reply-To: References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dfe2a6$0$22729$636a15ce@news.free.fr> <41e2e8cf$0$5744$626a14ce@news.free.fr> Message-ID: <34iejgF4akofdU1@individual.net> Antoon Pardon wrote: > Op 2005-01-10, Bruno Desthuilliers schreef : >> Antoon Pardon a ?crit : >>> Op 2005-01-08, Bruno Desthuilliers schreef : >>> >>>>worzel a ?crit : >>>> >>>>>I get what the difference is between a tuple and a list, but why would I >>>>>ever care about the tuple's immuutability? >>>> >>>>Because, from a purely pratical POV, only an immutable object can be >>>>used as kay in a dict. >> >> s/kay/key/ >> >>> This is not true. >> >> Chapter and verse, please ? > > I don't need chapter and verse. I have already used mutable > objects as keys and it works just fine. > >>>> class hlst(list): >>>> >>>> def __hash__(self): >>>> sum = 0 >>>> for el in self: >>>> sum += hash(el) >>>> return sum % 0x37777777 >>>> Given this hash function, how do you handle changed keys? .class hlst(list): . def __hash__(self): . sum = 0 . for el in self: . sum += hash(el) . return sum % 0x37777777 . .lst = hlst([1,2,3]) . .d = {} .d[lst] = 1 . .lst[0] = 0 . .print d .try: . print d[hlst([0,2,3])] .except KeyError: . print "0,2,3: KeyError" .try: . print d[hlst([1,2,3])] .except KeyError: . print "1,2,3: KeyError" raises the KeyError twice. How do you access the element then? And if you can't access the element when it's changed, what is the advantage over using tuples? Reinhold From josh at yucs.org Thu Jan 13 15:53:10 2005 From: josh at yucs.org (josh at yucs.org) Date: Thu, 13 Jan 2005 15:53:10 -0500 Subject: why not datetime.strptime() ? In-Reply-To: <16870.32896.616979.730581@montanaro.dyndns.org> References: <20050111021152.GA20127@yucs.org> <16867.59681.423983.244528@montanaro.dyndns.org> <20050111173335.GB26246@yucs.org> <16869.62773.572880.581805@montanaro.dyndns.org> <16870.32896.616979.730581@montanaro.dyndns.org> Message-ID: <20050113205310.GA26290@yucs.org> On Thu, Jan 13, 2005 at 08:06:56AM -0600, Skip Montanaro wrote: > > Skip> I just checked in your changes. Thanks for the effort. > > Jeez Skip... That reads poorly. How about "Thanks for your contribution"? > In any case, thanks. My pleasure. Thanks for helping me to help. And I liked the first thanks just fine (the "checked in" was the important part :) ). From chris.lasher at gmail.com Thu Jan 13 16:22:33 2005 From: chris.lasher at gmail.com (Chris Lasher) Date: 13 Jan 2005 13:22:33 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <10udfj4c4rgkvcc@corp.supernews.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> <1105632841.461042.68310@c13g2000cwb.googlegroups.com> <10udfj4c4rgkvcc@corp.supernews.com> Message-ID: <1105651353.769879.229690@f14g2000cwb.googlegroups.com> >And besides, for long-term archiving purposes, I'd expect that zip et >al on a character-stream would provide significantly better >compression than a 4:1 packed format, and that zipping the packed >format wouldn't be all that much more efficient than zipping the >character stream. This 105MB FASTA file is 8.3 MB gzip-ed. From rootshell at gazeta.pl Fri Jan 14 12:01:40 2005 From: rootshell at gazeta.pl (rootshell at gazeta.pl) Date: 14 Jan 2005 09:01:40 -0800 Subject: Free python server. References: <002301c4f99a$cb4dcd50$55a01d53@unqku4k1fl8nea7> Message-ID: <1105722100.306305.107950@z14g2000cwz.googlegroups.com> > Your file probably need to (a) be in the cgi-bin, not public_html, (b) > be flagged executable ("chmod a+x file.py"), and (c) begin with the > line: '#!/usr/bin/env python' > > If the server doesn't provide you with CGI (or, strongly preferable, > SCGI or mod_python), you're probably out of luck. You're probably right, this machine doesn't provide with CGI, I'll send an e-mail to administrator of arbornet.org and make sure. So, I ask once again: does anyone know where I can put my *.py files? Greetings. Rootshell. From lutherrevisited at aol.com Sun Jan 2 02:45:24 2005 From: lutherrevisited at aol.com (LutherRevisited) Date: 02 Jan 2005 07:45:24 GMT Subject: What can I do with Python ?? References: Message-ID: <20050102024524.07592.00003025@mb-m01.aol.com> Speaking of the many libraries people have written I thought I'd mention pychess. Don't remember where I found it, but it's easy enough to find on a search engine. That's the whole reason I discovered python, searching for a good algorithm to use in parsing chess pgn files. From elephantum at dezcom.mephi.ru Sun Jan 9 09:01:53 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 17:01:53 +0300 Subject: Pygame and pyopengl with py2exe ? In-Reply-To: References: Message-ID: <34crqiF47stihU1@individual.net> Nyx42 wrote: > Second program (pygame + pyopenGL): > Py2exe can't import OpenGL.GL and OpenGL.GLU :( about that, may be names of imports are generated in runtime, so you can try to specify them directly options = {"py2exe": {"packages": ["OpenGL.GL","OpenGL.GLU"]}}, From ville at spammers.com Mon Jan 10 08:42:06 2005 From: ville at spammers.com (Ville Vainio) Date: 10 Jan 2005 15:42:06 +0200 Subject: Securing a future for anonymous functions in Python References: <7xvfa90w6g.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "James" == James Stroud writes: James> I think we should not try too hard to make everything James> "English" like. Its a crappy language anyway (though its James> the only one I speak good). Matt Neuberg, QOTW material, unless you stole this from someone else :-). -- Ville Vainio http://tinyurl.com/2prnb From steven.bethard at gmail.com Fri Jan 21 14:37:25 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 12:37:25 -0700 Subject: Unbinding multiple variables In-Reply-To: <1106334800.868412.27650@f14g2000cwb.googlegroups.com> References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> <35bnkeF4jpeetU1@individual.net> <1106334800.868412.27650@f14g2000cwb.googlegroups.com> Message-ID: <7pidncPdVepvxGzcRVn-jQ@comcast.com> Johnny Lin wrote: > my understanding about locals() from the nutshell book was that i > should treat that dictionary as read-only. is it safe to use it to > delete entries? No it's not: py> def f(): ... x = 1 ... del locals()['x'] ... print x ... py> f() 1 py> def f(): ... x = 1 ... del x ... print x ... py> f() Traceback (most recent call last): File "", line 1, in ? File "", line 4, in f UnboundLocalError: local variable 'x' referenced before assignment Steve From jayjbee at hotmail.com Tue Jan 11 21:39:37 2005 From: jayjbee at hotmail.com (jay j bee) Date: Wed, 12 Jan 2005 03:39:37 +0100 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: On 12-01-2005 03:06, in article 1105495569.479185.166340 at z14g2000cwz.googlegroups.com, "humblythegreatest at usa.com" wrote: > python.org "Python - why settle for snake oil when you can have the whole snake?" Greetzzzzz From fuzzyman at gmail.com Fri Jan 14 05:53:45 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 14 Jan 2005 02:53:45 -0800 Subject: file uploading via urllib2 (multipart/form-data) In-Reply-To: References: Message-ID: <1105700025.763417.149110@c13g2000cwb.googlegroups.com> Clark C. Evans wrote: > Hello. I was wondering if anyone has built a module that works with > urllib2 to upload file content via POST multipart/form-data. I'm > aware of ASPN 146306, however, I need to use urllib2 beacuse I'm > using HTTP Digest over SSL. > > Cheers, > > Clark There is an example showing exactly that over at voidspace. I think it's on the cgi page, as it is a companion to the cgi demo showing how to receive file uploads. Try : http://www.voidspace.org.uk/python/cgi.shtml Regards, Fuzzy http://www.voidspac.org.uk/python/index.shtml From reinhold-birkenfeld-nospam at wolke7.net Fri Jan 21 14:47:21 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 21 Jan 2005 20:47:21 +0100 Subject: make install with python In-Reply-To: References: Message-ID: <35d4i9F4makucU1@individual.net> Uwe Mayer wrote: > Hi, > > I am writing a Python application and use the GNU auto-tools to compile what > needs compilation (i.e. Qt's .ui files). > However, I don't know how to write an automake file that installs the main > file (lmc.py) and some library files (i.e. ClassA.py, ClassB.py) into the > appropriate directories. The regular way is to use distutils and a setup.py file (google for documentation). Reinhold From bokr at oz.net Sat Jan 8 21:49:35 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 09 Jan 2005 02:49:35 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> Message-ID: <41e09808.360402200@news.oz.net> On Sat, 08 Jan 2005 12:47:52 -0500, Peter Hansen wrote: >Paul Rubin wrote: >> When Unix was first written, people thought implementing an OS in C >> was ludicrous. Everyone knew OS's had to be written in assembler. > >Actually, when Unix was first written that belief was entirely >correct, and OSes *did* have to be written in assembler. > >That is, pure C did not have the capability to handle all >that was required. I recall it taking a good decade before it >became *common* to find C compilers with, for example, @interrupt >support to let the compiler generate code that properly saved >all registers and used RTI instead of RTS (or whatever it might >have been called one one's particular flavour of CPU). > >Now, once you added a few tiny interrupt handlers, and some context >switching (stack manipulation) routines, pretty much everything else >*could* be done in C, but that doesn't invalidate the point. > >I think it's safe to say that none of pure C, pure Lisp, or pure Python >are really capable of being used as the *sole* language to build >an operating system. > >It's also safe to say that this is a largely irrelevant point. >It would probably only be of academic interest to try to do >something like that. Any practical attempt would not think more >than twice of resorting to a little "glue" in assembler or in >the form of "canned" byte sequences built by hand and stuck >into the appropriate places in memory... Well, usually there's more than one tool in the chain from source to bootable loader and OS image, even if you are writing in C and assembler, and there's usually more to an OS than the bootable image contains. So ISTM "writing an OS in " is pretty loose talk ;-) Regards, Bengt Richter From mexica13 at aol.com Fri Jan 21 03:13:15 2005 From: mexica13 at aol.com (Gerardo C. Ruiz) Date: 21 Jan 2005 08:13:15 GMT Subject: Quick And EZ Money!!! Message-ID: <20050121031315.12769.00000162@mb-m11.aol.com> Dear Internet User, (Testimonial of Participant) Good day, This article I've written is all about the fact where I earned an ASTOUNDING amount of money in just over a month and I've decided to share or reveal the secrets behind making big bucks in the Mail Order Business. So all money seekers read this carefully. Hi, I'm 30 years old and I make more money now from my home than I ever did before by working, and so can you! Turn $6.00 into $30,000...read this to find out how!!! READING THIS COULD CHANGE YOUR LIFE! I found this on a bulletin board like this one and decided to try it. A little while back, I was browsing through several newsgroups, just like you are now, and came across an article similar to this that said you could make thousands of dollars within weeks with only an initial investment of $6.00! So I thought, "Yeah right, this must be a scam", but like most of us, I was curious, so I kept reading. Anyway, it said that you need to send $1.00 to each of the 6 names and addresses stated in the article, to have your name placed on their mailing list. You then place your own name and address in the bottom of the list at #6, and post the article in at least 200 newsgroups. (There are millions) No catch, that was it. So after thinking it over, and talking to a few people first, I thought about trying it. I figured: "what have I got to lose except 6 stamps and $6.00, right?" Then I invested the measly $6.00. Well GUESS WHAT!!... Within 7 days, I started getting money in the mail! I was shocked! I figured it would end soon, but the money just kept coming in. In my first week, I made about $25.00. By the end of the second week I had made a total of over $1,000.00! In the third week I had over $5,000.00 and it's still growing. By the fourth week, I have made just over $12,000.00 and it's still coming in rapidly. It's certainly worth $6.00, and 6 stamps, I have spent more than that on the lottery!! Let me tell you how this works and most importantly, why it works....Also, make sure you print a copy of this article NOW, so you can get the information off of it, as you need it. I promise you that if you follow the directions exactly, that you will start making more money than you thought possible by doing something so easy! SUGGESTION: Read this entire message carefully! (Print it out or download it.) Follow the simple directions and watch the money come in! It's easy. It's legal. And, your investment is only $6.00 (Plus postage). IMPORTANT: This is not a rip-off; it is not indecent; it is not illegal; and it is virtually no risk - it really works!!!! If all of the following instructions are adhered to, you will receive extraordinary dividends. PLEASE NOTE: Please follow these directions EXACTLY, and $30,000 or more can be yours in 20 to 60 days. This program remains successful because of the honesty and integrity of the participants. Please continue its success by carefully adhering to the instructions. You will now become part of the Mail Order business. In this business your product is not solid and tangible, it's a service. You are in the business of developing Mailing Lists. Many large corporations are happy to pay big bucks for quality lists. However, the money made from the mailing lists is secondary to the income, which is made from people like you and me asking to be included in that list. ~~>HERE ARE 4 EASY STEPS TO GET STARTED<~~ STEP 1: Get 6 separate pieces of paper and write the following on each piece of paper "PLEASE PUT ME ON YOUR MAILING LIST." Now get 6 US $1.00 bills and place ONE inside EACH of the 6 pieces of paper so the bill will not be seen through the envelope (Please make sure that the bill wouldn't be noticed in the envelope to prevent thievery). Send out US $ DOLLAR, so it would be more acceptable. STEP 2: Next, place one paper in each of the 6 envelopes and seal them properly. You should now have 6 sealed envelopes, each with a piece of paper stating the phrase, "PLEASE PUT ME ON YOUR MAILING LIST.", your name and address, and a $1.00 bill. What you are doing is creating a service. THIS IS ABSOLUTELY LEGAL! You are requesting for a legitimate service and you are paying for it! Like most of us, I was a little skeptical and a little worried about the legal aspects of it all. So I checked it out with the U.S. Post Office (1-800-725-2161) and they confirmed that it is indeed legal! Mail the 6 envelopes to the following addresses below: #1) Wilson Davis~ 2209 Continental Blvd. Orlando, Fl. 32808 USA #2) Wilson Darren Matsu~3052 11th Ave, Los Angeles, CA 90018 USA #3) Darren Matsu~3052 11th Ave, Los Angeles, CA 90018 USA #4) Jeremy West ~ 25 Wisteria Way, Wrentham, MA 02093 #5) J. Haze ~91 Prince St. Apt. 16, Boston, MA 02113-1732 #6)Gerardo Ruiz~706 Boone St., Uvalde, Tx 78801 STEP 3: Now take the #1 name off the list that you see above, move the other names up (6 becomes 5, 5 becomes 4, etc...) and add YOUR Name as number 6 on the list. STEP 4: Copy this article. Change anything you need to, but try to keep this article as close to original as possible. Now, post your amended article to at least 200 newsgroups. (I think there are close to 2.4million groups) All you need is 200, but remember, the more you post, the more money you make! This is perfectly legal! If you have any doubts, refer to Title 18, Section 1302 and 1341, US Postal and Lottery Laws or Title 18, Section 3005 in the US code, also in the code of Federal regulations, Volume 16, Sections 255 and 436, which states; "a product or service must be exchanged for money received. " The simple note in the letter, "PLEASE PUT ME ON YOUR MAILING LIST", makes it legal because you are paying for exchange of a service, (adding the purchasers name to his mailing list) for a $1.00 fee. Keep a copy of these steps for yourself and, whenever you need money, you can use it again, and again. PLEASE REMEMBER that this program remains successful because of the honesty and integrity of the participants and by their carefully adhering to the directions. Look at it this way. If you are of integrity, the program will continue and the money that so many others have received will come your way. NOTE: You may want to retain every name and address sent to you, either on a computer or hard copy and keeps the notes people send you. This VERIFIES that you are truly providing a service. So, as each post is downloaded and the directions carefully followed, six members will be reimbursed for their participation as a List Developer with one dollar each. Your name will move up the list geometrically so that when your name reaches the #1 position you will be receiving thousands of dollars in CASH!!! What an opportunity for only $6.00 ($1.00 for each of the first six people listed above) Send it now, add your own name to the list and you're in business! ~~>DIRECTIONS FOR HOW TO POST TO NEWSGROUPS~~> Step 1) You do not need to re-type this entire letter to do your own posting. Simply put your mouse cursor at the beginning of this letter, click and drag your cursor to the bottom of this document, right click and select 'copy' from the edit menu. This will copy the entire letter into the computer's memory. Step 2) Open a blank 'notepad' file and place your mouse cursor at the top of the blank page. Right click and from the 'edit' menu select 'paste'. This will paste a copy of the letter into notepad so that you can add your name and postal address to the list. Step 3) Save your new notepad file as a .txt file. If you want to do your postings in different settings, you'll always have this file to go back to. Step 4) Use Netscape or Internet explorer and try searching for various newsgroups (on-line forums, message boards, chat sites, discussions.) Step 5) Visit these message boards and post this article as a new message by highlighting the text of this letter and selecting paste from the edit menu. Fill in the Subject, this will be the header that everyone sees as they scroll through the list of postings in a particular group, click the "post" message button. You're done with your first one! NOTE: Please don't SPAM or send unsolicited emails. It's completely illegal. Send emails to all the people you know or any ways that allows you to, instead of SPAMMING. (Just a reminder). Congratulations...THAT'S IT! All you have to do is jump to different newsgroups and post away, after you get the hang of it, it will take about a minute for each newsgroup! **REMEMBER, THE MORE NEWSGROUPS YOU POST IN, THE MORE MONEY YOU WILL MAKE!! BUT YOU HAVE TO POST A MINIMUM OF 200** That's it! You will begin receiving money from around the world within days! You may eventually want to rent a P.O.Box due to the large amount of mail you will receive. If you wish to stay anonymous, you can invent a name to use, as long as the postman will deliver it. *JUST MAKE SURE ALL THE ADDRESSES ARE CORRECT.* *Now the WHY part; Out of 200 postings, say I receive only 5 replies (a very low example). So then I made $5.00 with my name at #6 on the letter. Now, each of the 5 persons who just sent me $1.00 make the MINIMUM 200 postings, each with my name at #5 and only 5 persons respond to each of the original 5, that is another $25.00 for me, now those 25 each make 200 MINIMUM posts with my name at #4 and only 5 replies each, I will bring in an additional $125.00! Now, those 125 persons turn around and post the MINIMUM 200 with my name at #3 and only receive 5 replies each, I will make an additional $626.00! OK, now here is the fun part, each of those 625 persons post a MINIMUM 200 letters with my name at #2 and they each only receive 5 replies, that just made me $3,125.00!!! Those 3,125 persons will all deliver this message to 200 newsgroups with my name at #1 and if still ONLY 5 persons per 200 newsgroups react I will receive $15,625,00! With an original investment of only $6.00! AMAZING! When your name is no longer on the list, you just take the latest posting in the newsgroups, and send out another $6.00 to names on the list, putting your name at number 6 again. And start posting again. The thing to remember is: do you realize that thousands of people all over the world are joining the internet and reading these articles everyday? JUST LIKE YOU are now!! So, can you afford $6.00 and see if it really works?? I think so... People have said, "what if the plan is played out and no one sends you the money? So what! What are the chances of that happening when there are tons of new honest users and new honest people who are joining the internet and newsgroups everyday and are willing to give it a try? Estimates are at 20,000 to 50,000 new users, every day, with thousands of those joining the actual internet!!! REMEMBER, PLAY FAIRLY AND HONESTLY AND THIS WILL WORK FOR YOU!!! From stewart.midwinter at gmail.com Wed Jan 26 16:25:12 2005 From: stewart.midwinter at gmail.com (stewart.midwinter at gmail.com) Date: 26 Jan 2005 13:25:12 -0800 Subject: smtplib bug with Windows XP In-Reply-To: References: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> <1106673048.851591.324490@f14g2000cwb.googlegroups.com> Message-ID: <1106774712.617069.310000@z14g2000cwz.googlegroups.com> it works! you da man! At the same time as my desktop was upgraded to Windows XP, the IT people switched virus checker products to McAfee Enterprise. And indeed, as soon as I disabled that 'mass worm sending' option, my Python scripts is once again able to send mail. thanks so much for this tip! 247 karma points for you. S From http Fri Jan 7 06:33:05 2005 From: http (Paul Rubin) Date: 07 Jan 2005 03:33:05 -0800 Subject: Excluded and other middles in licensing References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> <75r0b2-ohg.ln1@lairds.us> <1gq0jpn.1es49j7jrk3k5N%aleaxit@yahoo.com> <7x3bxd5ywz.fsf@ruckus.brouhaha.com> <1gq0o3c.1lnjwhxjgcefmN%aleaxit@yahoo.com> Message-ID: <7xmzvlxymm.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > > Note also from the Heine-Borel theorem that every closed source > > program can be covered by some finite collection of open source > > programs. > > Every _compact_ one, surely? Quoting by heart from old memories, but, > isn't Heine-Borel about (being able reduce any open covering of X to a > finite subcovering) <-> (X is compact) ...? Yeah, whoops, that's what I meant; your old memories are clearer than mine. Actually sometimes the definitions and theorems interchange. I do remember something about Tikhonov's Theorem that says that no matter how often bounded closed source programs multiply, the product is still closed source. So, for example, Adobe Acrobat is still closed source even if you can download it from Adobe's web site infinitely often. But that theorem doesn't apply to noncompact (i.e. unbounded) closed source programs. So ordering Microsoft to release parts of Windows as open source was one of the potential remedies discussed in the penalty phase of the US Justice Dept's antitrust suit. Unfortunately, the DoJ lawyers were not good topologists so they didn't give enough consideration to this possibility. From zanesdad at bellsouth.net Fri Jan 21 12:32:21 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri, 21 Jan 2005 12:32:21 -0500 Subject: DevX: "Processing EDI Documents into XML with Python" In-Reply-To: <35c0hcF4jnr7pU1@individual.net> References: <35c0hcF4jnr7pU1@individual.net> Message-ID: <41F13CA5.3050901@bellsouth.net> Claudio Grondi wrote: >"You don't have to rely on expensive and proprietary EDI conversion software >to parse, validate, and translate EDI X12 data to and from XML; you can >build your own translator with any modern programming language, such as >Python." > > by Jeremy Jones > http://www.devx.com/enterprise/Article/26854 > > Excerpt: > "Python is an object-oriented, byte-compiled language with a clean >syntax, clear and consistent philosophy, and a strong user community. These >attributes (both of the language and the community) make it possible to >quickly write working, maintainable code, which in turn makes Python an >excellent choice for nearly any programming task. Processing any "flavor" of >EDI is no exception." > > >Hi, >just wanted to share with you, that the last issue >of the DevX newsletter comes with a Python related >article as first item in the list of subjects. > >Claudio > > > > Anyone interested in processing EDI with Python will probably be interested in giving it a read. Please feel free to scrutinize the code mercilessly. I plan on creating a project on Sourceforge with the code that is attached to that article (and hopefully with modifications coming from user input in the ensuing months). Comments are greatly appreciated. Thanks for posting this, Claudio. Jeremy Jones From sam.wun at authtec.com Mon Jan 24 01:25:33 2005 From: sam.wun at authtec.com (sam) Date: Mon, 24 Jan 2005 14:25:33 +0800 Subject: compile python to binary In-Reply-To: References: <1d6cdae3050123080242bf8994@mail.gmail.com> Message-ID: Peter Hansen wrote: > Daniel Bickett wrote: > >> Fredrik Lundh wrote: >> >>> oh, you mean that "python compiler" didn't mean "the python compiler". >>> [snip] >> >> >> I simply inferred that he was using the wrong terminology, being that >> he said "binary" twice ;-) > > > While I suspect you've guessed correctly at what the OP > meant, one should also consider that the word "binary" > can be quite ambiguous in the hands of a newbie. > > After all, source code is stored in binary too... > Sorry for the vagues terms. I meant compile a python script into a binary program. Thanks Sam > -Peter From hanzspam at yahoo.com.au Wed Jan 12 20:28:32 2005 From: hanzspam at yahoo.com.au (hanz) Date: 12 Jan 2005 17:28:32 -0800 Subject: dict.updated References: <5GiFd.8571$Vj3.3354@newssvr17.news.prodigy.com> Message-ID: <1105579712.506893.316070@f14g2000cwb.googlegroups.com> Rick Morrison wrote: > >>> [updated(d, {'c':3}) for d in [{'a':1, 'b':2}, {'x':10, 'y':'11'}]] > [{'a': 1, 'c': 3, 'b': 2}, {'y': '11', 'x': 10, 'c': 3}] I don't really understand the use of this. Can you give a less toy example? I'd probably just do dicts = [{'a':1, 'b':2}, {'x':10, 'y':'11'}] for d in dicts: d.update({'c':3}) This isn't really more typing or any clumsier IMO, so I can't see why you'd want to use list comprehensions in this case. From michaels at rd.bbc.co.uk Mon Jan 10 05:23:34 2005 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Mon, 10 Jan 2005 10:23:34 +0000 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> Message-ID: Roose wrote: ... > I was thinking that there would be a Lisp interpreter in a kernel, > which afaik doesn't exist. There's an implementation of scheme that runs as a kernel module in Linux - it's designed to allow people to experiment with exploring kernel data structures at run time, and other fun things. It's a case in point for avoiding saying that something that doesn't necessarily sound sensible doesn't exist - there's a good chance it does :) Michael -- Michael.Sparks at rd.bbc.co.uk British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From sharidas at zeomega.com Thu Jan 27 08:04:17 2005 From: sharidas at zeomega.com (Satchidanand Haridas) Date: Thu, 27 Jan 2005 18:34:17 +0530 Subject: Please suggest on the book to follow In-Reply-To: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> Message-ID: <41F8E6D1.9060201@zeomega.com> Hi, Probably the best resources for learning Python are available online. Here are a few sites that you might find helpful: 1. http://byteofpython.info/ 2. http://www.diveintopython.org/ -- Writted by Mark Pilgrim, covers many advanced material. The site says /"Dive into Python"/ is a "Python book for experienced programmers." 3. http://gnosis.cx/TPiP/ -- "Site for Text Processing in Python", a book by David mertz. You will find many other very good Python related material on his website. regards, 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 santanu wrote: >Hi all, > >I know a little python (not the OOP part) learnt by studying the online > >tutorial. Now I would like to learn it more thoroughly. > >I have access to 'Programming Python' which I liked (on flipping >through the >pages), but the problem is it deals only with version 2.0 of Phython. > >So, I would be glad if you could suggest me whether it would be really >a good >idea to learn from this book. In other words, will I have to unlearn >too much >after I complete this book (by the time I am done with this book, I >believe >we will be having Python 2.6 or so). > >Please suggest. > >Regards, >Santanu > > > From simon.brunning at gmail.com Thu Jan 6 06:59:27 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 6 Jan 2005 11:59:27 +0000 Subject: OT: spacing of code in Google Groups In-Reply-To: References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> Message-ID: <8c7f10c60501060359537dcff1@mail.gmail.com> On Wed, 05 Jan 2005 22:57:33 GMT, JanC wrote: > Rectangular selection only works with the mouse in SciTE/Scintilla: > alt-click-drag. Nope - hold down alt-shift, and select with the cursor keys. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From gene.tani at gmail.com Sun Jan 30 20:21:58 2005 From: gene.tani at gmail.com (gene.tani at gmail.com) Date: 30 Jan 2005 17:21:58 -0800 Subject: a sequence question In-Reply-To: References: Message-ID: <1107134518.436145.309020@z14g2000cwz.googlegroups.com> cookbook's not an easy grep but: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303060 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303279 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347689 From tim.golden at viacom-outdoor.co.uk Fri Jan 28 04:06:15 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 28 Jan 2005 09:06:15 -0000 Subject: win32com/makepy question Message-ID: <9A28C052FF32734DACB0A288A3533991035A06@vogbs009.gb.vo.local> [Tom Willis] | It seems in COM late binding is something that should be | avoided if possible. | | Because python seems to be really good at doing thing dynamically I'm | wondering why no one has figured out how to make the functionality in | makepy fire automagically when you need it. I (nearly) always use win32com.client.gencache.EnsureDispatch. There are a few occasions when it refuses to play, and then I'm back to Dispatch. import win32com.client word = win32com.client.gencache.EnsureDispatch ("Word.Application") # # does the same as Dispatch ("Word.Application") but does # the makepy stuff first if it needs to. # 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 ncoghlan at iinet.net.au Fri Jan 7 10:20:31 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 01:20:31 +1000 Subject: Getting rid of "self." In-Reply-To: <740c3aec05010705393048a374@mail.gmail.com> References: <740c3aec05010705393048a374@mail.gmail.com> Message-ID: <41DEA8BF.5020608@iinet.net.au> BJ?rn Lindqvist wrote: > So I'm asking here if someone > knows a better way, maybe using decorators or metaclasses or other > black magic? Wait for Python 3k when this will work: class c: def __init__(self): with self: .x = 1 .y = 2 .hi = "Hi there!" Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jgrahn-nntq at algonet.se Wed Jan 12 17:00:01 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 12 Jan 2005 22:00:01 GMT Subject: encryption/decryption help References: <7xwtuibd26.fsf@ruckus.brouhaha.com> <1105562345.525224.319120@z14g2000cwz.googlegroups.com> Message-ID: On 12 Jan 2005 12:39:05 -0800, Kartic wrote: > Hi, > > Can you use ssh tunneling? You will not be changing anything except add > an extra ssh layer to tunnel your data through. Or, rather, he wouldn't be changing anything at all in the program itself. The approach would be "Ok, so this protocol is insecure. If you want to protect yourself from eavesdropping and man-in-the-middle attacks along the ways, you have to feed it through an ssh tunnel or something similar". But we don't really know what this person wants to accomplish, so this may or may not be a viable option. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From peter at engcorp.com Sat Jan 8 12:53:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 12:53:05 -0500 Subject: python3: 'where' keyword In-Reply-To: <3480qqF46jprlU1@individual.net> References: <3480qqF46jprlU1@individual.net> Message-ID: Andrey Tatarinov wrote: > >>> print words[3], words[5] where: > >>> words = input.split() > > - defining variables in "where" block would restrict their visibility to > one expression Then your example above doesn't work... print takes a sequence of expressions, not a tuple as you seem to think. -Peter From marcel.vandendungen at gmail.com Fri Jan 14 17:17:49 2005 From: marcel.vandendungen at gmail.com (Marcel van den Dungen) Date: Fri, 14 Jan 2005 23:17:49 +0100 Subject: Index server In-Reply-To: <1105735030.574794.74400@z14g2000cwz.googlegroups.com> References: <1105735030.574794.74400@z14g2000cwz.googlegroups.com> Message-ID: python at hope.cz wrote: > Is there an Index server available in Python? For example: > I have large intranet with several servers and I would like to index > documents like search engines do. Users then can search for a domument > in ALL intranet servers like I do on Google. > Thanks for answers > L.A. > Take a look at the following URLs: http://www.methods.co.nz/docindexer/ http://www.divmod.org/Home/Projects/Lupy/index.html http://www.divmod.org/Home/Projects/Pyndex/index.html HTH, -- Marcel From tim.peters at gmail.com Sun Jan 9 12:59:49 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 9 Jan 2005 12:59:49 -0500 Subject: time module precision In-Reply-To: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> References: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> Message-ID: <1f7befae0501090959442af517@mail.gmail.com> [Tim Peters] >> Python's time.sleep() calls the Win32 API Sleep() function on >> Windows. All behavior is inherited from the latter. See MS's docs: >> >> >> [janeaustine50 at hotmail.com] > Oh, after a short research, I found that time.sleep uses its customized > way of sleeping using "select". > > [http://groups.google.com/groups?threadm=ud7i1c9ck.fsf%40ctwd0143.fitlinxx.com] > > So I think its behaviour is more complicated than single MS Sleep call, > I suppose. Sorry, the information you found is wrong, as a brief look at Python's timemodule.c will confirm. select() is used to implement time.sleep() on Unixish boxes, but, contrary to the thread you found, it's not possible to do that on Windows -- the Winsock select() requires at least one of its socket-set arguments to be non-empty (see MS's select() docs -- they're telling the truth too ). Abusing select() for "short sleeps" is an ugly (but effective) hack limited to Unixish systems. ... > What I want to do is waiting(not busy-delaying) for a few tens to > hundreds of microseconds in some threads. The closet solution I got is > using windows QueryPerformanceCounter (in Python, time.clock) with busy > looping checking if we have past the target time. However, that makes > the cpu usage upto almost 100%. > > So the problem (waiting tens to hundreds of us without busy looping) > still remains... I agree with Peter Hansen's reply here, so please respond to it. Windows is not a real-time OS, so what you want to do either cannot be done on Windows, or you're approaching your actual problem (whatever that may be) in a way that doesn't make good sense. From chrisdewinN0SPAM at yahoo.com.au Wed Jan 19 03:36:40 2005 From: chrisdewinN0SPAM at yahoo.com.au (Dfenestr8) Date: Wed, 19 Jan 2005 18:36:40 +1000 Subject: python/cgi/html bug References: <1106113858.360940.298900@c13g2000cwb.googlegroups.com> Message-ID: On Tue, 18 Jan 2005 21:50:58 -0800, Dan Bishop wrote: > > Dfenestr8 wrote: >> Hi. >> >> I've written a cgi messageboard script in python, for an irc chan I > happen >> to frequent. >> >> Bear with me, it's hard for me to describe what the bug is. So I've >> divided this post into two sections: HOW MY SCRIPTS WORKS, and WHAT > THE >> BUG IS. >> ... >> The problem is when someone posts a new topic, and that topic happens > to >> have "" double quotes, or any other strange character, some strange >> glitches occur. > > Use cgi.escape(topic, True) to convert HTML special characters to the > equivalent ampersand escape sequences. Thanx. Seems to work now. :) From chris.lasher at gmail.com Thu Jan 13 10:52:48 2005 From: chris.lasher at gmail.com (Chris Lasher) Date: 13 Jan 2005 07:52:48 -0800 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <1105576444.510743.93120@f14g2000cwb.googlegroups.com> Message-ID: <1105631568.401570.255720@z14g2000cwz.googlegroups.com> >Before you get too carried away, how often do you want to do this and >how grunty is the box you will be running on? Oops, I should have specified this. The script will only need to be run once every three or four months, when the sequences are updated. I'll be running it on boxes that are 3GHz/100GB Ram, but others may not be so fortunate, and so I'd like to keep that in mind. >BTW, you need to clarify "don't have access to an RDBMS" ... surely >this can only be due to someone stopping them from installing good >free software freely available on the Internet. I understand your and others' sentiment on this. I agree, the open-source database systems are wonderful. However, keeping it Python-only saves me hassle by only having to assist in instances where others need help downloading and installing Python. I suppose if I keep it in Python, I can even use Py2exe to generate an executable that wouldn't even require them to install Python. A solution using interaction with a database is much sexier, but, for the purposes of the script, seems unnecesary. However, I certainly appreciate the suggestions. >My guess is that you don't need anything much fancier than the >effbot's index method -- which by now you have probably found works >straight out of the box and is more than fast enough for your needs. I think Mr. Lundh's code will work very well for these purposes. Thanks very much to him for posting it. Many thanks for posting that! You'll have full credit for that part of the code. Thanks very much to all who replied! Chris From apardon at forel.vub.ac.be Tue Jan 18 09:39:32 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2005 14:39:32 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-18, Steve Holden schreef : > Antoon Pardon wrote: > >> Op 2005-01-18, Nick Coghlan schreef : > [...] >> But don't use mutable keys is not a general principle. It is a principle >> introduced by the limitations of the python implementations. >> > Sorry, but it *is* a general principle, adduced from the potential > pitfalls available to inexperienced programmers when breaking the principle. But if these inexperienced programmers would have used dictionaries that were implemented more safely, those pitfalls would have been avoided. So are the pitfalls caused by breaking the principle or by using an unsafe dictionary implementation? >> I don't like it when a good rule of thumb because of implementation >> limitations is sold as a general principle. >> > So, since you are so good at nit-picking, perhaps you will explain the > difference between "rule of thumb" and "general principle". A rule of thumb is context sensitive. If circumstances change, so do the rules of thumb. Principles have a broader field of application. IMO there is nothing principally wrong with using a mutable object as a dictionary key. But avoiding doing so is a good rule of thumb if you have a python-like implementation of a dictionary. -- Antoon Pardon From gsakkis at rutgers.edu Thu Jan 6 12:45:51 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Thu, 6 Jan 2005 19:45:51 +0200 Subject: How about "pure virtual methods"? References: <10shetjeo2cbpfa@corp.supernews.com> <1gp9wjb.18uqvfi1ibk5wxN%aleaxit@yahoo.com> <86zn017miy.fsf@guru.mired.org> Message-ID: <345bqeF47qstbU1@individual.net> "Noam Raphael" wrote: > Thanks for your suggestion, but it has several problems which the added > class solves: > > * This is a very long code just to write "you must implement this > method". Having a standard way to say that is better. > * You can instantiate the base class, which doesn't make sense. > * You must use testing to check whether a concrete class which you > derived from the base class really implemented all the abstract methods. > Testing is a good thing, but it seems to me that when the code specifies > exactly what should happen, and it doesn't make sense for it not to > happen, there's no point in having a separate test for it. Here's a more refined implementation of the one posted before that addresses these issues. It defines 'abstractclass', which would be a nice class decoraror when (and if) class decorators make it into the language. The extra benefit compared to the MustImplement metaclass is that it allows a class with no abstract methods to be defined as abstract. This makes no sense if one defines an abstract class as "a class with one or more abstract (deferred) methods". Perhaps a more useful and general definition of an abstract class is "a class that is not allowed to be instantiated". Deferred methods are one reason for making a class uninstantiable, but it's not the only one. Sometimes it is useful to define a base class that provides a default implementation of a full protocol, yet disallow its direct instantiation, as in the example below. George #=========================================================== # test_abstract.py import unittest from abstract import abstractclass class AbstractTestCase(unittest.TestCase): def test_no_abstractmethods(self): class SomeBase(object): # This class has no abstract methods; yet calling foo() or bar() # on an instance of this class would cause infinite recursion. # Hence it is defined as abstract, and its concrete subclasses # should override at least one of (foo,bar) in a way that breaks # the recursion. def __init__(self, x): self._x = x def foo(self, y): return self.bar(self._x + y) def bar(self, y): return self.foo(self._x - y) SomeBase = abstractclass(SomeBase) class Derived(SomeBase): def __init__(self,x): SomeBase.__init__(self,x) def foo(self,y): return self._x * y self.assertRaises(NotImplementedError, SomeBase, 5) self.assertEquals(Derived(5).bar(2), 15) if __name__ == '__main__': unittest.main() #=========================================================== # abstract.py import inspect __all__ = ["abstractclass", "abstractmethod", "AbstractCheckMeta"] def abstractclass(cls): '''Make a class abstract. Example:: # hopefully class decorators will be supported in python 2.x # for some x, x>4 #@abstractclass class SomeBase(object): @abstractmethod def function(self): """Implement me""" # the only way as of python 2.4 SomeBase = abstractclass(SomeBase) @param cls: A new-style class object. @return: A surrogate of C{cls} that behaves as abstract. The returned class raises NotImplementedError if attempted to be instantiated directly; still its subclasses may call its __init__. A subclass of the returned class is also abstract if it has one or more abstract methods, or if it is also explicitly decorated by this function. A method is declared abstract by being assigned to NotImplemented (or decorated by L{abstractmethod}). @raise TypeError: If there is a metaclass conflict between C{type(cls)} and L{AbstractCheckMeta}, or if C{cls} has an C{__abstractmethods__} attribute. ''' # check if cls has AbstractCheckMeta (or a subtype) for metaclass metaclass = type(cls) if not issubclass(metaclass, AbstractCheckMeta): # it doesn't; try to make AbstractCheckMeta its metaclass by # inheriting from _AbstractCheck cls = metaclass(cls.__name__, (_AbstractCheck,) + cls.__bases__, dict(cls.__dict__)) # replace __init__ with a proxy ensuring that __init__ is called by a # subclass (but not directly) old_init = getattr(cls,'__init__',None) def new_init(self,*args,**kwds): if self.__class__ is cls: raise NotImplementedError("%s is an abstract class" % cls.__name__) if old_init is not None: old_init(self,*args,**kwds) setattr(cls,'__init__',new_init) return cls def abstractmethod(function): '''A method decorator for those who prefer the parameters declared.''' return NotImplemented class AbstractCheckMeta(type): '''A metaclass to detect instantiation of abstract classes.''' def __init__(cls, name, bases, dict): if '__abstractmethods__' in cls.__dict__: raise TypeError("'__abstractmethods__' is already defined in " "class '%s': %s" % (cls.__name__, cls.__dict__['__abstractmethods__'])) type.__init__(cls, name, bases, dict) cls.__abstractmethods__ = [name for name, value in inspect.getmembers(cls) if value is NotImplemented] def __call__(cls, *args, **kwargs): if cls.__abstractmethods__: raise NotImplementedError( "Class '%s' cannot be instantiated: Methods %s are abstract." % (cls.__name__,", ".join(map(repr,cls.__abstractmethods__)))) return type.__call__(cls, *args, **kwargs) class _AbstractCheck(object): ''' A class to stick anywhere in an inheritance chain to make its descendants being checked for whether they are abstract. ''' __metaclass__ = AbstractCheckMeta From jdhunter at ace.bsd.uchicago.edu Mon Jan 31 23:14:11 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 31 Jan 2005 22:14:11 -0600 Subject: Python's idiom for function overloads In-Reply-To: <200502010417.10481.frans.englich@telia.com> (Frans Englich's message of "Tue, 1 Feb 2005 04:17:10 +0000") References: <200502010417.10481.frans.englich@telia.com> Message-ID: >>>>> "Frans" == Frans Englich writes: Frans> Hello, Frans> Since Python doesn't have static typing, how is the same Frans> result as traditional function overloads results in Frans> acheived? With function overloads the "selection of code Frans> path depending on data type" is transparent and automatic Frans> since the typing system figure out what goes to what. Frans> But in Python, when one wants to be able to pass different Frans> data types into a single "entry point" for functionality, Frans> how is that best done? To in a function do an if statement Frans> with the type() function? Using type or isinstance is one way to do it. The other way is "duck typing". If it walks like a duck and talks like a duck, it probably is a duck. The core idea is that we care less about what type an object is, and more about what services the object provides. Eg def myoverload(x): try: noise = x.quack() except AttributeError: # do something else... else: # do something with noise Variants to the try/except approach include hasattr, getattr and so on.. googling python duck typing should speed you on your way. JDH From steve at holdenweb.com Wed Jan 12 18:00:34 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 12 Jan 2005 18:00:34 -0500 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: <7xmzvfn096.fsf@ruckus.brouhaha.com> References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > michele.simionato at gmail.com writes: > >>2. One could proposed hygienic pattern-matching macros in Python, >>similar to >>Scheme syntax-rules macros. Again, it is not obvious how to >>implement pattern-matching in Python in a non-butt-ugly way. Plus, >>I feel hygienic macros quite limited and not worth the effort. > > > It wasn't obvious how to do it in Scheme either. There was quite > a bit of head scratching and experimental implementation before > there was consensus. > > >>3. We would add to Python the learning curve of macros and their >>subtilities and we do not want it. > > > I can't imagine how it could be worse than the learning curve of > __metaclass__, which we already have. If it was done in a way that > most of us would just rely on a few standard ones, that would be fine. > Well the necessity to understand metaclasses could in some ways be regarded as the push for the summit, and therefore isn't something that would trouble newbies. Given that we are having this discussion in the context of a posited "where" clause intended to allow "multi-statement expressions" (whatever they turn out to be) I would still argue you are discussing the totally unnecessary. Given that Guido is on record as saying that expressions aren't statements because he wants those things to be separate, I don't really see why there's this consistent pressure to reverse that decision. > >>4. Macros would complicate a lot Python module system. > > > I don't see how, but maybe I'm missing something. > > >>5. We have Guido providing a good syntax for us all, why we should be >>fiddling with it? More seriously, if some verbosity is recognized >>in the language (think to the "raison d'etre" of decorators, for >>instance) I very much prefer to wait for Guido to take care of >>that, once and for all, than having 100 different custom made >>solutions based on macros. > > > Every time some newbie asks an innocent "how do I ..." question, we > see unbelievably horrid answers from gurus. Just check the FAQ about > conditional expressions, etc. I just don't see Python syntax changes > as forthcoming. > There's a reason for this ... > >>What I would be interested in is a Lisp/Scheme implementation >>compiling to Python bytecode, but I am not aware of any project >>in that direction. > > > But that sounds like a bizarre idea. Python bytecode is just a > CPython artifact, not part of the language. And it's not even that > good an artifact. Good Lisp/Scheme implementations compile to native > code that beats the pants off of CPython bytecode. It would make much > more sense to have a Python implementation that compiles Python to > S-expressions and then lets a high performance Lisp or Scheme system > take care of the rest. Which would be a worthier goal than trying to graft macros on to Python. You responded that macros would be difficult to implement in m4 because (in essence) of the indented structure of Python. I'm not convinced they'd be any easier in Python, and I'm *certainly* not convinced that their addition would improve Python's readability. At best it would offer new paradigms for existing constructs (violating the "there should be one obvious way to do it" zen); at worst it would obfuscate the whole language. If you really see the need for Python macros then a preprocessor would surely be the best way to prove the validity of such ideas? 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 remi at cherrypy.org Mon Jan 3 15:56:14 2005 From: remi at cherrypy.org (remi at cherrypy.org) Date: 3 Jan 2005 12:56:14 -0800 Subject: Ann: CherryPy-2.0-beta released References: <1104774372.943278.302050@f14g2000cwb.googlegroups.com> <1104783888.664232.72720@f14g2000cwb.googlegroups.com> Message-ID: <1104785774.524707.214290@f14g2000cwb.googlegroups.com> > I'm a great believer that avoiding query strings in URL's is good > practise ( http://www.holloway.co.nz/book/9 for good arguments why). CherryPy also supports that out of the box: class Book: def default(self, categoryName, bookId): ... cpg.root.book = Book() If you go to "http://domain/book/science/9", CherryPy will call book.default('science', '9') > Also how > much does it complicate matters to run cherryPy under an existing > webserver? Is any functionality lost? Well, you can easily run CherryPy behind Apache (see http://trac.cherrypy.org/cgi-bin/trac.cgi/wiki/BehindApache). Since CherryPy provides a WSGI interface (although it's still experimental), you can also run your CherryPy app with any WSGI-compatible HTTP server (although I don't really see any advantage to doing this). Remi From nick at craig-wood.com Thu Jan 27 10:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 27 Jan 2005 15:30:01 GMT Subject: Help With Python References: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Steven Bethard wrote: > Nick Vargish wrote: > > # this is one viking making one order repeated 511 times. if you want > > # 511 vikings making seperate orders, you'll have to write a loop. > > No need to write a loop: > > py> class Viking(object): > ... def order(self): > ... return 'Spam' > ... > py> v = Viking() > py> orders = [v.order()] * 7 > py> ', '.join(orders) > 'Spam, Spam, Spam, Spam, Spam, Spam, Spam' > py> orders = [Viking().order()] * 7 > py> ', '.join(orders) > 'Spam, Spam, Spam, Spam, Spam, Spam, Spam' Thats still one Viking making 7 orders surely? Eg >>> vikings = [Viking()] * 7 >>> vikings[0] is vikings[1] True whereas >>> vikings = [Viking() for _ in range(7)] >>> vikings[0] is vikings[1] False So you want this... >>> orders = [ Viking().order() for _ in range(7) ] -- Nick Craig-Wood -- http://www.craig-wood.com/nick From pfhreak at mac.com Fri Jan 21 16:38:53 2005 From: pfhreak at mac.com (Pfhreak) Date: Fri, 21 Jan 2005 16:38:53 -0500 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <1094141001.125507@teapot.planet.gong> Message-ID: Patrick, I maintain the web page that Rupert mentions in responce to your message about Nextstep and Mach. (http://www.macos.utah.edu/Documentation/MacOSXClasses/macosxone/unix.html) I'm curious to learn more about the development of Mach and its use in Nextstep. Can you point me to your sources -- preferably online so I can put them in the Bibliography section -- especially those that mention when Mach was turned into a Microkernel? From rbt at athop1.ath.vt.edu Mon Jan 10 12:34:22 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 10 Jan 2005 12:34:22 -0500 Subject: ftplib with unknown file names Message-ID: How can I use ftplib to retrieve files when I do not know their names? I can do this to get a listing of the directory's contents: ftp_server.retrlines('LIST') The output from this goes to the console and I can't figure out how to turn that into something I can use to actually get the files (like a list of file names). I read a bit about the callback function that can be passed to retrlines but I couldn't figure out how to use it. Any help is appreciated. Thanks! From jhefferon at smcvt.edu Tue Jan 18 13:03:12 2005 From: jhefferon at smcvt.edu (Jim) Date: 18 Jan 2005 10:03:12 -0800 Subject: script to automate GUI application (newbie) In-Reply-To: References: Message-ID: <1106071392.908441.262500@c13g2000cwb.googlegroups.com> It sounds like a case for the Expect program, to me. Try Google-ing for "Expect". If you are looking for a Python approach, then try googling for "Expect Python". Jim From aahzpy at panix.com Sun Jan 9 23:53:24 2005 From: aahzpy at panix.com (aahzpy at panix.com) Date: Sun, 9 Jan 2005 23:53:24 -0500 Subject: BayPIGgies: January 13, 7:30pm Message-ID: <20050110045324.GA16439@panix.com> 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, January 13 at 7:30pm. Danny Yoo leads a discussion of Python coding tricks and techniques. Please join the BayPIGgies mailing list to discuss which sample code will be demonstrated. The web site will contain more details. 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 February 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/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From s_david_rose at hotmail.com Wed Jan 19 14:35:22 2005 From: s_david_rose at hotmail.com (GMane Python) Date: Wed, 19 Jan 2005 14:35:22 -0500 Subject: Automatic Windows printer creation? Message-ID: Anyone know if there's a module which will allow me to 'create' windows printer definitions? Not from a Windows domain network, but just to add a printer that sends to a jet-direct-attached printer. Thanks! Dave From fredrik at pythonware.com Fri Jan 21 12:54:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 21 Jan 2005 18:54:50 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> Message-ID: "rm" wrote: > well, I did look at it, and as a text format is more readable than XML is. judging from http://yaml.org/spec/current.html (750k), the YAML designers are clearly insane. that's the most absurd software specification I've ever seen. they need help, not users. From rkern at ucsd.edu Thu Jan 13 15:34:07 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 13 Jan 2005 12:34:07 -0800 Subject: News Reader In-Reply-To: References: Message-ID: Daniel Bowett wrote: > Is anyone reading this list through thunderbird as news? If so - how did > you set it up? I subscribed to comp.lang.python under my USENET news server account. -- 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 fuzzyman at gmail.com Sat Jan 29 08:09:21 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Jan 2005 05:09:21 -0800 Subject: Help with web dashboard In-Reply-To: References: <1106924984.507889.265070@c13g2000cwb.googlegroups.com> Message-ID: <1107004161.954148.206750@f14g2000cwb.googlegroups.com> Chris wrote: > In article <1106924984.507889.265070 at c13g2000cwb.googlegroups.com>, > fuzzyman at gmail.com says... > > Ifd you want to use standard CGI I've written a CGI user > > authentication/management module called logintools. > > > > Would this be preferred (or easier) than using an application server > (ie. Zope or Webware)? > > If possible, I think it would be nice if the security aspect of it was > already built-in so I would not need to write/test it myself. > > Thanks for your help. For simple applications, writing CGIs is going to be quite a lot easier than using something like Zope. If your final product is big and complex then CGIs probably aren't suitable anyway. logintools is a module providing user authentication/administration and user management specifically for CGIs. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From exarkun at divmod.com Thu Jan 6 09:40:01 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 06 Jan 2005 14:40:01 GMT Subject: sorting on keys in a list of dicts In-Reply-To: Message-ID: <20050106144001.25734.834316519.divmod.quotient.3738@ohm> On Thu, 06 Jan 2005 15:31:22 +0100, J Berends wrote: >Suppose I have a list of dictionaries and each dict has a common keyname > with a (sortable) value in it. > > How can I shuffle their position in the list in such way that they > become sorted. > In Python 2.4, import operator L.sort(key=operator.itemgetter(key)) In Python 2.3, L2 = [(d[key], i, d) for (i, d) in enumerate(L)] L2.sort() L = [d for (v, i, d) in L2] Jp From gregor.jan at NOSPAM.quick.cz Thu Jan 27 06:07:57 2005 From: gregor.jan at NOSPAM.quick.cz (Jan Gregor) Date: Thu, 27 Jan 2005 12:07:57 +0100 Subject: redirect of standard output of jython to JTextArea Message-ID: Hello I want to redirect output of jython's functions print and println to JTextArea component. Is it possible ? I tried this (swingConsole.textArea is instance): In my class self.printStream= MyPrintStream(System.out) System.setOut(self.printStream) ---------------------------------------------------- class MyPrintStream (PrintStream): def println (str): swingConsole.textArea.append(str) def print (str): swingConsole.textArea.append(str) Output is still directed to standard output. Thanks for help, Jan From donn at u.washington.edu Fri Jan 7 14:53:37 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 07 Jan 2005 11:53:37 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> Message-ID: In article , Steven Bethard wrote: > Andrey Tatarinov wrote: > > It would be great to be able to reverse usage/definition parts in > > haskell-way with "where" keyword. Since Python 3 would miss lambda, that > > would be extremly useful for creating readable sources. > > > > Usage could be something like: > > > > >>> res = [ f(i) for i in objects ] where: > > >>> def f(x): > > >>> #do something > > > > or > > > > >>> print words[3], words[5] where: > > >>> words = input.split() > > > > - defining variables in "where" block would restrict their visibility to > > one expression > > How often is this really necessary? Could you describe some benefits of > this? I think the only time I've ever run into scoping problems is with > lambda, e.g. > > [lambda x: f(x) for x, f in lst] > > instead of > > [lambda x, f=f: for x, f in lst] > > Are there other situations where you run into these kinds of problems? Note that he says "would be extremely useful for creating readable sources", so the "these kinds of problems" he would have been thinking of would be where source was not as readable as it could be. You seem to be concerned about something else. I don't by any means agree that this notation is worth adopting, and in general I think this kind of readability issue is more or less a lost cause for a language with Python's scoping rules, but the motive makes sense to me. One way to look at it might be, if I observe that "words" is assigned to in a where clause, then I know it will not be used elsewhere in the surrounding scope so I can forget about it right away. If the name does occur elsewhere, it evidently refers to something else. Donn Cave, donn at u.washington.edu From skip at pobox.com Tue Jan 4 10:19:13 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Jan 2005 09:19:13 -0600 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: <1104849206.111461.70500@c13g2000cwb.googlegroups.com> References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> Message-ID: <16858.46065.784624.754021@montanaro.dyndns.org> michele> BTW what's the difference between .encode and .decode ? I started to answer, then got confused when I read the docstrings for unicode.encode and unicode.decode: >>> help(u"\xe4".decode) Help on built-in function decode: decode(...) S.decode([encoding[,errors]]) -> string or unicode Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registerd with codecs.register_error that is able to handle UnicodeDecodeErrors. >>> help(u"\xe4".encode) Help on built-in function encode: encode(...) S.encode([encoding[,errors]]) -> string or unicode Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors. It probably makes sense to one who knows, but for the feeble-minded like myself, they seem about the same. I'd be happy to add a couple examples to the string methods section of the docs if someone will produce something simple that makes the distinction clear. Skip From rnd at onego.ru Tue Jan 4 17:04:49 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 5 Jan 2005 01:04:49 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: <41DAFF93.7030502@pythonapocrypha.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> Message-ID: On Tue, 4 Jan 2005, Dave Brueck wrote: >> What about generic programming coming into fashion anytime soon? >Roman, I think I've read every single thread in the past year or three >wherein you've brought up generic programming, and I think you'd do well to >choose a new term for the idea you're trying to convey. Or, yes, and I forgot to mention that generic programming is much clearer idea than OO programming, as it is not so vague. At least for me: I still don't fully comprehend OOP (after N years of "studying" it!) and understanding of GP came after just one book on the topic. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From annaraven at gmail.com Mon Jan 10 13:16:12 2005 From: annaraven at gmail.com (Anna) Date: 10 Jan 2005 10:16:12 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: <10u5fu3o7v4h9e3@corp.supernews.com> References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <10u5fu3o7v4h9e3@corp.supernews.com> Message-ID: <1105380972.666888.75280@f14g2000cwb.googlegroups.com> Same here. From holywill at gmail.com Tue Jan 11 20:27:09 2005 From: holywill at gmail.com (Will) Date: Wed, 12 Jan 2005 14:27:09 +1300 Subject: Game programming in Python In-Reply-To: References: Message-ID: <11a4311705011117277e31db2e@mail.gmail.com> Hi Baza, On Tue, 11 Jan 2005 18:32:50 +0000, Baza wrote: > I'm looking for any books or on-line resources on game programming using > Python. Does anyone have any advice? You're probably beyond this book, however, for other newbies like moi checking this thread in future, I started with: "Python Programming for the absolute beginner" By Michael Dawson (Premier Press- www.premierpressbooks.com. ISBN: 1-59200-073-8) It's a great read and easy to follow, but more importantly in this instance, one learns Python by creating games (and then you can put this knowledge to use elsewhere). It comes with a CD that has Python 2.2.3, Pygame 1.5.6 and Livewires 2.0, the source code for the projects in the book, & useful links (as well as The Gimp for Windows and a demo version of the Cool Edit Pro multitrack recording studio). HTH. L8r, Will # Living & loving in Aotearoa, New Zealand. Kia ora Kiwis! From nick at craig-wood.com Sat Jan 22 04:30:07 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 22 Jan 2005 09:30:07 GMT Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Here's the message I had in mind: > > http://groups-beta.google.com/group/comp.lang.python/msg/adfbec9f4d7300cc > > It came from someone who follows Python crypto issues as closely as > anyone, and refers to a consensus on python-dev. I'm not on python-dev > myself but I feel that the author of that message is credible and is > not just "anyone". And here is the relevant part... "A.M. Kuchling" wrote: > On Fri, 27 Feb 2004 11:01:08 -0800 Trevor Perrin wrote: > > Are you and Paul still looking at adding ciphers to stdlib? That would > > make me really, really happy :-).... > > No, unfortunately; the python-dev consensus was that encryption raised > export control issues, and the existing rotor module is now on its way to > being removed. I'm sure thats wrong now-a-days. Here are some examples of open source software with strong crypto Linux kernel: http://www.kernel.org/ GNU crypto project: http://www.gnu.org/software/gnu-crypto/ TryCrypt: http://truecrypt.sourceforge.net/ OpenSSL: http://www.openssl.org/ AEScrypt: http://aescrypt.sourceforge.net/ Note that some of these are being worked on at sourceforge just like python. Surely it must be possible to add a few simple crypto modules to python? That said a) IANAL b) 'apt-get install python-crypto' works for me ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jacek.generowicz at cern.ch Tue Jan 11 03:26:09 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Jan 2005 09:26:09 +0100 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <1105381339.922714.23200@c13g2000cwb.googlegroups.com> <1oFEd.71967$Jk5.45632@lakeread01> Message-ID: Steve Holden writes: > Well, I suspect that Church originally chose lambda precisely because > of its meaninglessness, IAANM, Church didn't choose lambda at all. He chose to put a "hat" (like a circumflex accent) above the bound name. Then, because of some typesetting difficulties, this was transformed into the nearest thing that looked like it: a capital lambda in front of the name ... and later the capital lambda turned into a lowercase one. From http Thu Jan 6 02:19:39 2005 From: http (Paul Rubin) Date: 05 Jan 2005 23:19:39 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> Message-ID: <7x652bnhx0.fsf@ruckus.brouhaha.com> bokr at oz.net (Bengt Richter) writes: > What do you think of automated secure importing/installing from a > remote server? You know, you try to import something and it imports > a stub that was included as a battery-place-holder and that has > basic help info and will give you reasonable options in directing > the installation of the full thing (or subset you are interested in). You mean for Python modules, in ordinary operation? I'd hate that. For things like apt-get, used for installing nonstandard programs or getting security updates, I guess it's about as good as one can hope for. The user has to activate it explicitly though. I definitely don't want my computer opening internet connections unless I specifically ask it to. Doing otherwise is almost spyware. This may sound a little extreme but my distribution philosophy is I'd like to get closer to an environment where users normally never install any software of any type, ever. Microsoft cornered the OS market cornered by acheiving something pretty close to this: they deliver Windows with no installation needed. When people buy new computers, Windows is already on the hard drive, so the user just turns the computer on and Windows is there. Fedora Core (what I'm running now) isn't shipped that way by any computer makers that I know of, but it makes up for it by having lots of applications included. So I buy a new computer, put in the bootable Fedora DVD-ROM, and sit back for half an hour while a one-time installation runs. That's about as close as I can get to just turning on the new computer and having Fedora already there. > I don't see why every gee whiz thing has to be on your hard disk > from the first. And for those that want a big grabbag, the stubs > ought to be designed to to be runnable from a configured script, so > you can turn it loose and see what's up IRL. If I have a 400 gig hard drive, I don't see why I need 99.99% of it empty instead of 99.0% after I do my OS install. I don't want to hassle over downloading stuff for hours or days at a time, or about what components depend on other components, if the distro can just include it. I just tried to install a Python program that uses wxPython, except that meant I had to download both wxPython and wxWidgets, and the installations failed because of some version mismatch between the current wxWidgets distro and the version of GTK included with FC3. I spent an hour or so messing with it and then said screw it and gave up on the GUI part of that program. I'm more technical than most users (I'm a programmer) yet this installation stuff is too much hassle even for me. So I'd really rather that all that stuff be pre-configured. If a system has N downloadable components that are supposedly independent, there are 2**N combinations of them that anyone might have installed. In reality the indepdence is never that complete, so something can easily go wrong if you pick a combination that hasn't been tested and debugged by someone, and there's no way to test more than a few of the possibilities. So I'd rather that all N components already be included with the OS so that the combination will have been tested by the distro maintainers before the end user has to deal with it. Hard drives and distro media (DVD) are big enough now that it's quite reasonable for distros to include just about everything that most users could want. From andy at andygross.org Wed Jan 5 16:10:02 2005 From: andy at andygross.org (Andy Gross) Date: Wed, 5 Jan 2005 16:10:02 -0500 Subject: Embedding a restricted python interpreter In-Reply-To: References: Message-ID: <2A8E5F75-5F5E-11D9-923E-000A95CED3AC@andygross.org> Check out http://mail.python.org/pipermail/python-dev/2003-January/031851.html for a historical thread on rexec.py's vulnerabilities. Right now, the answer for people who want restricted execution is usually "wait for pypy", due to the number of tricks that can subvert the rexec model. There are probably some one-off, application-specific things you can do that might meet your requirements, like special import hooks, sys.settrace() callbacks that inspect each running frame (and are slow), and namespace restrictions on stuff passed to exec or eval. If you really need sandboxing, your probably out of luck. Setting up a usermode linux instance or chrooted jail is probably the best bet today. /arg On Jan 4, 2005, at 6:38 PM, Rolf Magnus wrote: > Hi, > > I would like to embed a python interpreter within a program, but since > that > program would be able to automatically download scripts from the > internet, > I'd like to run those in a restricted environment, which basically > means > that I want to allow only a specific set of modules to be used by the > scripts, so that it wouldn't be possible for them to remove files from > the > hard drive, kill processes or do other nasty stuff. > Is there any way to do that with the standard python interpreter? > > -- > http://mail.python.org/mailman/listinfo/python-list From mcfletch at rogers.com Mon Jan 24 10:14:40 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 24 Jan 2005 10:14:40 -0500 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> References: <41F427EB.3000200@rogers.com> <1f7befae0501231720428ca3c@mail.gmail.com> <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> Message-ID: <41F510E0.40301@rogers.com> Richie Hindle wrote: >[Tim] > > >>I'll note that one fairly obvious pattern works very well for weakrefs >>and __del__ methods (mutatis mutandis): don't put the __del__ method >>in self, put it in a dead-simple object hanging *off* of self. Like >>the simple: >> >>class BTreeCloser: >> def __init__(self, btree): >> self.btree = btree >> >> def __del__(self): >> if self.btree: >> self.btree.close() >> self.btree = None >> >>Then give self an attribute refererring to a BTreeCloser instance, and >>keep self's class free of a __del__ method. The operational >>definition of "dead simple" is "may or may not be reachable only from >>cycles, but is never itself part of a cycle". >> >> > >This is very nice - I've been wondering about just this problem recently, >and this will be very useful. Many thanks! > > From me too :) >One question: why the `self.btree = None` in the last line? Isn't >`self.btree` guaranteed to go away at this point anyway? (If the answer >is "it's necessary for weird cases that would take an hour to explain" >then I'll be more than happy to simply use it. 8-) > > It's to allow the Closer object to act as a substitute for a .close() method on the object, the final full code of the Closer looks like this: class Closer( object ): """Close the OIDStore""" def __init__( self, client ): """Initialise the closer object""" self.btree = client.btree def __call__( self ): """Close and cleanup to prevent multiple calls""" if self.btree: self.btree.close() self.btree = None def __del__( self ): """Handle deletion of the closer object (close btree if necessary)""" self() and we store one of these as self.close in the OIDStore instance' dictionary. self.close = Closer( self ) If the user explicitly calls storage.close() we don't want the __del__ trying to re-close the storage later. In other words, its an explicit requirement for *this* __del__, not a general requirement. Have fun, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From usenet_spam at janc.invalid Fri Jan 21 23:05:48 2005 From: usenet_spam at janc.invalid (JanC) Date: Sat, 22 Jan 2005 04:05:48 GMT Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> Message-ID: Robin Becker schreef: > well since rotor is a german (1930's) invention And AES is a Belgian invention... ;-) > it is a bit late for > Amricans (Hollywood notwithstanding) to be worried about its export -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From jack at performancedrivers.com Sun Jan 30 09:49:19 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Sun, 30 Jan 2005 09:49:19 -0500 Subject: limited python virtual machine In-Reply-To: <41FC3F8B.9080800@iinet.net.au> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr58wn.m3n0xac2j9qbN%aleaxit@yahoo.com> <41FC3F8B.9080800@iinet.net.au> Message-ID: <20050130144919.GV1607@performancedrivers.com> On Sun, Jan 30, 2005 at 11:59:39AM +1000, Nick Coghlan wrote: > Alex Martelli wrote: > >It didn't seem to me that Steven's question was so restricted; and since > >he thanked me for my answer (which of course is probably inapplicable to > >some custom interpreter that's not written yet) it appears to me that my > >interpretation of his question was correct, and my answer useful to him. > > Yes, I'd stopped following the thread for a bit, and the discussion had > moved further afield than I realised :) > > >If you _can_ execute (whatever) in a separate process, then an approach > >based on BSD's "jail" or equivalent features of other OS's may be able > >to give you all you need, without needing other restrictions to be coded > >in the interpreter (or whatever else you run in that process). > > I think that's where these discussion have historically ended. . . making a > Python-specific sandbox gets complicated enough that it ends up making more > sense to just use an OS-based sandbox that lets you execute arbitrary > binaries relatively safely. > > The last suggestion I recall along these lines was chroot() plus a > monitoring daemon that killed the relevant subprocess if it started > consuming too much memory or looked like it had got stuck in an infinite > loop. > The Xen virtual server[1] was recently metnioned on slashdot[2]. It is more lightweight and faster than full scale machine emulators because it uses a modified system kernel (so it only works on *nixes it has been ported to). You can set the virtual memory of each instance to keep programs from eating the world. I don't know about CPU, you might still have to monitor & kill instances that peg the CPU. If anyone does this, a HOWTO would be appreciated! -Jack From jwaixs at gmail.com Mon Jan 3 09:56:44 2005 From: jwaixs at gmail.com (Noud Aldenhoven) Date: Mon, 03 Jan 2005 15:56:44 +0100 Subject: removing comments form a file References: <5b617$41d956df$53e8229a$22273@freeler.nl> <1104765734.888089.279470@f14g2000cwb.googlegroups.com> Message-ID: <6e9c$41d969fe$53e8229a$23742@freeler.nl> Ah, Thank you, I never thaught about the re module. Now I can do some cool stuf. Greetings, Noud Aldenhoven ps. Zal ik een keer langs komen? ;-P wittempj at hotmail.com wrote: > You cold do something like this: > >>>> import re >>>> commentpattern = re.compile('.*(?=//)|.*(?!//)') >>>> stringwithcomment = 'Blah di blah // some comment' >>>> match = commentpattern.match(stringwithcomment) >>>> match.group() > 'Blah di blah ' >>>> stringwithoutcomment = 'Blah di blah' >>>> match = commentpattern.match(stringwithoutcomment) >>>> match.group() > 'Blah di blah' >>>> blankline = '\n' >>>> match = commentpattern.match(blankline) >>>> match.group() > '' >>>> > > and put this in a loop where you iterate over your file. > Martin (The Netherlands, Amsterdam, bij Diemen) > > Noud Aldenhoven wrote: >> Hello everyone, >> >> I was wondering how to remove comments away form a file. >> So that's why I made this script. >> >> =============================== >> #!/usr/bin/env python >> >> import sys >> import string >> import time >> >> helptext = "usage: python rmcomment [oldfile] [newfile] [comment]" >> >> def rmcomment(oldfile, newfile, comment): >> oldfile = open(oldfile, 'r') >> newfile = open(newfile, 'w') >> ccount = 0 >> lcount = 0 >> for line in oldfile.readlines(): >> splitline = string.split(line) >> pstest = 0 >> fileline = "" >> for word in splitline: >> if word[:2] == comment: >> pstest = -1 >> ccount += 1 >> pass >> elif pstest == -1: >> pass >> else: >> fileline += word + " " >> if len(fileline) == 0: >> pass >> else: >> newfile.write(fileline + "\n") >> lcount += 1 >> print "Done... in %s seconds\nRemoved comment from %s > lines\nWrote % >> lines to %s" % (time.time()-start , ccount, lcount, newfile) >> raw_input("Push the enter button to quit>") >> >> if __name__ == "__main__": >> if sys.argv[1] == "-h" or sys.argv[1] == "-help": >> print helptext >> else: >> start = time.time() >> oldfile = sys.argv[1] >> newfile = sys.argv[2] >> comment = sys.argv[3] >> rmcomment(oldfile, newfile, comment) >> >> >> ======================================== >> >> This script works fine with standard text files. An example is this > one: >> >> example.txt: >> >> Hello Fuckin' World //how are you doing today >> //I think it delete this sentence and the next sentence too! >> >> But this one not! #Even not this comment >> >> end example.txt >> >> If I use my script, named rmcomment.py I get this: >> >> jwaixs at linux:~/programmeren/python/rmcomment$ cat example.txt >> Hello Fuckin' World //how are you doing today >> //I think it delete this sentence and the next sentence too! >> >> But this one not! #Even not this comment's >> jwaixs at linux:~/programmeren/python/rmcomment$ python rmcomment.py >> example.txt newexample.txt // >> Done... in 0.00104999542236 seconds >> Removed comment from 2 lines >> Wrote 2nes to >> Push the enter button to quit> >> jwaixs at linux:~/programmeren/python/rmcomment$ cat newexample.txt >> Hello Fuckin' World >> But this one not! #Even not this comment >> jwaixs at linux:~/programmeren/python/rmcomment$ >> >> works fine... but here's my problem. If I use rmcomment.py also the >> whitelines will be removed. And I don't want that to happen. Here's > another >> example: >> >> jwaixs at linux:~/programmeren/python/rmcomment$ cat otherexample.txt >> //This shows what whitelines are doing here >> left from me is a nice white line tabs >> and here left are at least 3 white line tabs >> >> //and ofcourse, comments will be deleted >> jwaixs at linux:~/programmeren/python/rmcomment$ python rmcomment.py >> otherexample.txt newotherexample.txt // >> Done... in 0.0011351108551 seconds >> Removed comment form 2 lines >> Wrote 2nes to 0x403e1c60> >> Push the enter button to quit> >> jwaixs at linux:~/programmeren/python/rmcomment$ cat newotherexample.txt >> left from me is a nice white line tabs >> and here left are at least 3 white line tabs >> jwaixs at linux:~/programmeren/python/rmcomment$ >> >> My beautiful whitelines are gone! And I don't want that! >> I've thaught how to fix this for a time, but I can't make it on my > own. Too >> less programming experiance, I'm afraid. >> Could someone help me with this problem? Or fix the script or give a > hint or >> something? >> >> Thank you at least for reading this post, >> >> Noud Aldenhoven >> The Netherlands (In de beurt bij Nijmegen, voor de nieuwschierigen) >> >> ps. Yes, I'm a Dyslextion and can't write correct english. I'm sorry > for >> that. From peter at engcorp.com Tue Jan 18 20:01:01 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Jan 2005 20:01:01 -0500 Subject: file copy portability In-Reply-To: References: Message-ID: Bob Smith wrote: > Is shutil.copyfile(src,dst) the *most* portable way to copy files with > Python? I'm dealing with plain text files on Windows, Linux and Mac OSX. Yes, provided you don't need any of the features provided by the other shutil.copy functions, and assuming you can live with the Caveat listed in the docs for the MacOS system... -Peter From ncoghlan at iinet.net.au Thu Jan 20 07:27:05 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 20 Jan 2005 22:27:05 +1000 Subject: Class introspection and dynamically determining function arguments In-Reply-To: <359lfnF4hd6e3U1@individual.net> References: <359lfnF4hd6e3U1@individual.net> Message-ID: <41EFA399.6080504@iinet.net.au> Diez B. Roggisch wrote: > Mark English wrote: > As youself already mentioned that maybe you have to impose certain > prerequisites, you maybe want to extend this to the point where for each > class you want to make dynamically instantiatable you need some > declaration. This of course depends on your desired application - whatfor > is it planned? If this only has to work for classes created for the purpose (rather than for an arbitrary class): Py> class Buildable(object): ... __slots__ = ["x", "y"] ... def __init__(self, **kwds): ... super(Buildable, self).__init__(self, **kwds) ... for attr in Buildable.__slots__: ... setattr(self, attr, kwds[attr]) ... Py> b = Buildable(x = 1 , y = 2) Py> b.x 1 Py> b.y 2 (Note that you don't *have* to use slots, you can use a non-special class attribute if you don't want the other side effects) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jbperez808 at wahoo.com Sun Jan 2 14:08:30 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Mon, 03 Jan 2005 03:08:30 +0800 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <41d7f5eb$0$10383$e4fe514c@dreader18.news.xs4all.nl> References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <41d7f5eb$0$10383$e4fe514c@dreader18.news.xs4all.nl> Message-ID: <33qumeF4319dcU1@individual.net> none wrote: > Does Python really need yet another framework? Apart from the > intellectual excersise, wouldn't it be nice if Python would get a > framework "for the rest of us" (meaning: mere mortals) which would focus > upon getting work done in a simple manner instead of creating yet > another, new, hip, exciting, way of creating dynamic websites? If Python > cannot deliver a PHP clone, at least you would expect a Rails lookalike. Spyce (http://spyce.sf.net) would be the superior Python-based PHP clone you are looking for. From steve at holdenweb.com Mon Jan 3 14:45:36 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 14:45:36 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><7xmzvu1ycn.fsf@ruckus.brouhaha.com><7xd5wqd14y.fsf@ruckus.brouhaha.com><7xfz1lal5d.fsf@ruckus.brouhaha.com><7xekh423b6.fsf@ruckus.brouhaha.com> <_rTBd.66275$Jk5.46@lakeread01> Message-ID: Terry Reedy wrote: > "Steve Holden" wrote in message > news:_rTBd.66275$Jk5.46 at lakeread01... > >>Well clearly there's a spectrum. However, I have previously written that >>the number of open source projects that appear to get stuck somewhere >>between release 0.1 and release 0.9 is amazingly large, and does imply >>some dissipation of effort. > > > And how do the failure and effort dissipation rates of open source code > compare to those of closed source code? Of course, we have only anecdotal > evidence that the latter is also 'amazingly large'. And, to be fair, the > latter should include the one-programmer proprietary projects that > correspond to the one-programmer open projects. > > Also, what is 'amazing' to one depends on one's expectations ;-). It is > known, for instance, that some large fraction of visible retail business > fail within a year. And that natural selection is based on that fact that > failure is normal. > Well, since everything you say is true, I suppose there's not much wriggle room for me. But when a shop goes belly up, it's most often replaced by another business in fairy short order, and proprietary project failures are usually hushed up by firing the programmers and promoting the managers. Whereas the bleached bones of the failed open source projects are visible for all to see on the SourceForge beach. 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 pdemb at illx.org Sun Jan 2 06:55:40 2005 From: pdemb at illx.org (Peter Dembinski) Date: Sun, 02 Jan 2005 12:55:40 +0100 Subject: [OT] Re: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7x4qi2yik8.fsf@ruckus.brouhaha.com> <87mzvumz20.fsf@hector.domek> <7x8y7ed0yn.fsf@ruckus.brouhaha.com> Message-ID: <87oeg8avur.fsf_-_@hector.domek> Paul Rubin writes: > Peter Dembinski writes: >> If it has to be both reliable and secure, I suggest you used more >> redundant language such as Ada 95. > > That's something to think about and it's come up in discussions, > but probably complicates stuff since it's not currently available > on the target platform. Also, the people on the project have > significant Java and Python experience but haven't used Ada. > Do you think it has real advantages over Java? As I wrote before, it is more redundant language[1], plus (AFAIR) it has the strongest type checking of all the programming languages I know about. Plus, most of Ada compilers (such as gnat) generate machine/operating system - specific code[2], not bytecode, which could be advantage if performance is one of priorities. I may have a little skewed viewpoint because Ada 95 is the language I have recently studied on my RTS labs :> [1] for example, one has to define interface and implementation parts of each module in separate files [2] AFAIR gnat generates C code, which is then compiled with gcc. From john at grulic.org.ar Mon Jan 17 00:39:49 2005 From: john at grulic.org.ar (John Lenton) Date: Mon, 17 Jan 2005 02:39:49 -0300 Subject: strange note in fcntl docs Message-ID: <20050117053949.GA28456@grulic.org.ar> In the fnctl docs for both python 2.3 and 2.4 there is a note at the bottom that says The os.open() function supports locking flags and is available on a wider variety of platforms than the lockf() and flock() functions, providing a more platform-independent file locking facility. however, in neither of those versions does os.open support any kind of mysterious "locking flags", nor is there any reference in os to any kind of locking magic (nor do any C open()s I know of support any kind of locking semantics). The note seems bogus; am I missing something, or should it be elided? -- John Lenton (john at grulic.org.ar) -- Random fortune: Are Linux users lemmings collectively jumping off of the cliff of reliable, well-engineered commercial software? -- Matt Welsh -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From ncoghlan at iinet.net.au Sat Jan 8 01:47:16 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 16:47:16 +1000 Subject: python3: 'where' keyword In-Reply-To: <7xvfa8l9fb.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <7xvfa8l9fb.fsf@ruckus.brouhaha.com> Message-ID: <41DF81F4.6040306@iinet.net.au> Paul Rubin wrote: > the suite has its own scope so any variable created there is local to > the suite plus the following statement. The scope vanishes after the > statement. The second part of the idea is to give the statement greater prominence and 'hide' the uninteresting setup (the contents of the where clause). Putting the statement of interest after the where suite still gives the benefits of avoiding namespace clutter, but doesn't really help readability (it makes it worse, if you ask me). Particularly, what if the next statement is a compound statement? Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From rkern at ucsd.edu Mon Jan 3 20:21:38 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 03 Jan 2005 17:21:38 -0800 Subject: Howto Extract PNG from binary file @ 0x80? In-Reply-To: <1104797038.407042.32580@z14g2000cwz.googlegroups.com> References: <1102753727.706459.105920@f14g2000cwb.googlegroups.com> <1104797038.407042.32580@z14g2000cwz.googlegroups.com> Message-ID: flamesrock wrote: [snip] > flamesrock at flames:~/score$ python sc4png.py > Traceback (most recent call last): > File "sc4png.py", line 26, in ? > pngcopy(infile, outfile) > File "sc4png.py", line 14, in pngcopy > size, cid = struct.unpack("!l4s", chunk) > struct.error: unpack str size does not match format > > Any ideas on how to fix it? If I understand this page correctly, > http://www.python.org/doc/current/lib/module-struct.html > a png is basically a 'big endian string of 14 chars'? Changing it to > !14b" gives a"ValueError: unpack tuple of wrong size" > -thanks in advance for any help No, the chunk header is specified as "!l4s" where that second character is a lower-case "L", not one "1". The struct is "a 4-byte long integer in big-endian format followed by a 4-character string". I think the error you are running into is that the chunk you are passing in does not have 8 characters. Is your input truncated somehow? -- 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 steve at holdenweb.com Thu Jan 6 11:56:34 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 11:56:34 -0500 Subject: curses is not imported under Linux (and Python 2.4) In-Reply-To: <41dd65bd.785984171@news.compuserve.de> References: <41dd65bd.785984171@news.compuserve.de> Message-ID: Konrad Koller wrote: > import curses > produces the ImportError: No module named _curses > ("from _curses import *" in line 15 in __init__.py) > Of course imp.find_module ("_curses") reports the same error. > How can I make use of the curses package for writing a Python script > with curses? I get the same thing under Windows: _curses is the compiled extension supporting the curses library, so I must presume that isn't supported by default on Windows. No problems under Cygwin or on Linux. Googling for "python curses windows" might provide a few pointers. 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 roy at panix.com Sun Jan 2 09:06:33 2005 From: roy at panix.com (Roy Smith) Date: Sun, 02 Jan 2005 09:06:33 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> Message-ID: Stefan Axelsson wrote: > Yes, ignoring most of the debate about static vs. dynamic typing, I've > also longed for 'use strict'. You can use __slots__ to get the effect you're after. Well, sort of; it only works for instance variables, not locals. And the gurus will argue that __slots__ wasn't intended for that, so you shouldn't do it. > Sure Python isn't as bad as (say) Awk in this respect; you have to at > least assign a variable to make it spring into existence I think you've hit the nail on the head. In awk (and perl, and most shells, and IIRC, FORTRAN), using an undefined variable silently gets you a default value (empty string or zero). This tends to propagate errors and make them very difficult to track down. In Python, you raise NameError or AttributeError, so you find out about your mistake quickly, and you know exactly where it is. The only time you can really go wrong is when you've got multiple assignment statements with the same lhs and you make a typo in one of them. And even then, as you say, things like Pychecker will probably catch the mistake. In perl, I always use "use strict", but in Python, I just don't feel the need. Between the exception mechanism and unit tests, the odds of a typo going unnoticed for very long are pretty slim. I'll admit I don't use Pychecker, but if I was doing production code, I would probably use it as part of my QA process. > I don't think that anyone could argue that typing 'use apa' before > the first actual use (or words to that effect) would 'slow them > down', or be very onerous. Well, I'll have to (respectfully) disagree with you on that. It's not that there's no value in explicit declarations, it's just that (IMHO) the cost exceeds the value, given the other tools we have in Python to catch the mistake. From jdhunter at ace.bsd.uchicago.edu Sun Jan 30 23:25:10 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 30 Jan 2005 22:25:10 -0600 Subject: python and gpl Message-ID: I have a question about what it takes to trigger GPL restrictions in python code which conditionally uses a GPL library. Here is the context of my question. matplotlib, which I develop, is a plotting module which is distributed under a PSF compatible license, and hence we avoid using GPLd code so as to not trigger the GPL requirements. matplotlib has rigid segregation between the front end (plotting commands, figure objects, etc) and backends (gtk, wx, ps, svg, etc). The backend is chosen dynamically at runtime -- eg the same python script could trigger the import gtk, wx, or ps, depending an some rc settings or command line opts. The question is: does shipping a backend which imports a module that links with GPL code make some or all of the library GPL. This question is complicated, in my mind at least, by several factors. Here are some sub-questions: * If a backend module somebackend does import somelib where somelib is a python wrapper of GPL code, is somebackend GPLd? * Assuming the answer to the above question is yes, is matplotlib GPLd if it distributes somebackend? I think this is a nuanced situation because matplotlib would work just fine w/o somemodule, and only uses somemodule's code if it is selected at runtime by the user. Ie, no other part of the code depends on it since it is one of many interchangeable backends. * To further complicate the question, the backend in question is qt, which is dual licensed, commercial and GPL. The qt backend code just needs to 'import qt', and neither the backend writer nor the matplotlib frontend knows whether the deployed qt on the system is commercial or GPLd. To date, the only GPL-like backend is GTK, which is LGPL. Since we're only linking and not using the src, we're protected from the GPL requirements. With QT, which has a pure (non L) GPL variant, the situation is less clear to me. Thoughts, links, etc, appreciated... JDH From David.Holt at mmm.com Wed Jan 5 12:30:52 2005 From: David.Holt at mmm.com (DavidHolt) Date: 5 Jan 2005 09:30:52 -0800 Subject: Python 2.4 on Windows XP Message-ID: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> I have a problem that I see on two different machines, one running XP SP1 and one XP SP 2. On both I installed Python 2.4. I can't seem to start IDLE. When I try to start it, I get an hourglass cursor for a short time then nothing more happens. This happens whether I click the IDLE shortcut or click the pythonw.exe directly, or attempt to launch pythonw from a command line. I don't have any trouble running the python command line version. Any ideas? Thanks, David Holt Software Developer HighJump Software, a 3M Company From klachemin at comcast.net Sun Jan 2 21:49:47 2005 From: klachemin at comcast.net (Kamilche) Date: 2 Jan 2005 18:49:47 -0800 Subject: Calling Function Without Parentheses! In-Reply-To: <1104719332.876804.193020@c13g2000cwb.googlegroups.com> References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> <1104719332.876804.193020@c13g2000cwb.googlegroups.com> Message-ID: <1104720586.976564.307900@c13g2000cwb.googlegroups.com> Yep. Definitely time download PyChecker. Thanks for the tip! From snacktime at gmail.com Sun Jan 23 19:00:48 2005 From: snacktime at gmail.com (snacktime) Date: Sun, 23 Jan 2005 16:00:48 -0800 Subject: Quoting sql queries with the DB-API Message-ID: <1f060c4c050123160027d8145f@mail.gmail.com> I'm used to using the perl DBI and not very familiar with the python DB-API. I am using PyGreSQL. My question is what is the standard way to quote strings in sql queries? I didn't see any quoting functions in the DB-API docs. Is quoting handled internally by the PyGreSQL module? Also, is this a good way to use variables in an insert/update statement, or is there a better way? sql = "insert into test(a,b) values('%s','%s')" % (a,b) cursor.execute(sql) Chris From ncoghlan at iinet.net.au Sat Jan 29 20:59:39 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 30 Jan 2005 11:59:39 +1000 Subject: limited python virtual machine In-Reply-To: <1gr58wn.m3n0xac2j9qbN%aleaxit@yahoo.com> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr58wn.m3n0xac2j9qbN%aleaxit@yahoo.com> Message-ID: <41FC3F8B.9080800@iinet.net.au> Alex Martelli wrote: > It didn't seem to me that Steven's question was so restricted; and since > he thanked me for my answer (which of course is probably inapplicable to > some custom interpreter that's not written yet) it appears to me that my > interpretation of his question was correct, and my answer useful to him. Yes, I'd stopped following the thread for a bit, and the discussion had moved further afield than I realised :) > If you _can_ execute (whatever) in a separate process, then an approach > based on BSD's "jail" or equivalent features of other OS's may be able > to give you all you need, without needing other restrictions to be coded > in the interpreter (or whatever else you run in that process). I think that's where these discussion have historically ended. . . making a Python-specific sandbox gets complicated enough that it ends up making more sense to just use an OS-based sandbox that lets you execute arbitrary binaries relatively safely. The last suggestion I recall along these lines was chroot() plus a monitoring daemon that killed the relevant subprocess if it started consuming too much memory or looked like it had got stuck in an infinite loop. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From stephen.thorne at gmail.com Tue Jan 18 08:52:24 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Tue, 18 Jan 2005 23:52:24 +1000 Subject: generator expressions: performance anomaly? In-Reply-To: <377Hd.77904$Jk5.30235@lakeread01> References: <377Hd.77904$Jk5.30235@lakeread01> Message-ID: <3e8ca5c805011805522032ddf8@mail.gmail.com> On Tue, 18 Jan 2005 07:12:18 -0500, Steve Holden wrote: > Since it doesn't yet optimize 2+5 to a constant-folded 7 you should > realize that you are suggesting a large increase in the compiler's > analytical powers. As in interesting aside to this, you might be interested to know that PHP has constant folding, allowing you to do things like $foo = 7+9; and have it generate bytecode that is "let 'foo' equal 16" or somesuch. PHP achieves this by having a subset of expression parsing available only for situations where a folded constant is allowed. i.e. class Foo { var $bar = 1+4; /* this constant is folded */ } static_scalar: /* compile-time evaluated scalars */ common_scalar | T_STRING | '+' static_scalar | '-' static_scalar | T_ARRAY '(' static_array_pair_list ')' ; common_scalar: /* all numbers, strings-not-containing-variable-interpolation and a few hacks like __FILE__ and __LINE__ */ ; As you can see from the grammar, there are any number of ways this can break. i.e. Parse Error, * isn't allowed: class Foo { var $bar = 60*60*24; } Parse Error, neither is anything except + and -: class Foo { var $bar = 256 & 18; } Parse Error, and definately not variables: $baz = 12; class Foo { var $bar = $baz*2; } I compute 60*60*24 every time around the loop: foreach ($myarray as $value) { $x = 60*60*24*$value; } Thankful, Former PHP Programmer, Stephen Thorne. From bokr at oz.net Sun Jan 9 00:05:03 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 09 Jan 2005 05:05:03 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <41e09808.360402200@news.oz.net> <10u19a32e5affc1@news.supernews.com> Message-ID: <41e0abd1.365467113@news.oz.net> On Sat, 8 Jan 2005 21:29:47 -0600, "John Roth" wrote: > >"Bengt Richter" wrote in message >news:41e09808.360402200 at news.oz.net... >> On Sat, 08 Jan 2005 12:47:52 -0500, Peter Hansen >> wrote: >> >>>Paul Rubin wrote: >>>> When Unix was first written, people thought implementing an OS in C >>>> was ludicrous. Everyone knew OS's had to be written in assembler. >>> >>>Actually, when Unix was first written that belief was entirely >>>correct, and OSes *did* have to be written in assembler. >>> >>>That is, pure C did not have the capability to handle all >>>that was required. I recall it taking a good decade before it >>>became *common* to find C compilers with, for example, @interrupt >>>support to let the compiler generate code that properly saved >>>all registers and used RTI instead of RTS (or whatever it might >>>have been called one one's particular flavour of CPU). >>> >>>Now, once you added a few tiny interrupt handlers, and some context >>>switching (stack manipulation) routines, pretty much everything else >>>*could* be done in C, but that doesn't invalidate the point. >>> >>>I think it's safe to say that none of pure C, pure Lisp, or pure Python >>>are really capable of being used as the *sole* language to build >>>an operating system. >>> >>>It's also safe to say that this is a largely irrelevant point. >>>It would probably only be of academic interest to try to do >>>something like that. Any practical attempt would not think more >>>than twice of resorting to a little "glue" in assembler or in >>>the form of "canned" byte sequences built by hand and stuck >>>into the appropriate places in memory... >> Well, usually there's more than one tool in the chain from source >> to bootable loader and OS image, even if you are writing in C and >> assembler, >> and there's usually more to an OS than the bootable image contains. >> >> So ISTM "writing an OS in " is pretty loose talk ;-) > >Most people who work in the field know what it means, though. Even if they know the whole story intimately, IMO it is not unlikely that they are talking about particular chapters, and it may not be clear whether they are thinking totally radically of rewriting ALL software in the system in Python, visualizing a holy grail of saying goodby to both GNU and M$ and having a purely Python-defined system (which would mean Python tool chains that could prepare binary images (no theoretical problem) for a computer's boot BIOS and on from there, as a tour de force project, or whether they want e.g. to integrate Python front end to gcc (or at one remove via C as is easier), and not reinvent so many wheels. >One of the touchstones of language design is whether you can >write the compiler and runtime in that language. PyPy is working >on that for Python, Squeak Smalltalk is written in Smalltalk and >then converted to C for compilation of the runtime. Both of them This "runtime" is then represented as an executable file that an OS shell you are using will ask its host OS kernel to load and execute as an OS-managed user process, right? Or is it bootable? If so, in what format that what loader understands? >are completely virtualizable: you can run them (very slowly) under >themselves for testing. But what binary is running? The compiled C output of the backend? Interpeting the Python source of itself to spit out the same C that it itself was compiled from? That's cool. And it shows that you can prepare a binary with the help of the C compiler+linker (most likely with gcc libraries) to produce a userland program executable. But I suspect some are thinking that Python source should implement the whole environment it runs in. That's more radical ;-) I would guess a cross development system hosted on a normal PC OS but targeting some limited embedded environment would be where I'd expect to see this kind of thing first. But still going via C tools to the end product most likely, since C is so ubiquitous. > >Given that everything in Python is an object, I see no reason >why one couldn't create a set of objects that are appropriate >for an operating system kernel and can also be converted >cleanly to the operating system subset of C, and write a converter >that does it. OSCTypes? > >That's the easy part. The hard part is writing the operating >system. Look at the (lack of) progress the GNU HURD >project has been making recently. > There are more interesting things to do than reinvent wheels though, even if it is fun doing it in Python ;-) Regards, Bengt Richter From peter at engcorp.com Fri Jan 21 09:16:51 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Jan 2005 09:16:51 -0500 Subject: Funny Python error messages In-Reply-To: <1106315907.551660.276380@c13g2000cwb.googlegroups.com> References: <1106315907.551660.276380@c13g2000cwb.googlegroups.com> Message-ID: Will Stuyvesant wrote: > Perhaps this will even be a useful thread, to brighten the > life of the brave people doing the hard work of providing us > with error messages. > > My first one (i'm learning, i'm learning) is > > TypeError: 'callable-iterator' object is not callable > > # >>> it = iter(lambda:0, 0) > # >>> it() > # TypeError: 'callable-iterator' object is not callable Given that the supposed humour depends on the *name* of the object, which is "callable-iterator", I'd say it's probably not hard to come up with lots of "funny" error messages this way. For example: >>> def a(): ... print is_not ... is_not = 0 ... >>> a() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in a UnboundLocalError: local variable 'is_not' referenced before assignment My funny bone must be broken today, though, because I don't see these as very funny... (Did you understand *why* you got your error? You don't call iterators, you call .next() on them...) -Peter From ed at leafe.com Wed Jan 12 15:45:03 2005 From: ed at leafe.com (Ed Leafe) Date: Wed, 12 Jan 2005 15:45:03 -0500 Subject: py2exe Excludes Message-ID: I'm trying to make a Windows runtime for Dabo, and I want to exclude the framework code itself from the exe file, so that people can update with new releases as they are made. The relevant section of setup.py has: setup( # The first three parameters are not required, if at least a # 'version' is given, then a versioninfo resource is built from # them and added to the executables. version = "0.3.0", description = "Dabo Runtime Engine", name = "daborun", # targets to build console = ["daborun.py"], #exclude the actual framework options = { "py2exe": {"excludes" : ["dabo"]} }, ) Yet the generated library.zip still contains all of the Dabo module code. Why is this? What am I doing wrong? ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From ville at spammers.com Tue Jan 4 08:48:03 2005 From: ville at spammers.com (Ville Vainio) Date: 04 Jan 2005 15:48:03 +0200 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <7xpt0liawq.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "Paul" == Paul Rubin writes: Paul> Ville Vainio writes: >> Also, Python is not a monolithic entity. Guido certainly isn't >> going to write a better IDE for Python, so the time used on >> language features isn't removed from improving the >> infrastructure around the language. Paul> There aren't THAT many people working on Python. Any time Paul> spent on feature X does tend to divert resources from Paul> feature Y. But the people working on wxPython, pygtk, pyqt, pydev, whatever, are largely not the same guys that commit stuff to CPython CVS. Paul> fully deployed. Too much of Python as we know it today is Paul> shaped by the weirdness of CPython. We ought to be able to Paul> get away from that. Type declarations are a feature that might benefit IronPython and Jython more than they would CPython. -- Ville Vainio http://tinyurl.com/2prnb From beliavsky at aol.com Wed Jan 5 09:03:20 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 5 Jan 2005 06:03:20 -0800 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1104933800.156835.91350@f14g2000cwb.googlegroups.com> >is python more popular than coldfusion? >I realsie that is a very general question as one thing does not directly >relate to the other. My issue is that I am ditching coldfusion due to >there being next to no work for it, and I am thinking of taking on >python as a second language to java in the hope of improving my resume. For your specific purpose of learning a language to get a job, I suggest visiting the site http://mshiltonj.com/sm/categories/languages/ , where it appears that Python is mentioned about as often as Fortran or Ada in job listings at dice.com . Apart from Java, two languages in demand are C++ and Visual Basic. C++ may be easier to learn along with Java since the syntax is similar, but VB is a very easy language to learn and use. From bokr at oz.net Sun Jan 23 03:22:36 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 23 Jan 2005 08:22:36 GMT Subject: list unpack trick? References: Message-ID: <41f35e59.1590759250@news.oz.net> On Sun, 23 Jan 2005 15:43:43 +1000, Nick Coghlan wrote: >aurora wrote: >> I am think more in the line of string.ljust(). So if we have a >> list.ljust(length, filler), we can do something like >> >> name, value = s.split('=',1).ljust(2,'') > >Eh? > >Py> s.split('=',1).ljust(2,'') >Traceback (most recent call last): > File "", line 1, in ? >AttributeError: 'list' object has no attribute 'ljust' > Python 2.4b1 (#56, Nov 3 2004, 01:47:27) [GCC 3.2.3 (mingw special 20030504-1)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> help(''.ljust) Help on built-in function ljust: ljust(...) S.ljust(width[, fillchar]) -> string Return S left justified in a string of length width. Padding is done using the specified fill character (default is a space). I should upgrade too ;-) Regards, Bengt Richter From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Tue Jan 11 17:51:59 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?UTF-8?Q?Michel_Claveau_-_abstraction_m=C3=A9t?= =?UTF-8?Q?a-galactique_non_triviale_en_fui?= =?UTF-8?Q?te_perp=C3=A9tuelle.?=) Date: Tue, 11 Jan 2005 23:51:59 +0100 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> Message-ID: <41e458a9$1$7090$8fcfb975@news.wanadoo.fr> Hi ! >>> import math >>> ? = math.pi Good sample ! I like too : e=mc? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rschroev_nospam_ml at fastmail.fm Sun Jan 9 15:49:35 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 09 Jan 2005 20:49:35 GMT Subject: windows mem leak In-Reply-To: References: <41XDd.70234$Jk5.40626@lakeread01> <41E06C18.6050407@hotmail.com> Message-ID: Peter Hansen wrote: > Roel Schroeven wrote: > >>> Peter Hansen wrote: >>> >>>> How have >>>> you proven that it is not *that* program which is at fault?) >> >> >> It would surprise me: even if it consumes much CPU-time, memory and >> other resources, each instances returns all resources when it exits. > > > I agree with that statement, but you assume that the program *is* > exiting. And your initial analysis with "fake_nmap" suggests > that, at least to the extent of having leftover cmd.exe's kicking > around, maybe it is not. I see. The number of cmd.exe's running was not *that* big though: about 5-10 I would say. And their PID's kept changing. I took a look with Process Explorer from sysinternals, which shows the processes as a tree instead of a simple list. Apparently each fake_nmap is a child of a cmd.exe, meaning that os.popen indead uses the shell to run processes. I wouldn't be surprise if cmd.exe would be the culprit here. -- "Codito ergo sum" Roel Schroeven From foo at bar.com Tue Jan 18 21:39:51 2005 From: foo at bar.com (Steve Menard) Date: Tue, 18 Jan 2005 21:39:51 -0500 Subject: Integration with java (Jpype vs. JPE) In-Reply-To: References: <34s5krF4c85d5U1@individual.net> Message-ID: <41EDC877.8000101@bar.com> Istvan Albert wrote: > Steve Menard wrote: > >> To asnwer your question more fully, the jpype-specific cide is only >> for looking up the Classes and startting/stopping the environment. For >> everything else, Java objects and classes are used as regular Python >> objects. > > > Thanks for the response. Currently I don't need to use java but > in the past when I explored such a possibility I looked at jpype > and I was unable to understand from the documentation what it > actually does. > > There is a lot of text there, but it is all concerning catching > errors or other subtleties. For a new visitor the most important > question is about how it works, what does it do, and how can it be > applied for the given problem. > > > everything else, Java objects and classes are used as regular Python > > objects. > > This is too generic. My question was a little more specific, > how would I pass a python list as an argument of a java class/method or > transform a java list into a python one? You don't have to > answer it here, I'm just pointing out the kind of > questions that I was unable to get an answer for on the jpype > website. > > best, > > Istvan. I see what you mean. And I agree fully. I guess that's one more thing to put on the TODO list hehe. Thanks for the input. Steve From carribeiro at gmail.com Thu Jan 6 05:05:47 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 6 Jan 2005 08:05:47 -0200 Subject: Python evolution: Unease In-Reply-To: <1104982313.217034.308760@z14g2000cwz.googlegroups.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> <1104982313.217034.308760@z14g2000cwz.googlegroups.com> Message-ID: <864d3709050106020568bd8b8e@mail.gmail.com> On 5 Jan 2005 19:31:53 -0800, michele.simionato at gmail.com wrote: > John Roth: > > The bottom line is that I'm not going to be writing any > > extensive pieces of Python documentation. My time > > is better spent elsewhere. > > Well, a couple of years ago I realized that some documentation on the > MRO > was missing. I wrote a document in reST, posted here, and Guido put it > on > python.org. It was as easy as it sounds. So I don't see your problem. > > Dave Kulhman wrote some utility to convert reST in latex using the same > style of the standard library docs; I haven't used it myself, but you > may check > with him: http://www.rexx.com/~dkuhlman/ Couldn't a better document-writing interface be implemented? This is the kind of stuff Zope & Plone are used for on a daily basis; not to mention other countless web frameworks & CMS available in Python. Even a simple automated service to process & publish reST or SGML files would be better than requiring aspiring Python doc writers to install the full toolchain, as pointed out. But, whatever it is (and that's a difficult choice, politically speaking), it should be hosted on the main Python site... because that's the place where people look for info first place. > P.S. since you cite descriptors, what's wrong with Raimond Hetting > documentation? > http://users.rcn.com/python/download/Descriptor.htm > > The only problem I see is that it is not integrated with the official > docs, but this is a > minor issue, I think. The docs are great, but it took me some time to find them out after searching inside Python docs. This is not a minor issue IMHO. -- 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 sjmachin at lexicon.net Tue Jan 4 15:40:15 2005 From: sjmachin at lexicon.net (John Machin) Date: 4 Jan 2005 12:40:15 -0800 Subject: why does UserDict.DictMixin use keys instead of __iter__? In-Reply-To: <1RxCd.847728$8_6.18665@attbi_s04> References: <1104836152.639270.196200@z14g2000cwz.googlegroups.com> <1RxCd.847728$8_6.18665@attbi_s04> Message-ID: <1104871215.023027.46040@f14g2000cwb.googlegroups.com> Steven Bethard wrote: > John Machin wrote: > > Steven Bethard wrote: > > > >>So I was looking at the Language Reference's discussion about > >>emulating container types[1], and nowhere in it does it mention that > >> .keys() is part of the container protocol. > > > > I don't see any reference to a "container protocol". > > Sorry, I extrapolated "container protocol" from this statement: > > "Containers usually are sequences (such as lists or tuples) or mappings > (like dictionaries), but can represent other containers as well. The > first set of methods is used either to emulate a sequence or to emulate > a mapping" > > and the fact that there is a "sequence protocol" and a "mapping protocol". > > But all I was really reading from this statement was that the "first set > of methods" (__len__, __getitem__, __setitem__, __delitem__ and > __iter__) were more integral than the second set of methods (keys(), > values(), ...). > > > > What I do see is > > (1) """It is also recommended that mappings provide the methods keys(), > > ...""" > > You skipped the remaining 13 methods in this list: > > "It is also recommended that mappings provide the methods keys(), > values(), items(), has_key(), get(), clear(), setdefault(), iterkeys(), > itervalues(), iteritems(), pop(), popitem(), copy(), and update() > behaving similar to those for Python's standard dictionary objects." > > This is the "second set of methods" I mentioned above. I don't > understand why the creators of UserDict.DictMixin decided that keys(), > from the second list, is more important than __iter__, from the first list. > > > >>Because of this, I would assume that to > >>use UserDict.DictMixin correctly, a class would only need to define > >>__getitem__, __setitem__, __delitem__ and __iter__. > > > > > > So I can't see why would you assume that, given that the docs say in > > effect "you supply get/set/del + keys as the building blocks, the > > DictMixin class will provide the remainder". This message is reinforced > > in the docs for UserDict itself. > > Sorry, my intent was not to say that I didn't know from the docs that > UserDict.DictMixin required keys(). Clearly it's documented. Sorry, the combination of (a) "assume X where not(X) is documented" and (b) posting of tracebacks that demonstrated behaviour that is both expected and documented lead to my making an unwarranted assumption :-) > My > question was *why* does it use keys()? Why use keys() when keys() can > be derived from __iter__, and __iter__ IMHO looks to be a more basic > part of the mapping protocol. Now that I understand your question: Hmmm, good question. __iter__ arrived (2.2) before DictMixin (2.3), so primacy is not the reason. Ease of implementation by the user of DictMixin: probably not, "yield akey" vs "alist.append(akey)" -- not much in it in Python, different story in C, but a C extension wouldn't be using DictMixin anyway. > > > In any case, isn't UserDict past history? Why are you mucking about > > with it? > > UserDict is past history, but DictMixin isn't. OK, I'll rephrase: what is your interest in DictMixin? My interest: I'm into mappings that provide an approximate match capability, and have a few different data structures that I'd like to implement as C types in a unified manner. The plot includes a base type that, similarly to DictMixin, provides all the non-basic methods. From steven.bethard at gmail.com Thu Jan 27 18:26:57 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 16:26:57 -0700 Subject: String Fomat Conversion In-Reply-To: <1106865747.829698.119740@c13g2000cwb.googlegroups.com> References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> <1106865747.829698.119740@c13g2000cwb.googlegroups.com> Message-ID: <57ednS3MJPRs5WTcRVn-gA@comcast.com> enigma wrote: > Do you really need to use the iter function here? As far as I can > tell, a file object is already an iterator. The file object > documentation says that, "[a] file object is its own iterator, for > example iter(f) returns f (unless f is closed)." It doesn't look like > it makes a difference one way or the other, I'm just curious. Nope, you're right -- that's just my obsessive-compulsive disorder kicking in. ;) A lot of objects aren't their own iterators, so I tend to ask for an iterator with iter() when I know I want one. But for files, this definitely isn't necessary: py> file('temp.txt', 'w').write("""\ ... x y ... 1 2 ... 3 4 ... 5 6 ... """) py> f = file('temp.txt') py> f.next() 'x y\n' py> for line in f: ... print [float(f) for f in line.split()] ... [1.0, 2.0] [3.0, 4.0] [5.0, 6.0] And to illustrate Alex Martelli's point that using readline, etc. before using the file as an iterator is fine: py> f = file('temp.txt') py> f.readline() 'x y\n' py> for line in f: ... print [float(f) for f in line.split()] ... [1.0, 2.0] [3.0, 4.0] [5.0, 6.0] But using readline, etc. after using the file as an iterator is *not* fine, generally: py> f = file('temp.txt') py> f.next() 'x y\n' py> f.readline() '' In this case, if my understanding's right, the entire file contents have been read into the iterator buffer, so readline thinks the entire file's been read in and gives you '' to indicate this. Steve From jzgoda at gazeta.usun.pl Fri Jan 14 15:40:08 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 14 Jan 2005 21:40:08 +0100 Subject: python connect to db2 In-Reply-To: References: <1105689253.3167.0.camel@linux.tister.com> Message-ID: yuzx wrote: > >>> conn = DB2.connect(dsn='sample', uid='db2inst1', pwd='ibmdb2') > > but i don't know about dsn, If the database is DB2/400 and you try to connect from iSeries, dsn would be '*local' for local database, or its name (not hostname or IP address!) as returned by dsprdbdire command for remote databases. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From bill.mill at gmail.com Wed Jan 19 15:51:26 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 19 Jan 2005 15:51:26 -0500 Subject: a question In-Reply-To: References: Message-ID: <797fe3d405011912511a609c1c@mail.gmail.com> Nader, You've got a couple problems. First, you need to end the string before putting a continuation in. Secondly, you have 6 variables to be substituted and only provide 4. Here's some code, edited to show how to use continutations to join strings: >>> mosbin, jaar, filetype = (1,1,1) >>> cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s'\ ... '%s' % (mosbin, jaar, filetype, filetype, filetype, filetype) >>> cmd '1/mos user wmarch, cd /fa/wm/1/1, mkdir 1, put 1, chmod 6441' Peace Bill Mill bill.mill at gmail.com On Wed, 19 Jan 2005 16:16:32 +0000, Nader Emami wrote: > L.S., > > I have a long command in Unix and I have to use os.system(cmd) > statement. I do the following: > > cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, chmod 644 > %s' % (mosbin, jaar, filetype, filetype) > status = os.system(cmd) > > This is not very clear, and I have to break this long line in two > segment by means of the next character '\' : > cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, \ > chmod 644 %s' % (mosbin, jaar, filetype, filetype) > > But in this case I get a syntax error! I don't know how I can solve this > problem. Could somebody tell me about this? > > With regards, > Nader > > (this > -- > http://mail.python.org/mailman/listinfo/python-list > From tzot at sil-tec.gr Wed Jan 26 11:53:20 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 26 Jan 2005 18:53:20 +0200 Subject: string.atoi and string.atol broken? [OT] References: <1106700417.482871.45140@z14g2000cwz.googlegroups.com> Message-ID: On Wed, 26 Jan 2005 12:26:59 +0100, rumours say that Peter Otten <__peter__ at web.de> might have written: >> In current Greek hexadecimal is "????????????" ("dekaexadikon"). > >The Latin part escaped me. By Latin I suppose you jokingly mean the Greek parts... :) Just in case it didn't show up correctly in your ng/mail client, it does on groups.google.com (the post was in UTF-8, dammit! --excuse my romance language) message link (long URL): -- 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 lee at example.com Sat Jan 8 09:26:23 2005 From: lee at example.com (Lee Harr) Date: Sat, 08 Jan 2005 14:26:23 GMT Subject: Python/Qt Problem References: Message-ID: On 2005-01-08, Michael wrote: > Hi, > > I am experiencing something very weird with PyQt. I have created several > windows based on QWidget using Designer. I can easily hide and show > these with the hide and show methods. However I have just created a new > window with Designer and the show method works in my main script but not > inside the button action method (not using proper temrinology, sorry) of > another window. Why is that? This works fine for the other windows. > If you do not get a satisfactory answer here, you should try the dedicated PyQt mailing list: http://mats.imk.fraunhofer.de/mailman/listinfo/pykde The other thing I would suggest is to post some code along with your description of what you believe it should do. I do not think anyone will be able to diagnose the problem without seeing the code. From fuzzyman at gmail.com Mon Jan 24 10:34:40 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Jan 2005 07:34:40 -0800 Subject: urllib2 and proxy question In-Reply-To: References: <1106575675.520424.155310@f14g2000cwb.googlegroups.com> Message-ID: <1106580880.119328.240890@c13g2000cwb.googlegroups.com> rbt wrote: > Fuzzyman wrote: > > urllib2 (under windows) will auto-detect your proxy settings and use > > those. > > > > Normally that's a good thing (I guess), except when it's not ! > > > > How do I switch off this behaviour ? I'm behind a censoring proxy and > > wanting to test things *locally*. IE is set to not use the proxy when > > fetching local adresses, but urllib2 ignores that part of the setting > > and uses the proxy for everything. > > > > The only way I can test are changing my IE settings back and forth > > every time. Most annoying. > > > > I can see how to *add* a new proxy to urllib2, but not how to force it > > to not use a proxy. I may well be missing something obvious though. > > Anyone able to help ? > > Regards, > > > > Fuzzy > > http://www.voidspace.org.uk/python/index.shtml > > > > "Alternatively, the optional proxies argument may be used to explicitly > specify proxies. > It must be a dictionary mapping scheme names to proxy URLs, where an > empty dictionary causes no proxies to be used" > > # Don't use any proxies > filehandle = urllib.urlopen(some_url, proxies={}) Wikkid... I'll try that. Nice one, thanks for your help. It *still* means I have to have a different version for testing locally - but it's better than the alternative. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From sjmachin at lexicon.net Sat Jan 8 21:25:56 2005 From: sjmachin at lexicon.net (John Machin) Date: 8 Jan 2005 18:25:56 -0800 Subject: Speed revisited References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> Message-ID: <1105237556.402188.126980@c13g2000cwb.googlegroups.com> Bulba! wrote: > On 4 Jan 2005 14:33:34 -0800, "John Machin" > wrote: > > >(b) Fast forwarding 30+ years, let's look at the dictionary method, > >assuming you have enough memory to hold all your data at once: > > > >Step 1: read the "left" table; for each row, if english not in mydict, > >then do mydict[english] = MyObject(). In any case, do > >mydict[english].left_list.append(row) > >Step 2: same for the "right" table. > >Step 3: for english, obj in mydict.iteritems(): process(english, obj) > > >As your datasets are stored in MS Excel spreadsheets, N < 64K so > >whether your solution is O(N) or O(N*log(N)) doesn't matter too much. > >You are however correct to avoid O(N**2) solutions. > > Following advice of two posters here (thanks) I have written two > versions of the same program, and both of them work, but the > difference in speed is drastic, about 6 seconds vs 190 seconds > for about 15000 of processed records, taken from 2 lists of > dictionaries. > > I've read "Python Performance Tips" at > > http://manatee.mojam.com/~skip/python/fastpython.html > > ..but still don't understand why the difference is so big. > > Both versions use local variables, etc. Both have their > lists initially sorted. Both essentially use a loop with > conditional for comparison, > then process the record in the > same way. "process the record in the same way"??? That's an interesting use of "same". > The overhead of second version is that it also > uses cmp() function and two additional integer > variables - that should not slow the program _so much_. > > I have measured the run of snippet 2 with time checkpoints > written to a log (write time delta to log every 200 records), > even made a graph of time deltas in spreadsheet and in fact > snippet 2 seems after initial slowdown looks exactly linear, > like that: > > ^ (time) > | > | /----------- > | / > |/ > ---------------> (# of records written) > > So yes, it would scale to big files. On your empirical evidence, as presented. However, do read on ... >However, why is it so > frigging slow?! Mainly, because you are (unnecessarily) deleting the first item of a list. This requires copying the remaining items. It is O(N), not O(1). You are doing this O(N) times, so the overall result is O(N**2). Your graph has no obvious explanation; after how many cycles does the speed become constant? Secondly, you are calling cmp() up to THREE times when once is enough. Didn't it occur to you that your last elif needed an else to finish it off, and the only possible action for the else suite was "assert False"? It would appear after reading your "snippet 2" a couple of times that you are trying to implement the old 3-tape update method. It would also appear that you are assuming/hoping that there are never more than one instance of a phrase in either list. You need something a little more like the following. Note that in your snippet2 it was not very obvious what you want to do in the case where a phrase is in "new" but not in "old", and vice versa -- under one circumstance (you haven't met "end of file") you do nothing but in the the other circumstance you do something but seem to have not only a polarity problem but also a copy-paste-edit problem. In the following code I have abstracted the real requirements as handle_XXX_unmatched() !o = n = 0 !lenold = len(oldl) !lennew = len(newl) !while o < lenold and n < lennew: ! cmp_result = cmp(oldl[o]['English'], newl[n]['English']) ! if cmp_result == 0: ! # Eng phrase is in both "new" and "old" ! cm.writerow(matchpol(oldl[o], newl[n])) ! o += 1 ! n += 1 ! elif cmp_result < 0: ! # Eng phrase is in "old", not in "new" ! handle_old_unmatched(o) ! o += 1 ! else: ! assert cmp_result > 0 # :-) ! # Eng phrase is in "new", not in "old" ! handle_new_unmatched(n) ! n += 1 !while o < lenold: ! # EOF on new, some old remain ! handle_old_unmatched(o) ! o += 1 !while n < lennew: ! # EOF on old, some new remain ! handle_new_unmatched(n) ! n += 1 Some general hints: Try stating your requirements clearly, to yourself first and then to us. Try to ensure that your code is meeting those requirements before you bother timing it. Try not to use single-letter names -- in particularly using l (that's "L".lower(), not 1 i.e. str(4-3)) is barf-inducing and makes people likely not to want to read your code. HTH, John From paschott at no.worldnet.spamm.att.net Tue Jan 11 18:47:55 2005 From: paschott at no.worldnet.spamm.att.net (Peter A. Schott) Date: Tue, 11 Jan 2005 23:47:55 GMT Subject: Best way to trap errors in ftplib? Message-ID: <45p8u0t9cq0k6ar17s1udt0h3tj70ajhsa@4ax.com> Using ftplib.FTP object for a project we have here to upload/download files. I know that I can wrap everything in try/except blocks, but I'm having trouble getting the exact error messages out of the Exceptions. I'd like to either send an e-mail or log the failure to a database. It would also be nice to see what the message is and perhaps add some additional logic for delay/retry or something similar. Has anyone done any of the above? Willing to share some samples? Here's a little of my code - maybe you can see what I'm doing/not doing. def myuploadbinaryfunction(args here): objFTP = ftplib.FTP(HostName, UserName, Password) objFTP.cwd(RemotePath) try: objFTP.storbinary("STOR " + RemoteFile, file(os.path.join(LocalPath, LocalFile), "rb")) SQLLogging.LogFTP(LocalFile, Company, 1) except Exception, errObj: SQLLogging.LogFTP(LocalFile, Company, 0) reportError("Failed to upload " + LocalFile, str(errObj)) print Exception print errObj In the above, reportError will send an e-mail to alert. I realize that the errObj in this case may not have the ability to convert to string, but am not sure how to get the output otherwise. Not sure how to handle a retry of a failure, either. Thank you for your help! -Peter Schott From assafs at ixi.com Mon Jan 24 09:25:18 2005 From: assafs at ixi.com (assaf) Date: 24 Jan 2005 06:25:18 -0800 Subject: TCP server Message-ID: <1106576718.263709.280380@c13g2000cwb.googlegroups.com> i am try to create a server what am i suppose to send to SocketServer.TCPServer what is the client_address ("127.0.0.1:80" ?) and BaseRequestHandler = ? thanks From irmen at -nospam-remove-this-xs4all.nl Sat Jan 8 20:22:33 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 09 Jan 2005 02:22:33 +0100 Subject: Windows XP Installation In-Reply-To: References: Message-ID: <41e08757$0$6204$e4fe514c@news.xs4all.nl> Smitsky wrote: > Hi. I am a newbie to Python. I am running Win XP and want to know what the > best course is for installing Python on my system. Could someone kindly > direct me to some related resources? Thanks in advance, Steve The Python beginners guide contains a lot of information for you: http://www.python.org/moin/BeginnersGuide There's some info on downloading and installing Python too. Good luck and have fun with Python! --Irmen From pushlinque at hotmail.com Wed Jan 12 10:15:34 2005 From: pushlinque at hotmail.com (Jane) Date: Wed, 12 Jan 2005 10:15:34 -0500 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: wrote in message news:1105495569.479185.166340 at z14g2000cwz.googlegroups.com... > python.org = 194.109.137.226 > > 194 + 109 + 137 + 226 = 666 > > What is this website with such a demonic name and IP address? What > evils are the programmers who use this language up to? > Some people have too much time on their hands... Jane From daniel at bowettsolutions.com Tue Jan 25 15:43:54 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Tue, 25 Jan 2005 20:43:54 +0000 Subject: MySQLdb Message-ID: <41F6AF8A.3040102@bowettsolutions.com> I have just started playing around with MySQLdb for a project I am planning. As a test I have written a script that executes 3000 insert statements on a table. The table contains 10 fields with a mix of text and numbers - its a product table for a website eg UPC, ProductName, Price etc. The problem I have is that it takes just over two minuted to execute the 3000 insert statements which seems really slow! I am running it on a machine with a 1.5 Ghz Pentium M Processor and Gig Of Ram. I dont think the machine is to blame for the speed because during execution the processor sits at about 10% and there is loads of free RAM. Does anyone know if this sort of speed sounds right? Cheers, Dan. From drs at remove-to-send-mail-ecpsoftware.com Wed Jan 12 15:21:37 2005 From: drs at remove-to-send-mail-ecpsoftware.com (drs) Date: Wed, 12 Jan 2005 20:21:37 GMT Subject: encryption/decryption help Message-ID: Hi, I need to send secure data over an insecure network. To that end, I am needing to encrypt serialized data and then decrypt it. Is there a builtin way to do this in Python? MD5, SHA, etc encrypt, but I am not seeing a way to get back my data. Encryption is totally new to me, so any pointers of what to read up on would be appreciated. As a side note, I understand that I could use https, but this would involve changing things that I may not be at liberty to change -- though if this turns out to be the best solution, then I'll find a way to use it. Thanks From tdickenson at geminidataloggers.com Tue Jan 25 07:57:39 2005 From: tdickenson at geminidataloggers.com (Toby Dickenson) Date: Tue, 25 Jan 2005 12:57:39 +0000 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) In-Reply-To: References: Message-ID: <200501251257.39751.tdickenson@geminidataloggers.com> On Tuesday 25 January 2005 12:40, Richie Hindle wrote: > > [Steven] > > Can someone give me an example of where __-mangling really solved a problem > > for them, where a simple leading underscore wouldn't have solved the > > same problem? > > http://cvs.sourceforge.net/viewcvs.py/spambayes/spambayes/spambayes/Dibbler.py?r1=1.13&r2=1.13.4.1 > > That's a bugfix to SpamBayes, where I'd inadvertently named an instance > variable '_map' without realising that the base class > (asynchat.async_chat) also had an instance variable of that name. Using > double underscores fixed it, and had I used them from the beginning the > bug would never have cropped up (even if asynchat.async_chat had an > instance variable named '__map', which is the whole point (which you know, > Steven, but others might not)). I have a counterexample. Consider refactoring a class from.... class B(A): etc ....into.... class C(A): etc class B(C): etc Usage of some double-undescore attributes moved from B to the new intermediate base class C. Unit tests on B still passed, so that change is safe. right? The problem occured because the double-underscore mangling uses the class name, but ignores module names. A related project already had a class named C derived from B (same name - different module). My refactoring caused aliasing of some originally distinct double-underscore attributes. -- Toby Dickenson ____________________ Important Notice: This email and any attachments are confidential and may contain trade secrets or be legally privileged. If you have received this email in error you must not use, rely upon, disclose, copy or distribute the contents. Please reply to the sender so that proper delivery can be arranged and delete the email from your computer. Gemini Data Loggers monitor incoming and outgoing email to ensure satisfactory customer service, maintain company security and prevent abuse of their email system. However, any views expressed in this email are not necessarily those of Gemini and Gemini cannot be held responsible for the content. Gemini makes best efforts to ensure emails are virus free; however you are advised to carry out your own checks. Gemini does not accept responsibility for any damage resulting from email viruses. ____________________ From max at alcyone.com Fri Jan 7 23:31:56 2005 From: max at alcyone.com (Erik Max Francis) Date: Fri, 07 Jan 2005 20:31:56 -0800 Subject: "A Fundamental Turn Toward Concurrency in Software" In-Reply-To: References: Message-ID: aurora wrote: > Just gone though an article via Slashdot titled "The Free Lunch Is Over: A > Fundamental Turn Toward Concurrency in Software" > [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that the > continous CPU performance gain we've seen is finally over. And that future > gain would primary be in the area of software concurrency taking advantage > hyperthreading and multicore architectures. Well, I think it's reasonable to expect that _eventually_ (whether soon or relatively soon or not for a long time) Moore's law will fail, and the exponential increase in computing power over time will cease to continue. At that point, it seems reasonable to assume you'll do your best to take advantage of this with parallelization -- if your CPU won't get faster, just put more and more in the box. So I've always had it in the back of my mind that languages that can easily support massive (especially automatic) parallelization will have their day in the sun, at least someday. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis All the people in my neighborhood turn around and get mad and sing -- Public Enemy From aleaxit at yahoo.com Sun Jan 30 03:22:07 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 30 Jan 2005 09:22:07 +0100 Subject: limited python virtual machine References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr58wn.m3n0xac2j9qbN%aleaxit@yahoo.com> Message-ID: <1gr72vj.1mp35qg1ftc49dN%aleaxit@yahoo.com> Nick Coghlan wrote: ... > > If you _can_ execute (whatever) in a separate process, then an approach > > based on BSD's "jail" or equivalent features of other OS's may be able > > to give you all you need, without needing other restrictions to be coded > > in the interpreter (or whatever else you run in that process). > > I think that's where these discussion have historically ended. . . making a > Python-specific sandbox gets complicated enough that it ends up making more > sense to just use an OS-based sandbox that lets you execute arbitrary binaries > relatively safely. > > The last suggestion I recall along these lines was chroot() plus a monitoring > daemon that killed the relevant subprocess if it started consuming too much > memory or looked like it had got stuck in an infinite loop. "Yes, but" -- that ``if'' at the start of this quote paragraph of mine is, I believe, a meaningful qualification. It is not obvious to me that all applications and platforms can usefully execute untrusted Python code in a separate jail'd process; so, I think there would still be use cases for an in-process sandbox, although it's surely true that making one would not be trivial. Alex From xah at xahlee.org Thu Jan 13 05:18:26 2005 From: xah at xahlee.org (Xah Lee) Date: 13 Jan 2005 02:18:26 -0800 Subject: [perl-python] 20050112 while statement Message-ID: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> # here's a while statement in python. a,b = 0,1 while b < 20: print b a,b = b,a+b --------------- # here's the same code in perl ($a,$b)=(0,1); while ($b<20) { print $b, "\n"; ($a,$b)= ($b, $a+$b); } Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From wittempj at hotmail.com Mon Jan 31 03:58:42 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 31 Jan 2005 00:58:42 -0800 Subject: Nested scopes and class variables In-Reply-To: References: Message-ID: <1107161922.285810.8510@f14g2000cwb.googlegroups.com> To me it seems you should do it something like this: -def f(x): - class C(object): - def __init__(self, x): - self.x = x # here you set the attribute for class C - c = C(x) # instantiate a C object - print c.x -f(5) From francis.girard at free.fr Thu Jan 27 16:19:41 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 27 Jan 2005 22:19:41 +0100 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <200501272219.42090.francis.girard@free.fr> Le jeudi 27 Janvier 2005 22:07, Steven Bethard a ?crit?: > Francis Girard wrote: > > Le jeudi 27 Janvier 2005 21:29, Steven Bethard a ?crit : > >>So None being smaller than anything (except itself) is hard-coded into > >>Python's compare routine. My suspicion is that even if/when objects of > >>different types are no longer comparable by default (as has been > >>suggested for Python 3.0), None will still compare as smaller than > >>anything... > > > > Well, here's python doesn't seem to confirm what you're saying : > >>>>a = "10" > >>>>b = 10 > >>>>a > b > > > > True > > > >>>>b > a > > > > False > > > >>>>id(a) > > > > 1077467584 > > > >>>>id(b) > > > > 134536516 > > Actually, this code doesn't contradict what I said at all. I said that > None (and only None) was special-cased. > You're right. I just posted too soon. Sorry. > > It really looks like the addresses are compared when objects are of > > different types if there is no __cmp__ or __lt__ user made specification > > to compare objects of different types. > > Use the source Luke! ;) Download it from CVS and take a look. The end > of default_3way_compare: > Just want to know the specifications. No matter how it had been implemented. > static int > default_3way_compare(PyObject *v, PyObject *w) > { > ... > /* None is smaller than anything */ > if (v == Py_None) > return -1; > if (w == Py_None) > return 1; > > /* different type: compare type names; numbers are smaller */ > if (PyNumber_Check(v)) > vname = ""; > else > vname = v->ob_type->tp_name; > if (PyNumber_Check(w)) > wname = ""; > else > wname = w->ob_type->tp_name; > c = strcmp(vname, wname); > if (c < 0) > return -1; > if (c > 0) > return 1; > /* Same type name, or (more likely) incomparable numeric types */ > return ((Py_uintptr_t)(v->ob_type) < ( > Py_uintptr_t)(w->ob_type)) ? -1 : 1; > } > > So it looks like Python uses the type name. Testing this: > > py> A = type('A', (object,), {}) > py> Z = type('Z', (object,), {}) > py> lst = [str('a'), dict(b=2), tuple(), Z(), A()] > py> [type(o).__name__ for o in lst] > ['str', 'dict', 'tuple', 'Z', 'A'] > py> sorted(type(o).__name__ for o in lst) > ['A', 'Z', 'dict', 'str', 'tuple'] > py> sorted(lst) > [<__main__.A object at 0x011E29D0>, <__main__.Z object at 0x011E29F0>, > {'b': 2}, 'a', ()] > > Yup. Looks about right. (Note that the source code also special-cases > numbers...) > > So, the order is consistent, but arbitrary, just as Fredrik Lundh > pointed out in the documentation. > Ok. Thank you, Francis Girard > Steve From jeff at ccvcorp.com Tue Jan 25 14:46:04 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 25 Jan 2005 11:46:04 -0800 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <41f6162f.1768893674@news.oz.net> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> <41f6162f.1768893674@news.oz.net> Message-ID: <10vd84er6bjr2ad@corp.supernews.com> Bengt Richter wrote: > On 25 Jan 2005 08:30:03 GMT, Nick Craig-Wood wrote: > >>If you are after readability, you might prefer this... >> >>def hamming(): >> def _hamming(): >> yield 1 >> for n in imerge(imap(lambda h: 2*h, iter(hamming2)), >> imerge(imap(lambda h: 3*h, iter(hamming3)), >> imap(lambda h: 5*h, iter(hamming5)))): >> yield n >> hamming2, hamming3, hamming5, result = tee(_hamming(), 4) >> return result > > Are the long words really that helpful? > > def hamming(): > def _hamming(): > yield 1 > for n in imerge(imap(lambda h: 2*h, iter(hg2)), > imerge(imap(lambda h: 3*h, iter(hg3)), > imap(lambda h: 5*h, iter(hg5)))): > yield n > hg2, hg3, hg5, result = tee(_hamming(), 4) # four hamming generators > return result Well, judging by the fact that shortening the identifiers made it so that you felt the need to add a comment indicating what they were identifying, I'd say that yes, the long words *are* helpful. ;) Comments are good, but self-documenting code is even better. Jeff Shannon Technician/Programmer Credit International From chris.cavalaria at free.fr Mon Jan 3 17:07:40 2005 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Mon, 03 Jan 2005 23:07:40 +0100 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <41d9c22c$0$31927$626a14ce@news.free.fr> eeykay at gmail.com wrote: > Hello All, > I am trying to convince my client to use Python in his new product. He > is worried about the license issues. Can somebody there to point me any > good commercial applications developed using python ?. The licence > clearly says Python can be used for commercial applications. Is there > any other implications like that of GPL to make the source open ? > Thanks for any help. > eeykay Troika games use Python in their games. It seems you can even get the source .py files for Vampires: Bloodlines :) From adam at cognitcorp.com Tue Jan 4 22:38:14 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Tue, 04 Jan 2005 22:38:14 -0500 Subject: what is lambda used for in real code? In-Reply-To: References: Message-ID: <1104894385.5050.31.camel@localhost.localdomain> On Sat, 2005-01-01 at 11:42, Steve Holden wrote: > Adam DePrince wrote: > [...] > > > > In sort, we must preserve the ability to create an anonymous function > > simply because we can do so for every other object type, and functions > > are not special enough to permit this special case. > > > And you'd create an anonymous type how, exactly? > Okay, you got me. Let me rephrase: ... functions, types, classes and moduless are not special enough ... I had things like, um, strings, lists, integers, etc in mind. - adam > 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 Adam DePrince From pdemb at illx.org Sun Jan 2 06:46:40 2005 From: pdemb at illx.org (Peter Dembinski) Date: Sun, 02 Jan 2005 12:46:40 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <41d6ee45$1_2@127.0.0.1> Message-ID: <87sm5kaw9r.fsf@hector.domek> "Donn Cave" writes: [...] > For me, the effect is striking. I pound out a little program, > couple hundred lines maybe, and think "hm, guess that's it" and save > it to disk. Run the compiler, it says "no, that's not it - look > at line 49, where this expression has type string but context > requires list string." OK, fix that, iterate. I believe program-specific unit tests are more effective than compiler typechecking :) From "root\" at (none) Fri Jan 14 00:36:58 2005 From: "root\" at (none) (none) Date: Fri, 14 Jan 2005 13:36:58 +0800 Subject: Interesting gDeskCal Message-ID: <41e75a60$1_3@rain.i-cable.com> I found that gDeskCal is also written in Python. So if I have a theme used by gDesklets, how can I make the whole thing standalone so that it can be similar to the case of gDeskCal?? From craig at postnewspapers.com.au Sat Jan 1 13:00:48 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sun, 02 Jan 2005 02:00:48 +0800 Subject: exposing C array to python namespace: NumPy and array module. In-Reply-To: <41D6CF86.1040902@rice.edu> References: <41D6CF86.1040902@rice.edu> Message-ID: <1104602448.9326.5.camel@albert.localnet> On Sat, 2005-01-01 at 10:27 -0600, Bo Peng wrote: > Sorry if I was not clear enough. I was talking about the differece > between python array module > (http://docs.python.org/lib/module-array.html, Modules/arraymodule.c in > the source tree) and NumPy array. They both use C-style memory block > arrangement for efficient memory access. While NumPy has both, the array > module is designed to be used purely in Python so there is no header > file and no function to build an array from a pointer. Thanks for clarifying that - I had misunderstood your reference to arraymodule.c . I guess the core language doesn't have an array type, but as there's a standard lib module that does (I'd forgotten it was there), it hardly matters. It would seem sensible to extend that module with a C API for mapping an existing array. That would be a rather handy thing to have in the standard library. > One of the methods you suggested (creating a new type) already > implemented in arraymodule.c. I am not sure if it is appropriate to add > the file into my project and add a 'CreateFromLenAndBuf' function. That sounds like a reasonable approach to me, but I'm hardly an expert. The code's license permits you to do so, and it's hardly worth repeating the work if you don't have to. -- Craig Ringer From steve at holdenweb.com Mon Jan 31 09:51:14 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 09:51:14 -0500 Subject: re module - cannot make expression In-Reply-To: References: Message-ID: Laszlo Zsolt Nagy wrote: > Hi All! > > I would like to match strings not beginning with '/webalizer'. How can I > do this? > The only one negation command is ^ inside [] but it cannot be used here. > I looked > over "re" examples on the net but I could not find an example about how > to match > "not beginning with" type expressions. > > Thanks, > > Laci 2.0 > You can do taht with Python re's. Look in the re documentation for "negative lookahead assertion". 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 jepler at unpythonic.net Mon Jan 3 21:04:38 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 3 Jan 2005 20:04:38 -0600 Subject: Controlling newlines when writing to stdout (no \r\n). In-Reply-To: References: Message-ID: <20050104020437.GA11833@unpythonic.net> Well, here's the first page turned up by google for the terms 'python binary stdout': http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65443 Code from that page: import sys if sys.platform == "win32": import os, msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) Thanks, Google & the Python Cookbook website! 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 Fri Jan 14 11:53:29 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 11:53:29 -0500 Subject: newbie q In-Reply-To: <41e7098e.782680124@news.oz.net> References: <34mgq0F4dq4buU1@individual.net> <34mku4F4c8bdkU1@individual.net> <41e7098e.782680124@news.oz.net> Message-ID: <41E7F909.9020307@holdenweb.com> Bengt Richter wrote: > On Thu, 13 Jan 2005 09:16:40 -0500, Steve Holden wrote: > [...] > >>Any statement of the form >> >> for i in [x for x in something]: >> >>can be rewritten as >> >> for i in something: >> >>Note that this doesn't mean you never want to iterate over a list >>comprehension. It's the easiest way, for example, to iterate over the >>first item of each list in a list of lists: >> >> for i in [x[0] for x in something]: >> > > As I'm sure you know, with 2.4's generator expressions you > don't have to build the temporary list. > Which could be important if 'something' > is (or generates) a huge sequence. > > for i in (x[0] for x in something): > Yes. While I haven't yet done any more than play with generator sequences I do really feel that more of "the best of Icon" has arrived in Python with this new addition. > >>> something = ([x] for x in xrange(10,20)) > >>> something > > >>> list(something) > [[10], [11], [12], [13], [14], [15], [16], [17], [18], [19]] > >>> for i in (x[0] for x in something): print i, > ... > > oops, that list() used it up ;-) > > >>> something = [[x] for x in xrange(10,20)] > >>> for i in (x[0] for x in something): print i, > ... > 10 11 12 13 14 15 16 17 18 19 > > Really nice. > I quite agree. It's particularly useful for infinite sequences :-) 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 annaraven at gmail.com Sun Jan 9 11:49:51 2005 From: annaraven at gmail.com (Anna) Date: 9 Jan 2005 08:49:51 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Message-ID: <1105289391.534192.74060@c13g2000cwb.googlegroups.com> Jacek Generowicz wrote: > "Anna" writes: > > > Having taken some calculus (derivatives, limits, some integrals) but > > never even heard of lambda calculus, to me, lambda means absolutely > > NOTHING. Less than nothing. > > And before you took calculus, the chances are that derivatives, limits > and integrals meant less than nothing to you. > > But now, I am quite sure, you know that in Python lambda is a keyword > which creates anonymous functions. Now that you know what lambda does, > what's the problem with it? (It certainly doesn't mean "Less than > nothing" to you now.) > > > So, I guess I don't like the word itself > > Fair enough. I guess there are people out there who might have a > distaste for the word "class" or "def" or any of the other words which > are keywords in Python. > > > Every other word in Python has an obvious meaning. lambda doesn't. > > Obvious to whom? > > The meaning of every word is obvious, once you have been taught it; > and a complete mystery if you have not. > > What do you make of "seq[2:-2]"? It means "less than nothing" to the > uninitiated. Just like lambda. Actually - whether or not I understood the [2:-2] notation, knowing nothing else, the "seq" would clue me in that we're probably doing something with sequences... Personally, I like lambdas less than regular expressions (of which I'm particularly UNfond but understand their usefulness at times). At least with regular expressions - I know that the gibberish I need to decipher (probably) has to do with text parsing... With class and def, I at least have a *name* to start with - class Square pretty obviously is going to have something to do with geometric shapes, I would hope (or maybe with boring people...). def getfoo() tells me I'm the function is likely to go elsewhere and get something. It's a *start*, a handle, to deciphering whatever the following statements are doing. (Yes, I realize that often class and function names suck - but more often than not, they give *some* clue). Whereas, with lambda - I have *nothing* to go on. With lambdas, all I know is that the programmer wanted to hide whatever it is the program is doing behind the curtain... (at least that's the way it comes across). So, not only is the word itself not descriptive of anything to me - even knowing that it means "anonymous function" - the use of it precludes descriptiveness, as compared to defining a function. IMHO, YMMV, etc etc Anna From maxm at mxm.dk Sat Jan 8 11:32:34 2005 From: maxm at mxm.dk (Max M) Date: Sat, 08 Jan 2005 17:32:34 +0100 Subject: Another look at language comparisons In-Reply-To: References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> <1105188426.955508.263030@c13g2000cwb.googlegroups.com> Message-ID: <41e00ac1$0$265$edfadb0f@dread12.news.tele.dk> Jan Dries wrote: > beliavsky at aol.com wrote: > And there is hope for Python, as Guido has recently been seen with a > beard :-) > http://www.tbray.org/ongoing/When/200x/2004/12/08/-big/IMG_3061.jpg LOL, he is working on linux, isn't he? So it was about bloody time. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From dishking at mwqrvdua.com Fri Jan 7 04:55:40 2005 From: dishking at mwqrvdua.com (me to you) Date: Fri, 7 Jan 2005 01:55:40 -0800 Subject: Here is $50 for signing up free Message-ID: Hello, I'm trying out a new auto poster, and dont know how to use it very good, so if this end up in the wrong places, please forgive me, and disreguard, sorry for your incovenience, but everyone else, ENJOY!! KEEP READING TO GET YOUR $50.00 NOW!!! This is not spam, it is a legitament way to make money on the net, reading e-mail, and other things as well, plus you get $50.00 dollars for signing up. This is tottaly free, and requires no credit card on out of pocket money. You will get paid for various things on the net, hope you enjoy and find some usefull info here that will help you out. Plus you will get fifty dollars. this is not spam, its usefull news for all newsgroups readers, from me to you, hope you can use it for your benifit, please enjoy. If your not sure, get a new email address, and then try, you wont get spammed, and all info is carefully guarded, and not given out or traded or sold. Enjoy your $50.00, I did, so did my friends and family. You'll also be able to do survays if you want, P.S. forgive my spelling. Just copy and paste into your browser, thanks again. URL: http://www.CashRead.com/cgi-bin/signup.cgi?r=fogylight at yahoo.com Dont be mean and hatefull, if you dont want to Participate, DON'T. If you don't want $50.00, let someone else have it. From klachemin at comcast.net Tue Jan 25 02:06:58 2005 From: klachemin at comcast.net (Kamilche) Date: 24 Jan 2005 23:06:58 -0800 Subject: Open Folder in Desktop Message-ID: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> Is there a command you can execute in Python that will open a window on the desktop, such as 'My Documents'? Kind of like 'system', but for folder names, not just programs. I'm running on Windows 2000. From steve at holdenweb.com Thu Jan 6 22:34:03 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 22:34:03 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> <41DD4E62.1020404@holdenweb.com> Message-ID: Bulba! wrote: > On Thu, 06 Jan 2005 09:42:42 -0500, Steve Holden > wrote: > >>>You see, I'm not disagreeing with you that your model applies >>>_where it applies_. I only disagree that it applies in face of >>>stronger forces. Now what kind of forces is dominant in >>>most frequent scenarios would have to be worked out in tedious >>>empirical research I think. Which I haven't done, because >>>learning some economics is just a hobby to me. > > >>Yes, by all means let's just spout our opinions without any of that >>inconvenient tedious empirical research which might invalidate them. > > > Err, but what did I do that got you visibly pissed off? > > I certainly did not mean offending anyone. If I did smth > that did, I apologize, but honestly I didn't mean that. I > just expressed my opinion and cited some small bits of evidence, > which I think I'm entitled to. > I am probably not as pissed off as you might think, but I'm beginning to find (what I regard as) your naivety a little irritating. However, nothing I have said was intended to question your integrity. > [...] > >>>Oh, and by the way that installation doesn't get used much. >>>Somebody at the office didn't check carefully enough the >>>energy prices before ordering it and later someone discovered >>>that off-site specialized cutting firms that take advantage of >>>energy available at low prices at special times in other countries >>>can get it produced cheaper. Moving it elsewhere or selling >>>is not an option, since it is a specially constructed, low, 50-meters >>>long hall that stands inside the huge manufacturing hall of the >>>company. > > >>And you are using this example to try and argue that engineers are >>better-educated than sales people? > > > Nope. The context was that behavior of companies tends to > be highly rational, optimized and not wasting resources. My > naturally individual experience was that it was oft not the case, > and that was the example. > Well, anyone who *does* believe that companies are managed in a way that's any more rational than the way individual humans manage their own lives is deluding themselves. But perhaps I'm a little clearer now about *your* thinking on this. > Which was my point when explaining the clustering that > demonstrably happened: if the behavior of decisionmakers > is highly informed, rational and not really induced much by > risk avoidance as Alex claims, then the clusters are created > by "natural economic forces". > The agent of economic forces, however, are always individual humans. It just isn't possible to factor them out. > However, if the process is not that rational, then maybe > clusters are the correlation of "cover your ass" aspect > in managers' behavior all wanting to get their branch office > in yesterday in Tokyo, today in Beijing, and during > speculative craze in Russia in Moscow "because everybody > is doing that". Which observations of Paul Krugman on > "defective investors" seem to support. > > Now, I'm very strongly opposed to saying that all that > somehow invalidates economics, including economics > of software, as _science_. > > All I'm saying is that maybe this particular model is not > what some people think it is. This is the problem with > economics, people tend to get hot under the collar about > it for some reason and it's oft hard to debate that calmly. > Which personally I find a pity, because e.g. economics > of software is such an interesting subject.. > I can live with that, I guess. > >>Who sold this installation? Who >>bought it? > > > I have no idea, as I were not a manager there and it > didn't really pertain my work. > I was merely trying to point out that the sales people may well have worked a flanker on the "better educated" engineers who might have bought the plant. > >>>I was utterly shocked. Having grown up in Soviet times I have >>>been used to seeing precious resources wasted by organizations >>>as if resources were growing on trees, but smth like this?! In a >>>shining ideal country of Germany?! Unthinkable. > > > >>Indeed not. Quite often the brown paper bag is a factor in purchases >>like this. I wouldn't be at all surprised if somebody with a major input >>to the decision-making process retired to a nice place in the country >>shortly afterwards. You appear to be making the mistake of believing >>that people will act in the larger interest, when sadly most individuals >>tend to put their own interests first (some would go as far as to define >>self-interest as the determinant of behavior). > > > But there is a subtler point here: most likely it was NOT in the > short-term personal interest to make this mistake (as I believe > corruption was not the case in this decision)! > > After all, whoever responsible was still running the considerable risk > of getting fired. It is an example that precisely negates either > collective or individual, long-term or short-term, interest was > primary factor in this decision. > Well, you would know better than me, but believe me when I say that such decisions being made for the economic benefit of a single individual are far from rare. > >>>>The firm I was working for had a consensus decision-making process (even >>>>I was involved) and managers (and other employees) and stockholders were >>>>mostly the same people -- it wasn't all that large a firm at the time. >>>>Nobody needed to practice risk avoidance. > > >>>Again, you may have had good luck. Where I worked (including >>>some places in Germany and UK) it was almost the only factor >>>that seemed to matter to people - they'd do ANYTHING not to >>>take a risky decision, to "pass the buck", not to stick their necks >>>out, not to declare doing some work that involved challenges. > > > >>Some people are like that. I chose a long time ago to try not to work >>with them whenever I could avoid it and, while that may have had >>negative economic consequences I an convinced it has improved my quality >>of life immensely. Of course, I have no proof for such an assertion. > > > Which in economic terms could mean that your "utility function" > is "modeled" in this particular way (well, strictly speaking utility > functions regard simple consumption), while most people tend > to misunderstand it as the idea that supposedly is "vulgar > consumption of as much stuff as possible is what makes people > happy" and they feel rightly repulsed from such an idiotic idea. > The trouble is, well-informed people do not to argue that, while > people tend to think economists actually do... > Well, even assuming I were to allow that such an intellectual thing as a utility function were to apply to my behavior in this case (which would be allowing economists more credence than I believe most of them deserve, but what the heck), all we are really taking about is that "it takes all sorts to make a world". I'm as fond of what money can buy as the next guy, but there are still limits on what I will do to acquire it. So really a utility function is a very dry and abstract way of looking at human behavior, and is simply incapable (at the present stage of the game) of modeling human behavioral complexity. > > > -- > It's a man's life in a Python Programming Association. 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 __peter__ at web.de Sat Jan 22 04:23:35 2005 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Jan 2005 10:23:35 +0100 Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: Peter Otten wrote: > Paul McGuire wrote: > >>> Is there an elegant way to assign to a list from a list of unknown >>> size? For example, how could you do something like: >>> >>> >>> a, b, c = (line.split(':')) >>> if line could have less than three fields? > >> I asked a very similar question a few weeks ago, and from the various >> suggestions, I came up with this: >> >> line = "AAAA:BBB" >> expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen] >> a,b,c = expand( line.split(":"), "", 3 ) > > Here is an expand() variant that is not restricted to lists but works with > arbitrary iterables: > > from itertools import chain, repeat, islice > > def expand(iterable, length, default=None): > return islice(chain(iterable, repeat(default)), length) Also nice, IMHO, is allowing individual defaults for different positions in the tuple: >>> def expand(items, defaults): ... if len(items) >= len(defaults): ... return items[:len(defaults)] ... return items + defaults[len(items):] ... >>> expand((1, 2, 3), (10, 20, 30, 40)) (1, 2, 3, 40) >>> expand((1, 2, 3), (10, 20)) (1, 2) Peter From gerrit at nl.linux.org Mon Jan 10 05:53:44 2005 From: gerrit at nl.linux.org (Gerrit) Date: Mon, 10 Jan 2005 11:53:44 +0100 Subject: tuples vs lists In-Reply-To: References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dff650$0$29357$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <20050110105344.GA8384@topjaklont.student.utwente.nl> Steve Holden wrote: > worzel wrote: > >'Two-Pull' it is then, thanks. > > > Well, it might be "Two-Pull" in American, but in English it's "tyoopl" > -- NOT "choopl" (blearch!). I've also heard people say "tuppl". > > So, basically, say whatever you want. Language is about communication :-) Or just write it down and don't say the word at all (-: regards, Gerrit, who actually says t?pel. -- Weather in Lulea / Kallax, Sweden 10/01 10:20: -12.0?C wind 0.0 m/s None (34 m above NAP) -- In the councils of government, we must guard against the acquisition of unwarranted influence, whether sought or unsought, by the military-industrial complex. The potential for the disastrous rise of misplaced power exists and will persist. -Dwight David Eisenhower, January 17, 1961 From a at b.c Sun Jan 23 02:33:35 2005 From: a at b.c (Doug Holton) Date: Sun, 23 Jan 2005 01:33:35 -0600 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> Message-ID: <_cSdnRo1keDOzm7cRVn-ug@comcast.com> Daniel Bickett wrote: > In my (brief) experience with YAML, it seemed like there were several > different ways of doing things, and I saw this as one of it's failures > (since we're all comparing it to XML). However I maintain, in spite of > all of that, that it can easily boil down to the fact that, for > someone who knows the most minuscule amount of HTML (a very easy thing > to do, not to mention most people have a tiny bit of experience to > boot), the transition to XML is painless. YAML, however, is a brand > new format with brand new semantics. That's true and a very good point. Like you said, that's probably the reason XML took off, because of our familiarity with HTML. > As for the human read-and-write-ability, I don't know about you, but I > have no trouble whatsoever reading and writing XML. You might like programming in XML then: http://www.meta-language.net/ :) From sjmachin at lexicon.net Tue Jan 11 18:08:06 2005 From: sjmachin at lexicon.net (John Machin) Date: 11 Jan 2005 15:08:06 -0800 Subject: Importing Problem on Windows References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> Message-ID: <1105484886.837430.248940@f14g2000cwb.googlegroups.com> brolewis wrote: > I have a directory that has two files in it: > > parse.py > parser.py > > parse.py imports a function from parser.py and uses it to parse out the > needed information. On Linux, the following code works without a > problem: > > parse.py, line 1: > from parser import regexsearch > > However, when I run the same command in Windows, I get the following > error: > > ImportError: cannot import name regexsearch > Any suggestions on why this would work on Linux but not on Windows? Hint for the future: use the -v argument (python -v yourscript.py yourarg1 etc) to see where modules are being imported from. Example (I don't have a module named parser anywhere): python -v [big snip] >>> from parser import regexsearch import parser # builtin <<<<==== aha! Traceback (most recent call last): File "", line 1, in ? ImportError: cannot import name regexsearch >>> From christiancoder at gmail.com Mon Jan 17 15:41:25 2005 From: christiancoder at gmail.com (christiancoder at gmail.com) Date: 17 Jan 2005 12:41:25 -0800 Subject: Cygwin Popen object Message-ID: <1105994485.770313.141910@f14g2000cwb.googlegroups.com> Is anybody else getting the following error with the Popen object in cygwin? The code works fine in windows and linux. File "d:\atg\personal\python\buildroot\util.py", line 100, in System pipe = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True ) File "/usr/local/lib/python2.4/subprocess.py", line 554, in __init__ errread, errwrite) File "/usr/local/lib/python2.4/subprocess.py", line 914, in _execute_child self.pid = os.fork() OSError: [Errno 11] Resource temporarily unavailable From larry_wallet at yahoo.com Sat Jan 29 23:46:21 2005 From: larry_wallet at yahoo.com (Larry) Date: 29 Jan 2005 20:46:21 -0800 Subject: what's OOP's jargons and complexities? References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: <1107060381.623163.19850@z14g2000cwz.googlegroups.com> Xah Lee wrote: > in computer languages, often a function definition looks like this: > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html Your ideas are original, insightful and simply reflect incredibly deep creative genius. I have read your work and I want to hire you for highly classified work in software design and philosophical writing. Would you possibly be available to meet with me in my secret mountain compound to discuss terms? Larry From wuwei23 at gmail.com Wed Jan 5 17:38:57 2005 From: wuwei23 at gmail.com (alex23) Date: 5 Jan 2005 14:38:57 -0800 Subject: Python evolution: Unease In-Reply-To: <10to8qulnc3vke1@news.supernews.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> Message-ID: <1104964736.965029.96160@c13g2000cwb.googlegroups.com> John Roth wrote: > I've been reading this thread and quietly congratulating myself > on staying out of it, but this statement takes the cake. Honestly, I feel the same way about statements of your's like this: > The bottom line is that I'm not going to be writing any > extensive pieces of Python documentation. My time > is better spent elsewhere. The question is: *whose* time do you consider better spent on writing Python documentation *for you*? That is what I'm so incredulous about, the tone of demand in the original post (and also very visible in your quoted remark above) that insists this is *someone else's* responsibility. Again: if you want the documentation that badly, then you want to do what said documentation would illustrate. If you *really* want to do that, then you'll take the time to find out how it's done *anyway*, document it up as you go, no matter how briefly, and make a *start* on filling in what *you* perceive as being a void in the current documentation. But to point out how laborious a process it is and how your time is too valuable to undertake it personally...it's difficult to parse that any other way than "I want other people to do all the hard work for me". From beliavsky at aol.com Tue Jan 25 12:40:35 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 25 Jan 2005 09:40:35 -0800 Subject: Browsing text ; Python the right tool? References: Message-ID: <1106674835.862387.79030@z14g2000cwz.googlegroups.com> Here is an elementary suggestion. It would not be difficult to write a Python script to make a csv file from your text files, adding commas at the appropriate places to separate fields. Then the csv file can be browsed in Excel (or some other spreadsheet). A0 and C1 records could be written to separate csv files. There are Python programs to create Excel spreadsheets, and they could be used to format the data in more sophisticated ways. From http Sun Jan 9 23:50:27 2005 From: http (Paul Rubin) Date: 09 Jan 2005 20:50:27 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> Message-ID: <7xu0ppyjjg.fsf@ruckus.brouhaha.com> "Roose" writes: > Are you actually going to answer any of my questions? Let's see > this "JavaScript task scheduler" you have written! I wrote it at a company and can't release it. It ran inside a browser. There was nothing terribly amazing about it. Obviously the tasks it scheduled were not kernel tasks. Do you know how Stackless Python (with continuations) used to work? That had task switching, but those were not kernel tasks either. From matthew_shomphe at countrywide.com Wed Jan 26 16:31:30 2005 From: matthew_shomphe at countrywide.com (Matt) Date: 26 Jan 2005 13:31:30 -0800 Subject: Help With Python In-Reply-To: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> References: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <1106775090.890952.40590@c13g2000cwb.googlegroups.com> Nick Vargish wrote: > Here's my Monty Pythonic answer: > > ## cut here > class Viking(): > > def __init__(): > pass > > def order(): > return 'Spam' > > # this is one viking making one order repeated 511 times. if you want > # 511 vikings making seperate orders, you'll have to write a loop. > v = Viking() > orders = [ v.order() ] * 511 > > print ', '.join(orders) > ## cut here > > With no apologies to Eric Idle, > > 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?') Not to be nit-picky, but you got some issues here ;-). Never forget the importance of "self"! ####################### class Viking: . def __init__(self): . pass . def sing(self): . return 'Spam' v = Viking() spam_song = [ v.sing() ] * 511 print ', '.join(spam_song) From david at qssp.com Sat Jan 8 00:42:37 2005 From: david at qssp.com (D Flint) Date: Fri, 7 Jan 2005 21:42:37 -0800 Subject: Real Election Reform Message-ID: <_tadnQpw77cViX3cRVn-ow@comcast.com> What do you think about this and have you seen this popular site before? This was taken from a web site http://www.afvr.org How can we safeguard the integrity of each vote? Today we have technology that protects our financial systems, military weapon systems and national intelligent organizations. These proven systems can be combined in a way to issue serialized equipment to authorize personnel for the dates and hours needed. Each would have their own level of clearance to perform the tasks they are responsible for. Each action would be recorded and verified with a higher levels of network authority and again, only available during the hours and dates needed. Ballots would only be printed after the voter has cast their vote but before they leave the booth. If the voter made a mistake he could put the printed ballot into the booth's scanner for correction. All ballots scanned at the booth would go into a shredder and the voter could then correct his ballot on the screen and reprint his ballots. Once the voter accepts the printed ballot he submits his vote on the screen and takes the two ballots to the depository. So two computer generated, serialized and scanner perfect receipts of the completed ballot are printed.* One for the voter and one for the public record. This would eliminate all the extra ballots that could be used for unauthorized voting as well as any question of voter intent. Each piece of equipment involved in the issuing of the receipt would be linked to the serial# of that ballot and an electronic document would be generated that exactly matched the two printed receipts. So the voter themselves has validate the printed ballots, keeping one for themselves, while the other electronic time-stamped document is deposited into an optical scanner used as a secure depository. This second scanned count which should always match the electronic count. This paper ballot could also be used for recounts if needed. The voter could use the receipt to inquire about their vote in the future. The stuffing of the ballot box or "finding ballots" would be eliminated. With this system, if you find a ballot, you have to find the voter that cast that ballot too. This is not so in any of the current systems in place today nor have we ever heard such a system ever proposed. http://www.afvr.org From steven.bethard at gmail.com Wed Jan 12 13:47:13 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 11:47:13 -0700 Subject: counting items In-Reply-To: References: Message-ID: <1oOdnQwciYEy7XjcRVn-gQ@comcast.com> Mark McEahern wrote: > It's me wrote: > >> Okay, I give up. >> >> What's the best way to count number of items in a list [that may >> contain lists]? >> >> > a = [[1,2,4],4,5,[2,3]] > > def iterall(seq): > for item in seq: > try: > for subitem in iterall(item): > yield subitem > except TypeError: > yield item > > all = [x for x in iterall(a)] > print len(all) > Beware: py> list(iterall(['a'])) Traceback (most recent call last): File "", line 1, in ? File "", line 4, in iterall ... File "", line 4, in iterall RuntimeError: maximum recursion depth exceeded You need to special-case strings. I would do this explicitly, e.g.: py> def iterall(seq): ... for item in seq: ... if isinstance(item, basestring): ... yield item ... else: ... try: ... for subitem in iterall(item): ... yield subitem ... except TypeError: ... yield item ... py> list(iterall(['a'])) ['a'] but you can also do this by checking for __iter__ as in one of the other posted solutions. (This takes advantage of the fact that strings use the __getitem__ protocol for iteration instead of __iter__.) Steve From fredrik at pythonware.com Mon Jan 24 15:51:31 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 21:51:31 +0100 Subject: Question about reading a big binary file and write it into severaltext (ascii) files References: <1106599472.099182.312130@z14g2000cwz.googlegroups.com> Message-ID: Albert Tu wrote: > I am learning and pretty new to Python and I hope your guys can give me > a quick start. > > I have an about 1G-byte binary file from a flat panel x-ray detector; I > know at the beggining there is a 128-byte header and the rest of the > file is integers in 2-byte format. > > What I want to do is to save the binary data into several smaller files > in integer format and each smaller file has the size of 2*1024*768 > bytes. > > I know I can do something like >>>>f=open("xray.seq", 'rb') >>>>header=f.read(128) >>>>file1=f.read(2*1024*768) >>>>file2=f.read(2*1024*768) >>>>...... (using a loop might help) >>>>f.close() > > Bur I don't them how to save files in integer format (converting from > binary to ascii files) and how to do this in an elegant and snappy way. I think you have to define "integer format" a bit better. A text file with integer values, written out in decimal? If so, take a look at the array module: http://docs.python.org/lib/module-array.html Here's an (untested) example; tweak as necessary: linesize = 1024 data = array("h", filedata) for i in range(0, len(data), linesize): # convert to list of decimal integers list = map(str, data[i:i+linesize]) print " ".join(list) tools like PIL and NumPy may also come in handy, but I suspect they're overkill in this case. From andreasp at qbcon.com Thu Jan 27 08:07:47 2005 From: andreasp at qbcon.com (Andreas Pauley) Date: Thu, 27 Jan 2005 15:07:47 +0200 (SAST) Subject: Point of Sale Message-ID: Hi, My company has given me a rather cool project: I have to provide them with an open-source python-based point-of-sale / cash register system that can integrate with their existing ERP backend. The project will include development to ensure that the features they require are included in the open-source POS system. Can you recommend anything that I can use? Regards, Andreas From sjmachin at lexicon.net Sun Jan 23 21:08:36 2005 From: sjmachin at lexicon.net (John Machin) Date: 23 Jan 2005 18:08:36 -0800 Subject: Set parity of a string In-Reply-To: References: Message-ID: <1106532516.483892.292900@z14g2000cwz.googlegroups.com> Peter Hansen wrote: > snacktime wrote: > > Is there a module that sets the parity of a string? I have an > > application that needs to communicate with a host using even parity > > So what I need is before sending the message, convert it from space to > > even parity. And when I get the response I need to convert that from > > even to space parity. > > By what means are the messages being delivered? I've rarely > seen parity used outside of simple RS-232-style serial communications. > Certainly not (in my experience, though it's doubtless been done) > in TCP/IP based stuff. And if it's serial, parity can be > supplied at a lower level than your code. > > As to the specific question: a module is not really required. > The parity value of a character depends only on the binary > value of that one byte, so a simple 128-byte substitution > table is all you need, plus a call to string.translate for > each string. > > -Peter And for converting back from even parity to space parity, either a 256-byte translation table, or a bit of bit bashing, like chr(ord(c) & 127), on each byte. The bank story sounds eminently plausible to me. Pick up old system where branch manager had to dial HO every evening, insert phone into acoustic coupler, etc etc and dump it on the internet ... From skip at pobox.com Fri Jan 14 20:17:16 2005 From: skip at pobox.com (skip at pobox.com) Date: 14 Jan 2005 17:17:16 -0800 Subject: Handling fractions of seconds in strftime/strptime Message-ID: <1105751836.456124.69970@z14g2000cwz.googlegroups.com> I'm looking for a solution (or ideas about a solution) to the problem that strftime(3) and strptime(3) don't understand time increments of less than one second. Most operating systems can provide times with subsecond resolution and like Python I'm pretty sure Ruby, Perl and Tcl have objects or packages that can manipulate such times in a sane manner. I'm casting my net to a broader community than just Python (where I generally hang out) to see if/how others have addressed this problem. Here's my typical use case. I generate log files with subsecond resolution using Python's datetime module. By default it generates printable timestamps in an ISO format that includes fractions of seconds, e.g., "2005-01-14 18:56:54.546607". I often need to parse such times, and therein lies the rub. Python's date parsing is based on strptime(3) which can't handle fractions of seconds. I wind up worming around the problem with a little hackery, but it bothers me that given an otherwise complete solution to formatting and parsing times I can't handle this common (for me) case. I realize that other languages may not base their current time formatting and parsing on strftime(3) and strptime(3), but I suspect those two functions were at least the root of what is commonly used by most languages. In my investigation I came across a DateTime module in Perl that uses "%N" (or optionally "%nN" where n is a digit) to identify integers as nanoseconds or some other subsecond time. I belive "%3N" would cause "123" to be interpreted as 123 milliseconds, for instance. I've considered extending "%S" to accept fractional seconds or adding a new format specifier like "%F" to handle this case. I'm interested to know what solutions have been devised or considered for other languages. (Has this been addressed in some more recent version of the C or C++ standards I'm unaware of?) Rather than reinventing the wheel I'd like to adopt an existing solution if possible. At the very least I'd like to know how others have approached the problem. I think there's an opportunity to add some value that everyone can take advantage of. Thanks for your time, Skip Montanaro skip at pobox.com From eurleif at ecritters.biz Wed Jan 19 01:17:09 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 19 Jan 2005 01:17:09 -0500 Subject: Solutions for data storage? Message-ID: <356c7tF4g3f64U1@individual.net> I'm writing a relatively simple multi-user public Web application with Python. It's a rewrite of a similar application which used PHP+MySQL (not particularly clean code, either). My opinions on various Web frameworks tends to vary with the phase of the moon, but currently, I'm planning to use Quixote. Needless to say, my application will need some kind of persistent data storage. The previous PHP+MySQL application uses around 1.1GB of storage, so something like PyPerSyst where everything is kept in memory is out. I've looked at SQLObject, and it's very nice, but it doesn't provide certain features I really want, like the ability to store lists of strings or integers directly in the database (using commas in a varchar column or something). ZODB is very nice, but IndexedCatalog doesn't seem to provide any automatic mechanisms for things like ensuring attribute uniqueness (for e.g. usernames). I suppose I could implement manual checking in every class that needs it, but it really seems like very error-prone code to be implementing at the application level. My ideal solution would be an object database (or object-relational mapper, I guess) which provided total transparency in all but a few places, built-in indexing, built-in features for handling schema changes, the ability to create attributes which are required to be unique among other instances, and built-in querying with pretty syntax. Atop seems to come pretty close, but since it's meant to be used in the asynchronous Twisted environment, it doesn't provide any thread safety. So basically, I'm wondering if there are any Python data storage solutions I haven't noticed that come a bit closer to what I'm looking for. I could live without built-in schema evolution; the querying is really the most important feature I want. From andre.roberge at gmail.com Fri Jan 21 12:42:15 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Fri, 21 Jan 2005 13:42:15 -0400 Subject: Simple (newbie) regular expression question In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> Message-ID: Sorry for the simple question, but I find regular expressions rather intimidating. And I've never needed them before ... How would I go about to 'define' a regular expression that would identify strings like __alphanumerical__ as in __init__ (Just to spell things out, as I have seen underscores disappear from messages before, that's 2 underscores immediately followed by an alphanumerical string immediately followed by 2 underscore; in other words, a python 'private' method). Simple one-liner would be good. One-liner with explanation would be better. One-liner with explanation, and pointer to 'great tutorial' (for future reference) would probably be ideal. (I know, google is my friend for that last part. :-) Andre From ptmcg at austin.rr._bogus_.com Sun Jan 16 19:42:39 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 17 Jan 2005 00:42:39 GMT Subject: List problems in C code ported to Python References: Message-ID: <3SDGd.22010$Z%.6947@fe1.texas.rr.com> "Lucas Raab" wrote in message news:vrzGd.817$Rs.803 at newsread3.news.atl.earthlink.net... > I'm done porting the C code, but now when running the script I > continually run into problems with lists. I tried appending and > extending the lists, but with no avail. Any help is much appreciated > Please see both the Python and C code at > http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py > > TIA I didn't actually run your script, but you have some fundamental things to fix first. Here are some corrections that will get you closer: - Single-character strings are still strings as far as Python is concerned. Unlike C's distinction of single quotes for single characters (which allow you to do integer arithmetic) and double quotes for string literals (which don't support integer arithmetic), Python uses either quoting style for strings. So "A" == 'a' is true in Python, not true in C. To do single-char arithmetic, you'll need the ord() and asc() functions, so that instead of c-'A' you'll need ord(c)-ord('A') (and another little tip - since the ord('A') is likely to be invariant, and used *heavily* in a function such as an Enigma simulator, you're best off evaluating it once and stuffing it into a global, with an unimaginitive name like ord_A = ord('A') -Line 42: You are testing c == string.alpha_letters, when I think you *really* want to test c in string.alpha_letters. - encipher_file - the C version of this actually reads the file and calls encipher() with each character in it. Your Python version just calls encipher() with the complete file contents, which is certain to fail. (another tip - avoid variable names like 'file', 'string', 'list', 'dict', etc. as these collide with global typenames - also, your variable naming is pretty poor, using "file" to represent the filename, and "filename" to represent the file contents - err???) - usage() - print("blahblah \n") - the trailing \n is unnecessary unless you want to double-space your text Although you say you are "done porting the C code", you really have quite a bit left to do yet. You should really try to port this code a step at a time - open a file, read its contents, iterate through the contents, call a method, etc. "Big-bang" porting like this is terribly inefficient! -- Paul From peter at engcorp.com Sun Jan 30 13:05:10 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 30 Jan 2005 13:05:10 -0500 Subject: Disassembling strings and turning them into function parameters In-Reply-To: <1107107283.694377.286360@c13g2000cwb.googlegroups.com> References: <1107107283.694377.286360@c13g2000cwb.googlegroups.com> Message-ID: mercuryprey at gmail.com wrote: > Hi, > I'm pretty new to Python, to programming overall...so how would I make > something where the user inputs multiple words in a string - like > "connect 123.123.123.123 21 user password" or similar, and then I can > split this string up to pass these arguments to a function like > ftp_connect(ip, port, user, pw) etc...? I have no idea how to "break" > the string up so I can get these out of it.. The .split() method of strings should work for you. If you need more, provide more background... and maybe let us know that this isn't homework. ;-) -Peter From secun at yahoo.com Wed Jan 26 14:17:19 2005 From: secun at yahoo.com (secun at yahoo.com) Date: 26 Jan 2005 11:17:19 -0800 Subject: Web front-end for python scripts Message-ID: <1106767039.927592.49450@z14g2000cwz.googlegroups.com> I've written some python scripts to handle different tasks on my Windows network. I would like to have them accessible via a single web page (kind of like a dashboard) and have the scripts run on the server on which the web server resides (also a Windows box) This is an internal server only, but the scripts need to be secure since the server will have administrative rights on the network. Can anyone recommend a way of doing this? Security is important since this page will be accessible inside the company, but only people with the appropriate user name / password will be able to run the scripts. From firemoth at gmail.com Fri Jan 21 08:52:24 2005 From: firemoth at gmail.com (Timothy Fitz) Date: Fri, 21 Jan 2005 08:52:24 -0500 Subject: PyCon Preliminary Program Announced! In-Reply-To: <1f7befae0501201952139c57a8@mail.gmail.com> References: <20050121000607.DE1261E4010@bag.python.org> <41F061C3.3000802@gmail.com> <1f7befae0501201952139c57a8@mail.gmail.com> Message-ID: <972ec5bd0501210552512154aa@mail.gmail.com> > I don't care much for "parallel tracks" myself, because I want to hear > basically everything. But we had more proposals of higher quality > this year than ever before, so it came down to scheduling more talks > in parallel than ever before too, or rejecting perfectly good > proposals. Will there be recordings of any of these presentations? There are quite a few times when I want to be at all three tracks at the same time. From aurora00 at gmail.com Wed Jan 26 13:39:18 2005 From: aurora00 at gmail.com (aurora) Date: Wed, 26 Jan 2005 10:39:18 -0800 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> Message-ID: It is really necessary to build a VM from the ground up that includes OS ability? What about JavaScript? > On Wed, Jan 26, 2005 at 05:18:59PM +0100, Alexander Schremmer wrote: >> On Tue, 25 Jan 2005 22:08:01 +0100, I wrote: >> >> >>>> sys.safecall(func, maxcycles=1000) >> > could enter the safe mode and call the func. >> >> This might be even enhanced like this: >> >> >>> import sys >> >>> sys.safecall(func, maxcycles=1000, >> allowed_domains=['file-IO', 'net-IO', 'devices', >> 'gui'], >> allowed_modules=['_sre']) >> >> Any comments about this from someone who already hacked CPython? > > Yes, this comes up every couple months and there is only one answer: > This is the job of the OS. > Java largely succeeds at doing sandboxy things because it was written > that > way from the ground up (to behave both like a program interpreter and an > OS). > Python the language was not, and the CPython interpreter definitely was > not. > > Search groups.google.com for previous discussions of this on c.l.py > > -Jack From stephen.thorne at gmail.com Wed Jan 12 21:19:06 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 12:19:06 +1000 Subject: Refactoring; arbitrary expression in lists In-Reply-To: <41e5cb07.701137402@news.oz.net> References: <41e5cb07.701137402@news.oz.net> Message-ID: <3e8ca5c805011218193394b465@mail.gmail.com> On Thu, 13 Jan 2005 01:24:29 GMT, Bengt Richter wrote: > extensiondict = dict( > php = 'application/x-php', > cpp = 'text/x-c-src', > # etcetera > xsl = 'test/xsl' > ) > > def detectMimeType(filename): > extension = os.path.splitext(filename)[1].replace('.', '') > try: return extensiondict[extension] > except KeyError: > basename = os.path.basename(filename) > if "Makefile" in basename: return 'text/x-makefile' # XXX case sensitivity? > raise NoMimeError Why not use a regexp based approach. extensionlist = [ (re.compile(r'.*\.php') , "application/x-crap-language"), (re.compile(r'.*\.(cpp|c)') , 'text/x-c-src'), (re.compile(r'[Mm]akefile') , 'text/x-makefile'), ] for regexp, mimetype in extensionlist: if regexp.match(filename): return mimetype if you were really concerned about efficiency, you could use something like: class SimpleMatch: def __init__(self, pattern): self.pattern = pattern def match(self, subject): return subject[-len(self.pattern):] == self.pattern Regards, Stephen Thorne From mefjr75 at hotmail.com Sat Jan 1 02:47:55 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 31 Dec 2004 23:47:55 -0800 Subject: More baby squeaking - iterators in a class In-Reply-To: <1104548797.050583.19030@c13g2000cwb.googlegroups.com> References: <1104511354.639920.246830@c13g2000cwb.googlegroups.com> <1104548797.050583.19030@c13g2000cwb.googlegroups.com> Message-ID: <1104565675.172883.40190@z14g2000cwz.googlegroups.com> py> from __future__ import generators Hello again, I was thinking about the __iter__ and what you were saying about generators, so I opened up pyshell and started typing. py> class R3: ... def __init__(self, d): ... self.d=d ... self.i=len(d) ... def __iter__(self): ... d,i = self.d, self.i ... while i>0: ... i-=1 ... yield d[i] ... py> r = R3('qwerty') py> r.__class__ py> r.__iter__ > py> r.__iter__() py> a = r.__iter__() py> a.next() 'y' py> a.next() 't' py> a.next() 'r' py> a.next() 'e' py> a.next() 'w' py> a.next() 'q' py> a.next() Traceback (most recent call last): File "", line 1, in ? StopIteration >>> Doh! ok now I get it __iter__ RETURNS a generator ;) It seems so obvious now I look at it. Sometimes I am a bit slow to catch on , but I never forget, much. M.E.Farmer Deeper down the rabbit hole. M.E.Farmer wrote: > Terry , > Thank you for the explanation . That is much clearer now, I have played > a bit with generators but have never tried to create a custom iterator. > I am just now getting into the internals part of python objects... this > langauage is still amazing to me! > The reason I asked the question was because I tried that code I posted > and it worked fine in python2.2.3 ? > > >Ignoring the older iteration method based on __getitem__, which I > recommend > >you do ignore, yes, you cannot do that. > > py>class R3: > ... def __init__(self, d): > ... self.d=d > ... self.i=len(d) > ... def __iter__(self): > ... d,i = self.d, self.i > ... while i>0: > ... i-=1 > ... yield d[i] > ... > py>a = R3('qwerty') > py>dir(a) > ['__doc__', '__init__', '__iter__', '__module__', 'd', 'i'] > py>for i in a: > ... print i > ... > y > t > r > e > w > q > Ok I don't see __getitem__ anywhere in this object. > Still scratchin my head? Why does this work? > M.E.Farmer From t-meyer at ihug.co.nz Sun Jan 9 20:38:55 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 10 Jan 2005 14:38:55 +1300 Subject: Please Contribute Python Documentation! In-Reply-To: Message-ID: > It *is* in the docs now -- see the top of > http://www.python.org/doc/2.4/doc/doc.html Oops. I ought to have checked rather than going by memory (I suppose the last time I looked 2.3 would have been current). Thanks for correcting me! =Tony.Meyer From spam at nospam.org Wed Jan 26 23:56:49 2005 From: spam at nospam.org (Erik Johnson) Date: Wed, 26 Jan 2005 21:56:49 -0700 Subject: building Python: up arrow broken on SuSE Linux 8.2 References: <41f6c3f7$1@nntp.zianet.com> <41f85dd8@nntp.zianet.com> Message-ID: <41f87288@nntp.zianet.com> "Erik Johnson" wrote in message news:41f85dd8 at nntp.zianet.com... > So I downloaded & built libreadline version 5.0. I have libreadline.a > and shlib/libreadline.so.5.0 files. Having done Python & other scripting > languages for a while, I have sort of forgotten all the ugly details about C > compilation. I'm trying to figure out how to get Python2.3.4. statically > linked with the .a file and not muck with the system shared libraries and > let other applications fend for themselves. Any advice on how to statically > link in this library so the Python build is happy? What I thought might be obvious and easy does not work, BTW... In the Modules/Setup file I put this... readline readline.c -I/home/ej/readline-5.0 -L/home/ej/readline-5.0 -lreadline re-ran configure and tried the make again. No joy. :( Now I remember why I ended up using things like Perl & Python in the first place... ej at sand:~/Python-2.3.4> make gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototyp es -I. -I./Include -DPy_BUILD_CORE -o Modules/config.o Modules/config.c gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototyp es -I. -I./Include -DPy_BUILD_CORE -DPYTHONPATH='":plat-linux2:lib-tk"' \ -DPREFIX='"/usr/local"' \ -DEXEC_PREFIX='"/usr/local"' \ -DVERSION='"2.3"' \ -DVPATH='""' \ -o Modules/getpath.o ./Modules/getpath.c gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DPy_BUILD_CORE -I/home/ej/readline-5.0 -c ./Modules/readline.c -o Modules/readline.o Modules/readline.c:26:31: readline/readline.h: No such file or directory Modules/readline.c:27:30: readline/history.h: No such file or directory Modules/readline.c: In function `parse_and_bind': Modules/readline.c:49: warning: implicit declaration of function `rl_parse_and_bind' Modules/readline.c: In function `read_init_file': Modules/readline.c:68: warning: implicit declaration of function `rl_read_init_file' Modules/readline.c: In function `read_history_file': Modules/readline.c:89: warning: implicit declaration of function `read_history' Modules/readline.c: In function `write_history_file': Modules/readline.c:111: warning: implicit declaration of function `write_history' Modules/readline.c:113: warning: implicit declaration of function `history_truncate_file' Modules/readline.c: In function `set_completer_delims': Modules/readline.c:287: error: `rl_completer_word_break_characters' undeclared (first use in this function) Modules/readline.c:287: error: (Each undeclared identifier is reported only once Modules/readline.c:287: error: for each function it appears in.) From claird at lairds.us Thu Jan 27 11:08:06 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 27 Jan 2005 16:08:06 GMT Subject: Another scripting language implemented into Python itself? References: <0juic2-68k.ln1@lairds.us> Message-ID: In article , Arthur wrote: . . . >As long as we include the cost of treating adults as children, and >take it seriously as the kind of cost it is, I'm OK. > >I think Terry's point covers a wide range of the real world >situations. Though certainly not all. > >My "real" life is in the mid-market business world, not as a geometry >software developer. And I see a sort of hysteria descending, in this >realm on this subject. Of theY2k ilk, but with actually, it seems to >me, less substance. Family businesses out on the limb, as a business, >in a myriad of ways - because they are after all in business, focusing >on remote scenarios because they are somehow becoming convinced that >is what business people do (they don't), and demoralizing folks in the >process. Folks who know that if they wanted to hurt this business >they could have done so a hundred times in a hundred ways over the >years. But it wouldn't be by screwing with their computer system >because they wouldn't know how. So isn't it funny that is what the >boss is so concerned about - all of a sudden? > >(They always knew they were smarter then him. More proof) > >Art > > Pronouns quickly overload me. If you're saying that there's hysteria afoot, much of it about the harm that might come through use of computers left unprotected from evildoers, well, yes, I'm with you. Most people have far more important hazards in their lives and work than "security violations" as we technologists generally conceive them. From deetsNOSPAM at web.de Fri Jan 21 05:20:47 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 21 Jan 2005 11:20:47 +0100 Subject: Python and SOAP References: Message-ID: <35c39jF4im71aU1@individual.net> > I'd like to write a SOAP client and a SOAP server > in Python. > > Is SOAPy still the way to go, or are there better > methods? If you really need SOAP, Nelson did answer your question. But if you are only communicating between two python processes, I suggest pyro. -- Regards, Diez B. Roggisch From jepler at unpythonic.net Thu Jan 13 18:57:28 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 13 Jan 2005 17:57:28 -0600 Subject: directory bug on linux; workaround? In-Reply-To: References: Message-ID: <20050113235727.GB1513@unpythonic.net> Python is at the whim of the services the OS provides. Maybe you should ask in a linux-related newsgroup or mailing list, they might know more about the specifics of both detecting and working around "weird" filesystems like "fat". To find the type of a filesystem, Linux provides the statfs(2) function, but no built-in Python module includes access to that function. Writing the wrapper would be an easy first exercise in extending Python, or using Pyrex or ctypes. The filesystem "magic numbers" also aren't available in Python. A partial list can be found by "grep _SUPER_MAGIC /usr/include/linux/*" Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From peter at engcorp.com Thu Jan 13 08:41:06 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 08:41:06 -0500 Subject: why are people still using classic classes? In-Reply-To: <7x6522gegg.fsf@ruckus.brouhaha.com> References: <7x6522gegg.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Simon Wittber writes: > >>>Is there a reason NOT to use them? If a classic class works fine, what >>>incentive is there to switch to new style classes? >> >>Perhaps classic classes will eventually disappear? > > It just means that the formerly "classic" syntax will define a > new-style class. Try to write code that works either way. Unfortunately, if we should follow the recent advice about always using "super()" in the __init__ method, it's hard to do what you suggest (though it sounds like good advice) without resorting to extreme ugliness: >>> class Classic: ... def __init__(self): ... super(Classic, self).__init__() ... >>> c = Classic() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __init__ TypeError: super() argument 1 must be type, not classobj Could classic classes ever be removed without us having manually to fix all __init__ calls to the superclass? -Peter From tim.golden at viacom-outdoor.co.uk Thu Jan 20 05:02:25 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 20 Jan 2005 10:02:25 -0000 Subject: Oddity is shutil.copyfileobj Message-ID: <9A28C052FF32734DACB0A288A35339910359D3@vogbs009.gb.vo.local> [Neil Benn] | I'm running a program which is using | shutil.copyfileobj on a Win2K Pro, python 2.3 box. Just for (possible) reassurance, I've just run the following code snippet on my Win2k Python 2.3.4 box and it seemed to work without adding any oddities to the file name. I'm copying to a "real" Windows file share, not a Samba box, so it may make a difference. import shutil f = open ("test.py", "rt") g = open (r"\\tdi_nt4a\user\goldent\temp\test.py", "wt") try: shutil.copyfileobj (f, g) finally: f.close () g.close () | The source and dest file are both opened in | textual mode as 'w' Well my first question (which may or may not be relevant) is: what do you mean by this? Are they both opened for *writing*, which is what the "w" implies? Or was that merely a typo for "t", meaning that you had explcitly selected text mode as opposed to binary mode? | The files are copied across perfectly (diffing them shows | they are identical), however I have one small problem, | the destination filename has .read appended to the end. | I've checked my code again and again and I'm definatly | not apeending this. Any chance you could *post* the code (at least the section in question)? The source for copyfileobj, which was the first place I looked is this: def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf) And unless there's something *really* subtle going on, I'm not sure I could spot any filename changing there. I'm afraid that, short of some obscure bug in Samba, which should show up regardless of what you're copying across, your own code is the most likely culprit. 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 steven.bethard at gmail.com Mon Jan 31 02:06:11 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 31 Jan 2005 00:06:11 -0700 Subject: a Python bug in processing __del__ method ?? In-Reply-To: <1107154011.859866.23480@z14g2000cwz.googlegroups.com> References: <1107154011.859866.23480@z14g2000cwz.googlegroups.com> Message-ID: Baoqiu Cui wrote: > Today I was playing with a small Python program using Python 2.4 > on Cygwin (up-to-date version, on Windows XP), but ran into a > strange error on the following small program (named bug.py): > > ------------------------------- > #!/usr/bin/python > > class Person: > population = 0 > def __del__(self): > Person.population -= 1 > > peter = Person() > ------------------------------- > > The error returned is this: > > $ python bug.py > Exception exceptions.AttributeError: "'NoneType' object has no > attribute 'population'" in <__main__.Person instance at 0xa0c9fec>> ignored > > However, if I rename variable name 'peter' to something like 'peter1' > or 'david', the error is gone. Looks to me the > error only happens to variable name 'peter'. > > Does anyone know what is wrong? Is this a bug only on Cygwin? I get this error on a normal Python WinXP install too. Looks like Python deletes globals in order when exiting, so the Person class gets deleted before the Person instances: ---------- bug.py ---------- class Person(object): population = 0 def __del__(self): Person.population -= 1 = Person() print list(globals()) ---------------------------- I tried this with a few different names. Here are the results for 'apple', 'banana' and 'cranberry'. Only when the name appears after 'Person' in the globals do I get the error that you get. [D:\Steve]$ bug.py ['apple', '__builtins__', '__file__', 'Person', '__name__', '__doc__'] [D:\Steve]$ bug.py ['__builtins__', '__file__', 'banana', 'Person', '__name__', '__doc__'] [D:\Steve]$ bug.py ['__builtins__', '__file__', 'Person', 'cranberry', '__name__', '__doc__'] Exception exceptions.AttributeError: "'NoneType' object has no attribute 'population'" in > ignored I don't know whether this is a bug or a "feature". ;) Steve From rbt at athop1.ath.vt.edu Sat Jan 29 21:03:49 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sat, 29 Jan 2005 21:03:49 -0500 Subject: Description Field in WinXP Services In-Reply-To: References: <41fc0646$1_1@127.0.0.1> Message-ID: rbt wrote: > Roger Upole wrote: > >> ChangeServiceConfig2 is the api functions that sets the description, >> but it's not in the win32service module (yet). >> >> Roger > > > OK, I can use _winreg to add the 'Description' field under the > appropriate registry key. Here's an example of it... kludgey but it works ;) from _winreg import * import time def Svc_Description(): try: key_location = r"SYSTEM\CurrentControlSet\Services\test_py_service" svc_key = OpenKey(HKEY_LOCAL_MACHINE, key_location, 0, KEY_ALL_ACCESS) SetValueEx(svc_key,'Description',0,REG_SZ,u"Brad's Test Python Service") CloseKey(svc_key) except Exception, e: print e Svc_Description() time.sleep(10) From bokr at oz.net Fri Jan 21 19:31:33 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 22 Jan 2005 00:31:33 GMT Subject: Class introspection and dynamically determining function arguments References: Message-ID: <41f18d10.1471646806@news.oz.net> On Thu, 20 Jan 2005 11:24:12 -0000, "Mark English" wrote: >I'd like to write a Tkinter app which, given a class, pops up a >window(s) with fields for each "attribute" of that class. The user could >enter values for the attributes and on closing the window would be >returned an instance of the class. The actual application I'm interested >in writing would either have simple type attributes (int, string, etc.), >or attributes using types already defined in a c-extension, although I'd >prefer not to restrict the functionality to these requirements. My first reaction is that if you can limit the problem, it could be done fairly simply. [... having read to the end by now, I see you were thinking of inspecting the __init__ method, so you are close to what I was thinking, but maybe this will be useful anyway, so since it's done, I'll post it ;-) ] E.g., if the attributes of interest are all set by simple attribute assignment in the __init__ method of the class, using __init__ arguments with default arguments, then you could inspect the __init__ function for parameter names and infer types from the default arguments. If the instance attribute name are bound in the __new__ method, you could still conceivably do something if you had a similar known signature, but the for unrestricted general case your Tkinter app would have to supply too much information than can't be inferred or be known by the user. E.g., how would a Tkinter app (or any other) know what to ask the user to supply to set the attributes of class WhatEver: def __init__(self, attr): self.attr = attr ? > >The only way I can imagine to do this is to create an instance of the >class in question, and then start poking around in its attributes >dictionary (initially just using dir). So firstly, if there is instead a >way to do this without creating an instance I'd be interested. As above. IMO you will have to restrict the problem. But perhaps that is no so bad. > >Secondly, the code won't know exactly how to initialise the class >instance used to determinte the attributes. Do I need to make it a >prerequesite that all instances can be created with no arguments ? I think that is a byproduct of the approach I suggested (i.e., all args having default values for type inference), but there's probably other ways. >Should I force/allow the user to pass an instance instead of a class ? I would say no. Especially considering possible side effects. >Should I be using inspect.getargspec on the class __init__ method and >then a loop with a try and a lot of except clauses, or is there a nicer I don't know if you need a _lot_ of except clauses, but yes, at least one, and a loop to allow retrying after typos etc. >way to do this ? Presumably the pickling code knows how do >serialise/deserialise class instances but I'm not sure how I'd use this >without already having a class instance to hand. > >Lastly, does such an app already exist ? Don't know. Wouldn't be surprised. > >Thanks for any help. This shows you are probably close to solving your own problem with inspect.getargspec: >>> class C(object): ... def __init__(self, a=1, b='bee', c=1.2): ... self.a = a ... self.b = b ... self.c = c ... >>> inspect.getargspec(C.__init__) (['self', 'a', 'b', 'c'], None, None, (1, 'bee', 1.2)) >>> print inspect.getargspec.__doc__ 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. >>> args,_,_,defaults = inspect.getargspec(C.__init__) >>> values = [] Obviously you need an inner loop for correcting typos etc., and try/except to catch relevant errors, but I'm just typing interactively here, so her goes: >>> for name, defv in zip(args[-len(defaults):], defaults): ... vstr = raw_input('Please enter a string suitable for %s(s): '%type(defv).__name__) ... values.append(type(defv)(vstr)) ... Please enter a string suitable for int(s): 123 Please enter a string suitable for str(s): 'this is a string' Please enter a string suitable for float(s): 1.5 >>> values [123, "'this is a string'", 1.5] >>> c = C(*values) >>> c.a 123 >>> c.b "'this is a string'" >>> c.c 1.5 >>> cdef = C() >>> cdef.a, cdef.b, cdef.c (1, 'bee', 1.2) I guess the single quotes on the str(s) entry shows that all the characters get entered ;-) You might want to think about whether to process backslashes as escapes in your input. E.g., >>> raw_input('Enter some escape example: ') Enter some escape example: Not an newline: \n -- nor '\n' ;-) "Not an newline: \\n -- nor '\\n' ;-)" >>> print raw_input('Enter some escape example: ') Enter some escape example: Not an newline: \n -- nor '\n' ;-) Not an newline: \n -- nor '\n' ;-) BTW, You can avoid importing inspect and get the data of >>> inspect.getargspec(C.__init__) (['self', 'a', 'b', 'c'], None, None, (1, 'bee', 1.2)) that you want by looking at the unbound method C.__init__ (though im_func may be deprecated eventually?): >>> C.__init__.im_func.func_code.co_varnames ('self', 'a', 'b', 'c') >>> C.__init__.im_func.func_defaults (1, 'bee', 1.2) or by getting the __init__ function as such, by avoiding the attribute access that makes it and unbound or bound method >>> C.__dict__['__init__'].func_code.co_varnames ('self', 'a', 'b', 'c') >>> C.__dict__['__init__'].func_defaults (1, 'bee', 1.2) Regards, Bengt Richter From nun at example.com Mon Jan 31 17:34:36 2005 From: nun at example.com (Mitja) Date: Mon, 31 Jan 2005 23:34:36 +0100 Subject: "Mail receiver server" References: <41feaff2$0$2068$626a14ce@news.free.fr> Message-ID: On Mon, 31 Jan 2005 23:23:46 +0100, manatlan wrote: > in fact, i'd like to control "computer A" by sending smtp email from > "computer B". > > What kind of server should i write on computer "B", a smtp server ? a > pop server ? It would be easier if you used an existing mail server (which OS are you running on comp B?), then use its redirecting features to pipe the incoming mail to your python script. AFAIK most servers support that. Less hassle, though probably a wee bit more intensive for the computer. From craig at postnewspapers.com.au Fri Jan 21 17:38:03 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 22 Jan 2005 06:38:03 +0800 Subject: Tuple size and memory allocation for embedded Python In-Reply-To: References: Message-ID: <1106347083.19065.80.camel@bucket.localnet> On Fri, 2005-01-21 at 17:20 -0500, Steve Holden wrote: > Jinming Xu wrote: > > > Hi Folks, > > > > Python seems unstable, when allocating big memory. For example, the > > following C++ code creates a tuple of tuples: > > > > PyObject* arCoord = PyTuple_New(n); > > double d = 1.5; > > for(int i=0; i > { > > PyObject* coord = PyTuple_New(2); > > PyTuple_SetItem(coord,0, PyFloat_FromDouble(d));//x > > PyTuple_SetItem(coord,1, PyFloat_FromDouble(d));//y > > PyTuple_SetItem(arCoord,i, coord); > > } > > > > When the n is small, say 100, the code works fine. when n is big, say > > 10,000, Python has trouble allocating memory, saying: > > > > "Exception exceptions.IndexError: 'tuple index out of range' in 'garbage > > collection' ignored > > Fatal Python error: unexpected exception during garbage collection > > Aborted" > > > > Could anyone please give me some insight or a fix for this? > > > > Thanks in advance for your answer. > > > I'm going to guess that the problem is related to incorrect reference > counts. It's usually a safe bet, after all. Another biggie is unchecked return codes leaving the exception state set, though... that can cause _really_ _weird_ problems. ALWAYS check return values. > I don't see any IncRefs in there. In this case it looks OK. PyFloat_FromDouble() reuturns a new reference, as does PyTuple_New(), and PyTuple_SetItem() steals a reference to its PyObject* argument. Of course, there could be refcount errors outside the shown code segment, but in this case I'd say the immediate error will be because of an unhandled exception. As to why that exception is being thrown.... Also, forget my comment in my last post about not resizing - I'd failed to notice the initial creation size of the tuple (the creation of which isn't checked, but would segfault the app on failure). > Python is pretty stable, so it's usually best to suspect our own code > unless you're heavily into using the C API (which I'm not, so feel free > to ignore me). That's been my experience - stability issues in my Python/C code have almost always come down to refcounting bugs and/or failing to detect and handle or propagate an exception. -- Craig Ringer From http Fri Jan 7 16:29:29 2005 From: http (Paul Rubin) Date: 07 Jan 2005 13:29:29 -0800 Subject: DOS problem (simple fix??) References: Message-ID: <7xis690vye.fsf@ruckus.brouhaha.com> Gavin Bauer writes: > Thank you, and please make all answers simple enough to be understood > by a highschool student and his father :) . You might like to try IDLE, which is included with Python. From fredrik at pythonware.com Sun Jan 16 05:44:43 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 16 Jan 2005 11:44:43 +0100 Subject: generator expressions: performance anomaly? References: <1105854381.117059.59940@c13g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > Given a requirement to mutate the original list, this necessitates the assignment > to lst[:]. do you always pull requirements out of thin air? From fu.limin.tao at gmail.com Fri Jan 28 05:42:47 2005 From: fu.limin.tao at gmail.com (Limin Fu) Date: Fri, 28 Jan 2005 11:42:47 +0100 Subject: ANN: Tao Scripting Language 0.8.5 beta released! In-Reply-To: <20a7bea6e3332d34a1b170ffb808502f@gmail.com> References: <397cc8578b5e9adf0e31f18ffa556593@gmail.com> <20a7bea6e3332d34a1b170ffb808502f@gmail.com> Message-ID: I should admit I only read a little bit very simple introductions of Lua, so I can't answer you question exactly now. Maybe you can found the answer by yourself by spending some minutes to read the brief documentation of Tao. Depending how much time I have, probably I will make a comparison between Tao and other languages, and make it available in the website of Tao. But it will not be soon. Cheers On Thu, 27 Jan 2005 23:47:27 +0100, PA wrote: > > On Jan 27, 2005, at 23:42, Limin Fu wrote: > > > at that time I didn't heard about Lua. I knew it about > > 2 or 3 months after I began to implement Tao. > > So, compared to Lua for example, what does Tao brings to the table that > you found worthwhile? > > Cheers > > -- > PA, Onnay Equitursay > http://alt.textdrive.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Homepage for Tao Language: http://taoscript.sourceforge.net Tao Language project at sourceforge.net: http://sourceforge.net/projects/taoscript From ricardo.b at zmail.pt Thu Jan 13 21:41:38 2005 From: ricardo.b at zmail.pt (Ricardo Bugalho) Date: Fri, 14 Jan 2005 02:41:38 +0000 Subject: Unicode conversion in 'print' References: <1105655600.059496.70350@z14g2000cwz.googlegroups.com> Message-ID: Hi, thanks for the information. But what I was really looking for was informaion on when and why Python started doing it (previously, it always used sys.getdefaultencoding())) and why it was done only for 'print' when stdout is a terminal instead of always. On Thu, 13 Jan 2005 14:33:20 -0800, Serge Orlov wrote: > Sure. It uses the encoding of you console. Here is explanation why it uses > locale to get the encoding of console: > http://www.python.org/moin/PrintFails > -- Ricardo From FBatista at uniFON.com.ar Tue Jan 25 16:12:22 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 25 Jan 2005 18:12:22 -0300 Subject: MySQLdb Message-ID: [Daniel Bowett] #- The problem I have is that it takes just over two minuted to #- execute the #- 3000 insert statements which seems really slow! I am running it on a #- machine with a 1.5 Ghz Pentium M Processor and Gig Of Ram. I #- dont think #- the machine is to blame for the speed because during execution the #- processor sits at about 10% and there is loads of free RAM. #- #- Does anyone know if this sort of speed sounds right? Well, I made the following code. mod_mysql is mine, but is just a wrapper around the standard module. Here I only use the .accion() method of the Consulta object, that let me send an action (query, insert, etc) to the database. So I generate a temporary table of four fields, and prepared a list of 3000 entries, each one is a tuple of four elements: ten characters choosed randomly. --- import random, string, time import mod_mysql bdd = mod_mysql.Consulta("pytonisa", "fbatista", "password", "otainfo") bdd.accion("create temporary table tmp.prueba (c1 char(10), c2 char(10), c3 char(10), c4 char(10));") r = random.Random() let = string.letters + string.digits fuente = [tuple([''.join(r.sample(let, 10)) for j in range(4)]) for x in range(3000)] t = time.time() for reg in fuente: bdd.accion('insert into tmp.prueba values ("%s", "%s", "%s", "%s");' % tuple(reg)) print time.time() - t --- I only measure the time of the inserts. It took 0.269818067551 seconds. I'm using a Pentium 4 2.8 GHz, 256 MB of RAM, with Fedora Core 2, kernel 2.4.22, python 2.3.3 (GCC 3.3.2), and MySQL 4.0.18. Regards, . 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 craig at postnewspapers.com.au Fri Jan 7 11:11:34 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 08 Jan 2005 00:11:34 +0800 Subject: missing sys.setappdefaultencoding In-Reply-To: <1gq0pd4.id8j3sexmiexN%aleaxit@yahoo.com> References: <1gq0pd4.id8j3sexmiexN%aleaxit@yahoo.com> Message-ID: <1105114293.30384.6.camel@rasputin.localnet> On Fri, 2005-01-07 at 19:06, Alex Martelli wrote: > Uwe Mayer wrote: > > well, I wrote a nice python program which won't work if the default encoding > > has not been set from ascii to latin-1 or latin-15. > > Then your program is not very nice...;-) Agreed. I prefer to use explicit str.encode(), str.decode() and unicode() calls where appropriate. On a side note, PEP 263 handles the text encoding interpretation of Python program source, and is well worth reading and following. http://python.org/peps/pep-0263.html -- Craig Ringer From bokr at oz.net Thu Jan 13 03:13:14 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 08:13:14 GMT Subject: finding/replacing a long binary pattern in a .bin file References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> Message-ID: <41e6293f.725257715@news.oz.net> On Thu, 13 Jan 2005 16:51:46 +1000, Stephen Thorne wrote: >On 12 Jan 2005 22:36:54 -0800, yaipa wrote: >> What would be the common sense way of finding a binary pattern in a >> .bin file, say some 200 bytes, and replacing it with an updated pattern >> of the same length at the same offset? >> >> Also, the pattern can occur on any byte boundary in the file, so >> chunking through the code at 16 bytes a frame maybe a problem. The >> file itself isn't so large, maybe 32 kbytes is all and the need for >> speed is not so great, but the need for accuracy in the >> search/replacement is very important. > >Okay, given the requirements. > >f = file('mybinfile') >contents = f.read().replace(oldbinstring, newbinstring) >f.close() >f = file('mybinfile','w') >f.write(contents) >f.close() > >Will do it, and do it accurately. But it will also read the entire >file into memory. > You must be on linux or such, otherwise you would have shown opening the _binary_ files (I assume that's what a .bin file is) with 'rb' and 'wb', IWT. Not sure what system the OP was/is on. BTW, I'm sure you could write a generator that would take a file name and oldbinstring and newbinstring as arguments, and read and yield nice os-file-system-friendly disk-sector-multiple chunks, so you could write fout = open('mynewbinfile', 'wb') for buf in updated_file_stream('myoldbinfile','rb', oldbinstring, newbinstring): fout.write(buf) fout.close() (left as an exercise ;-) (modifying a file "in place" is another exercise) (doing the latter with defined maximum memory buffer usage even when mods increase the length of the file is another ;-) Regards, Bengt Richter From premshree.pillai at gmail.com Wed Jan 5 08:21:22 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Wed, 5 Jan 2005 18:51:22 +0530 Subject: is python more popular than coldfusion? In-Reply-To: <41dbe722$0$23057$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dbe722$0$23057$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: On Wed, 5 Jan 2005 21:09:54 +0800, worzel wrote: > How seriuosly do folk take the TIOBE index? Is it a good way to ague what > you should be keeping up to speed with or just a 'vague' guide? I use the TIOBE index -- sometimes -- when I give presentations on Python (and Ruby) to people who haven't heard of the languages. The index is not something to be relied upon (take a look at the calculation mechanism). However, more often than not, the indices seems to reflect what *I* perceive the indices are in reality. So I kinda use them. The thing about introducing a "new" language to a bunch of folks used to their "favorite" language is that they wouldn't care much for a language it isn't popular, or if it isn't "growing in popularity". Beyond these things, I don't think anybody uses the index. I mean I wouldn't tell people to learn languages that hold the top position on TIOBE ;). > > "Premshree Pillai" wrote in message > news:mailman.189.1104927428.22381.python-list at python.org... > > On Wed, 5 Jan 2005 19:59:21 +0800, worzel wrote: > >> > >> > >> > >> is python more popular than coldfusion? > > > > I don't know if Coldfusion _was_ ever more "popular" than Python, but > > Python is definitely more "popular" _now_. > > > > This might be of some help: http://www.tiobe.com/tpci.htm > > > >> > >> I realsie that is a very general question as one thing does not directly > >> relate to the other. My issue is that I am ditching coldfusion due to > >> there > >> being next to no work for it, and I am thinking of taking on python as a > >> second language to java in the hope of improving my resume. > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > >> > > > > > > -- > > Premshree Pillai > > http://www.livejournal.com/~premshree > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From jerf at jerf.org Sun Jan 9 19:01:55 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 09 Jan 2005 19:01:55 -0500 Subject: Getting rid of "self." References: <1gq4ery.1v79c2t9lsfinN%aleaxit@yahoo.com> <10u2dlj4p45psf0@news.supernews.com> Message-ID: On Mon, 10 Jan 2005 01:51:07 +0100, BJ?rn Lindqvist wrote: > This is promising, I'm content with whatever slowdowns necessary as long > as I can prove those who say "you can't do it" wrong. :) Since I think I'm the only person in this discussion that said anything about what you can't do, be clear on what I said. You can't have both of undeclared attributes on self and no use of "self", in particular to add new attributes. This is, if you take the time to understand what I mean, trivially true; *somewhere* you need to declare whether a var is local to the function or an instance member. For me, I prefer the explicit "self" and getting rid of "self" now leaves you with the need to declare member variables *somehow*, which I don't consider progress. But no matter what other magic Alex works, you're only going to get one or the other; it's impossible for the compiler to divine what you mean otherwise. My point here isn't that you "can't" hack together code to do something like what you want, and it is certainly a valid exercise in plumbing the depths of Python and learning. My point is that you'll have to pay a price in other ways. You can't make self go away "for free". And that "can't" I do mean. (You weren't necessarily claiming you could. But I thought it still worth saying; even if you weren't trying to remove "self" "for free", others certainly would mean it.) From stian at soiland.no Sun Jan 16 16:42:17 2005 From: stian at soiland.no (Stian Soiland) Date: Sun, 16 Jan 2005 22:42:17 +0100 Subject: Why would I get a TypeEror? In-Reply-To: References: <34ql1vF4dqd9pU1@individual.net> Message-ID: <7E2FF4BA-6807-11D9-90E4-000D934525B6@soiland.no> P? 14. jan 2005 kl. 22:58 skrev Steven Bethard: (Any mac users? How do I fix this to appear in Norwegian? =) > Note that if you're not comfortable with short-circuiting behavior, > you can also code this using lazy evaluation: > > (lambda: 1/x, lambda: 1.0e99)[x==0]() .. and people wonder why so many Python people want to get rid of Lambda =) -- Stian S?iland You can't say civilization don't Trondheim, Norway advance, however, for in every war http://www.soiland.no/ they kill you in a new way. [Rogers] =/\= From pdemb at illx.org Thu Jan 6 16:42:01 2005 From: pdemb at illx.org (Peter Dembinski) Date: Thu, 06 Jan 2005 22:42:01 +0100 Subject: [OT] Re: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <86ekh3qv1o.fsf@guru.mired.org> <03mlt0di3rcntvu7rlrk9k2m9bq8435bs5@4ax.com> Message-ID: <87r7kyck0m.fsf_-_@hector.domek> Bulba! writes: [...] > That's remarkable, first time I see smth like this - > out of curiosity, could you say a word where was that? Are you the same Bulba I know from alt.pl.comp.os.hacking? From dave.benjamin at gmail.com Wed Jan 19 10:50:33 2005 From: dave.benjamin at gmail.com (Dave Benjamin) Date: Wed, 19 Jan 2005 08:50:33 -0700 Subject: delay and force in Python In-Reply-To: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Message-ID: Will Stuyvesant wrote: > . def delay(exp): return lambda: exp If you look at the definition of "delay" in SICP, you'll notice that it's defined as "syntax sugar", in other words, a macro. Since Python does not have macros, you'll have to just use "lambda", because by defining "delay" as a function, you're forcing the expression "exp" to evaluate immediately. In other words, theres a crucial difference between:: delay(sys.stdout.write('evaluated\n')) and:: lambda: sys.stdout.write('evaluated\n') If you type in those two snippets, you'll see what I mean. Coincidentally, I attempted a similar experiment just a couple of days ago, and here's what I came up with:: # Stream.py - Stream class inspired by SICP class Stream(object): pass class EndOfStream(Exception): pass class Item(Stream): def __init__(self, current, nextf): self.current = current self.nextf = nextf next = property(lambda self: self.nextf()) def fold(self, f, init): return f(self.current, self.next.fold(f, init)) def __getitem__(self, n): if n == 0: return self.current else: return self.next[n - 1] def __str__(self): return '' % self.current __repr__ = __str__ class End(Stream): def fold(self, f, init): return init def __getitem__(self, n): raise EndOfStream() def _fail(self): raise EndOfStream() current = property(_fail) next = property(_fail) def __str__(self): return '' __repr__ = __str__ Here's how it works:: 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. >>> import Stream >>> s = Stream.Item(1, lambda: Stream.Item(2, lambda: Stream.End())) >>> s >>> s.current 1 >>> s.next >>> s.next.current 2 >>> s.next.next >>> s.next.next.next Traceback (most recent call last): File "", line 1, in ? File "Stream.py", line 37, in _fail raise EndOfStream() Stream.EndOfStream >>> def evens(n=0): ... return Stream.Item(n, lambda: evens(n + 2)) ... >>> s = evens() >>> s.current 0 >>> s.next.current 2 >>> s.next.next.current 4 I don't know if this is useful or not, but it was an interesting exercise nonetheless. Dave From nbbalane at gmail.com Wed Jan 26 02:57:17 2005 From: nbbalane at gmail.com (jrlen balane) Date: Wed, 26 Jan 2005 15:57:17 +0800 Subject: Graph, how to? Message-ID: <2cad20900501252357531a1eb0@mail.gmail.com> i'm going to use now the matplotlib in plotting a graph. i'm currently using python 2.3(enthought edition) on win 2000/xp. i'm using boa constructor on the GUI part. i am using an MDIParentFrame. one of the child frame will be used for the table part. then another child frame will be used to show the graph, how am i going to do this? will i just import the child frame containing the tables and then i'll be able to just get the data from the table and use it to plot a graph? how am i going to assign to a variable each input to the table? can you please show me a sample code to do this? i'm a little lost since i'm a bit new to python. also, how am i going to assign to a variable anything that a user inputs to a wxTxtCtrl? any help would greatly be appreciated. thanks and more power From cr999 at ir.hit.edu.cn Tue Jan 11 05:54:44 2005 From: cr999 at ir.hit.edu.cn (cr999) Date: Tue, 11 Jan 2005 18:54:44 +0800 Subject: "Architecture of Python" was removed ? Message-ID: <004801c4f7cb$f62d1d30$1d02a8c0@cr> I found the "Architecture of Python" ( http://wiki.cs.uiuc.edu/cs427/PYTHON By Jim Jackson, Kar-Han Tan )is very useful for my understanding of the Python's architecture. But I found the link is not link to that document today. It seems that the document was removed. Who knows what happened? Does anyone here have a copy of that document? Or who can tell me what is the email address of Jim Jackson or Kar-Han Tan. Thanks a lot. Best Regards. :) Robert. From smartinham at hotmail.com Thu Jan 27 09:37:36 2005 From: smartinham at hotmail.com (smartin) Date: 27 Jan 2005 06:37:36 -0800 Subject: python IIS cgi working but loading extremely slow Message-ID: <1106836656.699887.286600@c13g2000cwb.googlegroups.com> python IIS cgi loading extremely slow I recently uninstalled python 1.5.2 and installed python 2.3 on a Windows 2000 server running IIS 5.0. The issue is that when submitting a cgi request to a python script, it takes about 1 minute to process the python (2.3 code) and load the page on this particular server. Running a simple "print hi" script takes at least a minute. I have tested the uninstall and reinstall on a test Windows 2000 server and did not have any performance issues. I have tried the uninstall and reinstall twice, including removing all registry entries of the previous 1.5.2 python install. I have reverted back to python 1.52 and my 1.5.2 code and it runs slower than it did before the uninstall but not as slow as the 2.3.4 code. Has anyone every experienced this issue with speed? From bulba at bulba.com Wed Jan 5 21:28:20 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 03:28:20 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: On 04 Jan 2005 19:25:12 -0800, Paul Rubin wrote: >"Rob Emmons" writes: >> Me personally, I believe in free software, but always talk about open >> source. My answer regarding forcing people to share -- I like the GPL >> -- and I am perfectly happy to have anyone who does not like the GPL >> not to use any GPLed software. I don't feel compelled to share. >I'd go further. It's not possible to force anyone to share, but the >GPL aims to remove software from a system that instead aims to force >people NOT to share. Nope. IMHO, GPL attempts to achieve the vendor lock-in. For different purposes than another well-known vendor, but it still does. It's actually even worse: the only thing you can't share on a well-known vendor's platform is the software written by that well-known vendor -- you can choose to share or choose not to share whatever you or other people write on this platform. If GPL folks had their way, it would not be possible not to "share" _anything_ you create. It is widely acknowledged that GPL license has the "viral" aspect of extending itself on your software - can you point to closed-source licenses that would have this aspect? None of the licenses I've read except GPL has this aspect. LGPL is still a different story, though. > As the MPAA knows, people do want to share, and >forcing them not to do so is impossible without turning the world into >a police state. What's the cost of copying music files vs cost of combining some programs together, even in the form of e.g. using an external library? >Maybe if Python were GPL, then Bulba wouldn't use it, >but since it's not GPL, some people find themselves much less willing >to contribute to it than if it were GPL. Personally, I have precisely opposite impression: the OSS licensed with BSD/MIT/Artistic/Python-like license gets contributed to a lot simply because people like to use it and they are not afraid of licensing issues. When people share: _it is not because this or that license of software used by them says so, but because they want to for reasons orthogonal to licensing issues_. >(I myself contribute bug >reports and maybe small patches, but resist larger projects since >there are GPL'd things that I can do instead). So catering to the >wishes of Bulba and Microsoft may actually be impeding Python >development. Yes, there are some people selfless enough to do long >and difficult unpaid software tasks so that Bulba and Bill G can get >richer by stopping people from sharing it, but others of us only want >to do unpaid programming if we can make sure that the results stay >available for sharing. Actually, I get the impression that GPL-ed software is written by programmers for programmers, not really for end users. GPL folks just insulate themselves in their ghetto from the rest of the world. More and more of the successful OSS projects have non-GPLed licenses: Apache, Postgres, Perl, Mozilla, Python. Do you _really_ see few contributions made to those? -- It's a man's life in a Python Programming Association. From news+0409 at henrikholm.com Wed Jan 12 13:17:36 2005 From: news+0409 at henrikholm.com (Henrik Holm) Date: Wed, 12 Jan 2005 12:17:36 -0600 Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> <1105549514.563799.307030@z14g2000cwz.googlegroups.com> Message-ID: <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> John Lenton wrote: > > def dotproduct(a, b): > > psum = 0 > > for i in range(len(a)): > > psum += a[i]*b[i] > > return psum > > for this particular example, the most pythonic way is to do nothing at > all, or, if you must call it dotproduct, > >>> from Numeric import dot as dotproduct Downloading, installing, and getting to know numerical modules for Python is mext on my list :). However, I was under the impression that Numarray is preferred to Numeric -- is that correct? Are these two competing packages? (Hopefully this is not flame war bait...) -- "On some great and glorious day the plain folks of the land will reach in their heart's desire at last and the White House will be adorned by a downright moron." -H.L. Mencken (1880-1956) American Writer From cdavisNOSP at NOSPstaffmail.ed.ac.uk Wed Jan 12 08:30:59 2005 From: cdavisNOSP at NOSPstaffmail.ed.ac.uk (Cory Davis) Date: Wed, 12 Jan 2005 13:30:59 +0000 Subject: distutils linux script installation broken? In-Reply-To: <1105535625.443343.326560@z14g2000cwz.googlegroups.com> References: <1105535625.443343.326560@z14g2000cwz.googlegroups.com> Message-ID: Hi Christopher > distutils should replace that first line with the location of the > binary used to run setup.py. Are you running setup with the following > command line? > > python setup.py install > Yes. A possible complication is that I also have python 2.3.? on that machine, which I am reluctant to remove incase it disturbs my linux distribution (Fedora Core 2). Its also possible that I have done something silly to an environment variable. To check this I will try installing my package either as root or another user. Cheers, Cory. From rkern at ucsd.edu Fri Jan 7 04:43:33 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 07 Jan 2005 01:43:33 -0800 Subject: Excluded and other middles in licensing In-Reply-To: <1gq0jpn.1es49j7jrk3k5N%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> <75r0b2-ohg.ln1@lairds.us> <1gq0jpn.1es49j7jrk3k5N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Robert Kern wrote: > ... > >>>>While most people may not think of such programs as "closed source", >>>>they most definitely ARE: the definition of open source is very strict >>>>about this aspect. > > ... > >>>With my mathematical background, I'm consistent about calling >>>these "non-open" rather than "closed". I don't insist others >>>adopt my nomenclature ... >> >>I'm with Cameron on this one. > > > There is no "official" definition of closed-source as there is of > open-source, but I'm with the Wikipedia: > > http://en.wikipedia.org/wiki/Closed_source > > "any program whose licensing terms do not qualify as open source". A definition with a nice big "This article may need to be reworded to conform to a neutral point of view" warning at the top. ;-) > I'm not disputing it would be useful to draw many distinctions within > the universe of programs with non-opensource licenses, just pointing out > that such distinctions are not currently reflected in a popular > definition. Since it's a wiki, it may be worthwhile editing it to add > some materials to start influencing popular usage and perception, maybe. There seems to be such an edit on the way: http://en.wikipedia.org/wiki/Talk:Closed_source -- 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 marklists at mceahern.com Wed Jan 5 17:42:42 2005 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 05 Jan 2005 16:42:42 -0600 Subject: Building unique comma-delimited list? In-Reply-To: References: Message-ID: <41DC6D62.5010801@mceahern.com> Roy Smith wrote: >You've got a list of words (actually, they're found by searching a >data structure on the fly, but for now let's assume you've got them as >a list). You need to create a comma-delimited list of these words. >There might be duplicates in the original list, which you want to >eliminate in the final list. You don't care what order they're in, >except that there is a distinguised word which must come first if it >appears at all. > >Some examples ("foo" is the distinguised word): > >["foo"] => "foo" >["foo", "bar"] => "foo, bar" >["bar", "foo"] => "foo, bar" >["bar", "foo", "foo", "baz", "bar"] => "foo, bar, baz" or "foo, baz, bar" > >The best I've come up with is the following. Can anybody think of a >simplier way? > > Who knows whether this is "simpler", but it does demonstrate that you can customize the sort of a list: #!/usr/bin/env python def makesorter(first): """Return a sort function that sorts first to the top.""" def sorter(x, y): if x == first: return -1 elif y == first: return 1 else: return 0 return sorter words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] first = 'foo' sorter = makesorter(first) unique = {} for word in words: unique[word] = word keys = unique.keys() keys.sort(sorter) print ', '.join(keys) From hanzspam at yahoo.com.au Thu Jan 13 12:04:35 2005 From: hanzspam at yahoo.com.au (hanz) Date: 13 Jan 2005 09:04:35 -0800 Subject: dynamically inserting function into an object References: Message-ID: <1105634097.319563.156260@c13g2000cwb.googlegroups.com> # class Cell(object): # def __init__(self, initialvalue = 0): # self._func = lambda x: x # self.__value = initialvalue # # def setvalue (self, newvalue): # self.__value = self._func(newvalue) # # def getvalue (self): # return self.__value # # def delvalue (self): # del self.__value # # value = property(getvalue, setvalue, delvalue, "I'm the 'value' property.") # # def curry(self, func, *args): # self._func = lambda x: func(x, *args) From tim.peters at gmail.com Wed Jan 5 14:53:22 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 5 Jan 2005 14:53:22 -0500 Subject: Restore a unified diff In-Reply-To: <86hdlvptpx.fsf@guru.mired.org> References: <86hdlvptpx.fsf@guru.mired.org> Message-ID: <1f7befae05010511536d7d3a7f@mail.gmail.com> [Nick Allen] >>> Unfortunately, restore does not do the same for unified_diff. I do >>> not see any similar function that is intended for unified_diff. >>> Does anyone know how to "restore" from a unified diff generated >>> delta? [Tim Peters] >> That's in general impossible, since unified diffs generally omit >> most lines that compared equal to begin with. Unified and >> context diffs are, in part, compression gimmicks, showing only >> what changed plus a bit of context. ndiff shows everything, so >> can restore everything too. [Mike Meyer] > The unix patch utility seems to do a fine job of handling the unix > unified and context diffs. Of course it does, but "the diff" isn't the only input to `patch`, you also need to give `patch` the original source file (or one closely related to it). `patch` would be deep magic indeed if it could deduce either the "before" or "after" file from a context or unified diff *alone*. But both the "before" and "after" files *can* be deduced from an ndiff diff alone. This remains a truly trivial observation: ndiff can do this because the full text of both input files is part of the output it produces. unified/context diffs cannot generally do this because they don't generally contain the full text of either input file. From michele.simionato at gmail.com Mon Jan 3 09:51:21 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 3 Jan 2005 06:51:21 -0800 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) In-Reply-To: <1104763204.261322.59520@c13g2000cwb.googlegroups.com> References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <87u0py6elt.fsf@sme.intra.citec.fi> <1104763204.261322.59520@c13g2000cwb.googlegroups.com> Message-ID: <1104763881.161544.302910@z14g2000cwz.googlegroups.com> (Not sure if my other message arrived) I am guilty of using this idiom, too. The standard library http://www.python.org/dev/doc/devel/lib/module-sys.html#l2h-396 says: """ __stdin__ __stdout__ __stderr__ These objects contain the original values of stdin, stderr and stdout at the start of the program. They are used during finalization, and could be useful to restore the actual files to known working file objects in case they have been overwritten with a broken object. """ Notice the "during finalization" sentence. Maybe you should change the doc and explain what __stdout__ is intended for? Michele Simionato From skip at pobox.com Thu Jan 27 07:44:56 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 27 Jan 2005 06:44:56 -0600 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: <16888.57928.771177.303998@montanaro.dyndns.org> >> Finally, what if, saints be preserved, your whizbang new module is phr> It is not a whizbang module. It is a stripped-down, basic phr> implementation of a well-accepted set of standards that are being phr> used in thousands of other applications in other languages. Then there should be a library already out there already. All you should need to do is wrap it (manually, with SWIG, whatever). >> included in the core distribution and it's just not as popular as was >> first thought? phr> There is demand for it. Look at how this thread started: some phr> crypto user noticed that rotor was gone and wanted to know what to phr> do instead. Yes, and putting rotor back would be the wrong thing to do. phr> The issue of whether there's enough desire for a crypto module to phr> warrant including one in the stdlib was decided a long time ago. phr> The proof of that somebody decided to accept the rotor module into phr> the distro. No, rotor was added in Python's early days (July 1992). Times have changed. As long as we are discussing cryptography, what's wrong with m2crypto? http://sandbox.rulemaker.net/ngps/m2/ Why not incorporate it into the standard distribution? Or, what about Andrew Kuchling's crypto toolkit? http://www.amk.ca/python/code/crypto.html I believe both have been around awhile. If crypto-in-the-core is really what's needed why not see if one of them is ready to go? phr> The rotor module is gone (and good riddance). That's how this phr> thread started, remember? It shows that bogus modules can be phr> removed. Yeah, but it was there for over 10 years. phr> Have you ever used a crypto library in a serious way? Nope, never directly. Don't make this about me. I'm interested in the Python development process and how you'd like to turn it on its head. >> When it's the category king and there is substantial community >> support for inclusion, phr> It's already the category king, because there are precisely zero phr> other entrants in the category. See my above references. Note, I don't use crypto at all, yet I was aware of both of these (no Googling required). My guess would be they are substantially more mature than your proposed module. phr> I read those as saying that no crypto module will be considered for phr> inclusion whether or not it's the category king, because any such phr> module might conflict with crypto regulations in some countries. That may be a problem, sure. I'm not sure how the discussion here changes that. That's just life as we know it. phr> So tell me again what to do after writing and releasing a C module. phr> There's just no reason to write one, if the module can't go into phr> the stdlib. Why in the heck is inclusion in the standard library a requirement for you to write this thing? If it's useful to you, write it and get on with your life. >> Python is popular in part because of its fairly conservative >> development strategy. That goes for the libraries as well as the >> language itself. phr> Tell me again how rotor got into the distribution. Okay. It was 1992. Bill Clinton had recently been elected president. It was pretty much pre-WWW as we know it. Definitely pre-comp.lang.python and pre-Google (heck, pre-Yahoo, pre-Win98 and pre-Mac OSX as well). Pre-string methods. Pre-triple-quoted strings. Pre-spammers. Pre-DSL. Pre-lots of stuff. There was an Emacs python-mode and s, both thanks to Tim. People opined about Python's performance, just as they do today. Python's version number was around 0.9.4, definitel < 1.0. Guido was the only person with direct repository access. Including something in the distribution was probably the only convenient way to make new modules available. If nothing else, the rotor module (along with anything else included in the distribution back then) may have been a good exercise in and demonstration of writing extension modules, so it probably served a useful non-crypto purpose. Python's user community was probably a few hundred people. Guido likely had no thoughts of world domination with the little language that could. Times have changed. You seem think there was a PEP process and distutils and Wikis. I suspect some of the algorithms one might include in a robust crypto toolkit today weren't even invented in 1992. So throw away the rotor crutch and put your money where your mouth is. Skip From richie at entrian.com Mon Jan 24 07:59:57 2005 From: richie at entrian.com (Richie Hindle) Date: Mon, 24 Jan 2005 12:59:57 +0000 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <1f7befae0501231720428ca3c@mail.gmail.com> References: <41F427EB.3000200@rogers.com> <1f7befae0501231720428ca3c@mail.gmail.com> Message-ID: <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> [Tim] > I'll note that one fairly obvious pattern works very well for weakrefs > and __del__ methods (mutatis mutandis): don't put the __del__ method > in self, put it in a dead-simple object hanging *off* of self. Like > the simple: > > class BTreeCloser: > def __init__(self, btree): > self.btree = btree > > def __del__(self): > if self.btree: > self.btree.close() > self.btree = None > > Then give self an attribute refererring to a BTreeCloser instance, and > keep self's class free of a __del__ method. The operational > definition of "dead simple" is "may or may not be reachable only from > cycles, but is never itself part of a cycle". This is very nice - I've been wondering about just this problem recently, and this will be very useful. Many thanks! One question: why the `self.btree = None` in the last line? Isn't `self.btree` guaranteed to go away at this point anyway? (If the answer is "it's necessary for weird cases that would take an hour to explain" then I'll be more than happy to simply use it. 8-) -- Richie Hindle richie at entrian.com From roy at panix.com Fri Jan 14 18:33:24 2005 From: roy at panix.com (Roy Smith) Date: Fri, 14 Jan 2005 18:33:24 -0500 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: In article <1105569967.129284.85470 at c13g2000cwb.googlegroups.com>, "Chris Lasher" wrote: > Hello, > I have a rather large (100+ MB) FASTA file from which I need to > access records in a random order. The FASTA format is a standard format > for storing molecular biological sequences. Each record contains a > header line for describing the sequence that begins with a '>' > (right-angle bracket) followed by lines that contain the actual > sequence data. Three example FASTA records are below: > > >CW127_A01 > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACAT > >CW127_A02 > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACATTCCGCCTGGGGAGTACGGTCGCAAGATTAAAACTCAAAGGAATAGACGG > >CW127_A03 > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACATTCCGCCTGGG > ... > > Since the file I'm working with contains tens of thousands of these > records, I believe I need to find a way to hash this file such that I > can retrieve the respective sequence more quickly than I could by > parsing through the file request-by-request. First, before embarking on any major project, take a look at http://www.biopython.org/ to at least familiarize yourself with what other people have done in the field. The easiest thing I think would be to use the gdbm module. You can write a simple parser to parse the FASTA file (or, I would imagine, find one already written on biopython), and then store the data in a gdbm map, using the tag lines as the keys and the sequences as the values. Even for a Python neophyte, this should be a pretty simple project. The most complex part might getting the gdbm module built if your copy of Python doesn't already have it, but gdbm is so convenient, it's worth the effort. From tim.peters at gmail.com Fri Jan 14 15:56:40 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 14 Jan 2005 15:56:40 -0500 Subject: Pickled text file causing ValueError (dos/unix issue) In-Reply-To: References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> Message-ID: <1f7befae0501141256755a8b1b@mail.gmail.com> [Tim Peters] >>Yes: regardless of platform, always open files used for pickles >> in binary mode. ... [John Machin] > Tim, the manual as of version 2.4 does _not_ mention the need > to use 'b' on OSes where it makes a difference, not even in the > examples at the end of the chapter. Further, it still refers to > protocol 0 as 'text' in several places. There is also a reference to > protocol 0 files being viewable in a text editor. > > In other words, enough to lead even the most careful Reader of > TFM up the garden path :-) Take the next step: submit a patch with corrected text. I'm not paid to work on the Python docs either <0.5 wink>. (BTW, protocol 0 files are viewable in a text editor regardless, although the line ends may "look funny") From mike at maibaum.org Fri Jan 14 05:02:11 2005 From: mike at maibaum.org (Michael Maibaum) Date: Fri, 14 Jan 2005 02:02:11 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> <1105632841.461042.68310@c13g2000cwb.googlegroups.com> <10udfj4c4rgkvcc@corp.supernews.com> <1105651353.769879.229690@f14g2000cwb.googlegroups.com> <10ue4s49jl8s6d7@corp.supernews.com> Message-ID: <20050114100211.GC75688@remote.gene-hacker.net> On Thu, Jan 13, 2005 at 04:41:45PM -0800, Robert Kern wrote: >Jeff Shannon wrote: > >>(Plus, if this format might be used for RNA sequences as well as DNA >>sequences, you've got at least a fifth base to represent, which means >>you need at least three bits per base, which means only two bases per >>byte (or else base-encodings split across byte-boundaries).... That gets >>ugly real fast.) > >Not to mention all the IUPAC symbols for incompletely specified bases >(e.g. R = A or G). > >http://www.chem.qmul.ac.uk/iubmb/misc/naseq.html Or, for those of us working with proteins as well, all the single letter codes for proteins: http://www.chem.qmul.ac.uk/iupac/AminoAcid/A2021.html lots more bits. I have a db with approx 3 million proteins in it and would not want to be using a pure python approach :) Michael From fuzzyman at gmail.com Wed Jan 5 08:44:03 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2005 05:44:03 -0800 Subject: Reaching the real world In-Reply-To: References: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: <1104932643.699168.75640@c13g2000cwb.googlegroups.com> Thank you very much (to all who replied). There;'s more than enough here to make very good further enquiries. Much appreciated. Fuzzyman http://www.voidspace.org.uk/python/index.shtml From udias at ixi.com Sun Jan 16 11:36:33 2005 From: udias at ixi.com (nell) Date: 16 Jan 2005 08:36:33 -0800 Subject: protecting the python code. In-Reply-To: <41EA92A7.3080706@holdenweb.com> References: <1105884196.461107.28120@z14g2000cwz.googlegroups.com> <41EA92A7.3080706@holdenweb.com> Message-ID: <1105893393.214111.227550@f14g2000cwb.googlegroups.com> Hi Steve, First the "10x in advance" means thanks in advance. The main importance of protecting my code is to save headache of customers that want to be smart and change it and then complain on bugs and problems. 10x From steven.bethard at gmail.com Tue Jan 4 09:22:25 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 04 Jan 2005 14:22:25 GMT Subject: why does UserDict.DictMixin use keys instead of __iter__? In-Reply-To: References: Message-ID: Nick Coghlan wrote: > Steven Bethard wrote: > >> Sorry if this is a repost -- it didn't appear for me the first time. >> >> >> So I was looking at the Language Reference's discussion about emulating >> container types[1], and nowhere in it does it mention that .keys() is >> part of the container protocol. Because of this, I would assume that to >> use UserDict.DictMixin correctly, a class would only need to define >> __getitem__, __setitem__, __delitem__ and __iter__. So why does >> UserDict.DictMixin require keys() to be defined? > > > Because it's a DictMixin, not a ContainerMixin? "Containers usually are sequences (such as lists or tuples) or mappings (like dictionaries)". > .keys() is definitely part of the standard dictionary interface, and not > something the mixin can derive from the generic container methods. Why is that? Isn't keys derivable as: def keys(self): return list(self) if __iter__ is defined? Steve From andy at wild-flower.co.uk Thu Jan 20 13:47:53 2005 From: andy at wild-flower.co.uk (andy) Date: Thu, 20 Jan 2005 18:47:53 +0000 Subject: What's the best python web-developer's editor Message-ID: <41EFFCD9.7060302@wild-flower.co.uk> Anybody like to comment on which editor they use for python web app development - for both discrete and mixed python and html code, and why? I'm comfortable with IDLE (used it for years) but of course it lacks ftp or webDAV abilities, obviously because it's not intended for that type of use. I've had a look at Screem - and that seems to do python syntax highlighting, but it dosn't seem to be python syntax aware (unless there's a hidden option somewhere). Although I can live without auto indent, I'd rather not... I'm sure emacs, xemacs, vi, elvis and so on can do the same, but I have no experience with them for heavy python or html coding, nor the time to trip off down a blind-alley to find out! I know Enough Vi To Get By(tm) but it's by no means my favourite editor. Emacs is a complete mystery to me. I guess I *could* use IDLE and Screem together, but that's a clunky solution! all opinions greatfully received, -andyj From a at b.c Sun Jan 23 02:27:36 2005 From: a at b.c (Doug Holton) Date: Sun, 23 Jan 2005 01:27:36 -0600 Subject: [OT] XML design intent [was Re: What YAML engine do you use?] In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> <41F2C840.2050304@comcast.net> Message-ID: Peter Hansen wrote: > Good question. The point is that an XML document is sometimes > a file, sometimes a record in a relational database, sometimes an > object delivered by an Object Request Broker, and sometimes a > stream of bytes arriving at a network socket. > > These can all be described as "data objects". > """ > > I would ask what part of that, or of the simple phrase > "data object", or even of the basic concept of a markup language, > doesn't cry out "data interchange metalanguage" to you? Actually I don't see any explicit mention that XML was meant to be limited to data interchange only. "data object" has to do with more than data interchange. There is data entry as well. And people are having to hand enter XML files all the time for things like Ant, XHTML, etc. I guess all those people who learned how to write web pages by hand were violating some spec and so they have no cause to complain about any difficulties doing so. Tim Berners-Lee never intended people to have to type in URLs, either, but here we are. From cam.ac.uk at mh391.invalid Sat Jan 15 19:50:01 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 16 Jan 2005 00:50:01 +0000 Subject: deleting from tarfile In-Reply-To: References: Message-ID: Uwe Mayer wrote: > is it possible to delete a file from a tar-archive using the tarfile module? The tarlib.py in pyNMS claims to be able to do it. It doesn't use the tarfile module, though. http://cvs.sourceforge.net/viewcvs.py/pynms/pyNMS/lib/tarlib.py?rev=1.1.1.1&view=auto -- Michael Hoffman From steve at holdenweb.com Fri Jan 14 09:42:03 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 09:42:03 -0500 Subject: [Fwd: Re: Embedding Multiplr Python interpreter in C++] Message-ID: <41E7DA3B.9000005@holdenweb.com> Yogesh Sharma wrote: > one more question to add: > Is there a way to have 2 local copies of python interpreter ? > > Yogesh Sharma wrote: >> Hi, >> >> I have following setup: >> OS Linux Fedora Core 3 >> Python 2.3.4 >> >> How can I embed two python interpreters in one C++ program ? >> >> Thanks > Take a look at mod_python's code: that allows several independent interpreters in the same Apache process using Py_NewInterpreter(), which may well be what you want - initially, see http://www.modpython.org/live/mod_python-3.1.3/doc-html/pyapi-interps.html 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 davidf at sjsoft.com Thu Jan 20 03:04:30 2005 From: davidf at sjsoft.com (David Fraser) Date: Thu, 20 Jan 2005 10:04:30 +0200 Subject: Accessing MDB files on Windows In-Reply-To: <1575169.hWfiKyiV09@strongwill.g2ctech> References: <1635068.ZTfiooUzB4@strongwill.g2ctech> <4262806.PViGKJWPeZ@strongwill.g2ctech> <1575169.hWfiKyiV09@strongwill.g2ctech> Message-ID: Jorge Luiz Godoy Filho wrote: > Jorge Luiz Godoy Filho, Quarta 19 Janeiro 2005 14:25, wrote: > > >>Thanks! I'm looking at it. > > > Worked like a charm! And just now I noticed who's the author of the > recipe ;-) You may also be interested in using a DB-API compatible driver for ADO - see for example http://adodbapi.sourceforge.net/ That way if you want to switch to a different database you can more easily... David From bulba at bulba.com Thu Jan 6 17:41:18 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 23:41:18 +0100 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <344l83F45rstqU1@individual.net> Message-ID: On Thu, 06 Jan 2005 12:20:35 +0100, Stefan Axelsson wrote: >> If GPL folks had their way, it would not be possible not to "share" >> _anything_ you create. It is widely acknowledged that GPL >> license has the "viral" aspect of extending itself on your >> software - can you point to closed-source licenses that would >> have this aspect? None of the licenses I've read except GPL has >> this aspect. >Then you haven't read very many source code licenses, many (perhaps >most?) that state that if you've as much as looked at the code you're >not even allowed to write somethings similar twenty years down the line, >or anything that remotely resembles something similar. I've read Novell license of internal development tools it provides (which I reviewed for some purpose). This is I think relevant part: "Novell grants you a non-exclusive license to use the Software free of charge if (a) you are [...] (b) you are a contracted vendor (c) your use of the Software is for the purpose of evaluating whether to purchase an ongoing license to the Software. [...] You may not: * permit other individuals to use the Software except under the terms listed above; * permit concurrent use of the Software; * modify, translate, reverse engineer, decompile, disassemble (except to the extent applicable laws specifically prohibit such restriction), or create derivative works based on the Software; * copy the Software other than as specified above; * rent, lease, grant a security interest in, or otherwise transfer rights to the Software; or * remove any proprietary notices or labels on the Software. Novell may have patents or pending patent applications, trademarks, copyrights, or other intellectual property rights covering the Software. You are not granted any license to these patents, trademarks, copyrights, or other intellectual property rights except as expressly provided herein. Novell reserves all rights not expressly granted." Other than that, the license had to do only with usual stuff of disclaimers, different jurisdictions, export controls, "US govt restricted rights", etc. Didn't find there anything that forbids me to develop smth similar, unless it's very well hidden in hooking into the technicalities of specific intellecatual property laws. I've also read similar IBM licenses -- granted, not very carefully. The thing that pissed off various bosses most strongly in my impression was that the EULAs typically limited or prohibited transferring the rights to use this thing, e.g. to spin-offs or organizations cooperating with us. It's bothersome in practice. None of that had anything to do with source code or reverse-engineering or developing similar products (if we wanted to develop similar products, we would not be using this thing in the first place, except for 'discovery' purposes). I'm not saying licenses like you claim don't exist. Sure, they may exist and they suck. The point is, they have _limited impact_ and by the very fact of their "exclusion" nature, this aspect tends to repel users than attract them to use this thing. >(Most do in fact >Now, Stallman might or might not want to achieve world domination, not >by sharks with lasers on their heads, but by aiming for all software to >be free software, but the GPL is actually a lot less ambitious than >that. All the GPL says is that: if you received a binary, the person who > provided you with it, must provide you with the source code that built >it. *All* the source code, not just what he happened to receive, on the >off chance that he's modified it. Which I find again wrong: suppose this developer used GPL-ed library A, developed patches B and C. He provided you with the source code of publicly available library A and a patch C, but he doesn't want to release patch B. Now, I know that it would cost you the effort to recreate patch B or maybe it wouldn't work without modifying patch C. But that's an economic concern, which is orthogonal to GPL, as GPL is (supposedly) about "free as in speech, not free as in beer". >And as having the source code without >being able to modify it would be rather pointless, you're allowed to do >that too, it's a given. If you don't want to distribute binaries, that's >fine, and all of the GPL falls. The GPL doesn't *force* you to share >anything. It only says what must happen if you do. True, not directly. However, by attempting to create the context in which it's IMPRACTICAL to use any non-GPLed software, it's attempting to achieve vendor lock-in effect, and while in such situation you FORMALLY would not have to give away, you PRACTICALLY would have to give away. It's not there in license that you "have to give away whatever you create". It's just attempting to create particular _economic_ context with those licenses, just like the licenses and practices of a well-known vendor do, even though that is not spelled out explicitly, obviously. >And I'm rather tired of the GPL's so called 'viral' nature. Look, if >you're using my code, you play by my rules, that's called copyright. Of course. The point is, _what is specific content of those rules_. Python's copyrighted, too: http://www.python.org/2.3.2/license.html And yes, we have to play by those rules, too. That obviously doesn't mean that specific conditions are the same, and those specific conditions are the crux of controversy. > If >you don't want to play by my rules, fine, don't use my code. Do I have to point at who is also attempting to achieve this particular context - "you don't like our licenses, don't use our software"? >So far I'm >no better than Microsoft, or Sun (though that might change) or IBM for >that matter. With the GPL I'm actually not as bad as that, I'll even let >you look at the code, modify it, and distribute copies willy nilly >(though you I'm not forcing you to), in fact, I'll even *forbid* others >from taking that right away from you. If you use it, however, as a small >token of your appreciation, you'll have to also agree to not take the >same rights you had away from others. I don't believe person A automatically has this sort of "right" of reading/using whatever they want. >Finally, what *you* do with *your* code is of no concern to the GPL. As >long as you don't use *my* code you can do whatever you please. But, and >that's a big 'BUT', it really irks me when people release code under >e.g. the BSD (or as has happened to me in the past, public domain), and >then bitch and moan when I incorporate parts of it in *my* software and >release the whole under the GPL. As if that was somehow 'unfair'. In a way, it is: you're taking liberties with their source and use it in a way they did not _intend_ to. Just because this person doesn't lock they house in hope other people will be considerate enough not to rearrange the furniture in it just for fun... Yes, their license _allows it_. So what. > Look, >(and I'm obviously not saying this to the parent poster as he never >expressed any such sentiment, I'm just venting) that's what *you* wanted >when you released the code under that license. If you don't want me to >do that, then don't use those licenses, mkay. Sure, if too many people do that, they will "lock" their house. And only then I think we will be back on the way to the 17th century style "secret science". You're talking about taking the maximum liberties of agreements and situations to achieve ideological goals. I claim that maybe it would be nicer to base this thing on good-willed consensus rather than paranoia and legal technicalities. -- It's a man's life in a Python Programming Association. From ptmcg at austin.rr._bogus_.com Sun Jan 9 22:41:02 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 10 Jan 2005 03:41:02 GMT Subject: Old Paranoia Game in Python References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> <1105318366.966577.107460@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1105318366.966577.107460 at c13g2000cwb.googlegroups.com... > > Aahz wrote: > > Trust the computer, the computer is your friend. > > However, the computer isn't a fuckin' mind reader. > > If you're going to post source code on the usenet, don't > have lines longer than 72 characters. Otherwise you'll > find your code has wrapped lines. This not only causes > syntax errors in your choose and print statements but > also fucks up the formatting of of printed paragraphs. > > Stupid human. > I copy-and-pasted to a file named para1.py, then wrote the following python script with pyparsing to fix the erroneous line breaks. -- Paul =============================== from pyparsing import * extraLineBreak = White(" ",exact=1) + LineEnd().suppress() text = file("para1.py").read() newtext = extraLineBreak.transformString(text) file("para2.py","w").write(newtext) From tim.peters at gmail.com Thu Jan 20 22:52:13 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 20 Jan 2005 22:52:13 -0500 Subject: PyCon Preliminary Program Announced! In-Reply-To: <41F061C3.3000802@gmail.com> References: <20050121000607.DE1261E4010@bag.python.org> <41F061C3.3000802@gmail.com> Message-ID: <1f7befae0501201952139c57a8@mail.gmail.com> [Bryan] > can anyone tell me how the talks work? there are between 9 > and 12 talks for each time slot. do all talks start at the same > time? or are there just four talks at a time and the columns show > what talks are in a given room? The web page needs better formatting. In general, there are no more than 3 presentations going on at any given time, each presentation is scheduled for 30 minutes (including setup time, teardown time, and Q&A time), and all (up to 3) talks in a given time slot begin and end at the same time. All the talks in a given column in a given time block occur in the same room, and these are generally 1.5 hour blocks (so 3 30-minute presentations per block, and up to 3 concurrent blocks). > is it easy to go to the talks you want? I'd say it's impossible when you want to attend two or three presentations occurring at the same time. Otherwise, yes, it's easy -- all the presentation rooms are on the same floor in the same building. The program committee spent a lot of time trying to group "similar" presentations into blocks, so that there's a good chance someone (and especially a "one-issue" person) can sit in the same room for 1.5 hours and hear what they want to hear. That can't work for everyone simultaneously, though, and some amount of room-switching during blocks is unavoidable. I don't care much for "parallel tracks" myself, because I want to hear basically everything. But we had more proposals of higher quality this year than ever before, so it came down to scheduling more talks in parallel than ever before too, or rejecting perfectly good proposals. Because of time constraints, we had to reject some good proposals despite having 3 concurrent presentation tracks, and adding (compared to last year) an additional 6-talk block on Wednesday. It looks to be another great PyCon! From ods at strana.ru Fri Jan 14 09:52:48 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Fri, 14 Jan 2005 17:52:48 +0300 Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <20050114175248.55749afe.ods@strana.ru> On Fri, 14 Jan 2005 11:16:59 +0000 Michael Hoffman wrote: > from socket import gethostbyaddr, herror > > for a in xrange(256): > if a < 666-255*3: > continue > for b in xrange(256): > if a+b < 666-255*2: > continue > for c in xrange(256): > if a+b+c < 666-255: > continue > for d in xrange(256): > if a + b + c + d == 666: Certainly, it can be done more efficient: for a in xrange(256): for b in xrange(max(0, (666-255*2)-a), 256): for c in xrange(max(0, (666-255)-a-b), min(666-a-b+1, 256)): d = 666-a-b-c ... I've checked these IPs with ip2cc (which can miss entries registered last month): there are 2907248 "evil" addresses, most of them (1568430) in USA. Too many to resolve. -- Denis S. Otkidach http://www.python.ru/ [ru] From paschott at no.worldnet.spamm.att.net Mon Jan 17 15:11:52 2005 From: paschott at no.worldnet.spamm.att.net (Peter A. Schott) Date: Mon, 17 Jan 2005 20:11:52 GMT Subject: FTPLIB - retry files? Message-ID: Is there any way to retry sending files with some delay up to a set number on failure? Sometimes we encounter a locked file on our server or the destination server and we want to retry that file in X seconds. Not exactly sure how to go about that right now short of moving the files elsewhere and then queuing them up again. Anyone done this? I'm still kind of new to this so am open to suggestions on how this might be possible as well. Thanks for your help. -Pete Schott From rnd at onego.ru Tue Jan 4 17:20:28 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 5 Jan 2005 01:20:28 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: <41DB11DB.4090805@colorstudy.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> <41DB11DB.4090805@colorstudy.com> Message-ID: On Tue, 4 Jan 2005, Ian Bicking wrote: >Umm... this isn't helpful. "Generic" and "concept" are not terms that >belong to Boost or STL or whatever. They are just words. Coining the >term doesn't mean anyone else knows what it means, nor that anyone >*should* know what they mean -- personally I get very suspicious of >ideas that are based on redefined words, that tends to be a way of >hiding complexity or fuzziness. > >But anyway, if you use these terms, you really must provide references, >otherwise no one will know what you mean. "Python could have honest >support of concepts" is simply an incomplete sentence. "Python could >have honest support of Concepts (url)" would be more reasonable. Sorry. I use definitions from there sources: 1. http://www.cs.rpi.edu/~musser/gp/ 2. "A Formalization of Concepts for Generic Programming" (google could find PDF of that). If I am correct, this one: http://www.osl.iu.edu/publications/pubs/2004/willcock04:_formal_concep_gener_progr.pdf (it is safe to skip till example on Fig.1 to grasp the idea behind a concept. Relations between concepts are also very logical and remind of inheritance, association and aggregation) 3. "The Boost Graph Library" by Jeremy Siek, et al with A.Stepanov's foreword is a good way to see GP != STL. Probably Boost docs contain some knowledge on the topic, at least Boost Graph Library's ones (which I read). >"Python could have honest support of Concepts (url)" - of course, right now those sources are C++-specific. But I could see that Python has even greater potential to have concepts ahead of C++ and with greater usefulness at the same time. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From gabriel.barros at gmail.com Sat Jan 29 13:16:14 2005 From: gabriel.barros at gmail.com (Gabriel B.) Date: Sat, 29 Jan 2005 16:16:14 -0200 Subject: tk global bindings Message-ID: <5175a81c05012910162b5ae608@mail.gmail.com> I'm starting to write a POS application UI's module. There's no mouse, just a bunch of global shortcuts. the problem is that TK doesn't have global shortcuts! Is there a work-around or i will have to attach 80 or so bindings for every input element? Thanks, Gabriel From sizelji at insightbb.com Fri Jan 21 14:51:14 2005 From: sizelji at insightbb.com (Jim Sizelove) Date: Fri, 21 Jan 2005 19:51:14 GMT Subject: Configuring Python for Tk on Mac In-Reply-To: References: Message-ID: Martyn Quick wrote: > On my desk here at work I have a Mac G4 running Mac OS X v10.2.8. > > When I go into a terminal and type "python" up comes a nice python > interface and all seems great. However when I type "import Tkinter" > I'm greeted by the following error. > > >>>>import Tkinter > > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 35, in ? > import _tkinter # If this fails your Python may not be configured > for Tk > ImportError: No module named _tkinter > > So I guess something about this implementation is not appropriately > configured. I'm guessing this is the default behaviour since I don't > think anyone did anything special about python when they set up my > machine. > > What do I do to set it up so I can use Tkinter? > > Thanks... and sorry if this is an FAQ... but I couldn't find the info > easily. > > Yours, > Martyn You probably need to install Tcl/Tk Aqua: http://tcltkaqua.sourceforge.net After downloading and installing on my Mac running OS X v 10.2, I am able to open IDLE and other Tk apps. HTH, Jim Sizelove From flupke at nonexistingdomain.com Thu Jan 13 08:08:33 2005 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 13 Jan 2005 13:08:33 GMT Subject: seperating GUI from other code + reports Message-ID: Hi, i need to develop an app here which will be used to produce stats. I'm going to go with twisted pb for the client server communication. And wxPython for the GUI. Now i would want to split the GUI code from the pb code to make debugging easier amongst other things but i'm not sure how i would best implement the communication of between the GUI and the client. Do i also use pb for it? But then i would end up with the problems that some users have reported here that wxPython and pb have. This would look like this, where GUI and CLIENT are off course on the same machine. GUI pb CLIENT pb SERVER <-----------> <-----------> 1) Any thoughts about this or other methods of doing this or reason why i should not bother with this setup? 2) I will display the results of the query in a list of grid on the client. But then the users are going to want to print the results. Are there any tools that provide a way of printing queries or that provide a mechanism to build reports based on tables? The easiest way i can do it now is to make a html of the results and then opening a browser with that html page using popen. Any other ideas? Thanks, Benedict From bokr at oz.net Tue Jan 11 03:42:39 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 11 Jan 2005 08:42:39 GMT Subject: Writing huge Sets() to disk References: Message-ID: <41e38fd9.554915255@news.oz.net> On Mon, 10 Jan 2005 17:11:09 +0100, =?ISO-8859-2?Q?Martin_MOKREJ=A9?= wrote: >Hi, > I have sets.Set() objects having up to 20E20 items, What notation are you using when you write 20E20? IOW, ISTM 1E9 is a billion. So 20E20 would be 2000 billion billion. Please clarify ;-) >each is composed of up to 20 characters. Keeping >them in memory on !GB machine put's me quickly into swap. >I don't want to use dictionary approach, as I don't see a sense >to store None as a value. The items in a set are unique. > > How can I write them efficiently to disk? To be more exact, >I have 20 sets. _set1 has 1E20 keys of size 1 character. > >alphabet = ('G', 'A', 'V', 'L', 'I', 'P', 'S', 'T', 'C', 'M', 'A', 'Q', 'F', 'Y', 'W', 'K', 'R', 'H', 'D', 'E') >for aa1 in alphabet: > # l = [aa1] > #_set1.add(aa1) > for aa2 in alphabet: > # l.append(aa2) > #_set2.add(''.join(l)) >[cut] > > The reason I went for sets instead of lists is the speed, >availability of unique, common and other methods. >What would you propose as an elegant solution? >Actually, even those nested for loops take ages. :( If you will explain a little what you are doing with these set "items" perhaps someone will think of another way to represent and use your data. Regards, Bengt Richter From abkhd at earth.co.jp Sun Jan 30 17:27:30 2005 From: abkhd at earth.co.jp (A.B., Khalid) Date: 30 Jan 2005 14:27:30 -0800 Subject: pickle, cPickle, & HIGHEST_PROTOCOL Message-ID: <1107124050.160083.129630@f14g2000cwb.googlegroups.com> I wonder if someone can explain what is wrong here. I am pickling a list of dictionaries (see code attached) and unpickling it back using the HIGHEST_PROTOCOL of pickle and cPickle. I am getting an error message and trace backs if the list exceeds eight items. Whether I use pickle or cPickle does not matter, i.e., the eight number causes a problem in both modules, although the trace backs are of course dissimilar. This pickling and unpickling of the list of dictionaries worked when I stopped using the HIGHEST_PROTOCOL in both modules (pickle and cPickle), which got Python to use the ASCII format (I suppose) as I can read the pickled data. This behavior was observed in Python 2.3.4 (final), and 2.4 (final) on Win98. Any comments? Regards, Khalid # Sample program tester.py begin ! ! import pickle as pkl ! import os ! #----------------------------- ! def test_pickle(): ! fn = 'rkeys.txt' ! f = file(fn, 'r') ! lines = f.readlines() ! f.close() ! _test_list = [] ! for line in lines: ! sline = line.split(',') ! #print sline ! key, value = sline[0], sline[1].strip() ! _test_dict = {} ! _test_dict[key] = value ! _test_list.append(_test_dict) ! ! # Let's see the contents of our object ! print _test_list ! ! # Then pickle it ! f = file('pkl_' + fn, 'w') ! pkl.dump(_test_list, f, pkl.HIGHEST_PROTOCOL) ! f.close() ! ! # Empty it ! _test_list = [] ! print _test_list ! ! # Unpickling object here: ! f = file('pkl_' + fn, 'r') ! _test_list = pkl.load(f) ! f.close() ! ! # See contents after loading ! print _test_list !#----------------------------- !if __name__ == '__main__': ! test_pickle() ! !# Sample program end # Contents of file rkeys.txt (without the triple quotes): """ '1','v1' '2','v2' '3','v3' '4','v4' '5','v5' '6','v6' '7','v7' '8','v8' '9','v9' """ # Output (without the triple quotes) # Using "import pickle as pkl": """ [{"'1'": "'v1'"}, {"'2'": "'v2'"}, {"'3'": "'v3'"}, {"'4'": "'v4'"}, {"'5'": "'v5'"}, {"'6'": "'v6'"}, {"'7'": "'v7'"}, {"'8'": "'v8'"}, {"'9'": "'v9'"}] [] !Traceback (most recent call last): ! File "tester.py", line 41, in ? ! test_pickle() ! File "tester.py", line 34, in test_pickle ! _test_list = pkl.load(f) ! File "D:\PY23\PYTHON\DIST\SRC\lib\pickle.py", line 1390, in load ! return Unpickler(file).load() ! File "D:\PY23\PYTHON\DIST\SRC\lib\pickle.py", line 872, in load ! dispatch[key](self) ! File "D:\PY23\PYTHON\DIST\SRC\lib\pickle.py", line 1189, in load_binput ! i = ord(self.read(1)) !TypeError: ord() expected a character, but string of length 0 found """ # Output (without the triple quotes) # Using "import cPickle as pkl": """ [{"'1'": "'v1'"}, {"'2'": "'v2'"}, {"'3'": "'v3'"}, {"'4'": "'v4'"}, {"'5'": "'v5'"}, {"'6'": "'v6'"}, {"'7'": "'v7'"}, {"'8'": "'v8'"}, {"'9'": "'v9'"}] [] !Traceback (most recent call last): ! File "tester.py", line 41, in ? ! test_pickle() ! File "tester.py", line 34, in test_pickle ! _test_list = pkl.load(f) !EOFError """ # Output (without the triple quotes) # Using "import cPickle as pkl", or "import pickle as pkl" # but _not_ using the HIGHEST_PROTOCOL: """ [{"'1'": "'v1'"}, {"'2'": "'v2'"}, {"'3'": "'v3'"}, {"'4'": "'v4'"}, {"'5'": "'v5'"}, {"'6'": "'v6'"}, {"'7'": "'v7'"}, {"'8'": "'v8'"}, {"'9'": "'v9'"}] [] [{"'1'": "'v1'"}, {"'2'": "'v2'"}, {"'3'": "'v3'"}, {"'4'": "'v4'"}, {"'5'": "'v5'"}, {"'6'": "'v6'"}, {"'7'": "'v7'"}, {"'8'": "'v8'"}, {"'9'": "'v9'"}] """ From sam.sherlock at tiscali.co.uk Tue Jan 4 20:12:42 2005 From: sam.sherlock at tiscali.co.uk (Sam) Date: Wed, 05 Jan 2005 01:12:42 +0000 Subject: modpython, apache and windows Message-ID: <41DB3F0A.2010706@tiscali.co.uk> Hi All, I am interested in learning python since I am hearing more and more about python for use in web development I am starting out on python, with knowledge of PHP some perl my current hurdle is setting up either apache 1 or 2 with python 2.3.3 I have installed modpython fine which informed me that I need to make some configuration changes to httpd.conf I have not had it working yet, searches on the web give conflicting suggestions and so far has confused me some forums mention spyce and serving .spy files so far I one explanation worked in that a .py file was parsed but I had to set the name of the actual file within apache.conf this seems strange thanks in advance >> SS -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.298 / Virus Database: 265.6.7 - Release Date: 30/12/2004 From jfj at freemail.gr Thu Jan 27 22:48:35 2005 From: jfj at freemail.gr (jfj) Date: Thu, 27 Jan 2005 19:48:35 -0800 Subject: python memory blow out In-Reply-To: References: <4e4a11f805012617082ebd9b80@mail.gmail.com> Message-ID: <41F9B613.8070608@freemail.gr> Stephen Thorne wrote: > On Thu, 27 Jan 2005 09:08:59 +0800, Simon Wittber > wrote: > >>According to the above post: >> >>>a) If the allocation is > 256 bytes, call the system malloc. >>>b) If the allocation is < 256, use its own malloc implementation, which >>>allocates memory in 256 kB chunks and never releases it. >> >>I imagine this means that large memory allocations are eventually >>released back to the operating system. However, in my case, this >>appears to be not happening. > > > There was a recent patch posted to python-dev list which allows python > to release memory back to the operating system once the 256kb chunk is > no longer used. > The policy is that the memory allocated for those things is as much as the maximum number of them where needed during the program. This is "bad" in rare cases: A program which - at some point, while normally needs 10-20 integers, it peaks its requirements and allocates 10000000 integers. - which does not terminate after that peak but keeps running for a long time without ever needing again many integers. Such programs are rather rare. Moreover, the OS will happily swap out the unused int blocks after a while. A more pathetic situation would be, in the above scenario to release all the 100000000 integers except from every 1000th. Assuming those ints left are accessed frequently, the OS can't even swap out the pages! But such programs, unless intentionally constructed are, **very** rare and it's supposed to be better to have a faster python in the general case. Gerald. From me at privacy.net Sat Jan 1 10:50:05 2005 From: me at privacy.net (Mark Carter) Date: Sat, 01 Jan 2005 15:50:05 +0000 Subject: Which blog tool In-Reply-To: References: <41d6a22f$0$42579$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <41d6c6ad$0$56207$ed2619ec@ptn-nntp-reader02.plus.net> Premshree Pillai wrote: > You can use the Blogger API to post to your Blogger account. There's a > Python interface to the API -- PyBlogger -- available here: > http://beetle.cbtlsl.com/archives/category/pyblogger Hey, it Just Works! I got the whole basic thing working in a few minutes. It was exactly what I was looking for. Thanks for the link. From dbickett at gmail.com Mon Jan 24 00:53:23 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Mon, 24 Jan 2005 00:53:23 -0500 Subject: how to write a tutorial In-Reply-To: <1d6cdae305012321452fb71ca6@mail.gmail.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106531824.833549.28720@c13g2000cwb.googlegroups.com> <1d6cdae305012321452fb71ca6@mail.gmail.com> Message-ID: <1d6cdae3050123215312afc095@mail.gmail.com> Daniel Bickett wrote: > [snip] > You guys are just begging for a YHBT ;-) I apologize, that should have been "we" -- I was criticizing him too. no-one-wants-to-be-a-hypocrite-ly y'rs, Daniel Bickett From pythongnome at hotmail.com Sun Jan 23 17:11:40 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Sun, 23 Jan 2005 22:11:40 GMT Subject: how to write a tutorial In-Reply-To: References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: Daniel Bickett wrote: >>Most texts in computing are written by authors to defend and showcase >>their existence against their peers. > > > When you aren't busy `showcasing' your ignorance, this is *all* i see > in everything you write. Um, maybe that was his point... From ialbert at mailblocks.com Thu Jan 6 16:18:07 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 06 Jan 2005 16:18:07 -0500 Subject: Download .jpg from web In-Reply-To: References: Message-ID: GMane Python wrote: > Using a network camera with built-in webserver The first thing that might be worth investigating is this webserver. What kind of throughput is it capable of? How does it handle repeated requests etc. Your program won't be faster than the server that provides it with the data. Istvan. From bh at intevation.de Sat Jan 29 14:48:12 2005 From: bh at intevation.de (Bernhard Herzog) Date: Sat, 29 Jan 2005 20:48:12 +0100 Subject: limited python virtual machine References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> <16891.41849.882856.527798@montanaro.dyndns.org> <1gr5th5.13asce21fjmj8tN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > OK then -- vars(type(object)) is a dict which has [[the unbound-method > equivalent of]] object.__subclasses__ at its entry for key > '__subclasses__'. Scratch 'vars' in addition to 'getattr'. And 'eval' > of course, or else building up the string 'object.__subclasses__' (in a > way the regex won't catch) then eval'ing it is easy. I dunno, maybe I'm > just being pessimistic, I guess... You can defeat the regexp without any builtin besides object: >>> eval("# coding: utf7\n" "+AG8AYgBqAGUAYwB0AC4AXwBfAHMAdQBiAGMAbABhAHMAcwBlAHMAXwBf-") >>> Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ From bokr at oz.net Wed Jan 26 05:43:53 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 26 Jan 2005 10:43:53 GMT Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> <10vdj4s9ib19fe3@corp.supernews.com> Message-ID: <41f772b2.1858112584@news.oz.net> On Wed, 26 Jan 2005 11:55:59 -0800, jfj wrote: >Jeff Shannon wrote: > >> >> >> So, what problem is it, exactly, that you think you'd solve by making >> tuple slices a view rather than a copy? >> > >I think views are good for > 1) saving memory > 2) saving time (as you don't have to copy the elements into the new tuple) > >And they are worth it. However, (as in other cases with slicing), it is >very easy and fast to create a view for a slice with the default step >'1', while it's a PITA and totally not worth it to create a view for a >slice with non default step. I think it would be good to: > > if slice_step == 1 > create_view > else > create_new_tuple > >Actually, i think that slices with step, is a bad feature in general >and i think I will write a PEP to suggest their removal in python3k. > What's the big deal with other than 1 steps? It is just adjusting a few numbers so that you can either index the new virtual slice with an integer and return the element, in which case the index into the original tuple will be someoffset+i*somefactor once you get past the limit checks for the virtual slice. By the same token, transforming a few numbers of one virtual slice into similar numbers for a a new virtual slice of that shouldn't be rocket science. And it wouldn't have to be done more than once. Don't have time to do it now, but there are plenty around here that could, I'm sure. Regards, Bengt Richter From aleaxit at yahoo.com Wed Jan 5 08:35:38 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 5 Jan 2005 14:35:38 +0100 Subject: Cookbook 2nd ed Credits References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> Message-ID: <1gpx70u.1ug02dpsxhx39N%aleaxit@yahoo.com> Premshree Pillai wrote: > On Wed, 5 Jan 2005 08:55:39 +0100, Alex Martelli wrote: > > Premshree Pillai wrote: > > > Do contributors of less than 5 recipes get a copy too? :-? > > Of course! > > > Btw, is there a comprehensive list of ALL contributors put up anywhere? > > Not yet -- do you think I should put it up on my website? > > If you can, why not! Hmmm, essentially, because the list is *tentative* until the very last minute -- even at proofreading time it's possible, though very unlikely, that we might have to excise a recipe completely. But, as long as this is understood -- I sent both lists (first-authors only, and all-contributions) to Anand Pillai, since he asked in mail, and I gather he'll be putting them up on his site. Alex From duncan.booth at invalid.invalid Wed Jan 26 11:11:29 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Jan 2005 16:11:29 GMT Subject: re.search - just skip it References: <1106754436.876675.144290@c13g2000cwb.googlegroups.com> Message-ID: wrote: > Input is this: > > SET1_S_W CHAR(1) NOT NULL, > SET2_S_W CHAR(1) NOT NULL, > SET3_S_W CHAR(1) NOT NULL, > SET4_S_W CHAR(1) NOT NULL, > ; > > .py says: > > import re, string, sys > s_ora = re.compile('.*S_W.*') > lines = open("y.sql").readlines() > for i in range(len(lines)): > try: > if s_ora.search(lines[i]): del lines[i] > except IndexError: > open("z.sql","w").writelines(lines) > > but output is: > > SET2_S_W CHAR(1) NOT NULL, > SET4_S_W CHAR(1) NOT NULL, > ; > > It should delete every, not every other! No, it should delete every other line since that is what happens if you use an index to iterate over a list while deleting items from the same list. Whenever you delete an item the following items shuffle down and then you increment the loop counter which skips over the next item. The fact that you got an IndexError should have been some sort of clue that your code was going to go wrong. Try one of these: iterate backwards iterate over a copy of the list but delete from the original build a new list containing only those lines you want to keep also, the regex isn't needed here, and you should always close files when finished with them. Something like this should work (untested): s_ora = 'S_W' input = open("y.sql") try: lines = [ line for line in input if s_ora in line ] finally: input.close() output = open("z.sql","w") try: output.write(str.join('', lines)) finally: output.close() From craig at postnewspapers.com.au Fri Jan 7 12:34:18 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 08 Jan 2005 01:34:18 +0800 Subject: how to extract columns like awk $1 $5 In-Reply-To: <41DEC3C4.2030103@abisen.com> References: <41DEC3C4.2030103@abisen.com> Message-ID: <1105119258.30384.54.camel@rasputin.localnet> On Sat, 2005-01-08 at 01:15, Anand S Bisen wrote: > Hi > > Is there a simple way to extract words speerated by a space in python > the way i do it in awk '{print $4 $5}' . I am sure there should be some > but i dont know it. The 'str.split' method is probably what you want: .>>> x = "The confused frog mumbled something about foxes" .>>> x.split() ['The', 'confused', 'frog', 'mumbled', 'something', 'about', 'foxes'] .>>> x.split(" ")[4:6] ['something', 'about'] so if 'x' is your string, the rough equivalent of that awk statement is: .>>> x_words = x.split() .>>> print x_words[4], x_words[5] or perhaps .>>> print "%s %s" % tuple(x.split()[4:6]) -- Craig Ringer From bulba at bulba.com Sat Jan 8 19:34:45 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 09 Jan 2005 01:34:45 +0100 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> Message-ID: <21v0u012jb2lslg0hra6t55virb31r8ta2@4ax.com> On Sat, 08 Jan 2005 08:28:12 GMT, "Roose" wrote: >I am not trying to be insulting... but unless someone would like to educate >me otherwise, the idea of an OS written in Python is almost ludicrous. As I >said, I think you might mean an OS SHELL, which would be a reasonable >(although maybe unconventional) thing to write in python. That's a crazy idea I once had - what if a user could run Python as a shell of Linux/other free U**x, and access every single subsystem and piece of data in the object-like manner? Sure, things like pipes and immediate access to files without having to open() them and the whole filesystem hierarchy would have to be added. Quite a lot of plumbing work would have to be done, but once it were done, it would be like an object operating system, everything organized nicely in predictable object hierarchies with dot access. System scripts would no longer be a mess that breaks every now and then depending on slight differences in filesystem hierarchy. Python dictionaries with their ability to quickly bind names to various objects would make it possible to keep such hierarchy stable, even with data moving around on different physical disk partitions and folders. Instead of saying: # cp /etc/postfix/main.cf /mnt/floppy the user could say e.g. .>>> copy system[config][mta] floppy or .>>> copy system.config.mta floppy In an "object system" like Python it could be reasonable to consider writing a class that would implement at least a subset of generic interface to the equivalent functionalities of various MTAs. Maybe. With traditional filesystems trying smth like that is not really reasonable, because 99% of the time it would work, but 1% of the time it would fail and that 1% would ruin the whole venture, as handling low-level OS complexity for a non-tech user has to be more reliable than that - in two cases when I installed Linux for free for someone the installation was finally deleted by those users because the desktop shortcuts to devices like floppy and CD ultimately failed to work for some reason and using 'mount -t iso9660 ...' was not an option that they would consider learning and using really. Think about all the potential! On top of clean, stable system interface a user could use map, filter and reduce functions on various system objects. Handlers for files with known structure could be written, so dot or list or dictionary access would allow manipulating data inside the files, like file[rownumber]='spam', or spreadsheet_file['A2', 100]. Or you could issue commands like browser.go('somewhere') or desktop.edit('hello.txt'). I was considering writing smth like this myself but it's way over my head re low-level OS and kernel stuff. :-( IMHO Linux problem has long been that in its lower level interface (above kernel and below GUI) is way too much like traditional UNIX. Sure someone with sysadmin experience can use it - but in my experience it's way over the head of the typical user. Trying to teach them about mknod and /dev/* hierarchy is hopeless and too hard for them. -- It's a man's life in a Python Programming Association. From premshree.pillai at gmail.com Sun Jan 30 14:38:19 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Mon, 31 Jan 2005 01:08:19 +0530 Subject: search engine In-Reply-To: <1107112770.301449.49070@c13g2000cwb.googlegroups.com> References: <1107112770.301449.49070@c13g2000cwb.googlegroups.com> Message-ID: On 30 Jan 2005 11:19:30 -0800, jlrodilla at gmail.com wrote: > hi all, i?m doing a search engine using python for the spider and php > to make a web for the search. The Database i have choosen is Just curious: is there any particular reason you want to use PHP for building the web interface? > postgreSQL. Do you think it is a good choosen? Any suggestion? > > if anybody in interested in colaborate please send an e-mail to > jlrodilla at gmail.com > > In a few weeks i will upload all the code to one domain and so i can be > able to send you information about this project. > > The idea is to build a search engine like "google", but my/our search > engine only look for tech pages, i also wants that users can select if > they want to search a web, faqs/howto, manuals/tutorials... > > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From peter at engcorp.com Mon Jan 24 22:05:02 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jan 2005 22:05:02 -0500 Subject: smtplib bug with Windows XP In-Reply-To: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> References: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> Message-ID: stewart.midwinter at gmail.com wrote: > I'm having problem with a script that used to work under Win2k but is > now broken after an install of WinXP Pro. I can no longer connect to a > local mail server. Has anyone else seen this? If so, were you able to > work around it? Here's the traceback (below). The usual first step to troubleshooting such a problem is to use Telnet to connect manually. Type this "telnet 10.50.200.6 25" and see what you get. If it appears correct (it helps to know some of the SMTP protocol: you should get a "220" response here plus the host's name), type "helo blech.org" or something like that to see the response. "Help" is usually a valid command at this point. If you can't do this manually, then smtplib certainly cannot either. > Interestingly, if I > change ports to the POP port 110, I get a different error, but one that > lets me know that I can reach the server. "ping" would let you know you can reach the server as well, but using SMTP to connect to a POP3 server is perhaps a somewhat more complicated and hopeless, but interesting way to do the same thing. >>>>s = smtplib.SMTP('10.50.200.6',25) > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Programs\Python24\Lib\smtplib.py", line 241, in __init__ > (code, msg) = self.connect(host, port) > File "C:\Programs\Python24\Lib\smtplib.py", line 303, in connect > raise socket.error, msg > socket.error: (10053, 'Software caused connection abort') Try manually, but think about these options: a firewall that has suddenly been enabled, an SMTP server that now requires authentication, some kind of proxy like what virus scanners use (though why they would intercept outgoing mail I don't know)... -Peter From steven.bethard at gmail.com Mon Jan 10 16:48:50 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 10 Jan 2005 14:48:50 -0700 Subject: [OT] Re: Old Paranoia Game in Python In-Reply-To: References: <2005010903390916807%spk00@coxnet> Message-ID: Terry Reedy wrote: > Never saw this specific game. Some suggestions on additional factoring out > of duplicate code. > > >>def next_page(this_page): >> print "\n" >> if this_page == 0: >> page = 0 >> return > > > The following elif switch can be replaced by calling a selection from a > list of functions: > > [None, page1, pag2, ... page57][this_page]() > > >> elif this_page == 1: >> page1() >> return >> elif this_page == 2: >> page2() >> return > > ... > >> elif this_page == 57: >> page57() >> return > > > Also, a chose3 function to complement your chose (chose2) function would > avoid repeating the choose-from-3 code used on multiple pages. > > Terry J. Reedy This is what I love about this list. Where else is someone going to look at 1200+ lines of code and give you useful advice?! ;) Very cool. (Thanks Terry!) While we're making suggestions, you might consider writing dice_roll as: def dice_roll(num, sides): return sum(random.randrange(sides) for _ in range(num)) + num for Python 2.4 or def dice_roll(num, sides): return sum([random.randrange(sides) for _ in range(num)]) + num for Python 2.3. You also might consider writing all the pageX methods in a class, so all your globals can be accessed through self, e.g.: class Game(object): def __init__(self): ... self.page = 1 self.computer_request = 0 ... def page2(): print ... if self.computer_request == 1: new_clone(45) else: new_clone(32) ... You could then have your class implement the iteration protocol: def __iter__(self): try: while True: self.old_page = self.page yield getattr(self, "page%i" % page) except AttributeError: raise StopIteration And then your main could look something like: def main(args): ... instructions() more() character() more() for page_func in Game(): page_func() print "-"*79 Anyway, cool stuff. Thanks for sharing! Steve From vze4rx4y at verizon.net Mon Jan 31 19:43:21 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 01 Feb 2005 00:43:21 GMT Subject: set, dict and other structures References: <1107214762.198058.55680@f14g2000cwb.googlegroups.com> Message-ID: > I'm frequently using Py2.4 sets, I find them quite useful, and I like > them, even if they seem a little slower than dicts. Glad to hear that you find them to be a useful abstraction. Since sets are internally implemented as dicts, they should have almost identical performance (net of a small difference for the time to forward the calls). > Sets also need the > same memory of dicts (can they be made to use less memory, not storing > values? Maybe this requires too much code rewriting). Yes, an alternate implementation could be written that would take less memory (by about 1/3) and be a bit faster. The approach would be to copy relevant sections of the dictionary implementation and then remove anything pertaining to dict values. If the need arises and I find the time, this will probably happen someday. In the meantime, the current implementation is rock solid and gives great performance. Have you encountered situations where a 1/3 memory savings and a slight speed improvement would have made a critical difference in a real application? > I presume such sets are like this because they are kind of dicts. If > this is true, then converting a dict to a set (that means converting > just the keys; this is often useful for a successive processing with > set operators like intersection, etc) can be a very quick operation; > but this little code shows me that this isn't true, set-ify a dict is > even slower than doing it on a list. Can this operation made faster (by > people that writes Python interpreter)? Dicts take longer than lists because dict iteration takes longer than for lists. If set-ifying a dictionary turns out to be an essential and time-critical operation, it is possible to add some special case code for this. The question is whether it is worth it. If you find the need is pressing, file a feature request explaining why it is essential. Then, I'll implement it for you. On the other hand, if this is a theoretical nice-to-have, then why clutter up the code (with pre-sizing and forcing all values to True). > I've studied the nice sets python module from Py2.3, and I am... > well... writing something similar, a (python) graph module for sparse > graphs. I've found 3 modules like that around on the Net, but I think > they can be improved (even if I'm not an expert of Python, and I know, > my code is probably quite rough/naive compared to "sets" module one...) > Graphs are complex data structures, so probably one person needs from a > graph data structure are different from other people needs, so it's > probably not easy to define a "standard" graph module fit for everyone. > Still, I think it can be useful to have a standard module to manage > them. > Do you think it be useful to add a (well made) standard module like > that? Start by posting a module outside the standard library; gathering user feedback; and, if popular, propose it for inclusion in the standard library. My guess is that there will be two issues. One is that no one implementation of graphs seems to satisfy all users. The second is that only a small fraction of Python users need for graph support (there is probably a much greater demand for combinatorics, numeric/numarray, or financial modules). If the appeal is not broad, it has little chance of making it into the standard library. Raymond Hettinger From nightmarch at gmail.com Mon Jan 24 22:23:51 2005 From: nightmarch at gmail.com (nightmarch) Date: Tue, 25 Jan 2005 11:23:51 +0800 Subject: Why can't use cursor.nextset() in adodbapi package? In-Reply-To: References: Message-ID: <31d9b15c05012419231edc7646@mail.gmail.com> Thank you Dennis! You mean I should execute many select statement like this " rec = crsr.fetchall() " ? But the result is the same, still got the error like "... 'Current provider does not support returning multiple recordsets from a single execution.'..." On Mon, 24 Jan 2005 17:00:39 GMT, Dennis Lee Bieber wrote: > On Mon, 24 Jan 2005 17:18:05 +0800, nightmarch > declaimed the following in comp.lang.python: > > > >>> sql = "select * from wjtmp" > > >>> crsr.execute(sql) > > >>> rec = crsr.fetchone() > > >>> crsr.nextset() > > > com_error: (-2147352567, '\xb7\xa2\xc9\xfa\xd2\xe2\xcd\xe2\xa1\xa3', > > (0, 'ADODB.Recordset', 'Current provider does not support returning > > multiple recordsets from a single execution.', > > 'C:\\WINNT\\HELP\\ADO210.CHM', 0, -2146825037), None) > > > > > > > > > > Why? > > > > Could it be because you don't have multiple recordsets in crsr? > > You're executing a single select statement, retrieving the > /first/ record from the result, and then trying to get a totally > different result set. > > Maybe you want the next record in the record set you already > have? crsr.fetchnext()? > > > thanks > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < > -- > http://mail.python.org/mailman/listinfo/python-list > From apardon at forel.vub.ac.be Mon Jan 17 04:45:52 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2005 09:45:52 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> Message-ID: Op 2005-01-14, Steve Holden schreef : > Antoon Pardon wrote: > >> Op 2005-01-13, hanz schreef : >> >>>Antoon Pardon wrote: >>> >>>>So if I have a call with an expression that takes more than >>>>one line, I should assign the expression to a variable and >>>>use the variable in the call? >>> >>>Yes, that's sometimes a good practice and can clarify >>>the call. >>> >>> >>>>But wait if I do that, people will tell me how bad that it >>>>is, because it will keep a reference to the value which >>>>will prevent the garbage collector from harvesting this >>>>memory. >>> > Of course, unless that reference is in the global scope of the __main__ > module its lifetime will be transient anyway. If the reference is stored > in a function's local variable then unless its value is returned from > the function it will become available for garbage collection when the > function returns. > >>>Nobody will tell you that it's bad. >> >> >> Sorry, someone already did. If I recall correctly it >> was Alex Martelli. >> > "A foolish consistency is the hobgoblin of little minds". Rules are made > to be broken. Like only use immutables as dictionary keys. > Besides which, if you don't understand the language > environment, rules alone will do you very little good. Try to focus a > little more on principles and a little less on minutiae. And what are the difference between those two? Sometimes I get the impression that everything is a principle until one personnaly finds the need to break it. After that it is a rule. -- Antoon Pardon From limodou at gmail.com Tue Jan 18 23:31:11 2005 From: limodou at gmail.com (limodou) Date: Wed, 19 Jan 2005 12:31:11 +0800 Subject: safest way to kill a thread In-Reply-To: <1106106497.429643.307440@f14g2000cwb.googlegroups.com> References: <1106106497.429643.307440@f14g2000cwb.googlegroups.com> Message-ID: <41EDE28F.1020401@gmail.com> Using Thread's method setDaemon() before you call the start() method. Just like : t.setDaemon(True) t.start() martinnitram at excite.com wrote: > Dear all, > in python, a thread can be created by t = threading.Thread. But i > found that when the main (and the thread) program is running and user > use Crtl+C/Crtl+Z to break the program abnormally, the thread is still > running and needed to kill manually (by the pid). Is there had any > safest way to kill/exit the thread program under python (when the > thread program part is a forever loop)? > > Thank a lot > -- I love python! My Blog: http://www.donews.net/limodou From roy at panix.com Sun Jan 16 19:48:05 2005 From: roy at panix.com (Roy Smith) Date: Sun, 16 Jan 2005 19:48:05 -0500 Subject: List problems in C code ported to Python References: <3SDGd.22010$Z%.6947@fe1.texas.rr.com> Message-ID: "Paul McGuire" wrote: > "A" == 'a' is true in Python, not true in C. It could be true in C, if the string is stored in very low memory :-) From apardon at forel.vub.ac.be Fri Jan 28 10:14:12 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Jan 2005 15:14:12 GMT Subject: How to test that an exception is raised ? References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> <41fa400b$0$2029$6c56d894@feed0.news.be.easynet.net> Message-ID: Op 2005-01-28, StepH schreef : > Thanks for you answer. > I'm new to Python (coming from C/C++). > > Do you say that it's not possible to test (using unittest) if an exception > is well raised if the tested code catch it ? > How to solve this paradoxe ? How to automaticaly test such code ? IMO you want something unittest are not designed for. Unittest are supposed to test for particular results, not for particular behaviour within. If the expected behaviour is that calling code doesn't see an exception raised, then the test passed if no exception was seen. You equally can't test which branch of an if statement was taken or which parameter was given to a helper function in order to get to the desired result. That you internally raise an exception and catches it, is an implementation detail, that normally is of no concern to the tester. -- Antoon Pardon From harold.fellermann at upf.edu Wed Jan 12 13:12:44 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Wed, 12 Jan 2005 19:12:44 +0100 Subject: Why would I get a TypeEror? In-Reply-To: References: Message-ID: <8EA8DF22-64C5-11D9-B3E0-003065FB7B26@upf.edu> On 12.01.2005, at 18:35, It's me wrote: > For this code snip: > > a=3 > .... > b=(1,len(a))[isinstance(a,(list,tuple,dict))] > > Why would I get a TypeError from the len function? because len() works only for sequence and mapping objects: >>> help(len) Help on built-in function len in module __builtin__: len(...) len(object) -> integer Return the number of items of a sequence or mapping. - harold - -- Ceci n'est pas une signature. -- From steve at holdenweb.com Sun Jan 16 12:28:56 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 16 Jan 2005 12:28:56 -0500 Subject: nntplib: abstraction of threads In-Reply-To: References: <1105840367.526347.110160@c13g2000cwb.googlegroups.com> Message-ID: <41EAA458.1020501@holdenweb.com> Werner Amann wrote: > Rakesh schrieb: > > >>What I want is to *group the messages belonging to each thread* . > > > Hello > > Why not sort with Message-ID and References? > Attention - it is a Newbie-Solution. > > import nntplib > > hamster = nntplib.NNTP('127.0.0.1', 119, 'user', 'pass') > resp, count, first, last, name = hamster.group('comp.lang.python') > resp, items = hamster.xover(first,last) > > start_dic = {} > re_dic = {} > numb = 1 > > for id,subject,author,date,message_id,references,size,lines in items: > if 'Re:' not in subject: > start_dic[subject] = (author, message_id) > else: > re_dic[numb] = (subject, author, references) > numb += 1 > > resp = hamster.quit() > > for a in start_dic: > print a > print start_dic[a][0] > for b in re_dic: > if start_dic[a][1] in re_dic[b][2]: > print '|' > print ' ->', re_dic[b][0] > print ' ', re_dic[b][1] > print > Better still, do a Google search on "mail threading algorithm", implement the algorithm described in http://www.jwz.org/doc/threading.html and post your implementation back to the newsgroup :-) 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 lbates at syscononline.com Fri Jan 28 19:45:14 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 28 Jan 2005 18:45:14 -0600 Subject: some kind of LFU dict... In-Reply-To: <63b5e209.0501280739.3887d82@posting.google.com> References: <63b5e209.0501280739.3887d82@posting.google.com> Message-ID: Sounds like you want a database (e.g. on disk storage of keys and values that get accessed via the key). Take a look at one of the databases for storing your key/value pairs. Larry Bates Joh wrote: > Hello, > > (first i'm sorry for my bad english...) > > for a program, i need to have some kind of dictionary which will > contain a huge amount of keys and values. i have tried 'to do it > simple' using a normal dict but when available memory was exhausted, > my computer started to be really slow as it swap-ed. > > so i wondered if i can not use some kind of cache, i googled and found > information on LRU, LFU, and LFU interested me : keep only most > frequently used items inside dict (and memory) and writing others on > disk for a possible future reuse. > > here is a silly attempt to do it, it still missed some features but > before to continue i would like to have your opinions. i'm interested > in any propositions or refactorisations :) and btw i may have missed > others already/tuned/better solutions... > > best. > > --- > > import fileinput, pickle, random, shutil, sys > > class sLFU: > TMP = """%s.bak""" > """ a simple kind of Least Frequently Used container""" > def __init__(self, size, ratio, filename = None): > """ filename = a temporary file which will could be deleted""" > self.d = {} # container > self.size, self.ratio = size, ratio > self.freqs, self.fmin = {}, 0 > self.filename = filename > if self.filename: open(self.filename, 'w') > def __setitem__(self, obj, v): > self.d[obj] = v > self.freqs[obj] = self.freqs.get(obj, self.fmin) + 1 > if len(self.d) > self.size: > """ lfu = { (size / ratio) least frequently used > objects... }""" > freqs = [(f, obj) for (obj, f) in self.freqs.items()] > # maybe should i use a generator () like > # ((f, obj) for (obj, f) in self.freqs.items()) > freqs.sort() > lfu = {} > # and here enumerate(sorted(freqs)) > for i, (f, obj) in enumerate(freqs): > if i > self.size / self.ratio: > break > lfu[obj] = self.d[obj] > """ next minimal frequency will be max frequency of the > lfu > (maybe it would be better to substract this from others in > self.freqs)""" > self.fmin = f > """ and now delete theses objects...""" > for obj in lfu: > del self.freqs[obj] > del self.d[obj] > if self.filename: > """ now must save lfu to disk... > as i do not managed to do otherwise, copy file to a > tmp > file and read it line by line, updating when > necessary... > there must be plenty rooms for improvement here :(""" > shutil.copy(self.filename, self.TMP % self.filename) > fhs = open(self.TMP % self.filename) > fh = open(self.filename, 'w') > """ flag to ignore 'value' line""" > ignoreNext = False > for i, line in enumerate(fhs): > """ first copy old lfu which were already set, > updating > them if necessary...""" > if ignoreNext: > ignoreNext = False > continue > line = line.rstrip() > if i % 2 == 0: > obj = self.loads(line) > if obj not in lfu and obj in self.d: > """ obj available from memory, do not to > keep it on disk...""" > ignoreNext = True > continue > elif obj in lfu: > """ obj was available from memory, but as > a lfu, > was removed and must be updated on disk""" > fh.write("%s\n" % line) > fh.write("%s\n" % self.dumps(lfu[obj])) > del lfu[obj] > ignoreNext = True > continue > """ default behaviour : copy line...""" > fh.write("%s\n" % line) > """ from now lfu should contain only unseen lfu > objects, > add them to file...""" > fh = open(self.filename, 'a') > for obj in lfu: > fh.write("%s\n" % self.dumps(obj)) > fh.write("%s\n" % self.dumps(lfu[obj])) > def __getitem__(self, obj): > if obj in self.d: > """ from memory :)""" > return self.d[obj] > if self.filename: > """ if a filename was provided, search inside file if > such an obj is present, then return it ; else raise > IndexErrror.""" > fh = open(self.filename) > found = False > for i, line in enumerate(fh): > line = line.rstrip() > if found: > v = self.loads(line) > self.d[obj] = v > self.freqs[obj] = self.fmin + 1 > return v > if obj == self.loads(line): > found = True > raise KeyError(obj) > """ maybe class methods would have been better here, > actually i would have liked static + class... > totally arbitrary format, haved choosed to use pickle, > odd line contain 'obj' > (next) even line contain 'value' > """ > def dumps(self, s): > return pickle.dumps(s).replace("\n", "\t") > staticmethod(dumps) > def loads(self, s): > return pickle.loads(s.replace("\t", "\n")) > staticmethod(loads) > > > > lfu = sLFU(2, 2, 'slfu.txt') > lfu[1] > 8 > = {'1': > 1fd2 > 'a'} > lfu[2] = [] > lfu[3] = '3' > lfu[2] = [1,] > lfu[2] = [1,2] > lfu[4] = 4 > lfu[5] = '5' > > print "#d", len(lfu.d) > print lfu.d > print "".join(open(lfu.filename).readlines()) From jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com Sun Jan 2 10:57:43 2005 From: jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com (Miklós P) Date: Sun, 2 Jan 2005 16:57:43 +0100 Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: "Erik Bethke" wrote: > Hello Everyone, > > I have to say: > > Python! Is! Truly! Amazing! > > So I started with python about a month ago and put in 24 hours across > three weekends. ... > > Truly thank you. > > -Erik > I enjoyed to read about your enthusiasm about Python you have recently discovered. :) After checking out your personal and business site, I'm sure you'll be even more pleased when Python will be an essential component in your business and, say, GoPets take on a bit of snake-like inner working. :-) Best, Mikl?s --- Jegenye 2001 Bt. Egyedi szoftverk?sz?t?s, tan?csad?s | Custom software development, consulting Magyarul: http://jegenye2001.parkhosting.com In English: http://jegenye2001.parkhosting.com/en From jerf at jerf.org Fri Jan 21 08:46:18 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 21 Jan 2005 08:46:18 -0500 Subject: Dynamic properties References: Message-ID: On Fri, 21 Jan 2005 23:27:28 +0800, Craig Ringer wrote: > The chances are that whatever you want to do with dynamically created > properties is better done with __getattr__ and __setattr__ instead. Rather than post my own comment, I'd like to highlight this, emphasize it, and underline it twice. The two other repliers I see were nice to explain how to do what you were trying to do, but you probably shouldn't do it that way. class DictWrap(object): def __init__(self, dictToWrap): self.__dict__['dictToWrap'] = dictToWrap def __getattr__(self, key): return self.__dict__['dictToWrap'][key] def __setattr__(self, key, value): self.__dict__['dictToWrap'][key] = value def __delattr__(self, key): del self.__dict__['dictToWrap'][key] Note the direct use of __dict__, which bypasses the *attr machinery. This implements a "full" dict wrap; adjust as needed. Be sure to read about *attr in the Python manual so you understand what they do. You can do more in getattr if you want, but it doesn't sound like you want much else. Python 2.3.4 (#1, Oct 26 2004, 20:13:42) [GCC 3.4.2 (Gentoo Linux 3.4.2-r2, ssp-3.4.1-1, pie-8.7.6.5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class DictWrap(object): ... def __init__(self, dictToWrap): ... self.__dict__['dictToWrap'] = dictToWrap ... def __getattr__(self, key): ... return self.__dict__['dictToWrap'][key] ... def __setattr__(self, key, value): ... self.__dict__['dictToWrap'][key] = value ... def __delattr__(self, key): ... del self.__dict__['dictToWrap'][key] ... >>> a = {'LV1': .5, 'LV10': 5, 'LV100': 50} >>> d = DictWrap(a) >>> d.LV1 0.5 >>> d.LV1 = "Hello!" >>> d.LV5 = 2.5 >>> d.__dict__ {'dictToWrap': {'LV5': 2.5, 'LV10': 5, 'LV100': 50, 'LV1': 'Hello!'}} >>> del d.LV100 >>> d.__dict__ {'dictToWrap': {'LV5': 2.5, 'LV10': 5, 'LV1': 'Hello!'}} >>> From 2004b at usenet.alexanderweb.de Wed Jan 26 11:18:59 2005 From: 2004b at usenet.alexanderweb.de (Alexander Schremmer) Date: Wed, 26 Jan 2005 17:18:59 +0100 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> Message-ID: <1a72l6umj80r6.dlg@usenet.alexanderweb.de> On Tue, 25 Jan 2005 22:08:01 +0100, I wrote: >>>> sys.safecall(func, maxcycles=1000) > could enter the safe mode and call the func. This might be even enhanced like this: >>> import sys >>> sys.safecall(func, maxcycles=1000, allowed_domains=['file-IO', 'net-IO', 'devices', 'gui'], allowed_modules=['_sre']) Every access to objects that are not in the specified domains are restricted by the interpreter. Additionally, external modules (which are expected to be not "decorated" by those security checks) have to be in the modules whitelist to work flawlessy (i.e. not generate exceptions). Any comments about this from someone who already hacked CPython? Kind regards, Alexander From sjmachin at lexicon.net Sat Jan 15 19:34:00 2005 From: sjmachin at lexicon.net (John Machin) Date: 15 Jan 2005 16:34:00 -0800 Subject: How to del item of a list in loop? In-Reply-To: References: Message-ID: <1105835640.771989.163400@f14g2000cwb.googlegroups.com> Fredrik Lundh wrote: > > lst = [i for i in lst if i != 2] > > (if you have 2.4, try replacing [] with () and see what happens) The result is a generator with a name ("lst") that's rather misleading in the context. Achieving the same result as the list comprehension, by doing lst = list(i for ... etc etc), appears to be slower. From http Sat Jan 22 12:09:38 2005 From: http (Paul Rubin) Date: 22 Jan 2005 09:09:38 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <7xu0p9lk4h.fsf@ruckus.brouhaha.com> Message-ID: <7x8y6l8k6l.fsf@ruckus.brouhaha.com> "Andrew Koenig" writes: > In this case, I think the right solution to the problem is two-fold: > > 1) from __future__ import lexical_comprehensions > > 2) If you don't import the feature, and you write a program that depends > on a list-comprehension variable remaining in scope, the compiler > should issue a diagnostic along the lines of > > Warning: This program should be taken out and shot. It's not obvious to me how the compiler can tell. Consider: x = 3 if frob(): frobbed = True squares = [x*x for x in range(9)] if blob(): z = x Should the compiler issue a warning saying the program should be taken out and shot? With lexical comprehensions, the program is perfectly valid and sets z to 3 if blob() is true. The whole point of lexical comprhensions is to make Python safe for such programs. Without lexical comprehensions, the program still doesn't depend on the listcomp leakage if frob() and blob() aren't simultaneously true (envision "assert not frobbed" before the "z = x"). So "should be taken out and shot" is maybe a little bit extreme. From chris.cavalaria at free.fr Fri Jan 28 18:19:18 2005 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Sat, 29 Jan 2005 00:19:18 +0100 Subject: Daylight savings and getmtime References: <8b2d5523.0501281503.253269@posting.google.com> Message-ID: <35vvjmF4sbe8jU1@individual.net> Qvx wrote: > Hello, > > I'we written a simple web deployment program which scans for the > changes made to local copy of web site. Changed files are than > packaged into a zip file and deployed to web server. > > Now here's the catch. Changes are computed using (1) log file from the > last deployment and (2) local file system. Log file contains > datestamps (integers) returned from os.path.getmtime(f) function at > the time of last deployment. So i'm comparing two getmtime() values. > The problem is when Daylight saving kicks in: suddenly all local files > are reported as older than they were at the time of deployment. > > How do I compensate for this? > > Thanks, > Tvrtko Never use the local time, always use GMT ( UTC ) time instead. Since it seems os.path.getmtime already gives UTC time, onemust wonder if your OS isn't broken in some way ;) If you can't solve that problem, then use a simple md5sum of the files instead. md5sum isn't that slow to compute and it gives better results than timestanps. Or use a specialised tool like rsync which does a very good job for that. From ville at spammers.com Wed Jan 5 10:02:05 2005 From: ville at spammers.com (Ville Vainio) Date: 05 Jan 2005 17:02:05 +0200 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "Paul" == Paul Rubin writes: Paul> Ville Vainio writes: >> To me, this seems to be the job for the Fedora maintainers, not >> Python maintainers. If something essential is not in the distro >> the distro maintainers have screwed up. Paul> I can't parse that. It says two contradictory things. Paul> Sentence 2 says that if something essential is not in the Paul> (Python) distro then the (Python) distro maintainers have Paul> screwed up. Sentence 1 says it's the Fedora maintainer's Paul> job to deal with it. Huh? By "distro" I meant the Linux distribution, not the Python distribution. Distro is a customary term for a Linux distribution so I didn't qualify the word at the time. -- Ville Vainio http://tinyurl.com/2prnb From peter at engcorp.com Mon Jan 3 17:03:12 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Jan 2005 17:03:12 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><7xmzvu1ycn.fsf@ruckus.brouhaha.com><7xd5wqd14y.fsf@ruckus.brouhaha.com><7xfz1lal5d.fsf@ruckus.brouhaha.com><7xekh423b6.fsf@ruckus.brouhaha.com> <_rTBd.66275$Jk5.46@lakeread01> Message-ID: Steve Holden wrote: > Whereas the bleached bones of the failed open source projects are > visible for all to see on the SourceForge beach. It occurs to me that the value of those projects can be judged in a number of ways. One of them is in how much those involved in the projects have learned from the experience. Perhaps one rarely starts a second open source project with quite as much rabid, unthinking enthusiasm as one did the first time around, and maybe the world is a better place for it. I know that I've started many one-man projects over the years, and only slowly (I'm a little thick, you see) came to realize that while it's incredibly easy to start something, seeing it through to the end is rather more difficult. At this point, perhaps largely as a result of a new world-view inspired by the agile movement, I rarely start anything... and when I do, it's driven by a strong, recurring need, and I only do just enough to meet that need, in the simplest way I can find. (Often, that ends up not involving a computer.) -Peter From francis.girard at free.fr Fri Jan 21 10:54:52 2005 From: francis.girard at free.fr (Francis Girard) Date: Fri, 21 Jan 2005 16:54:52 +0100 Subject: need help on generator... In-Reply-To: <1106320014.19065.14.camel@bucket.localnet> References: <63b5e209.0501210558.686f5c10@posting.google.com> <1106318290.19065.11.camel@bucket.localnet> <1106320014.19065.14.camel@bucket.localnet> Message-ID: <200501211654.52900.francis.girard@free.fr> Le vendredi 21 Janvier 2005 16:06, Craig Ringer a ?crit?: > On Fri, 2005-01-21 at 22:38 +0800, Craig Ringer wrote: > > consecutive_sets = ( x[offset:offset+subset_size] > > for subset_size in xrange(2, len(x)) > > for offset in xrange(0, len(x) + 1 - subset_size) ) > > Where 'x' is list to operate on, as I should've initially noted. Sorry > for the reply-to-self. > > I did say "awful" for a reason ;-) > > -- > Craig Ringer First, I think that you mean : consecutive_sets = [ x[offset:offset+subset_size] for subset_size in xrange(2, len(x)) for offset in xrange(0, len(x) + 1 - subset_size)] (with square brackets). Second, this is not lazy anymore (like Denis S. Otkidach previous answer was) because the __whole__ list get constructed __before__ any other piece of code have a chance to execute. The type of consecutive_sets is simply a list, not a generator. I'm just trying to understand and obviously I'm missing the point. Thank you Francis Girard FRANCE From steve at holdenweb.com Mon Jan 31 15:35:57 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 15:35:57 -0500 Subject: python and gpl In-Reply-To: <804tv01vej83hm602acfoh291fobov5l4a@4ax.com> References: <7xmzuqgmv6.fsf@ruckus.brouhaha.com> <804tv01vej83hm602acfoh291fobov5l4a@4ax.com> Message-ID: <41FE96AD.5040000@holdenweb.com> Scott Robinson wrote: > On 30 Jan 2005 21:59:25 -0800, Paul Rubin > wrote: > > >>John Hunter writes: >> >>>The question is: does shipping a backend which imports a module that >>>links with GPL code make some or all of the library GPL. >> >>Literally speaking, no, not automatically, any more than driving a car >>makes you into a licensed driver if you weren't one already. But if >>you weren't licensed, then you've broken the law by driving the car. >>So your question should be: 1) is shipping that backend one of the >>things you need the GPL to license you to legally do, and 2) if so, >>does the GPL in fact give you that license? >> >>If you're asking in terms of legal enforcement, the answer is 1) maybe >>and 2) almost certainly not. I think it's better to ask in terms of >>the GPL's spirit. I would say that it's not in the GPL's spirit and >>that GPL die-hards would consider that use objectionable, though they >>might make exceptions for specific cases (so it doesn't hurt to ask). >>Some authors who use the GPL are less strict about how they interpret >>it, so again, the friendly thing to do is ask the author. >> >> * If a backend module somebackend does >> >> import somelib >> >> where somelib is a python wrapper of GPL code, is somebackend GPLd? >> >>It's GPL'd if you GPL it. If you don't GPL it, then distributing it >>it may be a GPL violation that could get you taken to court. I >>believe the FSF's view is that it is fact a violation; however, the >>courts have not yet established this. The law doesn't have a >>black-and-white boundary. It's more like a fractal. The only way to >>find out what a court will decide is to actually try a case there. >> >>Rather than try to probe how closely you can dance around the >>boundaries of the GPL, you might just ask the author of the GPL'd >>library whether what you want to do is ok with him or her. If s/he >>says no and you do it anyway, you're both inviting trouble over the >>possible infringement, and also inviting people to try to use your >>code in ways you don't like. Since the free software movement depends >>on a spirit of cooperation, I think it's best to avoid trying to press >>too hard against the boundaries of anyone's licenses. >> >>http://www.gnu.org/licenses/gpl-faq.html > > > If you read the GPL, it claims everything it can (any "work" created > using GPLed "work"). My guess is that anything that calls the code in > a way not specifically allowed by the author is going to get you into > trouble. IANAL, but from what I can remember about earlier licensing > issues, any code specific for a GPLed library (especially "import") > will get you into to trouble. Having a non-free library with an > identical API and issuing > exec("import "+sys.argv[1]) > where the user can supply sys.argv as the name of the gpl'ed library > will work (I think there is a free/non-free library out there that is > never run, but exists for exactly this condition). > > Scott Robinson > I presume the appropriate way to answer this question is to ask the Gnu, since under these circumstances the Python zen would advise "refuse the temptation to guess". So I am Cc'ing gnu at gnu.org with a request for an answer to the (apparently relatively simple) question: If a Python program imports a module licensed under the GPL, in your opinion does the Python program become a derivative work of the GPL'd software? 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 bokr at oz.net Thu Jan 6 16:09:45 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 06 Jan 2005 21:09:45 GMT Subject: Other notes References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> <41DD40F1.5030301@holdenweb.com> Message-ID: <41dda7c5.167823026@news.oz.net> On Thu, 06 Jan 2005 19:24:52 GMT, Andrew Dalke wrote: >Me >>>>> (BTW, it needs to be 1 .. 12 not 1..12 because 1. will be interpreted >>>>> as the floating point value "1.0".)< > >Steve Holden: >> Indeed, but if ".." is defined as an acceptable token then there's >> nothing to stop a strict LL(1) parser from disambiguating the cases in >> question. "Token" is not the same thing as "character". > >Python's tokenizer is greedy and doesn't take part in the >lookahead. When it sees 1..12 the longest match is for "1." > But it does look ahead to recognize += (i.e., it doesn't generate two successive also-legal tokens of '+' and '=') so it seems it should be a simple fix. >>> for t in tokenize.generate_tokens(StringIO.StringIO('a=b+c; a+=2; x..y').readline):print t ... (1, 'a', (1, 0), (1, 1), 'a=b+c; a+=2; x..y') (51, '=', (1, 1), (1, 2), 'a=b+c; a+=2; x..y') (1, 'b', (1, 2), (1, 3), 'a=b+c; a+=2; x..y') (51, '+', (1, 3), (1, 4), 'a=b+c; a+=2; x..y') (1, 'c', (1, 4), (1, 5), 'a=b+c; a+=2; x..y') (51, ';', (1, 5), (1, 6), 'a=b+c; a+=2; x..y') (1, 'a', (1, 7), (1, 8), 'a=b+c; a+=2; x..y') (51, '+=', (1, 8), (1, 10), 'a=b+c; a+=2; x..y') (2, '2', (1, 10), (1, 11), 'a=b+c; a+=2; x..y') (51, ';', (1, 11), (1, 12), 'a=b+c; a+=2; x..y') (1, 'x', (1, 13), (1, 14), 'a=b+c; a+=2; x..y') (51, '.', (1, 14), (1, 15), 'a=b+c; a+=2; x..y') (51, '.', (1, 15), (1, 16), 'a=b+c; a+=2; x..y') (1, 'y', (1, 16), (1, 17), 'a=b+c; a+=2; x..y') (0, '', (2, 0), (2, 0), '') Regards, Bengt Richter From tanghaibao at gmail.com Fri Jan 7 15:37:43 2005 From: tanghaibao at gmail.com (Haibao Tang) Date: 7 Jan 2005 12:37:43 -0800 Subject: Display Function Code Body? Message-ID: <1105130263.788520.96710@f14g2000cwb.googlegroups.com> Hail Python pals! I played with the R (http://r-project.cran.org) last night to do some statistics and it has an interactive session too, and I found a feature that is quite useful. I found by actually typing a function name, the R gives you a code body output. > f1 = function(x){x*x} > f1 function(x){x*x} # more examples (you can try some) > sd function (x, na.rm = FALSE) { if (is.matrix(x)) apply(x, 2, sd, na.rm = na.rm) else if (is.vector(x)) sqrt(var(x, na.rm = na.rm)) else if (is.data.frame(x)) sapply(x, sd, na.rm = na.rm) else sqrt(var(as.vector(x), na.rm = na.rm)) } # ------------------------------------------------ While our python gives an output which is more pro but less informational. >>> def f1(x):return x*x >>> f1 What I would like to do is to write a function like disp(), when typed, it can give you the code infomation. >>> disp(f1) def f1(x): return x*x # or any shallow function code from a file >>> import calendar; disp(calendar.isleap) def isleap(year): """Return 1 for leap years, 0 for non-leap years.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) # surely the compiled function code cannot be displayed >>> disp(blabla) : internal/compiled function Can someone please point out how this can be achieved nicely. I've tried some text searching approach, too dirty I must say. Oh! Thank you ... Haibao Tang From http Mon Jan 10 19:30:21 2005 From: http (Paul Rubin) Date: 10 Jan 2005 16:30:21 -0800 Subject: Writing huge Sets() to disk References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> Message-ID: <7xmzvgren6.fsf@ruckus.brouhaha.com> Martin MOKREJ? writes: > >> I have sets.Set() objects having up to 20E20 items, > just imagine, you want to compare how many words are in English, German, > Czech, Polish disctionary. You collect words from every language and record > them in dict or Set, as you wish. > > Once you have those Set's or dict's for those 4 languages, you ask > for common words and for those unique to Polish. I have no estimates > of real-world numbers, but we might be in range of 1E6 or 1E8? > I believe in any case, huge. They'll be less than 1e6 and so not huge by the standards of today's computers. You could use ordinary dicts or sets. 1e20 is another matter. I doubt that there are any computers in the world with that much storage. How big is your dataset REALLY? > I wanted to be able to get a list of words NOT found in say Polish, > and therefore wanted to have a list of all, theoretically existing words. > In principle, I can drop this idea of having ideal, theoretical lexicon. > But have to store those real-world dictionaries anyway to hard drive. One way you could do it is by dumping all the words sequentially to disk, then sorting the resulting disk file using an O(n log n) offline algorithm. Basically data sets of this size are outside of what you can easily handle with builtin Python operations without putting some thought into algorithms and data structures. From "ribosome" I'm guessing you're doing computational biology. If you're going to be writing code for these kinds of problems on a regular basis, you probably ought to read a book or two on the topic. "CLRS" is a good choice: http://theory.lcs.mit.edu/~clr/ http://mitpress.mit.edu/algorithms/ From whereU at now.com Mon Jan 3 02:59:53 2005 From: whereU at now.com (Eric Pederson) Date: Sun, 2 Jan 2005 23:59:53 -0800 Subject: The Industry choice In-Reply-To: <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Message-ID: <20050102235953.1631636599.whereU@now.com> Alex Martelli commented: > It's not just _foreign_ companies -- regional clustering of all kinds > of > business activities is a much more widespread phenomenon. Although I'm > not sure he was the first to research the subject, Tjalling Koopmans, > as > part of his lifework on normative economics for which he won the Nobel > Prize 30 years ago, published a crucial essay on the subject about 50 > years ago (sorry, can't recall the exact date!) focusing on > _indivisibilities_, leading for example to transportation costs, and to > increasing returns with increasing scale. Today, Paul Krugman is > probably the best-known name in this specific field (he's also a > well-known popularizer and polemist, but his specifically-scientific > work in economics has mostly remained in this field). > > > China right now)? According to standard economics it should > > not happen - what's the point of getting into this overpriced > > city if elsewhere in this country you can find just as good > > conditions for business. > > Because you can't. "Standard" economics, in the sense of what you > might > have studied in college 25 years ago if that was your major, is quite > able to account for that if you treat spatial variables as exogenous to > the model; Krugman's breakthroughs (and most following work, from what > I > can tell -- but economics is just a hobby for me, so I hardly have time > to keep up with the literature, sigh!) have to do with making them > endogenous. > > Exogenous is fine if you're looking at the decision a single firm, the > N+1 - th to set up shop in (say) a city, faces, given decisions already > taken by other N firms in the same sector. > > The firm's production processes have inputs and outputs, coming from > other firms and (generally, with the exception of the last "layer" of > retailers etc) going to other firms. Say that the main potential > buyers > for your firm's products are firms X, Y and Z, whose locations all > "happen to be" (that's the "exogenous" part) in the Q quarter of town. > So, all your competitors have their locations in or near Q, too. Where > are you going to set up your location? Rents are higher in Q than > somewhere out in the boondocks -- but being in Q has obvious > advantages: > your salespeople will be very well-placed to shuttle between X, Y, Z > and > your offices, often with your designers along so they can impress the > buyers or get their specs for competitive bidding, etc, etc. At some > points, the competition for rents in quarter Q will start driving some > experimenters elsewhere, but they may not necessarily thrive in those > other locations. If, whatever industry you're in, you can strongly > benefit from working closely with customers, then quarter Q will be > where many firms making the same products end up (supply-side > clustering). > > Now consider a new company Z set up to compete with X, Y and Z. Where > will THEY set up shop? Quarter Q has the strong advantage of offering > many experienced suppliers nearby -- and in many industries there are > benefits in working closely with suppliers, too (even just to easily > have them compete hard for your business...). So, there are easily > appreciated exogenous models to explain demand-side clustering, too. > > That's how you end up with a Holliwood, a Silicon Valley, a Milan (for > high-quality fashion and industrial design), even, say, on a lesser > scale, a Valenza Po or an Arezzo for jewelry. Ancient European cities > offer a zillion examples, with streets and quarters named after the > trades or professions that were most clustered there -- of course, > there > are many other auxiliary factors related to the fact that people often > _like_ to associate with others of the same trade (according to Adam > Smith, generally to plot some damage to the general public;-), but > supply-side and demand-side, at least for a simpler exogenous model, > are > plenty. > > Say that it's the 18th century (after the corporations' power to stop > "foreign" competition from nearby towns had basically waned), you're a > hat-maker from Firenze, and for whatever reason you need to move > yourself and your business to Bologna. If all the best hat-makers' > workshops and shops are clustered around Piazza dell'Orologio, where > are > YOU going to set up shop? Rents in that piazza are high, BUT - that's > where people who want to buy new hats will come strolling to look at > the > displays, compare prices, and generally shop. That's close to where > felt-makers are, since they sell to other hat-makers. Should your > business soon flourish, so you'll need to hire a worker, that's where > you can soon meet all the local workers, relaxing with a glass of wine > at the local osteria after work, and start getting acquainted with > everybody, etc, etc... Right, and distribution in general is "clumpy"; i.e. one doesn't find the spatial distribution of people to be uniform (unless at saturation!) I'm decades behind on economics research, but I remember modeling clustering based on mass and distance (the gravity model). On a decision making basis there seems to be an aspect of it that is binary: (0) either give in to gravity and gain shared advantage as part of a massive object, or (1) choose an alternate "location" far enough away not to be much affected by the force of the massive objects, and try to build "mass" there. I suspect Python is a (1) in that regard, but I may be wrong. Gravity as a model of technology adoption appeals to me as I've been thinking about cosmology a fair bit, and I have grave suspicions that much of the universe's dark (and green) matter is in Redmond. 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 bingham at cenix-bioscience.com Wed Jan 19 03:06:37 2005 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Wed, 19 Jan 2005 09:06:37 +0100 Subject: Fuzzy matching of postal addresses In-Reply-To: <$aq2IQPQ8X7BFwRy@at-andros.demon.co.uk> References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> <$aq2IQPQ8X7BFwRy@at-andros.demon.co.uk> Message-ID: <41EE150D.5050001@cenix-bioscience.com> Andrew McLean wrote: > Thanks for all the suggestions. There were some really useful pointers. > > A few random points: [snip] > 4. You need to be careful doing an endswith search. It was actually my > first approach to the house name issue. The problem is you end up > matching "12 Acacia Avenue, ..." with "2 Acacia Avenue, ...". Is that really a problem? That looks like a likely typo to me. I guess it depends on your data set. In my case, the addresses were scattered all over the place, with relatively few in a given city, so the likelyhood of two addresses on the same street in the same town was very low. We /wanted/ to check for this kind of 'duplication'. Note that endswith will not deal with 'Avenue' vs. 'Ave.', but I supose a normalization phase could take care of this for you. The Monge algorithm I pointed you to takes care of this pretty nicely. -- -------------------------------------------------------------------- Aaron Bingham Application Developer Cenix BioScience GmbH -------------------------------------------------------------------- From nick at craig-wood.com Thu Jan 27 04:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 27 Jan 2005 09:30:01 GMT Subject: Classical FP problem in python : Hamming problem References: <63b5e209.0501210558.686f5c10@posting.google.com> <6PKdnVpD-4f3CGvcRVn-gQ@comcast.com> Message-ID: Francis Girard wrote: > Thank you Nick and Steven for the idea of a more generic imerge. You are welcome :-) [It came to me while walking the children to school!] [snip] > class IteratorDeiterator: > def __init__(self, iterator): > self._iterator = iterator.__iter__() > self._firstVal = None ## Avoid consuming if not requested from outside > ## Works only if iterator itself can't return None You can use a sentinel here if you want to avoid the "can't return None" limitation. For a sentinel you need an object your iterator couldn't possibly return. You can make one up, eg self._sentinel = object() self._firstVal = self._sentinel Or you could use self (but I'm not 100% sure that your recursive functions wouldn't return it!) > def __iter__(self): return self > > def next(self): > valReturn = self._firstVal > if valReturn is None: and if valReturn is self._sentinel: > valReturn = self._iterator.next() > self._firstVal = None self._firstVal = self._sentinel etc.. [snip more code] Thanks for some more examples of fp-style code. I find it hard to get my head round so its been good exercise! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From steve at holdenweb.com Sat Jan 1 11:42:16 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Jan 2005 11:42:16 -0500 Subject: what is lambda used for in real code? In-Reply-To: References: Message-ID: Adam DePrince wrote: [...] > > In sort, we must preserve the ability to create an anonymous function > simply because we can do so for every other object type, and functions > are not special enough to permit this special case. > And you'd create an anonymous type how, exactly? 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 donn at u.washington.edu Wed Jan 12 14:51:32 2005 From: donn at u.washington.edu (Donn Cave) Date: Wed, 12 Jan 2005 11:51:32 -0800 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <10u5fu3o7v4h9e3@corp.supernews.com> <10u8e65lju3atbd@corp.supernews.com> Message-ID: In article , Jacek Generowicz wrote: > Donn Cave writes: > > > List incomprehensions do not parse well in my eyes. > > Are you familiar with the Haskell syntax for list comprehensions? > > For example: > > http://www.zvon.org/other/haskell/Outputsyntax/listQcomprehension_reference.h I haven't used it more than once or twice in the modest amount of Haskell code I've written, but I've seen it a few times. > Does their striking similarity to mathematical set notation help at > all ? Not a bit. If it's any more obvious than the Python version, I suppose it's the | -- my parser sees [a|b] on the first pass. But it isn't like I ever made any real effort to get comfortable with Python list comprehensions. I was just relaying my (lack of) intuitive grasp of them, compared to map and lambda. Donn Cave, donn at u.washington.edu From aleaxit at yahoo.com Sun Jan 2 18:14:48 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 3 Jan 2005 00:14:48 +0100 Subject: ? about file() and open() References: <1104706607.022890.314500@c13g2000cwb.googlegroups.com> Message-ID: <1gpsduc.bbh4xyw3ymg6N%aleaxit@yahoo.com> Sean wrote: > Was wondering if there was any difference between these two functions. Not today: >>> open is file True they're two names for the same object. Which isn't a function, btw: >>> type(open) the object, as you see, is a type (besides calling it to instantiate it, you might inherit from it, etc). > I have read some text that said file() wasn't introduced until 2.2 and > that it was synonymous with open(). Does this mean that I should be > using file() where I used open() before? According to Guido, you should keep _calling_ 'open' -- that's the name to which a factory function to be called may be bound in the future if and when a good way is found to return filelike objects of some other type depending on circumstances (e.g., one day it might become possible to open some kinds of URL that way). You should use 'file' when you're subclassing, or in other situations where you want to be sure you're naming a type, not a function (few good cases come to mind, but maybe isinstance is a possible case, although likely not _good_...;-). Alex From jzgoda at gazeta.usun.pl Tue Jan 25 17:03:04 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Tue, 25 Jan 2005 23:03:04 +0100 Subject: python without OO In-Reply-To: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: Davor wrote: > Is it possible to write purely procedural code in Python, or the OO > constructs in both language and supporting libraries have got so > embedded that it's impossible to avoid them? Sure, but you will got problem with libraries. Some of them are in fact frameworks and need some subclassing or other OO fluff. > Also, is anyone aware of > any scripting language that could be considered as "Python minus OO > stuff"? (As you can see I'm completely new to Python and initially > believed it's a nice&simple scripting language before seeing all this > OO stuff that was added in over time) Icon, the language for OO haters. May I ask why you do you hate OO so much? -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From honor2003 at yahoo.com Tue Jan 4 00:50:52 2005 From: honor2003 at yahoo.com (john) Date: 3 Jan 2005 21:50:52 -0800 Subject: FS: PC Doctor Message-ID: <1104817852.587703.310920@c13g2000cwb.googlegroups.com> Bought from http://www.PCbeginner.com two weeks ago. Now my computer got fixed and I do not need it any more. Asking $15 only. I will ship to you by first class mail. Email: honor2003 at yahoo.com From zslist at gmail.com Thu Jan 6 19:05:07 2005 From: zslist at gmail.com (zslist at gmail.com) Date: 6 Jan 2005 16:05:07 -0800 Subject: python reading/writing ms-project files? Message-ID: <1105056307.322989.54930@z14g2000cwz.googlegroups.com> any existing or pointers on how to do this? thanks. From bokr at oz.net Mon Jan 24 02:30:32 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 24 Jan 2005 07:30:32 GMT Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) References: <41f325b5.1576259210@news.oz.net> <6I2dnYLoXdcTmGncRVn-vw@comcast.com> Message-ID: <41f490e8.1669238027@news.oz.net> On Sun, 23 Jan 2005 13:14:10 -0700, Steven Bethard wrote: >Bengt Richter wrote: >> On Sat, 22 Jan 2005 16:22:33 +1000, Nick Coghlan wrote: >> >> [Steven Bethard] >>>> > If you really want locals that don't contribute to arguments, I'd be >>>> > much happier with something like a decorator, e.g.[1]: >>>> > >>>> > @with_consts(i=1, deftime=time.ctime()) >>>> > def foo(x, y=123, *args, **kw): >>>> > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime >>>> > >>>> > Then you don't have to mix parameter declarations with locals >>>> > definitions. [...] [Nick Coghlan] >>>Raymond's constant binding decorator is probably a good model for how to do it: >>>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 >>> >> >> [Bengt Richter] >> I thought so too. I modified it to accept **presets as a keyword argument >> and generate constants and assignments from its values matching assignment names >> when the rhs was __frompresets__, e.g., >> >> >>> from makeconstpre import make_constants as pre >> >>> import time >> >>> @pre(verbose=True, deftime=time.ctime(), a=1, b=2, c=3, pi=__import__('math').pi) >> ... def foo(): >> ... deftime = __frompresets__ >> ... b, a = __frompresets__ >> ... c = __frompresets__ >> ... pi = __frompresets__ >> ... return locals() >> ... >> __frompresets__ : deftime --> Sat Jan 22 20:18:09 2005 >> __frompresets__ : ('b', 'a') --> (2, 1) >> __frompresets__ : c --> 3 >> __frompresets__ : pi --> 3.14159265359 >> locals --> > [Steven Bethard] >Hmm... Having to state > deftime = __frompresets__ >when you've already stated > deftime=time.ctime() >seems a little redundant to me... > Yeah, but as a quick hack, it made the byte code twiddling all changing byte codes in-place. I didn't want to verify that byte code wouldn't need relocation fixups if I inserted something, (unless of course within a suite with branches or loops) but hopefully it's easily so at the beginning. BTW, unlike default arguments, varname = __frompresets__ will work anywhere in the code, (for the current decorator version) and the generated byte code will have a load of an appropriate constant (the same one if the same name is being assigned). This would be tricky to get right if done in a hidden just-in-time manner only in branches that used the values, but hidden initialization of the whole presets set at the beginning should be relatively easy if there are no relocation problems. So, e.g., for >>> presets = dict(a=1, b=2, deftime=__import__('time').ctime()) in the decorator args, the next version will act as if the decorated function had the source code >>> print '%s = __frompresets__' % ', '.join(sorted(presets)) a, b, deftime = __frompresets__ for the current version, except that it will be hidden. Regards, Bengt Richter From ian at kirbyfooty.com Sun Jan 2 17:12:04 2005 From: ian at kirbyfooty.com (ian at kirbyfooty.com) Date: 2 Jan 2005 14:12:04 -0800 Subject: ctypes NULL pointers; was: Python To Send Emails Via Outlook Express In-Reply-To: References: Message-ID: <1104703924.410611.35820@c13g2000cwb.googlegroups.com> Thanks again Lenard!! From craig at postnewspapers.com.au Sat Jan 8 00:40:40 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 08 Jan 2005 13:40:40 +0800 Subject: Help uninstalling/installing Python 2.4 In-Reply-To: References: Message-ID: <1105162839.31717.21.camel@rasputin.localnet> On Sat, 2005-01-08 at 08:08, Baggs wrote: > Tk calls did not work, the output from Python when running a program > stated that I probably did not have TK installed. I got and installed > TK 8.4 and the problem persisted (I know I should have written down the > exact error, but I didn't... but the story gets worse!) You probably didn't have the -devel packages for Tcl and Tk installed, so Python would've decided you didn't have Tk and not built tkinter support. Chances are if you install the devel packages and recompile Python, it'll work fine. > when I re-installed I still have > problems.. everything installs ok, but now I get the following errors > with Python... > > bash: /usr/bin/python: No such file or directory Is that when you run a script, or when you type 'python' in your shell? If the former, make sure you write your scripts with a #! like this: #!/usr/bin/env python not #!/usr/bin/python That way, the right python will get run so long as it's on your path - it doesn't have to be in /usr/bin. If the error is when typing 'python' on the command line, ensure you have no aliases for the name 'python' hanging around ('alias python' to find out). Also check what is actually being run with 'which python' and see if it's a wrapper script that calls /usr/bin/python. > when I go to /usr/local/bin and type ./python I get > > Python 2.4 (#6, Jan 7 2005, 18:44:57) > [GCC 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > Traceback (most recent call last): > File "/etc/pythonrc.py", line 2, in ? > import readline > ImportError: No module named readline > > I think some paths are screwed up.. can someone take pity on me and give > me a hand. I'd say that'll be the same as with Tkinter - you probably didn't have the GNU readline development headers installed, so Python disabled readline support when it was compiled. That's just a guess, but seems pretty likely. -- Craig Ringer From fumanchu at amor.org Wed Jan 26 01:46:34 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 25 Jan 2005 22:46:34 -0800 Subject: I want update one record using ADO,but I can't ,why? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339829C@exchange.hqamor.amorhq.net> nightmarch wrote: > Sorry, I mean this code line " rs.Supports( wc.constants.adUpdate ) " > got False result, So I can't update one record,i.e. I can't execute > this code "rs.Fields.Item(0).Value = 11". > > And , if code is written like this: > > ## conn.Open(connStr ) > rs.Open( tblName, conn, wc.constants.adOpenKeyset, > wc.constants.adLockOptimistic ) > > rs.Fields.Item(0).Value = 11 > s.Update() > ##>code------------------------- > > I got error msg like following: > > ## self._oleobj_.Invoke(*(args + (value,) + defArgs)) > com_error: (-2147352567, '\xb7\xa2\xc9\xfa\xd2\xe2\xcd\xe2\xa1\xa3', > (0, 'ADODB.Field', 'Current Recordset does not support updating. This > may be a limitation of the provider, or of the selected locktype.', > 'C:\\WINNT\\HELP\\ADO210.CHM', 0, -2146825037), None) > ##>errorMsg---------------------------- Well, without knowing your entire Oracle setup, I'm not sure how far one can get. My only thought is to try a full SELECT statement instead of just the tablename, and preface the tablename with the schema, something like: "select * from %s.%s;" % (schema, tblName) It's possible the trailing semicolon is important to close the statement. The next thing to check would be permissions. Robert Brewer MIS Amor Ministries fumanchu at amor.org From mgarrett at garrett-technologies.com Wed Jan 26 23:53:02 2005 From: mgarrett at garrett-technologies.com (mcg) Date: 26 Jan 2005 20:53:02 -0800 Subject: String Fomat Conversion Message-ID: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Investigating python day 1: Data in file: x y 1 2 3 4 5 6 Want to read file into an array of pairs. in c: scanf("%d %d",&x,&y)---store x y in array, loop. How do I do this in python?? In the actual application, the pairs are floating pt i.e. -1.003 From itsme at yahoo.com Tue Jan 11 23:22:00 2005 From: itsme at yahoo.com (It's me) Date: Wed, 12 Jan 2005 04:22:00 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: "Robert Kern" wrote in message news:cs1mp9$sg9$1 at news1.ucsd.edu... > > That's *it*. So, how would you overload an operator to do: With native complex support: def twice(a): return 2*a print twice(3+4j), twice(2), twice("abc") Let's presume for a moment that complex is *not* a native data type in Python. How would we implement the above - cleanly? From rnd at onego.ru Fri Jan 7 01:59:24 2005 From: rnd at onego.ru (Roman Suzi) Date: Fri, 7 Jan 2005 09:59:24 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: <7xd5wh7qdf.fsf@ruckus.brouhaha.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 6 Jan 2005, Paul Rubin wrote: >software when I buy a new computer, or at least a new hard drive. I >don't try to migrate system or configuration files. I just install >the OS distro from scratch and migrate my user files. > >> There are several parts to those frustrations. But you are presuming >> that they would have been solved for you and put on a DVD with all >> dependency problems resolved. Ok, let's assume that. In that case, >> an installation stub module could just as well have the solution built >> into it as to what versions etc are needed to make the module work. I do not like the idea of having stubs. Once I had an experience working with CPAN (I tried to install SpamAssassin and it required some specific modules.) "Magic" install shell, provided by Perl, upgraded half the Perl distro, including newer version of Perl! So, I do like Python distutils better. it is not a major problem to install something even if it required something else. Of course, this depends on the package authors. >How can it work just as well, when it requires a high-speed internet >connection which I might not have? And why is "just as well" good >enough, given how inconvenient and error-prone it is, compared with >just installing from a DVD once and for all? To have any attraction >what ever, the installation stub scheme (for me at least) has to work >"an order of magnitude better", not "just as well", as a one-time >complete install. > >> To bring a large collection into version-alignment ISTM you need a version >> freeze across too many libraries of different kinds with different >> development schedules and resources to make it reliable. > >One part of the problem is excessive version dependence between >package X and package Y. That's why I think there should be more >integration within packages, i.e. the Python distro should include a >lot more modules that you currently have to download from other >places. > >> I realize this problem has been "solved" with various RPM and >> app-loading methods, but I think python could wrap its solution >> nicely. I don't think distutils and setup.py is easy enough to >> create (at least I have been somewhat frustrated in using it >> effectively), though it deals with a lot of what has to be done. > >Since all these schemes have failed whenever they've been tried, all I >can think is that it's a harder problem than it sounds. I have installed many packages with Distutils, and usually there were no problems. If there were, they were no greater than installing some devel library and/or adding an include directory. So, Distutils, IMHO, are successful. Yes, probably there could be a no-brainer script to run install directly from zip and/or tar.gz/bz2 file, but I usually check md5, pgp sigs and look inside anyway before running something. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From eric_brunel at despammed.com Mon Jan 3 10:23:21 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 03 Jan 2005 16:23:21 +0100 Subject: Tkinter zoom box In-Reply-To: References: Message-ID: <41d96195$0$4122$8fcfb975@news.wanadoo.fr> Philippe C. Martin wrote: > Hi, > > I have the following convern: I have Tkinter applications that require a zoom > box, and have had the following behavior without changing a line of code: > > 1) Mandrake 10.0/KDE 3.2/Python 2.3: no zoom box > 2) Mandrake 10.0/KDE 3.2/Python 2.4: zoom box shows > 3) Mandrake 10.1/KDE 3.3/Python 2.4: no zoom box > 4) Mandrake 10.1/Gnome 2.6/Python 2.4: zoom box shows > > I know that sounds strange, but I am fairly certain this is what happened. > > Is there a way to _force_ that zoom box ? What do you call a "zoom box"? There's no widget with this name in "regular" Tkinter widgets, so it must be built with some other one... Which one is it? A button, a menubutton, or what else? If you had some (simple) code showing the problem, that would also help a lot to understand what's going on... -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From guettli at thomas-guettler.de Mon Jan 10 08:24:41 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 10 Jan 2005 14:24:41 +0100 Subject: Powerful CGI libraries for Python? References: Message-ID: Am Mon, 10 Jan 2005 10:11:16 +0800 schrieb sam: > Hi, > > I m looking for a CGI libraries just like perl's CGI.pm for Python. > From google, I found quite a few of CGI libraries already written for > python. But I haven't had experience to try any of them in Python. > > Can anyone share your Python CGI experience with me? Which library is > better in terms of functionality and stability? Hi, in the standard library there is cgi and cgitb. If you just want to write a small cgi script, both modules should be all you need. I found quixote simple and easy to learn. Quixote 1.x is quite stable. The version I use is more then six months old, and there is no need to update. Take a look at: http://www.python.org/cgi-bin/moinmoin/WebProgramming Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From steve at holdenweb.com Wed Jan 12 15:42:58 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 12 Jan 2005 15:42:58 -0500 Subject: Newbie: Pythonwin In-Reply-To: References: Message-ID: <41E58BD2.2030102@holdenweb.com> Brent W. Hughes wrote: > 1) I'm running a program within Pythonwin. It's taking too long and I want > to stop/kill it. What do I do (other than ctrl-alt-del)? > When PythonWin is running it puts an icon in the system tray. You can right-mouse on this icon and select "Break into running code". > 2) I'm running a long program and I want to minimize it to let it continue > to run in the background while I do something else in the foreground. I try > clicking on Pythonwin's minimize box but it doesn't respond until the Python > program finally quits Then it minimizes! Any way I can do what I want > here? > Sorry, I think you'll need to ask Mark Hammond to have PythonWin pump events more aggressively or some such. 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 ashot at removethismolsoft.com Sat Jan 15 19:23:26 2005 From: ashot at removethismolsoft.com (Ashot) Date: Sat, 15 Jan 2005 16:23:26 -0800 Subject: video analysis with python Message-ID: Hi, I need to write a video analysis tool which extracts statistics from microsocope video. Essentially what I need is to translate the video data into numerical matrices. I have been using Python for the past 1.5 years anytime I could for absolutely everything, because it has every library imaginable... Alas, I can not find a library for decoding video/using codecs. The only solution I have been able to come up with is to create an image sequence and load those in with PIL, however this is not really feasible as the images are too large (nor is it proffessional). Is there a library or project that I have missed, or is there a way to incorporate something like vfw.lib directly? If there isn't I think this would be a pretty large whole in Python's arsenal. Thanks in advance for any help. -- Ashot Petrosian University of Texas at Austin, Computer Sciences From Serge.Orlov at gmail.com Fri Jan 14 14:46:57 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 14 Jan 2005 11:46:57 -0800 Subject: Why 'r' mode anyway? (was: Re: Pickled text file causing ValueError (dos/unix issue)) References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> <41e80785$0$6203$e4fe514c@news.xs4all.nl> Message-ID: <1105732017.740111.135650@f14g2000cwb.googlegroups.com> Irmen de Jong wrote: > Tim Peters wrote: > > > Yes: regardless of platform, always open files used for pickles in > > binary mode. That is, pass "rb" to open() when reading a pickle file, > > and "wb" to open() when writing a pickle file. Then your pickle files > > will work unchanged on all platforms. The same is true of files > > containing binary data of any kind (and despite that pickle protocol 0 > > was called "text mode" for years, it's still binary data). > > I've been wondering why there even is the choice between binary mode > and text mode. Why can't we just do away with the 'text mode' ? We can't because characters and bytes are not the same things. But I believe what you're really complaining about is that "t" mode sometimes mysteriously corrupts data if processed by the code that expects binary files. In Python 3.0 it will be fixed because file.read will have to return different objects: bytes for "b" mode, str for "t" mode. It would be great if file type was split into binfile and textfile, removing need for cryptic "b" and "t" modes but I'm afraid that's too much of a change even for Python 3.0 Serge. From zombiehunter at gmail.com Mon Jan 24 08:43:14 2005 From: zombiehunter at gmail.com (zombiehunter at gmail.com) Date: 24 Jan 2005 05:43:14 -0800 Subject: short programming projects for kids In-Reply-To: References: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> Message-ID: <1106574194.187150.112570@c13g2000cwb.googlegroups.com> I was just about to suggest Livewires. I'm a programming newb (35 yrs old ) haha- and I'm finding the lIvewires course pretty helpful, even though it's geared for teens. I suppose my brain works on that functional level. :) And a book that's great for beginner's (know you probably don't want to buy books but just wanted to throw this info out there in case it helps somehow) is Python Programming for the Absolute Beginner by Michael Dawson. I'm working through that too and it's wonderful. It had many fairly simple to implement programs (lots of them simple games) that build on each other in a very easily comprehended, step-by-step manner. Hope htis helps- From x2164 at mailcity.com Sun Jan 30 22:52:55 2005 From: x2164 at mailcity.com (x2164 at mailcity.com) Date: 31 Jan 2005 03:52:55 GMT Subject: test_socket.py failure References: <41FD4F53.2040507@holdenweb.com> Message-ID: Steve Holden wrote: > 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. > > > Compiling from source requires you to indicate the features that you > want compiled in. Without thread support, sockets din't work, so it > looks like you need to configure threads in. IIRC you do this by editing > the Modules.? file. > regards > Steve hi Steve, Here's a cut down version of the compilation line for socketmodule.c which contains the 'socket_getservbyname' code: gcc -pthread -DNDEBUG ... -c /usr/src/Python-2.4/Modules/socketmodule.c -o build/temp.linux-i686-2.4/socketmodule.o Is '-pthread' the type of thread i need? I'm still curious why only the call with one argument to 'socket.getservbyname' fails while the two other calls which pass two arguments don't fail. Any ideas? pete jordan x2164 at mailcity com -- ............ From steven.bethard at gmail.com Fri Jan 7 15:12:58 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 13:12:58 -0700 Subject: switching an instance variable between a property and a normal value Message-ID: I'd like to be able to have an instance variable that can sometimes be accessed as a property, and sometimes as a regular value, e.g. something like: py> class C(object): ... def usevalue(self, x): ... self.x = x ... def usefunc(self, func, *args, **kwds): ... self._func, self._args, self._kwds = func, args, kwds ... self.x = C._x ... def _get(self): ... return self._func(*self._args, **self._kwds) ... _x = property(_get) ... py> c = C() py> c.usevalue(4) py> c.x 4 py> c.usefunc(list) py> c.x # I'd like this to print [] Of course, the code above doesn't do what I want because C._x is a property object, so the assignment to self.x in usefunc just adds another name for that property object. If I use self._x (or getattr(self, '_x'), etc.) then self._func only gets called that one time: py> class C(object): ... def usevalue(self, x): ... self.x = x ... def usefunc(self, func, *args, **kwds): ... self._func, self._args, self._kwds = func, args, kwds ... self.x = self._x ... def _get(self): ... return self._func(*self._args, **self._kwds) ... _x = property(_get) ... py> c = C() py> c.usefunc(list) py> c.x is c.x # I'd like this to be False True Is there any way to get the kind of behavior I'm looking for? That is, is there any way to make self.x use the property magic only some of the time? Steve P.S. Yes, I know I could make both access paths run through the property magic, with code that looks something like: py> class C(object): ... _undefined = object ... def __init__(self): ... self._value, self._func = C._undefined, C._undefined ... def usevalue(self, x): ... self._value = x ... self._func = C._undefined ... def usefunc(self, func, *args, **kwds): ... self._func, self._args, self._kwds = func, args, kwds ... self._value = C._undefined ... def _get(self): ... if self._value is not C._undefined: ... return self._value ... if self._func is not C._undefined: ... return self._func(*self._args, **self._kwds) ... raise AttributeError('x') ... x = property(_get) ... py> c = C() py> c.usevalue(4) py> c.x 4 py> c.usefunc(list) py> c.x is c.x False This code is kinda complicated though because I have to make sure that only one of self._func and self._value is defined at any given time. From paul at subsignal.org Thu Jan 27 08:11:01 2005 From: paul at subsignal.org (paul koelle) Date: Thu, 27 Jan 2005 14:11:01 +0100 Subject: subprocess.Popen() redirecting to TKinter or WXPython textwidget??? In-Reply-To: <41f811fe$0$148$3a628fcd@reader1.nntp.hccnet.nl> References: <41f80b1b$0$148$3a628fcd@reader1.nntp.hccnet.nl> <1106775371.049857.36360@z14g2000cwz.googlegroups.com> <41f811fe$0$148$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <35s44aF4qo76cU1@individual.net> Ivo Woltring wrote: > The output of mencoder is not readable with readlines (i tried it) because > after the initial informational lines You don't get lines anymore (you get a > linefeed but no newline) > The prints are all on the same line (like a status line) > something like > Pos: 3,1s 96f ( 0%) 42fps Trem: 0min 0mb A-V:0,038 [171:63] Have you tried popen3 with stdout and stderr? hth Paul From steve at holdenweb.com Wed Jan 19 08:58:10 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Jan 2005 08:58:10 -0500 Subject: generator expressions: performance anomaly? In-Reply-To: <7xhdlejenm.fsf@ruckus.brouhaha.com> References: <377Hd.77904$Jk5.30235@lakeread01> <41ED1C0F.4030800@holdenweb.com> <7xhdlejenm.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steve Holden writes: > >>You probably already know that sensible compiled language systems have >>used constant folding since time immemorial, but Python has always >>eschewed it. That's what comes of being a pragmatist's language: if >>such optimizations really are required the programmer is expected to >>perform them. > > > You mean the lack is deliberate? I just figured it was an artifact of > the implementation and that PyPy had some reasonable chance of fixing it. No, it's not been deliberately omitted, it's just not a development priority. Pragmatic Python programmers are prepared to do the folding themselves in the (exceptionally rare) cases where it has a significant effect on performance. PyPy may or may not fix it. And, of course, a dynamic language has rather less ability to take advantage of more advanced optimizations since it's much harder to guarantee functional behavior for any given subexpression. Once side effects rear their ugly heads all bets are off. 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 cold_fusion at fastmail.fm Wed Jan 5 16:40:07 2005 From: cold_fusion at fastmail.fm (Avi Berkovich) Date: Wed, 05 Jan 2005 23:40:07 +0200 Subject: Reaching the real world In-Reply-To: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> References: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: <41dc5ef2$1@news.012.net.il> Hey, If you want to do something simple, you can use your parallel port to control other circuitry. I've made an extension module before for DLPortIO which is a free lib for doing port IO in win2k/xp. I have to dig it out of my hdds/discs if you want it, but it's really easy to make with pyrex anyway. Avi. From steven.bethard at gmail.com Tue Jan 4 10:20:34 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 04 Jan 2005 15:20:34 GMT Subject: Lambda as declarative idiom (was RE: what is lambda used for in real code?) In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: <6vyCd.617042$wV.607079@attbi_s54> Roman Suzi wrote: > On Mon, 3 Jan 2005, Steven Bethard wrote: > > >>Roman Suzi wrote: >> >>>I wish lambdas will not be deprecated in Python but the key to that is >>>dropping the keyword (lambda). If anybody could think of a better syntax for >>>lambdas _with_ arguments, we could develop PEP 312 further. >> >>Some suggestions from recent lambda threads (I only considered the ones >>that keep lambda as an expression): > > Wow! Is there any wiki-page these could be put on? It's now on: http://www.python.org/moin/AlternateLambdaSyntax and I added Bengt Richter's and your recent suggestions. Steve From mefjr75 at hotmail.com Tue Jan 25 22:36:30 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 25 Jan 2005 19:36:30 -0800 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> Message-ID: <1106710590.312881.222520@c13g2000cwb.googlegroups.com> Davor, I was gonna let it go but .... I never was good at shutin up ;) The greatest strength a manager can have is delegation. And with that add the ability to best use the resources available . It seems you are telling me that : 1) You do not understand most programming concepts 2) You are not willing to learn. 3) You might not have the skill set to manage developers What does it all mean? Stop telling your programmers how to program! Seriously NOW. If you managed a group of doctors would you tell them that they could only use techniques that *YOU* understood, even if the were STANDARD and well known by others? That brings me to the other point , you have mentioned design patterns, did YOU read GOF Design Patterns? It seems to me that if you were to spend a week with the book you could grasp at least the gist of the major patterns.They are pretty simple and quite informative. You should at least speak the lingo of the field you manage in. If your guys occasionally do something and you feel lost, that is a sign you are normal. Oh yea and don't confuse programming idioms of various language with design patterns. Start cultivating a talent for setting clear goals and clear objectives , learn how to manage people and have better communication (that is two way) with your developers. Your job is to be a manager , so __manage__ your team , have the overview have the design concept have the long road in mind and then at the same time listen to your team and do what it takes to smooth the rough edges and move the project forward, don't fiddle the details unless needed. Set goals not details unless they are real restrictions. Life is full of real restrictions and so are most projects so avoid getting into the unrealistic and unreasonable. Let your talent make you look good and help them do it. This advice holds true for every field I can think of. Ignorance can be remedied with a book , but apathy sometimes needs a swift kick in the ass. Hope you do well, M.E.Farmer From mcturra2000 at yahoo.co.uk Tue Jan 4 05:34:36 2005 From: mcturra2000 at yahoo.co.uk (Mark Carter) Date: Tue, 04 Jan 2005 10:34:36 +0000 Subject: How can engineers not understand source-code control? In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> <41d8417e$0$14596$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: <41da713a$0$610$ed2619ec@ptn-nntp-reader03.plus.net> > Cameron Laird wrote: > >> I've seen the infatuation for Excel (and so on) for years, True story: when I began working for my current employer, there was a guy there doing some work with a spreadsheet. He was given two weeks to perform the task. It was a loss-leader to get some real work from the client. There already existed a spreadsheet, which did financial projections. It used VBA fairly extensively, and his task was to adapt it to remove the VBA code. This means converting things like functions into equivalent cell formulae. The rationale behind this is that VBA is too hard for most people to understand, whereas formulae are easier to understand. Conditionals look really confusing in formulae, and I don't know how he coped with loops. And then, of course, you have to replicate them to every cell that requires them. Can you imagine that? Is this very the definition of madness, or what? The whole thing was a gigantic spreadsheet (I can't remember, it was either 9Mb or 90Mb in size), and kept crashing every few minutes. Utter utter insanity. Whenever he went back the client, she demanded improvements. We had effectively told her that she could have whatever whe wanted. And oh, it would only take 2 weeks. The managers never pulled the plug on the project. Apparently, our guy sat in on a conversation that the client had with a potential contractor who would replace the spreadsheet. His first question was, surprise surprise, "why on earth did you try to do it that way?" The thing is, our guy was scheduled to be booted out the door because he was in a business area that was being discontinued by us, so from my employer's point-of-view, I guess that all this lunacy actually made sense. From fredrik at pythonware.com Tue Jan 18 02:19:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Jan 2005 08:19:02 +0100 Subject: Problem parsing namespaces with xml.dom.minidom References: <41eca38d@clear.net.nz> Message-ID: Mike McGavin wrote: > I'm not terribly experienced with XML in general, so it's possible that I'm just incorrectly > interpreting how things are supposed to work to begin with. If this is the case, please accept my > apologies, but I'd like any suggestions for how I should be doing it. I'd really just like to be > able to parse an XML document into a DOM, and then be able to pull out elements relative to their > namespaces. is the DOM API an absolute requirement? From peter at engcorp.com Tue Jan 18 11:04:01 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Jan 2005 11:04:01 -0500 Subject: Advice to a Junior in High School? In-Reply-To: <1106034944.793262.19950@z14g2000cwz.googlegroups.com> References: <1106034944.793262.19950@z14g2000cwz.googlegroups.com> Message-ID: collegebabe2004 wrote: > I would suggest taking Japanese because you will have to work with them > eventually if you do decide to choose compsci as your proffesion. Over what time frame should I expect this requirement to become critical? I'd like to know so I can reserve a spot in the next Japanese course in the area, if you think it's really urgent. Also, should I plan on adopting various aspects of the Japanese culture as well, or will a mastery of the language be sufficient? -Peter From peter at engcorp.com Sat Jan 8 12:38:18 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 12:38:18 -0500 Subject: sorting on keys in a list of dicts In-Reply-To: References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: Nick Coghlan wrote: > Stability in sorting is a property not to be sneezed at - it means > switching to sorting by a second key gives the effect of "sort by key 1, > then by key 2", whereas that doesn't hold with an unstable sort Assuming "key 1" refers to the first key, and "key 2" to the second key, then I believe you meant "gives the effect of 'sort by key 2 then by key 1'". In other words, if you have a stable sort algorithm and do one sort operation using key 2, then a second sort operation using key 1, it's the same as doing a single sort with the key combination "key 1, key 2", not the other way around. -Peter From flamesrock at gmail.com Sun Jan 2 23:54:20 2005 From: flamesrock at gmail.com (flamesrock) Date: 2 Jan 2005 20:54:20 -0800 Subject: XML: Better way to accomplish this? Message-ID: <1104728060.417168.277780@c13g2000cwb.googlegroups.com> Hi, I'm working on creating an xml structure like the following, as effiecienty and elegantly as possible using minidom preferably: # # # # 0 # # # 0 # # # 0 # # # 0 # # # # # # # # # # 0 # # # 0 # # # 0 # # # # # # # # # # 0 # # # 0 # # # 0 # # # # # # # # # # 0 # # # 0 # # # 0 # # # # # (left out) The following code accomplishes that, but being a newb to xml..I'm not sure if this can be done a better (I'd like to stick with dom due to the nature of this app): (left textnode parts like mayor, cityname out to keep code concise for now) # from xml.dom.minidom import parseString # #create a new document # scoreXML = parseString(u''.encode('UTF-8')) # art = scoreXML.documentElement # # #create a total population, cities and some city elements # population = scoreXML.createElementNS(None,u'population') # cities = scoreXML.createElementNS(None,u'cities') # city1 = scoreXML.createElementNS(None,u'city1') # city2 = scoreXML.createElementNS(None,u'city2') # city3 = scoreXML.createElementNS(None,u'city3 and so on') # # #add it under the region element # art.appendChild(population) # art.appendChild(cities) # # # create a total element with a population number inside # # and do this for all RCI numbers # population.appendChild(scoreXML.createElementNS(None,u'total')) # total = scoreXML.createTextNode(u'0') # population.firstChild.appendChild(total) # #will get RCI with seperate function # RCI = [scoreXML.createTextNode(u'0'), # scoreXML.createTextNode(u'0'), # scoreXML.createTextNode(u'0')] #[r,c,i] # for populationElement in [u'R',u'C',u'I']: # population.appendChild(scoreXML.createElementNS(None,populationElement)) # population.lastChild.appendChild(RCI[0]) # RCI.pop(0) # # #add the elements underneath city # allcities = [city1,city2,city3] # for city in allcities: # cities.appendChild(city) # # for cityattribute in [u'cityname',u'mayor',u'morelater']: # city.appendChild(scoreXML.createElementNS(None,cityattribute)) # # citypopulation = scoreXML.createElementNS(None,u'citypopulation') # city.appendChild(citypopulation) # #will get RCI with seperate function # RCI = [scoreXML.createTextNode(u'0'), # scoreXML.createTextNode(u'0'), # scoreXML.createTextNode(u'0')] #[r,c,i] # # for populationElement in [u'R',u'C',u'I']: #>>>>>>>>>>citypopulation.appendChild(scoreXML.createElementNS(None,populationElement)) # citypopulation.lastChild.appendChild(RCI[0]) # RCI.pop(0) # #write the result # print scoreXML.toprettyxml() Any ideas? -thanks in advance From erikbethke at gmail.com Thu Jan 20 09:58:57 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 20 Jan 2005 06:58:57 -0800 Subject: ElementTree cannot parse UTF-8 Unicode? In-Reply-To: References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106230846.455765.7310@c13g2000cwb.googlegroups.com> Message-ID: <1106233137.588111.216480@z14g2000cwz.googlegroups.com> Woo-hoo! Everything is working now! Thank you everyone! The TWO problems I had: 1) I needed to save my XML file in the first place with this code: f = codecs.open(paths[0], 'w', 'utf8') 2) I needed to download the UNICODE version of wxPython, duh. So why are there non-UNICODE versions of wxPython??? To save memory or something??? Thank you all! Best! -Erik From michael_r_campbell at att.net Fri Jan 28 13:33:19 2005 From: michael_r_campbell at att.net (mike) Date: 28 Jan 2005 10:33:19 -0800 Subject: py.dll for version 2.2.1 (Windows) Message-ID: <1106937199.667357.42040@z14g2000cwz.googlegroups.com> Just recently, my virus checker detected what it called a Trojan Horse in the py.dll file in the python22 folder. Installation is version 2.2.1 and I think that it came installed when I bought the PC in October 2002. Does anyone know where I can get a copy of the py.dll file from version 2.2.1 for Windows (XP) ? I looked at www.python.org and do not see a py.dll file in the self-installation or .tgz versions of 2.2.1 that are posted. Thanks ! Mike From emami at knmi.nl Tue Jan 4 05:00:34 2005 From: emami at knmi.nl (Nader Emami) Date: Tue, 04 Jan 2005 11:00:34 +0100 Subject: csh to Python Message-ID: Hello, I am new in Python world, and would like to begin with translate a csh file to a python script. Could somebody give me an advise (documentation or web-site) where I can do that. with regards, Nader From Serge.Orlov at gmail.com Tue Jan 11 18:57:52 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 11 Jan 2005 15:57:52 -0800 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <41e41633$1@nntp0.pdx.net> <41e458a9$0$7090$8fcfb975@news.wanadoo.fr> Message-ID: <1105487872.494278.128510@f14g2000cwb.googlegroups.com> Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: > Hi ! > > >>> It is a least-common-denominator argument, not a "this is better" > argument. > > I understand, but I have a feeling of attempt at hegemony. Is english > language really least-common-denominator for a russian who writes into > cyrillic, or not anglophone chinese? I don't know about Chinese but English *is* the least common denominator for native Russian software developers, there are a lot of reasons for that: - to switch between Russian keyboard layout and English keyboard you need to press a switch key or usually even two keys (at the same time). Since language syntax and library calls are in English you have to switch often. Very often you forget what is the current keyboard layout and start typing in wrong one and you have to delete the garbage, hit switch key and type it again. If it happens ten times every ten minutes it will drive you crazy. - Most of native Russian developers graduated from universities or institutes. They attended hundreds of hours of math and physics classes. All these classes use latin notation. - Any serious local sw development job application mentions "Technical English" as requirement. It means you're expected to read technical documents in English. - At the same time majority of native Russians developers do not speak English very well and they feel they need more English practice. Using English identifiers is a chance to practice while you work. - The amount of useful information in English is much greater than in Russian, thanks to Internet. Surprised? :) Serge. From bokr at oz.net Sun Jan 9 16:50:51 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 09 Jan 2005 21:50:51 GMT Subject: time module precision References: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> Message-ID: <41e1a171.428347721@news.oz.net> On 9 Jan 2005 03:09:27 -0800, janeaustine50 at hotmail.com wrote: [...] > >What I want to do is waiting(not busy-delaying) for a few tens to >hundreds of microseconds in some threads. The closet solution I got is >using windows QueryPerformanceCounter (in Python, time.clock) with busy >looping checking if we have past the target time. However, that makes >the cpu usage upto almost 100%. > >So the problem (waiting tens to hundreds of us without busy looping) >still remains... > Microseconds is tough if you are going to give up control to a scheduling/dispatching mechanism that works in milliseconds (e.g. 10ms normal slice on NT4), and where badly written interrupt handling may cause significant latency hiccups. There's a reason CD burners come with big buffers. One question is if you are waiting for an event that causes and interrupt, or if you are guaranteeing a delay to give something a chance to happen (e.g. like some pysical process like a sound echo) so you can read a sensor interface at an appropriate time after starting some process, or whether you're waiting for an event that originates in another thread running under ordinary scheduling constraints. If you want close time control under windows, you may have to write driver-level software and/or raise priorities to real-time levels and make sure those things don't run very long before blocking. I suspect that multimedia support stuff in windows might be useful for quasi-real-time stuff, but I haven't used it. (I just seem to remember reading something about that in the MSDN docs, but I am not sure. And too lazy to go back and look ;-) Regards, Bengt Richter From fuzzyman at gmail.com Tue Jan 4 09:55:40 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 Jan 2005 06:55:40 -0800 Subject: Reaching the real world Message-ID: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> I have a friend who would like to move and program lights and other electric/electro-mechanical devices by computer. I would like to help - and needless to say Python would be an ideal language for the 'programmers interface'. What I'd like is an electronic interface that connects to several relays and a python extension module to switch on and off the relays. I've had a quick google and can't see anything too similar to what I want. pyro (python robotics) seems to require expensive (relatively) robotic equipment. Does anyone know anything *similar* to what I have in mind, or have alternative suggestions ? Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From google-groups at slippytoad.com Thu Jan 13 19:51:37 2005 From: google-groups at slippytoad.com (Nick Atkins) Date: 13 Jan 2005 16:51:37 -0800 Subject: Pygtk: How to remove title bar from a window In-Reply-To: References: <1105653476.254139.58810@f14g2000cwb.googlegroups.com> Message-ID: <1105663897.698607.17720@z14g2000cwz.googlegroups.com> Thanks for the reply Diez. I'm not sure I can draw a border on its own with pyGTK but admittedly I am not yet an expert. I have the following minimal test program which opens a window and I cannot get it to draw a window with no title bar, just a border: #!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk if __name__ == "__main__": # create a popup w = gtk.Window() w.set_size_request(100, 100) w.set_decorated(False) w.set_has_frame(False) w.set_border_width(10) w.show() gtk.main() I tried removing the set_decorated and set_has_frame lines and changing them to True but I either get a complete title-bar window or nothing at all. Any ideas? Thanks. From craig at postnewspapers.com.au Mon Jan 10 18:17:51 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Tue, 11 Jan 2005 07:17:51 +0800 Subject: C structure in the Python extension In-Reply-To: References: Message-ID: <1105399071.3938.1.camel@albert.localnet> Dave win wrote: >Howdy: > When I was writting interface functions of the extending python, I >meet a question. As I using the "PyArg_ParseTuple(args,arg_type,...)" >function call, if I wanna use the personal defined argument, such as the >C structure which I made. How to make it? > >static PyObject* Call_V_ABSUB(PyObject *self, PyObject* args){ > myStruct FU; > myStruct result; > if(!PyArg_ParseTuple(args,"O&",&FU)) return NULL; > ^^^^^^^ > How to modify here??? > V_ABSUB(FU); > > return Py_BuildValue("i",result); >} > > You can't, really. Python code can't work with C structs directly, so it can't pass you one. I have used one utterly hideous hack to do this when prototyping code in the past, but that was before I knew about PyCObject. PyCObject is also pretty evil if abused, but nowhere NEAR on the scale of what I was doing. Can you say passing pointers around as Python longs? Can't bring yourself to say it? Don't blame you. My only defense was that it was quick hack prototype code, and that the Python/C API for making classes is too painful to use when quickly prototyping things. To do what you want, you could encapsulate a pointer to the struct in a PyCObject, then pass that around. Your Python code will just see a PyCObject with no attributes or methods; it can't do anything to it except pass it to other Python code (and delete it, but that'll result in a memory leak if the PyCObject holds the only pointer to the struct). Your C code can extract the pointer to the struct and work with that. DO NOT do this if the Python code just deleting the PyCObject could ever discard the last pointer to the struct, as you'll leak the struct. A much BETTER option is probably to rewrite myStruct to be a Python type ("class") implemented in C, and provide it with both a C and Python API. This isn't too hard, though the Python/C API does make creating types a bit cumbersome. (Most of this seems to be because you're playing pretend-we-have-objects in C, rather than issues specific to the Python/C API). -- Craig Ringer From craig at postnewspapers.com.au Sat Jan 22 04:46:15 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 22 Jan 2005 17:46:15 +0800 Subject: need help on need help on generator... In-Reply-To: <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> Message-ID: <1106387175.4103.16.camel@albert.localnet> On Sat, 2005-01-22 at 10:10 +0100, Alex Martelli wrote: > The answer for the current implementation, BTW, is "in between" -- some > buffering, but bounded consumption of memory -- but whether that tidbit > of pragmatics is part of the file specs, heh, that's anything but clear > (just as for other important tidbits of Python pragmatics, such as the > facts that list.sort is wickedly fast, 'x in alist' isn't, 'x in adict' > IS...). A particularly great example when it comes to unexpected buffering effects is the file iterator. Take code that reads a header from a file using an (implicit) iterator, then tries to read() the rest of the file. Taking the example of reading an RFC822-like message into a list of headers and a body blob: .>>> inpath = '/tmp/msg.eml' .>>> infile = open(inpath) .>>> for line in infile: .... if not line.strip(): .... break .... headers.append(tuple(line.split(':',1))) .>>> body = infile.read() (By the way, if you ever implement this yourself for real, you should probably be hurt - use the 'email' or 'rfc822' modules instead. For one thing, reinventing the wheel is rarely a good idea. For another, the above code is horrid - in particular it doesn't handle malformed headers at all, isn't big on readability/comments, etc.) If you run the above code on a saved email message, you'd expect 'body' to contain the body of the message, right? Nope. The iterator created from the file when you use it in that for loop does internal read-ahead for efficiency, and has already read in the entire file or at least a chunk more of it than you've read out of the iterator. It doesn't attempt to hide this from the programmer, so the file position marker is further into the file (possibly at the end on a smaller file) than you'd expect given the data you've actually read in your program. I'd be interested to know if there's a better solution to this than: .>>> inpath = '/tmp/msg.eml' .>>> infile = open(inpath) .>>> initer = iter(infile) .>>> headers = [] .>>> for line in initer: .... if not line.strip(): .... break .... headers.append(tuple(line.split(':',1))) .>>> data = ''.join(x for x in initer) because that seems like a pretty ugly hack (and please ignore the variable names). Perhaps a way to get the file to seek back to the point last read from the iterator when the iterator is destroyed? -- Craig Ringer From fredrik at pythonware.com Thu Jan 20 02:21:13 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jan 2005 08:21:13 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> Message-ID: Timothy Fitz wrote: > While I agree that the Zen of Python is an amazingly concise list of > truisms, I do not see any meaning in: > > Flat is better than nested. Python's not Pascal. From x2164 at mailcity.com Sun Jan 30 08:35:27 2005 From: x2164 at mailcity.com (x2164 at mailcity.com) Date: 30 Jan 2005 13:35:27 GMT Subject: test_socket.py failure Message-ID: 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 -- ............ From john at grulic.org.ar Tue Jan 18 09:22:13 2005 From: john at grulic.org.ar (John Lenton) Date: Tue, 18 Jan 2005 11:22:13 -0300 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: <20050118142213.GB26210@grulic.org.ar> On Mon, Jan 17, 2005 at 03:20:01PM +0000, Antoon Pardon wrote: > Op 2005-01-17, John Lenton schreef : > > > > knowledgeable and experienced users know when to ignore the rules. > > Then why seems there to be so few acknowledgement that these rules > may indeed be broken by users. My experience is that anyone who suggests > so runs the risk of being branded a (python) heretic. First you learn the basics, then you think you're knowledgeable and experienced, then you learn the rules, then you become one with the rules, and then you may break them. Most people suggesting these things haven't gotten past step #3. Using Craig's parallel to C's goto, every and all newbie using gotos should be lambasted: even if the use might be correct for the problem they are trying to solve, the reasons for its correctness are far too complex for them to grasp. But really, in practically any system, the rules are generalizations, and they exist because the particulars are too delicate to trust the unexperienced. The small print is unprintable. He dicho. -- John Lenton (john at grulic.org.ar) -- Random fortune: Yo siempre ser? el futuro Nobel. Debe ser una tradici?n escandinava. -- Jorge Luis Borges. (1899-1986) Escritor argentino. -------------- 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 Thu Jan 13 14:30:10 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 13 Jan 2005 12:30:10 -0700 Subject: Refactoring; arbitrary expression in lists In-Reply-To: References: Message-ID: BJ?rn Lindqvist wrote: >> # do other non-extension-related tests here >> if basename.find( "Makefile" ) != -1: >> return "text/x-makefile" > > > I believe this can be nicelier written as: > > if "Makefile" in basename: > +1 for "nicelier" as VOTW (Vocabulation of the week) =) Steve From fredrik at pythonware.com Sat Jan 15 07:54:05 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 15 Jan 2005 13:54:05 +0100 Subject: How to del item of a list in loop? References: Message-ID: "skull" wrote: > It makes a copy operation! so? in python, shallow copies are cheap. > here is a faster and 'ugly' solution: faster? did you try it, or are you combining a C++ mindset with an urge to do premature optimizations? (hint: it's slower) if you care about performance, you shouldn't use "remove", btw. building a new list is more efficient, especially if you use a list comprehension: lst = [i for i in lst if i != 2] (if you have 2.4, try replacing [] with () and see what happens) From bulba at bulba.com Wed Jan 5 14:08:42 2005 From: bulba at bulba.com (Bulba!) Date: Wed, 05 Jan 2005 20:08:42 +0100 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <16859.16548.249527.30210@montanaro.dyndns.org> <864d37090501050117761a32e6@mail.gmail.com> Message-ID: On Wed, 5 Jan 2005 07:37:25 -0600, Skip Montanaro wrote: > > Terry> Numarray has a record array type. If there is not one publicly > Terry> available, perhaps you could write a CSV file to record-array > Terry> slurper and contribute it to the Recipes site or maybe even the > Terry> CSV module. > >> > >> -1 on putting such a beast into the CSV module, especially if, as it > >> seems, it would rely on something outside the core. > > Carlos> Although I see your point, in the long term it will be required. > Carlos> Assuming that Numarray will, at some point in the future, be > Carlos> included in the stdlib... why not give these people some help, > Carlos> easing the integration? > >I'm not sure they really need my help. I've never needed Numarray (or >Numeric) in my own work. I've never needed numeric stuff either. I just need to do things like: .>>> table.sort(column_name) # that obviously would sort rows of table by the values of column column_name or .>>> unique = table.unique(column_name) # that would yield such a subset of all the rows that would contain unique values from column column_name or .>>> table1.union(table2 [,drop_missing_columns | ,fill_missing_with_None]) or .>>> common = table1.intersection(table2, column_name [, unique | , redundant]) # that would yield all the rows that have the same values in column_name in both table1 and table2; if optional keyword "unique" were given, those could e.g. be only rows from table1, when the "redundant" keyword were specified, that could be a union of common rows from table1 and table2 or .>>> complement = table.complement(complement_function) # where complement function could be anything, like (!cellvalue) or string.upper; that obviously would run the complement_function on every cell in table (obviously, this could also be implemented as map(table, complement_function) ) Now suppose a programmer could write a custom complement function that detects all the irregularly distributed "anomalous" data points (be it whatever, missing surnames from personnel records or values from a physical experiments that are below some threshold) in this table and returns, say, a list of tuples that are coordinates of those data points. Getting it from a specific table would be a matter of one instruction! Yes, I know, it can be written by hand. But by this line of logic why bother learning VHLL and not just stay with C? >If it's deemed useful I'm sure someone from that >community could whip something out in a few minutes. The concepts >represented by the csv module are a lot shallower than those represented by >Numarray. True, and I may scratch enough time together to learn all the necessary stuff (I'm not even half done in learning Python) to write it myself. That is not the point, however: the biggest boost and one of the main points of getting into Python, at least for me, but I'm sure this is also motivation for quite a lot of other people, is precisely the ease of exploiting capabilities of data structures like dictionaries and lists, which when coupled with this data structure's object-style .method are simply very convenient and fast. This is where IMHO Python excels among the VHLL languages. I'm about to post reworked version of my program that doesn't use a _single_ traditional loop to do all the data transformations I need (I just still need to solve some problems there / polish it). This is not just about that damn CSV file that I already have the way I wanted it and sent it to customer, this is about _terse and clear_ manipulations of rich data structures in Python. Why not extend them with flexible tables / matrices / arrays that would work in as "Pythonic" ways as dictionaries and lists already do? If Pythoners say a=['A'], it's only logical to say a.append('B'). :-) -- It's a man's life in a Python Programming Association. From ola.natvig at infosense.no Tue Jan 18 08:21:18 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Tue, 18 Jan 2005 14:21:18 +0100 Subject: generator expressions: performance anomaly? In-Reply-To: <354gj7F4etgn8U1@individual.net> References: <377Hd.77904$Jk5.30235@lakeread01> <354gj7F4etgn8U1@individual.net> Message-ID: Diez B. Roggisch wrote: >> lst = list(genexp) >> tpl = tuple(genexp) >> >> >>Since in such cases the object is build in memory any way, I don't >>think it would be a problem of having them prebuilt in memory, or am >>I missing something? > > > Yes. Consider this: > > lst = list(time.time() for i in xrange(10)) > tpl = tuple(time.time() for i in xrange(10)) > > Would it be a bad solution to make that a list or tuple of ten time.time() calls, you could also restrict what theese prebuilding sequenses could contain, or perhaps try to prebuild them, and then fail if it's impossible. -- -------------------------------------- Ola Natvig infoSense AS / development From Scott.Daniels at Acm.Org Wed Jan 12 15:14:43 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 12 Jan 2005 12:14:43 -0800 Subject: Iteration over two sequences In-Reply-To: <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> <1105549514.563799.307030@z14g2000cwz.googlegroups.com> <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> Message-ID: <41e58244$1@nntp0.pdx.net> Henrik Holm wrote: > John Lenton wrote: > > >>>def dotproduct(a, b): >>> psum = 0 >>> for i in range(len(a)): >>> psum += a[i]*b[i] >>> return psum >> >>for this particular example, the most pythonic way is to do nothing at >>all, or, if you must call it dotproduct, >> >>>>>from Numeric import dot as dotproduct > > > Downloading, installing, and getting to know numerical modules for > Python is mext on my list :). However, I was under the impression that > Numarray is preferred to Numeric -- is that correct? Are these two > competing packages? (Hopefully this is not flame war bait...) > Numarray is the future, Numeric is the "past", but in the present Numeric is better (and more mature) at some stuff than Numarray. Learning both is not much harder than learning one, actually (they share a lot). --Scott David Daniels Scott.Daniels at Acm.Org From ialbert at mailblocks.com Mon Jan 17 11:11:55 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 17 Jan 2005 11:11:55 -0500 Subject: pychecker - sets.Set need to be overridden In-Reply-To: <1105978024.706237.304360@c13g2000cwb.googlegroups.com> References: <1105978024.706237.304360@c13g2000cwb.googlegroups.com> Message-ID: wittempj at hotmail.com wrote: > <__main__.Foo instance at 0x00C578A0> Set([]) > on 2.4. on WinXP. What environment do you run in? I'm running it on cygwin, but still don't get it, why the warning? Istvan. From steve at holdenweb.com Sat Jan 1 11:51:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Jan 2005 11:51:40 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <1104511661.928284.10200@z14g2000cwz.googlegroups.com> Message-ID: <5CABd.65441$Jk5.59430@lakeread01> Cameron Laird wrote: > In article <1104511661.928284.10200 at z14g2000cwz.googlegroups.com>, > wrote: > >>Bulba wrote: >> >>>OK, so what projects and why would you consider >>>Python: >>>1. "clearly unsuitable" >> >>Large-scale scientific computing projects, such as numerical weather >>prediction, where performance is critical. Python could be used as the >>"glue" but not the "guts", where Fortran 95 and C++ are more >>appropriate. In my tests, some posted here, there has been a > > . > . > . > I feel like growling that it's clearly a mistake for large-scale > scientific computing projects not to leverage dynamic languages, > at least in part. Yes, I've seen projects that would have been > disasters if done entirely in Python. I've also seen many, many > large-scale scientific projects that soaked up far more resources > than they should have because they limited themselves to C++ or > Fortran. > > I argue that it's a false opposition to categorize projects in > terms of use of single languages. Many projects are MUCH better > off with a mix of Python and Fortran, say (and probably SQL and > JavaScript and ...), and it's pernicious to accomodate the > managerial conceit that One Language will suffice. Indeed it's sensible to choose language based on the nature of the task to be performed, to avoid "language-blindness" and to build systems in mixed languages. Unfortunately the hierarchy of power in most modern commercial and academic organizations is such that large-scale efforts will be nominally run by single individuals, and since those individuals typically can dispense favors and determine who advances within the organization it's often unwise *not* to accommodate the managerial conceit it career advancement is one's primary goal. which-is-why-i-run-my-own-business-ly y'rs - 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 lbates at syscononline.com Mon Jan 31 15:19:23 2005 From: lbates at syscononline.com (Larry Bates) Date: Mon, 31 Jan 2005 14:19:23 -0600 Subject: barchart for webpage needed In-Reply-To: References: Message-ID: dimitri pater wrote: > Hello, > > I am looking for a Python tool to create graphs and charts on a > webpage. Chartdirector is too expensive for me. A simple script for > creating a barchart should be sufficient as a starting point. > > Thanks! > Dimitri ReportLab's Graphics module is free and works quite well for me. www.reportlab.org Larry Bates From martin at v.loewis.de Sun Jan 30 03:46:51 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 30 Jan 2005 09:46:51 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xsm4j1wbe.fsf@ruckus.brouhaha.com> References: <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> <7xacqsbfk2.fsf@ruckus.brouhaha.com> <41fbcb11$0$12030$9b622d9e@news.freenet.de> <7xsm4j1wbe.fsf@ruckus.brouhaha.com> Message-ID: <41fc9eec$0$25945$9b622d9e@news.freenet.de> Paul Rubin wrote: > Oh, ok. Earlier you said you wanted user feedback before you could > conclude that there was reason to want an AES module at all. I believe I never said that. I said that I wanted user feedback to determine whether *this* AES module (where this is either your from-scratch implementation, or any other specific implementation contributed) is desirable. > Hmm, this is very very interesting. I am highly confident that all > the purely technical questions (i.e. everything about the API and the > code quality, etc.) can converge to a consensus-acceptable solution > without much hassle. I had thought there were insurmountable > obstacles of a nontechnical nature, mainly caused by legal issues, and > that these are beyond any influence that I might have by writing or > releasing anything. These obstacles are indeed real. But I believe they are not unsurmountable. For example, there is the valid complaint that, in order to export the code from SF, we need to follow U.S. export laws. 10 years ago, these would have been unsurmountable. Today, it is still somewhat painful to comply with these laws, but this is what the PSF is for, which can fill out the forms necessary to allow exporting this code from the U.S.A. Regards, Martin From elephantum at dezcom.mephi.ru Sun Jan 9 06:05:31 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 14:05:31 +0300 Subject: python3: 'where' keyword In-Reply-To: <7xk6qnzd3d.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> Message-ID: <34chfrF490f8aU1@individual.net> Paul Rubin wrote: > You mean I can't say > > # compute sqrt(2) + sqrt(3) > x = (sqrt(a) where: > a = 2.) \ > + sqrt (a) where: > a = 3. No, I'd prefer to not embed 'where' into expression. From t-meyer at ihug.co.nz Wed Jan 26 21:52:54 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Thu, 27 Jan 2005 15:52:54 +1300 Subject: Which is faster? In-Reply-To: Message-ID: > Any idea which of the following is faster? > > 'a/b/c/'[:-1] > > or > > 'a/b/c/'.rstrip('/') > > Thanks in advance. > > P.S. I could time it but I thought of trying my luck here > first, in case someone knows already, and of course the reason. Timing it is almost no work, though: >>> import timeit >>> timeit.Timer("'a/b/c/'[:-1]").timeit() 0.23856551600831949 >>> timeit.Timer("'a/b/c/'.rstrip('/')").timeit() 0.74258655778876914 The obvious reason for the former to be faster (although I haven't checked to see whether it's true) is because the latter checks for a specific character, whereas the former just snips it off whatever it is. =Tony.Meyer From phr at localhost.localdomain Mon Jan 24 15:25:18 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Mon, 24 Jan 2005 20:25:18 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <1106564799.011057.181280@c13g2000cwb.googlegroups.com> Message-ID: "Fuzzyman" writes: > I also feel the lack of a standard cryptography module in the core... > even a *basic* one. At least rotor provided that, before it was deprecated. Rotor was insecure and really shouldn't have been used. If you need crypto in pure Python, try this: http://www.nightsong.com/phr/crypto/p3.py It's a nonstandard algorithm, but so was rotor. Its security should be much better than rotor's, and its speed should be tolerable for most purposes. From tim.peters at gmail.com Fri Jan 14 18:20:57 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 14 Jan 2005 18:20:57 -0500 Subject: oddities in the datetime module In-Reply-To: <41e84175$0$258$edfadb0f@dread12.news.tele.dk> References: <41e79a1a$0$264$edfadb0f@dread12.news.tele.dk> <41e84175$0$258$edfadb0f@dread12.news.tele.dk> Message-ID: <1f7befae050114152031a6f13f@mail.gmail.com> [Max M] > ... > First of, it should be possible to easily convert between the > datetime objects. Why? All the conversions people asked for when the module was being designed were implemented. > And eg. the date object doesn't have a datetime() method. Which > it could easily have. But not a *sensible* one. If you only have a date (or time), what's a conversion to datetime supposed to do about the "missing values"? Guess? No good. > Neither does time. They could have. But I don't think that > is the way to solve it. datetime.datetime objects have .date() and .time() methods, returning the obvious datetime.date and datetime.time slices of the datetime.datetime. The class constructor datetime.combine() goes in the other direction, building a datetime.datetime object by combining a datetime.date and a datetime.time. > It is a problem if you make a subclass of datetime. Often you > will ned to make datetime arithmetics with the new class. > > Like: datetime_subclass_1 + datetime_subclass_2 > > The result of that is a plain datetime If your subclass doesn't override __add__, yes. > In that case you will rather want your own subclass returned. While possible, that's not necessarily so of all subclasses. > But subclasses of datetime returns datetime objects. Not the > subclass. That depends on whether the subclass overrides __add__, and if so, the code in its __add__ method. > So to do an add of your own objects you must convert the output > to your own class "manually" > > class my_datetime(datetime): > > def __add__(self, other): > result = datetime.__add__(self, other) > return my_datetime(result.timetuple()[:6]) > > datetime(), time() etc. methods will not help with this. Well, it's unclear where you think you need help there. If that's what you want your subclass __add__ to do, you've already done it, right? It could save tedium to give your subclass a class constructor, e.g., from_datetime(), and then code __add__ as def __add__(self, other): return my_datetime.from_datetime(datetime.__add__(self, other)) Whether the implementation wants to use timetuple() depends on what the subclass wants to do; for example, a subclass that intends to support a notion of time zone needs more than just that. From beliavsky at aol.com Thu Jan 20 21:21:16 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 20 Jan 2005 18:21:16 -0800 Subject: problems with duplicating and slicing an array References: Message-ID: <1106274076.241474.245030@f14g2000cwb.googlegroups.com> Yun Mao wrote: >I have some questions when I'm using python numeric: >1. When I do v = u[:, :], it seems u and v still point to the same >memory. e.g. When I do v[1,1]=0, u[1,1] will be zero out as well. >What's the right way to duplicate an array? Now I have to do v = >dot(u, identity(N)), which is kind of silly. You can use v = 1*u or v = u.copy() to get the type of copy you want. >2. Is there a way to do Matlab style slicing? Use the take function. The output of the following code from Numeric import array,take a = array([1,2]) b = a c = 1*a d = a.copy() a[0] = 3 print b print c print d print take(a,[1,0,1]) is [3 2] [1 2] [1 2] [2 3 2] From a at b.c Sat Jan 22 14:18:57 2005 From: a at b.c (Doug Holton) Date: Sat, 22 Jan 2005 13:18:57 -0600 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> Message-ID: <46ednYMe9-q4Om_cRVn-tQ@comcast.com> Fredrik Lundh wrote: > A.M. Kuchling wrote: > > >>IMHO that's a bit extreme. Specifications are written to be detailed, so >>consequently they're torture to read. Seen the ReStructured Text spec >>lately? > > > I've read many specs; YAML (both the spec and the format) is easily > among the worst ten-or-so specs I've ever seen. What do you expect? YAML is designed for humans to use, XML is not. YAML also hasn't had the backing and huge community behind it like XML. XML sucks for people to have to write in, but is straightforward to parse. The consequence is hordes of invalid XML files, leading to necessary hacks like the mark pilgrim's universal rss parser. YAML flips the problem around, making it harder perhaps to implement a universal parser, but better for the end-user who has to actually use it. More people need to work on improving the YAML spec and implementing better YAML parsers. We've got too many XML parsers as it is. From steve at holdenweb.com Fri Jan 21 09:37:28 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Jan 2005 09:37:28 -0500 Subject: PyCon Preliminary Program Announced! In-Reply-To: References: <20050121000607.DE1261E4010@bag.python.org> <41F061C3.3000802@gmail.com> <1f7befae0501201952139c57a8@mail.gmail.com> Message-ID: <41F113A8.8020908@holdenweb.com> Timothy Fitz wrote: >>I don't care much for "parallel tracks" myself, because I want to hear >>basically everything. But we had more proposals of higher quality >>this year than ever before, so it came down to scheduling more talks >>in parallel than ever before too, or rejecting perfectly good >>proposals. > > > Will there be recordings of any of these presentations? There are > quite a few times when I want to be at all three tracks at the same > time. There are currently loose plans to have each session recorded. This will, however, require massive volunteer effort which so far nobody has offered to coordinate, so unless someone steps up to the plate with a sound plan to ensure that at least the initial capture takes place this may remain a pipe dream (there are limits to the chairman's powers that he is starting to treat as actual rather than theoretical ;-) What's actually required? Someone needs to start a resource, with a copy of the schedule ( and a Wiki page might do, its source can be lifted directly from the Wiki source of http://www.python.org/moin/PyConDC2005/Schedule) that allows volunteers to sign up to record specific sessions. We also need a release form that speakers can sign to allow the recording to take place and for it to be published under a suitable Creative Commons license. We need advice on file formats and software for Linux, Windows and Mac (plus any other platforms that may be used): experience says that apparently it's possible to make acceptable recordings with an external microphone such as a lapel mike from the front of the room, without involving the University. If someone wants to liaise about electronic feeds I'll certainly facilitate interaction with GWU as long as the cost is acceptable (zero would be best). Finally we need someone coordinating at the conference to make sure this all happens, that the release forms are collected, and that the sound files are made available - probably on www.python.org. This is a /community conference/, guys. I *know* the Python community can collectively take this task and eat it for breakfast, but please don't believe it will happen as a result of a few newsgroup posts saying what a nice idea it would be. Things don't happen that way, and I have the grey hairs to prove it. Please, make this happen! 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 tdelaney at avaya.com Sun Jan 30 18:02:12 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 31 Jan 2005 10:02:12 +1100 Subject: Pystone benchmark: Win vs. Linux (again) Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025202F1@au3010avexu1.global.avaya.com> Franco Fiorese wrote: > * Windows XP Pro: 16566.7 pystones/second > * Linux (kernel 2.6.9 NPTL): 12346.2 pystones/second First of all, realise that pystone is not meant to be a general-purpose benchmarking program. It test a specific, *small* subset of the functionality available in Python. It's also not meant to be able to compare across machines, etc. It's highly susceptible to cache effects and various other things. If you include parrotbench you will get a better view of things, but it's also not designed for comparisons across machines. Tim Delaney From http Thu Jan 6 17:16:13 2005 From: http (Paul Rubin) Date: 06 Jan 2005 14:16:13 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> Message-ID: <7xzmzmurte.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > Yes, apart from libraries and similar cases (frameworks etc), it's no > doubt rare for closed-source "end-user packages" to be sold with > licenses that include source and allow you to "do anything with it". > > However, allowing customization (at least for internal use within the > customer organization), while rare, is far from unheard of. There's no obstacle to doing that with GPL'd software either. From bulba at bulba.com Tue Jan 4 14:06:57 2005 From: bulba at bulba.com (Bulba!) Date: Tue, 04 Jan 2005 20:06:57 +0100 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> Message-ID: On Tue, 4 Jan 2005 11:15:54 +0100, aleaxit at yahoo.com (Alex Martelli) wrote: >Also, you keep talking about "the core python team" on the basis, it >would appear, of reading one document by Guido. Have you bothered doing >a MINIMUM of homework, such as, looking at > http://www.amk.ca/diary/archives/cat_python.html >and specifically AMK's entry for September 30? This complaint about "syntax cruft" is really weird, as while browsing through the old and new docs I got the impression that Python hasn't really changed so much as just added new, and mostly well-chosen features. What's not to like in sets for instance?! However, I do have to concede that Python as environment still has a way to go - not the language features are missing, but better _standard_ IDE and debugger. E.g. Pythonwin debugger sometimes simply dies on me, I have no idea why. This is not to criticize the great work that you guys are doing and the results of which we get FOR FREE (something in principle I don't believe), but merely to indicate that Python has grown and so did the expectations. People tend to get spoilt: they expect to find in a free product the gazillion of VS-like features. :-) As we say here, "appetite tends to grow as you eat". E.g. right now I would kill for a standard, built-in matrix type that would be as flexible as lists and dictionaries are in Python, so that I could slurp the whole CSV file or some other table in one instruction into a matrix that could accomodate data types likes strings and floats (just like dictionaries do - just, say, declare, "column 1 of matrix contains strings, and please convert the values in column 2 into floats"), and then easily do some fancy matrix transformations. Clean and expressive syntax plus flexibility of lists and dictionaries are the main reasons I got into Python. Where else could I do smth as neat as writing a CSV header with: DictWriterInstance.writerow(dict(zip(titles,titles))) Note I didn't have to do any operations myself: all that was necessary for me as a programmer was to figure out how to connect the Lego pieces together. We need more of this sort of expressive power in a standard library and built-in types. This is the subconscious power of attraction in Python I think. :-) I'm not a language designer. I don't know how to get there. I just would love to see more of that around. To summarize, it's not the language that is would be nice to develop further. Those are: - more of the rich, flexible data types - more extensive standard debugger - possibly standard IDE with more features that are typically found in commercial products No, really, guys, great thanks for all that work. -- Real world is perfectly indifferent to lies that are the foundation of leftist "thinking". From rnd at onego.ru Wed Jan 12 12:03:53 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 12 Jan 2005 20:03:53 +0300 (MSK) Subject: java 5 could like python? In-Reply-To: References: Message-ID: On Wed, 12 Jan 2005, vegetax wrote: >-No naming convention. The speech of "it fits in my head" is no longer valid >when i use a lot of functionality,modules,classes in a large proyect. >For example if i remember a function i want ie:get attribute, i dont >remember if the module implementer coded it as >getAttribute,GetAttribute,get_attribute, then i have to go and check the >doc, every time,which is a waste of time. Or yes, I hate those 'get' too. Why not to use just obj.attribute instead? Otherwise, the pluralism present in Python, makes me feel more at home. >-library Organization,we have modules that can have 20 classes(I imagine >that is because of the commodity of having all in one file) which makes >reading the doc horribly painfull and is very hard to find the stuff >coupled with the "pool" of modules that is the python installation >directory,all throwed away at the installation directory without a >categorization. Probably some Really Large Corporation could add Python Standard Library Enterprise Edition and win big. >-Is python library half object oriented? half functional oriented? I can Right now it change its orientation to iterator/generators... I image a nice box with Python 3 in it, where there will be no more inconsistencies with naming, etc. >understand that python allows some functional programing components when >they are necesary,but there are libraries that totaly ignore object >orientation which makes them problematic to use.for example,Whats with the >os.path module and files? why do i have to say os.path.getfilesize(f.name) >all the time? why cant i say f.size? Why does urlparse returns a tuple of 7 >items instead of an URL object? why there isnt an URL object? and so on.. This reminds me of attributes vs. tags debate of how to structure XML. size(f) or f.size() - that is the question >I havent figured out a way to overcome those factors,the delaying and lost >of focus that is having to check the docs all the time,every 5 seconds and >having to make object oriented wrapers for several libraries or having to >go and read the source code to know what the heck a function returns or >what are its arguments makes coding unpleasant an very slow , i often have >15 pydocs windows open at the same time. What should i do? Do not use windows. Sit for an evening add read all the docs. Coding will becaome much faster. >-Realying on ides is imposible due to python dinamic nature,very litle(next >to nothing) assistance can be espected from them. Class browsing and auto-completion are probably the only features I sometime miss. But otherwise what IDEs are for? >-Memorazing all the function names,parameters,return values,conventions of >the modules i use doesnt look like a good solution. But it is a must: how do you communicate if you do not nother to remember words? >Join it with poor and outdated documention and we have a very unpleasant >standard library. >class C{ > public void func(){ > print("hello world"); // instead of System.out.println("hello world"); Probably print statement will not make it into Python 3.0. Very sad. > print(run("ls /tmp")); > } >} > >Same for almost all python builtin functions. > >Also there is the generics support and so on.. > >But for some reason i dont know,the switch back feels wrong =( ,would it be >posible to imitate python's behavior with the new java features and some >hacks? would be worth the effort? If not what can i do to use efficiently >python modules and libraries? I recall, i didnt had this problem when doing >small applications with a small set of modules. > >Sorry for my bad english. That is it. I hate English. It has sooo much exceptions to remember! Esperanto is much cleaner language. UN should drop all it's official languages and use Esperanto instead. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From steven.bethard at gmail.com Sun Jan 23 15:14:10 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 23 Jan 2005 13:14:10 -0700 Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) In-Reply-To: <41f325b5.1576259210@news.oz.net> References: <41f325b5.1576259210@news.oz.net> Message-ID: <6I2dnYLoXdcTmGncRVn-vw@comcast.com> Bengt Richter wrote: > On Sat, 22 Jan 2005 16:22:33 +1000, Nick Coghlan wrote: > > >>Steven Bethard wrote: >> >>>I wrote: >>> > If you really want locals that don't contribute to arguments, I'd be >>> > much happier with something like a decorator, e.g.[1]: >>> > >>> > @with_consts(i=1, deftime=time.ctime()) >>> > def foo(x, y=123, *args, **kw): >>> > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime >>> > >>> > Then you don't have to mix parameter declarations with locals >>> > definitions. >>> > >>> > Steve >>> > >>> > [1] I have no idea how implementable such a decorator would be. I'd >>> > just like to see function constants declared separate from arguments >>> > since they mean such different things. >>> >>>I played around with this, and I think it's basically implementable: >> >>Raymond's constant binding decorator is probably a good model for how to do it: >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 >> > > > I thought so too. I modified it to accept **presets as a keyword argument > and generate constants and assignments from its values matching assignment names > when the rhs was __frompresets__, e.g., > > >>> from makeconstpre import make_constants as pre > >>> import time > >>> @pre(verbose=True, deftime=time.ctime(), a=1, b=2, c=3, pi=__import__('math').pi) > ... def foo(): > ... deftime = __frompresets__ > ... b, a = __frompresets__ > ... c = __frompresets__ > ... pi = __frompresets__ > ... return locals() > ... > __frompresets__ : deftime --> Sat Jan 22 20:18:09 2005 > __frompresets__ : ('b', 'a') --> (2, 1) > __frompresets__ : c --> 3 > __frompresets__ : pi --> 3.14159265359 > locals --> Hmm... Having to state deftime = __frompresets__ when you've already stated deftime=time.ctime() seems a little redundant to me... Steve From FBatista at uniFON.com.ar Wed Jan 5 14:58:47 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 5 Jan 2005 16:58:47 -0300 Subject: Python evolution: Unease Message-ID: [Daniel Bowett] #- Contribute to where on Sourceforge??? Which domentation are #- we talking #- about in general? Suppose you're reading Python documentation. Don't know, for example, os.remove(). There you find that a particular parragraph is difficult to understand. You say "Hey, this could be better written", so you write i a more pedagogic way. After that you go to SF, Python project (http://sourceforge.net/projects/python), and go to Bugs. There, if you are logged in SF, you will see a "Submit new" link. You click on it and you'll see a form to fill. Select some fields (specially bug group in "Documentation") and in "Detailed Description:" you put something like "This particular sentence was difficult to read. Attaching a new way to write it". Of course, then attach the file of your text (if it's short enough you can put it directly in that field). Of course, if you write any NEW documentation about something that is not documented at all, or find some more serious issues with the docs (for example, bad argument count in a function) you can follow the same steps. . 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 grahamd at dscpl.com.au Thu Jan 6 05:10:11 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 6 Jan 2005 02:10:11 -0800 Subject: Contributor's List References: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> Message-ID: <1105006211.527899.318740@c13g2000cwb.googlegroups.com> Anand wrote: > A list of contributors to Python Cookbook (Second Edition) is available > at the following links. Original list courtesy Alex Martelli. > > Since the book is not yet in print, the lists are still tentative > because of potential last minute editing changes. > > List of first authors > o http://harvestman.freezope.org/cookbook/credau.html > > List of all authors > o http://harvestman.freezope.org/cookbook/creds.html Is this mean't to only cover additional entries which were added in the 2nd edition, or is it also mean't to encompass entries which were carried over from the 1st edition as well. If it is both, then the editing must have been quite cut throat as I dropped from 3 entries in the 1st edition to 0 in the 2nd edition. I can sort of understand if the intent was to get rid of entries which referenced packages which weren't regarded as mainstream. I guess it is only 14 years of work down the drain. ;-( From steve at holdenweb.com Mon Jan 17 09:45:51 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 09:45:51 -0500 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Antoon Pardon wrote: > Op 2005-01-17, Steve Holden schreef : > >>Antoon Pardon wrote: >> >> >>>Op 2005-01-17, Steve Holden schreef : >>> >>> >>>>Antoon Pardon wrote: >>>>[...] >>>> >>>> >>>>>>"A foolish consistency is the hobgoblin of little minds". Rules are made >>>>>>to be broken. >>>>> >>>>> >>>>>Like only use immutables as dictionary keys. >>>>> >>>> >>>>Fair enough, but don;t go advising newbies to do this. >>> >>> >>>How about something like this. >>> >>>Because of the extra precautions one has to take when >>>using mutables as hash keys, we advise newbies >>>to stick with immutable keys until they have gathered >>>enough knowledge and experience to adequatly weight >>>the pro and cons of a mutable key solution against >>>an immutable key solution. >>> >> >>There you go with the minutiae again. How about: >> >>"Don't use mutables as hash keys"? > > > That sounds too dogmatic to my ears. I also find it > too selective. The problem with mutables as dictionary > keys is not specific to dictionaries. Everywhere you > have mutables in a container, it is possible that > mutating the object in the container will cause > problem. Heck even using mutables as arguments can > cause trouble. Why else the specific advice against > > def foo(p = []) > > type of arguments. So should we adopt the principles: > > Don't use mutables in containers > > Don't use mutables as default values for parameters > > Don't use mutables as arguments. > > Don't assign one mutable to an other. > > > I don't see a big difference between these principles > and the hash key principle, so in the end may be we > should just stick with the more general principle: > > Don't use mutables! > > > and be done with it. > http://redwing.hutman.net/~mreed/warriorshtm/tirelessrebutter.htm 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 jacek.generowicz at cern.ch Thu Jan 13 08:13:28 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 Jan 2005 14:13:28 +0100 Subject: from __future__ import decorators References: Message-ID: Peter Otten <__peter__ at web.de> writes: > Have a look at Bill Mill's redecorate utility: > > http://llimllib.f2o.org/files/redecorate.py Heh, this is exactly the sort of thing I wanted do avoid writing, as it would be difficult to get right. Looks like it's author has similar feelings. However, it could well be the most pragmatic solution in my case. Thanks. From chris.cavalaria at free.fr Sun Jan 16 09:25:57 2005 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Sun, 16 Jan 2005 15:25:57 +0100 Subject: Newbie inheritance question. References: Message-ID: <41ea7975$0$6635$626a14ce@news.free.fr> bwobbones wrote: > Hi all, > > I'm a java programmer struggling to come to terms with python - bear > with me! > > I'm trying to subclass a class, and I want to be able to see it's > attributes also. Here are my classes: > > two.py > ***************************** > from one import one > > class two(one): > def __init__(self): > print "two" > > def printTestVar(self): > print "testVar: " + str(self.testVar) > ***************************** You simply forgot to call the parent __init__. You have to do that explicitely in Python. From lbates at syscononline.com Wed Jan 26 17:49:51 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 26 Jan 2005 16:49:51 -0600 Subject: exclude binary files from os.walk In-Reply-To: References: <41f8167b$0$8648$a1866201@visi.com> Message-ID: There's no definitive way of telling a file is "non-ascii". Bytes in a binary file define perfectly good ascii characters. Windows depends on file extensions to try to keep track of the "type" of data in a file, but that isn't foolproof. I can rename a plain ascii file with a .EXE extension. We could be of more help, if you would take the time to explain a little about what you are trying to do. Larry Bates rbt wrote: > Grant Edwards wrote: > >> On 2005-01-26, rbt wrote: >> >> >>> Is there an easy way to exclude binary files (I'm working on >>> Windows XP) from the file list returned by os.walk()? >> >> >> >> Sure, assuming you can provide a rigorous definition of 'binary >> files'. :) > > > non-ascii From peter at engcorp.com Sat Jan 29 22:57:34 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 Jan 2005 22:57:34 -0500 Subject: cx_freeze error In-Reply-To: <1107054796.999110.18380@c13g2000cwb.googlegroups.com> References: <1107048210.548048.152870@z14g2000cwz.googlegroups.com> <1107054796.999110.18380@c13g2000cwb.googlegroups.com> Message-ID: zyqnews at 163.net wrote: > There is no any module like "re.py", I just compiled the hello.py it > has only one line: > print "hello!" Interesting. Just to confirm, could you try this? Run Python, and at the interactive prompt, type the following: >>> import re >>> re.compile >>> re.__file__ (path to file re.pyc) If you get an AttributeError after the second line, then the result of the third line (re.__file__) will tell you where this "re" module is that doesn't have a compile() function like it should have. Either there's an "re" kicking around that shouldn't be there, or cx_freeze is doing something weird... at least, those are the only theories that come to mind. -Peter From fireeagle at comcast.net Thu Jan 27 01:58:35 2005 From: fireeagle at comcast.net (fireeagle) Date: Wed, 26 Jan 2005 22:58:35 -0800 Subject: (no subject) Message-ID: <20050127065832.49BCA1E4004@bag.python.org> Subscribe -------------- next part -------------- An HTML attachment was scrubbed... URL: From binux.lists at gmail.com Thu Jan 6 03:57:40 2005 From: binux.lists at gmail.com (Binu K S) Date: Thu, 6 Jan 2005 14:27:40 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> <003801c4f3b9$af17fa20$0800a8c0@vishnu> <2b7d8b42050105232546083758@mail.gmail.com> Message-ID: <2b7d8b420501060057270f1878@mail.gmail.com> On Thu, 6 Jan 2005 13:17:11 +0530, Gurpreet Sachdeva wrote: > On Thu, 6 Jan 2005 12:55:22 +0530, Binu K S wrote: > >>>The file's current position moves as you write into it. > I concure and have figured out the solution BUT while reading from the > file from the position where the file handler is, should return > "Null/Blank/Anything in this world" BUT should not write into the > file... > The information written was that in the Buffer of the handler... Does > that mean reading a file will actually release the buffer by throwing > the contents in the file??? > I'm sorry, I didn't get what you trying to say here. Where do you see a read altering the file? An example might help. > Please Comment... > > >>>You normally wouldn't read from the file that you are writing into. > > May be applicable in handling logs... Sometimes after opening a file you read the contents of a file and then append to it. I haven't seen writing to a file and then going back to see what was written. > > Regards, > Garry > From martin at v.loewis.de Wed Jan 12 03:12:43 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 12 Jan 2005 09:12:43 +0100 Subject: Wide Unicode build for Windows available somewhere? In-Reply-To: <1105485536.966610.76570@z14g2000cwz.googlegroups.com> References: <1105485536.966610.76570@z14g2000cwz.googlegroups.com> Message-ID: <41e4dbf8$0$30343$9b622d9e@news.freenet.de> cwittern at yahoo.com wrote: > I am trying to locate a windows binary of a recent python (2.4 > preferred, but not essential) with support for Unicode characters > with values greater than 0x10000. I have tested the python.org > binaries and those from Activestate, both give me a traceback on > unichr(0x10000) and tell me its a "narrow" build. Wide unicode is currently not supported on Windows. A number of internal APIs (in particular for the registry, and for the "mbcs" codec) assume that sizeof(Py_UNICODE) is 2. Contributions are welcome. Even with that fixed, Pythonwin would still need a major rework to support wide Unicode. Regards, Martin From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 13:48:46 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-15?Q?Martin_MOKREJ=A6?=) Date: Mon, 10 Jan 2005 19:48:46 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <1105381712.3588.15.camel@localhost.localdomain> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> Message-ID: <41E2CE0E.5000704@ribosome.natur.cuni.cz> Adam DePrince wrote: > On Mon, 2005-01-10 at 11:11, Martin MOKREJ? wrote: > >>Hi, >> I have sets.Set() objects having up to 20E20 items, >>each is composed of up to 20 characters. Keeping >>them in memory on !GB machine put's me quickly into swap. >>I don't want to use dictionary approach, as I don't see a sense >>to store None as a value. The items in a set are unique. > > > Lets be realistic. Your house is on fire and you are remodeling the > basement. > > Assuming you are on a 64 bit machine with full 64 bit addressing, your > absolute upper limit on the size of a set is 2^64, or > 18446744073709551616 byte. Your real upper limit is at least an order > of magnitude smaller. > > You are asking us how to store 20E20, or 2000000000000000000000, items > in a Set. That is still an order of magnitude greater than the number > of *bits* you can address. Your desktop might not be able to enumerate > all of these strings in your lifetime, much less index and store them. > > We might as well be discussing the number of angles that can sit on the > head of a pin. Any discussion of a list vs Set/dict is a small micro > optimization matter dwarfed by the fact that there don't exist machines > to hold this data. The consideration of Set vs. dict is an even less > important matter of syntactic sugar. > > To me, it sounds like you are taking an AI class and trying to deal with > a small search space by brute force. First, stop banging your head > against the wall algorithmically. Nobody lost their job for saying NP > != P. Then tell us what you are tring to do; perhaps there is a better > way, perhaps the problem is unsolvable and there is a heuristic that > will satisfy your needs. Hi Adam, just imagine, you want to compare how many words are in English, German, Czech, Polish disctionary. You collect words from every language and record them in dict or Set, as you wish. Once you have those Set's or dict's for those 4 languages, you ask for common words and for those unique to Polish. I have no estimates of real-world numbers, but we might be in range of 1E6 or 1E8? I believe in any case, huge. My concern is actually purely scientific, not really related to analysis of these 4 languages, but I believe it describes my intent quite well. I wanted to be able to get a list of words NOT found in say Polish, and therefore wanted to have a list of all, theoretically existing words. In principle, I can drop this idea of having ideal, theoretical lexicon. But have to store those real-world dictionaries anyway to hard drive. Martin From bokr at oz.net Fri Jan 14 17:29:01 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 14 Jan 2005 22:29:01 GMT Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> <39ednWfqlrgB6HvcRVn-iA@powergate.ca> <41e6f606.777680996@news.oz.net> <34qjvcF4dkctuU2@individual.net> Message-ID: <41e83e05.861647303@news.oz.net> On Fri, 14 Jan 2005 20:13:48 +0100, Reinhold Birkenfeld wrote: >Bengt Richter wrote: >> On Thu, 13 Jan 2005 08:18:25 -0500, Peter Hansen wrote: >> >>>and-google at doxdesk.com wrote: >>>> In Mythical Future Python I would like to be able to use any base in >>>> integer literals, which would be better. Example random syntax: >>>> >>>> flags= 2x00011010101001 >>>> umask= 8x664 >>>> answer= 10x42 >>>> addr= 16x0E800004 # 16x == 0x >>>> gunk= 36x8H6Z9A0X >>> >>>I think I kinda like this idea. Allowing arbitrary values, >>>however, would probably be pointless, as there are very >>>few bases in common enough use that a language should make >>>it easy to write literals in any of them. So I think "36x" >>>is silly, and would suggest limiting this to 2, 8, 10, and >>>16. At the very least, a range of 2-16 should be used. >>>(It would be cute but pointless to allow 1x000000000. :-) >>> >> My concern is negative numbers when you are interested in the >> bits of a typical twos-complement number. (BTW, please don't tell me >> that's platform-specific hardware oriented stuff: Two's complement is >> a fine abstraction for interpreting a bit vector, which is another >> fine abstraction ;-) >> >> One way to do it consistently is to have a sign digit as the first >> digit after the x, which is either 0 or base-1 -- e.g., +3 and -3 would be >> >> 2x011 2x101 >> 8x03 8x75 >> 16x03 16xfd >> 10x03 10x97 > >Why not just -2x11? IMHO, Py2.4 does not produce negative values out of >hex or oct literals any longer, so your proposal would be inconsistent. > Inconsistent with what? This is a new based-literal representation, not the old hex or octal representation. It is separate and self-consistent, and can live along side the old. The fact that there is no longer a way to represent negative numbers with traditional octal or hex is due to getting away from the platform-dependent assumptions that bit 31 was a sign bit of a 32-bit two-s complement machine represenentation. That was a good thing to get away from. But it means you now have to write a unary minus expression for negative numbers, not a self-contained literal. Re your question, -2x11 is the same as -(2x11) so you have to decide what you want 2x11 to mean. If it means +3, we are back to the original problem of having no way to see any of the 111111111111....101 or ffff....fd of a -3 ;-) (Except of course by '%02x'%(-0x3&0xff) -- ick) I am not proposing a change to the new Py2.4 positive-only hex and octal literals. I just want to be able to write literals for both positive and negative numbers as self-contained literals (not expressions) without a '-' sign, and have the representation be a readable representation of typical twos-complement representation. You can't do that with -0x3, because (though the expression equals -3) it doesn't show the information about the bits that you get with 16xfd or 2x101. Note that -16xfd == 16x03 and -2x101 == 2x011 and -16x03 == 16xfd and -2x011 == 2x101. The '-' sign is not part of the literal. Regards, Bengt Richter From a at b.c Thu Jan 6 21:34:31 2005 From: a at b.c (Doug Holton) Date: Thu, 06 Jan 2005 20:34:31 -0600 Subject: Embedding a restricted python interpreter In-Reply-To: References: Message-ID: Rolf Magnus wrote: > Hi, > > I would like to embed a python interpreter within a program, but since that > program would be able to automatically download scripts from the internet, > I'd like to run those in a restricted environment, which basically means > that I want to allow only a specific set of modules to be used by the > scripts, so that it wouldn't be possible for them to remove files from the > hard drive, kill processes or do other nasty stuff. > Is there any way to do that with the standard python interpreter? Hi, there is a page on this topic here: http://www.python.org/moin/SandboxedPython The short answer is that it is not possible to do this with the CPython, but you can run sandboxed code on other virtual machines, such as Java's JVM with Jython, or .NET/Mono's CLR with Boo or IronPython. In the future it may also be possible to do this with PyPy or Parrot. From wuwei23 at gmail.com Mon Jan 24 02:09:07 2005 From: wuwei23 at gmail.com (alex23) Date: 23 Jan 2005 23:09:07 -0800 Subject: how to write a tutorial In-Reply-To: References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106531824.833549.28720@c13g2000cwb.googlegroups.com> Message-ID: <1106549330.444901.170110@f14g2000cwb.googlegroups.com> Daniel Bickett wrote: > You guys are just begging for a YHBT ;-) Point taken :) I've noticed very few people even acknowledge his posts at all; I'll follow the group lead and do the same. Cheers! - alex23 From __peter__ at web.de Thu Jan 27 03:17:33 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Jan 2005 09:17:33 +0100 Subject: Which is faster? References: <1106793602.782397.61260@z14g2000cwz.googlegroups.com> Message-ID: Aggelos I. Orfanakos wrote: > Any idea which of the following is faster? > > 'a/b/c/'[:-1] > > or > > 'a/b/c/'.rstrip('/') Don't ask for the speed, decide whether you want to transform "a/b/c" --> "a/b/c" "a/b/c//" --> "a/b/c" or "a/b/c" --> "a/b/" "a/b/c//" --> "a/b/c/" That is much more important. Peter From rkern at ucsd.edu Fri Jan 7 22:06:31 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 07 Jan 2005 19:06:31 -0800 Subject: Python evolution: Unease In-Reply-To: <41deb485$1@nntp0.pdx.net> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7x4qhw859p.fsf@ruckus.brouhaha.com><7xk6qrnbum.fsf@ruckus.brouhaha.com><41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41deb485$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > If you can wait, the plan for MacEnthon (Python 2.4 on Mac) looks great: Actually, just packages for 2.3 (or 2.3.x for Tiger) as of right now. When someone else packages up 2.4 nicely, I'll start making packages for that, too. > http://www.scipy.org/wikis/featurerequests/MacEnthon > > I seem to remember discussion about synchronizing with the windows 2.4 > version to have essentially the same list. They probably won't be synchronized too much. My additions to the list are primarily for the people I need to support within my organization. Or my own personal sense of whimsy. -- 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 fuzzyman at gmail.com Wed Jan 5 07:13:18 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2005 04:13:18 -0800 Subject: is python more popular than coldfusion? In-Reply-To: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1104927198.542009.208630@z14g2000cwz.googlegroups.com> Definitely ! Fuzzy http://www.voidspace.org.uk/python/index.shtml From fredrik at pythonware.com Thu Jan 13 14:15:20 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Jan 2005 20:15:20 +0100 Subject: sorted (WAS: lambda) References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com><7x7jmh1eek.fsf@ruckus.brouhaha.com> <7xpt09xizb.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> Note that sorted is a builtin function, not a method of a list >> object. > > Oh, same difference. I thought it was a method because I'm not using > 2.4 yet. The result is the same nope. sorted works on any kind of sequence, including forward-only iterators. sorted(open(filename)) works just fine, for example. > other than that having it as a function instead of a method is another > inconsistency to remember I suspect that you don't really understand how sequences and iterators work in Python... From ionel.mc at gmail.com Sun Jan 9 10:07:53 2005 From: ionel.mc at gmail.com (ionel) Date: Sun, 9 Jan 2005 17:07:53 +0200 Subject: raw sockets ? i need a python sniffer Message-ID: on windows xp well i got pylibpcap-0.4 but i can't compile it :( i got python 2.4, visual studio 2003 when i run "setup.py build" i get this: C:\Python24\lib\distutils\dist.py:222: UserWarning: 'licence' distribution optio n is deprecated; use 'license' warnings.warn(msg) running build running build_py running build_ext building 'pcapcmodule' extension Traceback (most recent call last): File "d:\_PRO\__11\lib\pylibpcap-0.4\pylibpcap-0.4\setup.py", line 104, in ? cmdclass = {'clean': pcapclean, 'build_ext':pcap_build_ext}, File "C:\Python24\lib\distutils\core.py", line 149, in setup dist.run_commands() File "C:\Python24\lib\distutils\dist.py", line 946, in run_commands self.run_command(cmd) File "C:\Python24\lib\distutils\dist.py", line 966, in run_command cmd_obj.run() File "C:\Python24\lib\distutils\command\build.py", line 112, in run self.run_command(cmd_name) File "C:\Python24\lib\distutils\cmd.py", line 333, in run_command self.distribution.run_command(command) File "C:\Python24\lib\distutils\dist.py", line 966, in run_command cmd_obj.run() File "C:\Python24\lib\distutils\command\build_ext.py", line 279, in run self.build_extensions() File "C:\Python24\lib\distutils\command\build_ext.py", line 405, in build_exte nsions self.build_extension(ext) File "C:\Python24\lib\distutils\command\build_ext.py", line 442, in build_exte nsion sources = self.swig_sources(sources, ext) TypeError: swig_sources() takes exactly 2 arguments (3 given) any help please? :) -- ionel. From sjmachin at lexicon.net Wed Jan 12 19:34:04 2005 From: sjmachin at lexicon.net (John Machin) Date: 12 Jan 2005 16:34:04 -0800 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: <1105576444.510743.93120@f14g2000cwb.googlegroups.com> Chris Lasher wrote: > Hello, > I have a rather large (100+ MB) FASTA file from which I need to > access records in a random order. The FASTA format is a standard format > for storing molecular biological sequences. Each record contains a > header line for describing the sequence that begins with a '>' > (right-angle bracket) followed by lines that contain the actual > sequence data. Three example FASTA records are below: > > >CW127_A01 > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACAT [snip] > Since the file I'm working with contains tens of thousands of these > records, I believe I need to find a way to hash this file such that I > can retrieve the respective sequence more quickly than I could by > parsing through the file request-by-request. However, I'm very new to > Python and am still very low on the learning curve for programming and > algorithms in general; while I'm certain there are ubiquitous > algorithms for this type of problem, I don't know what they are or > where to look for them. So I turn to the gurus and accost you for help > once again. :-) If you could help me figure out how to code a solution > that won't be a resource whore, I'd be _very_ grateful. (I'd prefer to > keep it in Python only, even though I know interaction with a > relational database would provide the fastest method--the group I'm > trying to write this for does not have access to a RDBMS.) > Thanks very much in advance, > Chris Before you get too carried away, how often do you want to do this and how grunty is the box you will be running on? Will the data be on a server? If the server is on a WAN or at the other end of a radio link between buildings, you definitely need an index so that you can access the data randomly! By way of example, to read all of a 157MB file into memory from a local (i.e. not networked) disk using readlines() takes less than 4 seconds on a 1.4Ghz Athlon processor (see below). The average new corporate desktop box is about twice as fast as that. Note that Windows Task Manager showed 100% CPU utilisation for both read() and readlines(). My guess is that you don't need anything much fancier than the effbot's index method -- which by now you have probably found works straight out of the box and is more than fast enough for your needs. BTW, you need to clarify "don't have access to an RDBMS" ... surely this can only be due to someone stopping them from installing good free software freely available on the Internet. HTH, John C:\junk>python -m timeit -n 1 -r 6 "print len(file('bigfile.csv').read())" 157581595 157581595 157581595 157581595 157581595 157581595 1 loops, best of 6: 3.3e+006 usec per loop C:\junk>python -m timeit -n 1 -r 6 "print len(file('bigfile.csv').readlines())" 1118870 1118870 1118870 1118870 1118870 1118870 1 loops, best of 6: 3.57e+006 usec per loop From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 20:11:53 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?windows-1252?Q?Martin_MOKREJ=8A?=) Date: Tue, 11 Jan 2005 02:11:53 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <7xis64ree5.fsf@ruckus.brouhaha.com> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <7xmzvgren6.fsf@ruckus.brouhaha.com> <7xis64ree5.fsf@ruckus.brouhaha.com> Message-ID: <41E327D9.4000202@ribosome.natur.cuni.cz> Paul Rubin wrote: > Paul Rubin writes: > >>handle with builtin Python operations without putting some thought >>into algorithms and data structures. From "ribosome" I'm guessing >>you're doing computational biology. If you're going to be writing Well, trying sort of ... Not much successfull so far. ;) >>code for these kinds of problems on a regular basis, you probably >>ought to read a book or two on the topic. "CLRS" is a good choice: >> >> http://theory.lcs.mit.edu/~clr/ >> http://mitpress.mit.edu/algorithms/ > > > Correction to unclarity: I meant a book on the topic of algorithms and > data structures (e.g. CLRS). Since you're presumably already a > biologist, I wouldn't presume to suggest that you read a book on > biology ;-). Yes, I'm. I still don't get what that acronym CLRS stands for ... :( From simon.brunning at gmail.com Fri Jan 21 07:37:46 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 21 Jan 2005 12:37:46 +0000 Subject: map in Python In-Reply-To: <1106310327.213874.305660@f14g2000cwb.googlegroups.com> References: <1106310327.213874.305660@f14g2000cwb.googlegroups.com> Message-ID: <8c7f10c605012104373199e615@mail.gmail.com> On 21 Jan 2005 04:25:27 -0800, Stu wrote: > I have recently switched over to Python from Perl. I want to do > something like this in Python: > > @test = ("a1", "a2", "a3"); > map {s/[a-z]//g} @test; > print @test; > > However, I take it there is no equivalent to $_ in Python. But in that > case how does map pass the elements of a sequence to a function? I > tried the following, but it doesn't work because the interpreter > complains about a missing third argument to re.sub. > > import re > test = ["a1", "a2", "a3"] > map(re.sub("[a-z]", ""), test) > print test This what you want? >>> import re >>> test = ["a1", "a2", "a3"] >>> test = [re.sub("[a-z]", "", item) for item in test] >>> test ['1', '2', '3'] -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From bkc at Murkworks.com Mon Jan 17 16:22:19 2005 From: bkc at Murkworks.com (Brad Clements) Date: Mon, 17 Jan 2005 16:22:19 -0500 Subject: Scriptomatic 2.0 References: <41eab05f$0$25799$8fcfb975@news.wanadoo.fr> Message-ID: If you stick an 's' into the URI, so it's https:// you'll get a certificate warning from FireFox. Looks like MS is running a self-signed certificate on www.microsoft.com weird. really -- Novell DeveloperNet Sysop #5 _ "Do Re Mi chel La Si Do" wrote in message news:41eab05f$0$25799$8fcfb975 at news.wanadoo.fr... > Hi ! > > Scriptomatic 2.0 can, now, to generate scripts in Python. > > Download : > > http://www.microsoft.com/downloads/thankyou.aspx?FamilyID=09dfc342-648b-4119-b7eb-783b0f7d1178&displaylang=en > > > Note : scriptomatic is a generator of WMI's scripts, for Windows, (and > compatibles WBEM). > > > > Good night > -- > Michel Claveau > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From mauriceling at acm.org Wed Jan 5 00:43:46 2005 From: mauriceling at acm.org (Maurice LING) Date: Wed, 05 Jan 2005 05:43:46 GMT Subject: Embedding a restricted python interpreter In-Reply-To: References: Message-ID: <41db7e8f$1@news.unimelb.edu.au> Rolf Magnus wrote: > Hi, > > I would like to embed a python interpreter within a program, but since that > program would be able to automatically download scripts from the internet, > I'd like to run those in a restricted environment, which basically means > that I want to allow only a specific set of modules to be used by the > scripts, so that it wouldn't be possible for them to remove files from the > hard drive, kill processes or do other nasty stuff. > Is there any way to do that with the standard python interpreter? > I won't really count on that. In my opinions, which may be wrong, Python is not constructed to work in a sandbox like Java. Java does it by subjecting all classes that it loads through a security manager. What you seems to want is a Python to have Java applet-typed of restrictions. You can try to use 'exec' to run your scripts in a constructed environment. For example, global = {} local = {} ... your stuffs .... statement = [] # to hold the script to run for line in statement: exec statement in global, local global and local are the global and local namespaces respectively. Although it had been explained to me before but I can't recall the details of how it works. In gist, you may be able to craft a global and local environment for your script to run in. I do not know if it is possible to disable or override 'import'...... maurice From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 18:05:02 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Tue, 11 Jan 2005 00:05:02 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <41e2f24d$1@nntp0.pdx.net> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <41e2f24d$1@nntp0.pdx.net> Message-ID: <41E30A1E.2000000@ribosome.natur.cuni.cz> Dear Scott, thatnk you for you excellent email. I also thought about using some zip() function to compress the strings first before using them as keys in a dict. But I don't think I can use one-way hashes, as I need to reconstruct the string later. I have to study hard to get an idea what the proposed code really does. Scott David Daniels wrote: > Tim Peters wrote: > >> [Martin MOKREJ?] >> >>> just imagine, you want to compare how many words are in English, German, >>> Czech, Polish disctionary. You collect words from every language and >>> record >>> them in dict or Set, as you wish. >> >> >> Call the set of all English words E; G, C, and P similarly. >> >>> Once you have those Set's or dict's for those 4 languages, you ask >>> for common words >> >> >> This Python expression then gives the set of words common to all 4: >> E & G & C & P >> >>> and for those unique to Polish. >> >> P - E - G - C > > > One attack is to define a hash to get sizes smaller. Suppose you find > your word sets are 10**8 large, and you find you need to deal with sets > of size 10**6. Then if you define a hash that produces an integer below > 100, you'll find: > E & G & C & P == Union(E_k & G_k & C_k & P_k) for k in range(100) > P - E - G - C == Union(P_k - E_k - G_k - C_k) for k in range(100) > where X_k = [v for v in X if somehash(v) == k] I don't understand here what would be the result from the hashing function. :( Can you clarify this please in more detail? P is the largest dictionary in this example, or was it shifted by one to the right? > This means, you can separate the calculation into much smaller buckets, > and combine the buckets back at the end (without any comparison on the > combining operations). Yes. > > For calculating these two expressions, you can dump values out to a > file per hash per language, sort and dupe-elim the contents of the > various files (maybe dupe-elim on the way out). Then hash-by-hash, > you can calculate parts of the results by combining iterators like > inboth and leftonly below on iterators producing words from files. > > > def dupelim(iterable): > source = iter(iterable) > former = source.next() # Raises StopIteration if empty > yield former > for element in source: > if element != former: > yield element > former = element > > def inboth(left, right): > '''Take ordered iterables and yield matching cases.''' > lsource = iter(left) > lhead = lsource.next() # May StopIteration (and we're done) > rsource = iter(right) > for rhead in rsource: > while lhead < rhead: > lhead = lsource.next() > if lhead == rhead: > yield lhead > lhead = lsource.next() > > def leftonly(left, right): > '''Take ordered iterables and yield matching cases.''' > lsource = iter(left) > rsource = iter(right) > try: > rhead = rsource.next() > except StopIteration: # empty right side. > for lhead in lsource: > yield lhead > else: > for lhead in lsource: > try: > while rhead < lhead: > rhead = rsource.next() > if lhead < rhead: > yield lhead > except StopIteration: # Ran out of right side. > yield lhead > for lhead in lsource: > yield lhead > break Aaaah, so the functions just walk one line in left, one line in right, if values don't match the value in left is unique, it walks again one line in left and checks if it already matches the value in riught file in the last position, and so on untill it find same value in the right file? So, it doesn't scan the file on right n-times, but only once? Yes, nice thing. Then I really don't need an index and finally I really believe flatfiles will do just fine. > >> Real-word dictionaries shouldn't be a problem. I recommend you store >> each as a plain text file, one word per line. Then, e.g., to convert >> that into a set of words, do >> >> f = open('EnglishWords.txt') >> set_of_English_words = set(f) >> f.close() >> >> You'll have a trailing newline character in each word, but that >> doesn't really matter. >> >> Note that if you sort the word-per-line text files first, the Unix >> `comm` utility can be used to perform intersection and difference on a >> pair at a time with virtually no memory burden (and regardless of file >> size). > > In fact, once you've sorted these files, you can use the iterators > above to combine those sorted files. > > For example: > > Ponly = open('polishonly.txt', 'w') > every = open('every.txt', 'w') > for hashcode in range(100): > English = open('english_%s.txt' % hashcode) --------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^ this is some kind of eval? > German = open('german_%s.txt' % hashcode) > Czech = open('czech_%s.txt' % hashcode) > Polish = open('polish_%s.txt' % hashcode) > for unmatched in leftonly(leftonly(leftonly(dupelim(Polish), > dupelim(English)), dupelim(German)), dupelim(Czech)): > Ponly.write(unmatched) > English.seek(0) > German.seek(0) > Czech.seek(0) > Polish.seek(0) > for matched in inboth(inboth(dupelim(Polish), dupelim(English)), > inboth(dupelim(German), dupelim(Czech))): > every.write(matched) > English.close() > German.close() > Czech.close() > Polish.close() > Ponly.close() > every.close() > > > --Scott David Daniels > Scott.Daniels at Acm.Org From jurgenex at hotmail.com Mon Jan 17 19:48:44 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Tue, 18 Jan 2005 00:48:44 GMT Subject: [perl-python] 20050117, filter, map References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: Abigail wrote: > Steven Bethard (steven.bethard at gmail.com) wrote on MMMMCLVII September > $$ Is there any chance you could post these all as part of the same > thread? > > Just killfile him, and stop replying. Remember, don't feed the trolls. True, except that he spreads lies about Perl and really bad code all over the place. If you don't tell people about how awful his skills are then they may actually mistake his incompetency for flaws in Perl. jue From ianb at colorstudy.com Wed Jan 26 00:55:21 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Tue, 25 Jan 2005 23:55:21 -0600 Subject: [ANN] SQLObject 0.6.1 Message-ID: <41F730C9.2040104@colorstudy.com> SQLObject 0.6.1 --------------- Version 0.6.1 is a bug fix release for 0.6. Most of the work on this release has been thanks to the contributions of Oleg Broytmann. Thanks Oleg! A brief list of changes: * All class methods take a connection argument. * "DISTINCT" option for select results. * Connection objects have a new module attribute, to get access to the connection's exceptions. * New UnicodeCol() for encoding and decoding values from the database. * Added Indexing (patch from Jeremy Fitzhardinge). * Database connections explicitly closed, instead of just letting them be garbage collected. * selectBy can take be called with instances instead of only IDs for foreign key columns. * DBMConnection was removed (it's been broken a long time). What Is SQLObject? ------------------ SQLObject is an Object-Relational Mapper. Basically it makes your database rows feel like (relatively) normal Python objects: Tables are classes, rows are instances, columns are attributes. SQLObject both allows you to define your classes in Python, and SQLObject will create the tables on your behalf, or SQLObject may use database reflection to dynamically create a class given a table name. SQLObject portably supports a variety of database backends: MySQL, PostgreSQL, SQLite, Firebird, MaxDB/SAPDB, and SyBase. SQLObject is being used in a variety of external projects: ezSQLObject, sqlo for Zope 3, and Subway (a Ruby on Rails clone), among others. Where Is SQLObject? ------------------- Website: http://sqlobject.org News: http://sqlobject.org/docs/News.html#sqlobject-0-6-1 Documentation: http://sqlobject.org/docs/SQLObject.html Subversion repository: http://svn.colorstudy.com/trunk/SQLObject Mailing list: http://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://dir.gmane.org/gmane.comp.python.sqlobject Download: http://prdownloads.sourceforge.net/sqlobject/SQLObject-0.6.1.tar.gz?download -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From bulba at bulba.com Sun Jan 2 12:15:56 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 02 Jan 2005 18:15:56 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: On Sat, 01 Jan 2005 15:08:01 -0500, Steve Holden wrote: >> There is the stability issue you mention... but also probably the fear >> issue. If you choose a solution from a major company -- then it fails for >> some reason or they drop the product -- it's their fault -- you've got an >> automatic fall guy. On the other hand, an open source solution or >> otherwise less accepted solution ... it will probably be consider >> your fault by the organization. It's a rational decision to avoid >> personal risk when you don't get much reward for choosing something >> different. >You are ignoring the fact that with the open source solution you do at >least have the option of hiring bright programmers to support the >framework which has now become moribund, Theoretically. Because even though the source code is available and free (like in beer as well as in speech) the work of programmers isn't cheap. This "free software" (not so much OSS) notion "but you can hire programmers to fix it" doesn't really happen in practice, at least not frequently: because this company/guy remains ALONE with this technology, the costs are unacceptable. It's a case of "marginal cost" (cost of making yet another copy) becoming equals to the costs of a project: that is extraordinarily expensive software. If this software gets sold or copied by the millions, the marginal costs is going down to zero, like it is the case with Linux. Imagine NOT being a technology company (say, Sun or IBM or Borland) and trying to hire programmers to fix you the kernel of this operating system. >whereas when a company goes >bust there's no guarantee the software IP will ever be extricated from >the resulting mess. There is a good _chance_ here: money. Somebody has poured a lot of money into this thing. It's not going to get dropped bc of that. >So I'm not sure I'd agree with "rational" there, though "comprehensible" >might be harder to argue with. It depends on definition of "rational", on definition of your or company's goals and on the definitions of the situations that are the context. >Avoidance of blame is way too large a motivator in large organizations, >and it leads to many forms of sub-optimal decision making. This might be of interest to some people: http://www.pkarchive.org/new/DefectiveInvestors.html -- It's a man's life in a Python Programming Association. From apardon at forel.vub.ac.be Thu Jan 20 07:19:11 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Jan 2005 12:19:11 GMT Subject: Freezing a mutable (was Re: lambda) References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> <41ed8c13.1209309354@news.oz.net> Message-ID: Op 2005-01-20, Nick Coghlan schreef : > Antoon Pardon wrote: >> Interesting idea. But I think you are wrong when you say that two lists >> that compare equal at the time they are frozen, will get the same >> dictionary entry. The problem is an object must compare equal to >> the key in the dictionary to get at the same entry. So if you freeze >> a list and its copy but then mutate them differently, they no longer >> are equal and so wont get you at the same entry. > > The trick is that the result of the freezing operation is cached until such time > as you explicitly unfreeze the object. I missed that you would use it with the idiom: dct[x.frozen()] I have two problems with this approach. 1) It doesn't work when you get your keys via the keys/items methods. 2) This is rather minor, but a user could still unfreeze untimely -- Antoon Pardon From alanmk at hotmail.com Sun Jan 23 07:23:27 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 23 Jan 2005 12:23:27 +0000 Subject: Textual markup languages (was Re: What YAML engine do you use?) In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> Message-ID: [Effbot] > ReST and YAML share the same deep flaw: both formats are marketed > as simple, readable formats, and at a first glance, they look simple and read- > able -- but in reality, they're messy as hell, and chances are that the thing > you're looking at doesn't really mean what you think it means (unless you're > the official ReST/YAML parser implementation). experienced designers > know how to avoid that; the ReST/YAML designers don't even understand > why they should. I'm looking for a good textual markup language at the moment, for capturing web and similar textual content. I don't want to use XML for this particular usage, because this content will be entered through a web interface, and I don't want to force users through multiple rounds of submit/check-syntax/generate-error-report/re-submit in order to enter their content. I have no strong feelings about YAML: If I want to structured data, e.g. lists, dictionaries, etc, I just use python. However, I'm torn on whether to use ReST for textual content. On the one hand, it's looks pretty comprehensive and solidly implemented. But OTOH, I'm concerned about complexity: I don't want to commit to ReST if it's going to become a lot of hard work or highly-inefficient when I really need to use it "in anger". From what I've seen, pretty much every textual markup targetted for web content, e.g. wiki markup, seems to have grown/evolved organically, meaning that it is either underpowered or overpowered, full of special cases, doesn't have a meaningful object model, etc. So, I'm hoping that the learned folks here might be able to give me some pointers to a markup language that has the following characteristics 1. Is straightforward for non-technical users to use, i.e. can be (mostly) explained in a two to three page document which is comprehensible to anyone who has ever used a simple word-processor or text-editor. 2. Allows a wide variety of content semantics to be represented, e.g. headings, footnotes, sub/superscript, links, etc, etc. 3. Has a complete (but preferably lightweight) object model into which documents can be loaded, for transformation to other languages. 4. Is speed and memory efficient. 5. Obviously, has a solid python implementation. Most useful would be a pointer to a good comparison/review page which compares multiple markup languages, in terms of the above requirements. If I can't find such a markup language, then I might instead end up using a WYSIWYG editing component that gives the user a GUI and generates (x)html. htmlArea: http://www.htmlarea.com/ Editlet: http://www.editlet.com/ But I'd prefer a markup solution. TIA for any pointers. regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From ajsiegel at optonline.com Sun Jan 30 07:51:08 2005 From: ajsiegel at optonline.com (Arthur) Date: Sun, 30 Jan 2005 07:51:08 -0500 Subject: The next Xah-lee post contest References: Message-ID: On Sat, 29 Jan 2005 15:41:00 +0100, PA wrote: > >On Jan 29, 2005, at 15:32, rbt wrote: > >> Unix donkey! You not elegant. You have poor design. >> Sloppy Perl monkey! You be lazy! You code very very bad. >> >> Xah know all! > >Follow The True Path, follow The Xah Way To Enlightenment: > >"The Unix Pestilence" >http://www.xahlee.org/UnixResource_dir/freebooks.html > >Cheers Not sure how Xah got himself into all this. When I actually read the substance of Xah's articles like the one referenced above, and ignore the stuff in Red, I don't find it all that bizarre - or uninformative. He links to substantive resources. He has postive things to say about lots of things, including Python. Guess I am prejudiced by the fact that I have always enjoyed his plane curve pages, and after David Eppsteins Geometry Junkyard and a few others, consider it one of the more interesting web resources in respect to geometry. I knew of him for this, well before I knew of him as the Usenet character he is. Wish he would do himself the favor of better separating he various "interests". One can google on "plane curves", and the first hit will be Xah's site. I certainly find it interesting and well done. On the other hand, if one goes by way of his home page, one is greeted first with a vitriolic message expressing a sentiment not all that uncommon but not very relevant to the substance of much of what is to be found at the site. Oh well. Art From fredrik at pythonware.com Sun Jan 23 13:33:58 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 19:33:58 +0100 Subject: What is print? A function? References: <200501231835.07310.frans.englich@telia.com> Message-ID: Frans Englich wrote: > I find this a nice solution. The most practical would be if it was possible to > do this with print, of course. But print won't budge. you can disable print, though: class dev_null: def write(self, text): pass sys.stdout = dev_null() or pipe all print requests to a debug stream: if my_debug_flag: debug = sys.stdout else: debug = dev_null() print >>debug, "hello" print >>debug, "the value is", value > Is it possible to create own statements, such that it would be possible to do: > > printDebug "test" no. From caseyhHAMMER_TIME at istar.ca Wed Jan 26 23:11:57 2005 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Thu, 27 Jan 2005 04:11:57 GMT Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: "The object-oriented programming paradigm has an undeserved reputation as being complicated; most of the complexity of languages such as C++ and Java has nothing to do with their object orientation but comes instead from the type declarations and the mechanisms to work around them. This is a prime example of how Scheme's approach of removing restrictions compares with the "piling feature on top of feature" needed in other languages, such as the C++ template mechanism." "Handbook of Programming Languages, Volume IV: Functional and Logic Programming Languages" Peter H. Salus, editor 1998 page 63 Similarly, now, Java's generics! -- Regards, Casey From jbperez808 at wahoo.com Wed Jan 12 04:54:49 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Wed, 12 Jan 2005 17:54:49 +0800 Subject: Another look at language comparisons In-Reply-To: <41e00ac1$0$265$edfadb0f@dread12.news.tele.dk> References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> <1105188426.955508.263030@c13g2000cwb.googlegroups.com> <41e00ac1$0$265$edfadb0f@dread12.news.tele.dk> Message-ID: <34kaf5F4ag9k6U1@individual.net> Max M wrote: > Jan Dries wrote: > >> beliavsky at aol.com wrote: >> And there is hope for Python, as Guido has recently been seen with a >> beard :-) >> http://www.tbray.org/ongoing/When/200x/2004/12/08/-big/IMG_3061.jpg > > > LOL, he is working on linux, isn't he? > > So it was about bloody time. Guido Van Rossum is now working on linux?? From xah at xahlee.org Sun Jan 23 04:28:28 2005 From: xah at xahlee.org (Xah Lee) Date: 23 Jan 2005 01:28:28 -0800 Subject: how to write a tutorial In-Reply-To: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: <1106472508.591411.40140@c13g2000cwb.googlegroups.com> adding to my previosu comment... In the Python tutorial: http://python.org/doc/2.3.4/tut/node11.html the beginning two paragraphs should be deleted. Nobody gives a shit except a few smug academicians where the author wrote it for pleasing himself. For 99% of readers, it is incomprehensible and irrelevant. the first paragraph of 9.1 "A Word About Terminology" is epitome of masturbation. The entire 9.1 is not necessary. Large part of 9.2 "Python Scopes and Name Spaces" is again masturbatory. -- Most texts in computing are written by authors to defend and showcase their existence against their peers. In a tutorial, nobody cares how the language compared to x y and z, or what technicality is it all about, or some humorous snippet of history only funny to the author himself. Particularly for texts in a tutorial context, you want to write it as simple as possible covering the most useful basic functionalities and concepts, and self-contained. Not showcasing your knowledge of history of languages or your linguistic lineage byways. For example this chapter 9 on Objects, it is not difficult to write it without making a show of lingoes. One simply write what is of Python, without thinking about relation to xyz languages or the "computer science" establishment and their ways of thinkings of namespaces and scopes and dynamic and statics and inheritances ... fucking bags of shit. Also, in the computing industry, documentations and tutorials often lacks examples. Especially important in tutorials. Be fewer in words, more in examples. (for example, unix man pages are full of arcane abstract syntax specifications and inner-working technicalities while most don't contain a single example of usage that is much needed.) also, this does not mean beginning to write for dummies as the highly successful series of "xyz for Dummies" books. These are successful because the corpus of textbook writers are all inclined and habituated to chalk up to jargons and intellectualization on the accounts of their own esteem and careers. Dummy books are moronic because they assumed the general readers are morons. PS Another illustrative case is the official Java Tutorial. Python tutorial is to the point on the whole. The Java Tutorial is completely asinine. Chalking up to rocket sciences every chance with unhelpful and misleading drivel. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From godoy at ieee.org Wed Jan 19 11:25:31 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Wed, 19 Jan 2005 14:25:31 -0200 Subject: Accessing MDB files on Windows References: <1635068.ZTfiooUzB4@strongwill.g2ctech> Message-ID: <4262806.PViGKJWPeZ@strongwill.g2ctech> Larry Bates, Quarta 19 Janeiro 2005 14:01, wrote: > I'm assuming the application will be run on Windows. You're right. It will be run on Windows. I discarded some other platform due to the difficulty of supporting this file format. > You can use ODBC or DAO. > > An DAO solution that I wrote (and use) can be found > at: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303349 Thanks! I'm looking at it. > For ODBC you would just use the standard library module. Thanks. I'll be trying the DAO first. -- Godoy. From ncoghlan at iinet.net.au Mon Jan 10 05:26:23 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 10 Jan 2005 20:26:23 +1000 Subject: python3: accessing the result of 'if' In-Reply-To: References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> <1105236383.521393.40680@c13g2000cwb.googlegroups.com> Message-ID: <41E2584F.3050808@iinet.net.au> Steve Holden wrote: > Excuse me, these are supposed to be IMPROVEMENTS to Python? I think it's more messing around before coming to the conclusion that, of the many things that 'where' helps with, this sure as hell ain't one of them :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From andrea.gavana at agip.it Fri Jan 14 05:44:39 2005 From: andrea.gavana at agip.it (andrea.gavana at agip.it) Date: Fri, 14 Jan 2005 11:44:39 +0100 Subject: Threading Or Other Suggestions?!? Message-ID: Hello NG, I have a wxPython application that does a lot of things. One of them, in particular, I have doubts on how to implement it. Essentially, this part of my application calls an external executable (an oil reservoir simulator). What I would like to do, is to give the user the possibility to run more than 1 simulation at the same time. This means: 1) Writing the executable "data file" needed by the simulator 2) Run the executable file (and wait until completion) 3) Examine the simulation results For this, I was thinking about threads... does anyone have other/better suggestion(s)? Does anyone see any difficulty/memory problems in using threads? Thanks to you all for every suggestion. Andrea. ------------------------------------------------------------------------------------------------------------------------------------------ Message for the recipient only, if received in error, please notify the sender and read http://www.eni.it/disclaimer/ From bulba at bulba.com Wed Jan 5 21:11:59 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 03:11:59 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> Message-ID: On Wed, 5 Jan 2005 11:19:56 +0100, aleaxit at yahoo.com (Alex Martelli) wrote: >Say that the city has ten hat shops of the same quality. One is in >Piazza dell'Unita`, all the way to the Northern border of the city. One >is in Piazza Saragozza, all the way to the Southern border. The other >eight are in Piazza dell'Orologio, smack in the middle of downtown. >Each shop offers hats taken from the same random distribution: we can >say that a normal curve measuring the utility function for the customer >(some function of price, quality, looks, fit, ...), with identical >average and variance, represents the best hat available today from a >given shop from the POV of a given customer. >Say that a customer has one day to shop for their new hat, and the >locations are too far apart for a customer to visit more than one >location within that day. If a customer chooses to visit the one >southern shop, or the one northern shop, the customer expects to be >presented with the choice of hat from said normal curve. If the >customer goes downtown, they expect a choice which overall lies along a >DIFFERENT curve -- the best-of-eight samples from the normal curve. >Sorry I can't model that analytically, but both intuitively and from any >little simulation (easy to code in Python) you can see the customer's >expectations are much better if they choose the location where they can >do more comparison shopping! Obviously. I completely agree with you that is how it works _in a model_, if reality were similar to that model. What I doubt is that _in practice_ simple costs associated with physical distance are so overwhelming. Maybe they used to be in the past. I keep asking: what exactly is the premium to customer to go to that place? what is the cost? Suppose in your example the customer has to get in the car in order to get to the hat shop anyway. And when he gets to that quarter of the city, he finds no parking place. And we know that even highly paid people tend to spend seemingly irrationally much time driving around in order to find the free place because they find the thought of having to pay little money to pay for parking so disgusting. >Note that I'm not saying there are no forces pushing against clustering: >of course there are, varying by industry etc. But they're easy to >overstate. True, true... What I'm getting at is that "repelling forces" can also be easy to understate and "pulling forces" can be easy to overstate. >Consider the highly skilled worker who has a choice: they >can stay in some crowded cluster, say Silicon Valley, and keep facing >congestion, high rents, etc, for high salaries and great opportunities >to keep hopping to the highest bidder; or, they can accept an offer at a >lower salary in some more isolated area, say a minor cluster such as >Austin, Tx, and get less congestion, cheaper housing, etc, although also >less opportunity to keep enhancing their careers. I personally know a developer who worked in Orange County, absolutely loved the place and refused to leave for years even though it consumed almost half of his wage in rent. Then, one day, when he called me (we like to have long talks over the phone), he said "screw it, I truly hate to leave, but I'm not going to suffer that rent anymore". Now he claims that due to other factors California is going down the drain and educated people and businesses escape that state. Apparently some stronger "repelling force" has overcome the pulling clustering forces. > Which kind of worker >will tend to pick which of the two? Somebody who thinks they may be >past the peak of their career, and won't get many more lucrative offers >in the future anywa, might be more tempted by (say) Austin, while >somebody who's keenly competitive and on a sharp upwards path may keep >braving the congestion for the (to them) attractive lures and challenges >of Silicon Valley. Not if the state has had rollling black-outs, which puts the production on automated semiconductor line in danger, because backup generators have not been designed to operate for such a long black-out. You see, I'm not disagreeing with you that your model applies _where it applies_. I only disagree that it applies in face of stronger forces. Now what kind of forces is dominant in most frequent scenarios would have to be worked out in tedious empirical research I think. Which I haven't done, because learning some economics is just a hobby to me. >Of course there are a zillion other factors, but in >as much as we're talking about factors strictly related to clustering, >this is the bias, and therefore (in an Akerlovian model) this is the >message which tends to be sent by such choices. This I agree with. >But there are other transaction costs, mostly connected to the need for >face-to-face interaction as being the most effective form. I've worked >for a SW development firm which tried to coordinate development >distributed across many locations via cheap video-based teleconferences >spanning timezones from California all the way to India; I've done way >more than my share of telecommuting and airport- and plane-hopping for >development projects geographically distributed and/or mostly located >far from the customers and/or other stakeholders; I know whereof I >speak... Oh I do not mean smth so extreme. >I remember glancing at some costly booklet called something like "Poland >Infrastructure Report" back when an employer was considering setting up >a branch office somewhere in Poland (selling and customizing SW for the >mechanical industry), and back then issues such as internet and other >telecom access, easy availability of top graduates, ease for expatriates >from Italy to live in the place for a while knowing only English and >Italian, at most German and French, and not Polish or Russian, closeness >to good international airports and other good transportation, closeness >to partner firms and potential customers' decision-makers, all appeared >to point to Warsaw, if I recall correctly. Mechanical engineers with >some programming experience or viceversa, good translators, and good >salespeople with connections in the mechanical industry, are not as >ultra-specialized as all that, after all. Most sales offices in Warsaw do not employ esp. educated people in my impression. OTOH, the carmaking facilities nowadays require more much more know-how and specialized workforce than a sales office does. Or at least that was my impression when I worked at the construction machine manufacturer in Berlin. Capital investments per worker in auto industries are reportedly very high. Simple physical tasks are done largely by machines, like this 100 million Deutschmark costing laser-cutting installation that I've seen there, where a pile of iron bars is pulled in at one end and the pile of ready components is spitted out of the other end (unlike typical thermal cutting, laser has the advantage of not destroying the metal structure adjacent to the cut, so the parts of the machines subject to high-stress are oft produced this way). Oh, and by the way that installation doesn't get used much. Somebody at the office didn't check carefully enough the energy prices before ordering it and later someone discovered that off-site specialized cutting firms that take advantage of energy available at low prices at special times in other countries can get it produced cheaper. Moving it elsewhere or selling is not an option, since it is a specially constructed, low, 50-meters long hall that stands inside the huge manufacturing hall of the company. 100 million DM (when 1 DM was worth some half of Euro back then) down the drain. When the company was in rather bad financial situation (later I've learned it was finally bought out by Americans). Oh well. No big deal. I was utterly shocked. Having grown up in Soviet times I have been used to seeing precious resources wasted by organizations as if resources were growing on trees, but smth like this?! In a shining ideal country of Germany?! Unthinkable. >The firm I was working for had a consensus decision-making process (even >I was involved) and managers (and other employees) and stockholders were >mostly the same people -- it wasn't all that large a firm at the time. >Nobody needed to practice risk avoidance. Again, you may have had good luck. Where I worked (including some places in Germany and UK) it was almost the only factor that seemed to matter to people - they'd do ANYTHING not to take a risky decision, to "pass the buck", not to stick their necks out, not to declare doing some work that involved challenges. Though maybe that is just my impression - such issues as interpreting behavior of another human being are contrived and tend to be heavily "filtered" in a subjective filters. Policemen for instance place little value in witnesses of events, because the testimonies tend to be made up of so much disinformation and personal sentiments rather than perceiving what really happened. If that happens re simple events, it is probably much worse re interpretations of another person's motives. >The infrastructure advantages >of Warsaw vs other locations loomed HUGELY large, judging of course from >some consultants' reports purchased for the purpose -- I'd be skeptical of such reports - I don't know about situation from the beginning of 1990s, where this partially may have been the case; however, back then pretty much all of the country has had lousy infrastructure, and today, many bigger cities have comparatively good infrastructure. Workers - here's the difference. Warsaw has been a big "vacuum cleaner" for talented people from all over the country. This may have been a factor. >it may look >different to people living in the place, although I'd like to get a >second opinion from Warsaw's Chamber of Commerce since you appear to >have a very specific individual bone to pick (and I can sympathize: even >though Milan may be the economically correct choice for foreign >investors, I'd never want to LIVE there myself, being a Bolognese... but >I must admit that Milan's infrastructure, connections, location, etc, >etc, may in several cases drive a rational decision to set up there). It's not so much individual as the fact that 80% of foreign investments in this country (in terms of amounts of money invested) are made in Warsaw. While Warsaw REALLY does not have so much better infrastructure. There's the same problem with Russia: similar fraction of foreign investments take place in Moscow, which drives real estate prices there to simply insane levels. Even though other big cities, e.g. Saint-Petersburg has 4.5 million inhabitants and lots of educated people there, too. I doubt that foreign investments in more developed countries are so concentrated in capital cities. Can your clustering model really explain this difference? IOW, I do not claim that your model has zero relevance to real world. I only think that there may be other, fundamental and stronger factors that overwhelm the "clustering forces". There is another factor in this game: govt is a big customer and stability and consistency of legal acts as well as transparency in this country leave much to be desired with, to put it lightly. So the companies HAVE TO be close to the centers of power, just to have its property secure. In this way it is most definitely rational decision to invest in Warsaw even thought the office space there is more expensive than in London (at least that was the case several years ago). > Not all corporations do that: in this country Coca-Cola has made >> their big "green field" investment almost in the middle of nowhere >> in this country. GM, Volkswagen, FIAT, and most of other carmakers >> have made similar decisions. Doesn't seem like those were bad business >> decisions for them. >If their needs were for cheap land for greenfield factories, and cheap >workers for said factories, then they were acting under very different >forces than a midsize company looking to set up a mostly-sales branch >office, not an industrial factory. True. I grant that. >> The cluster I've seen - an IT "corporate area" in Dublin, >> Ireland - was specifically created not due to "natural clustering", >> but due to govt policy of tax breaks and preparing good >> infrastructure in this place rather than some inter-business and >> inter-customer dependencies, since e.g. Microsoft (where the company >> sent me for training) neither is able to get all the workers it needs >> just from this city, nor it sells mostly to local customers, but it >> sells all over Europe. >That's addressing only the issue of endogenous vs exogenous original >causes for clustering. Many attempts to create clusters artificially >have happened ever since the economical advantages of clusters were >discussed in the literature, together with the crucial point that WHERE >the cluster originally happens is in most cases almost random, it's >self-reinforcing once it's properly underway. Note that a lot of deliberate or half-deliberate attempts to create clusters have failed: "content industry" in NY, there was a failed attempt to create high-tech IT/telecom cluster in southern France, etc. "Jumpstarting" the cluster should be easy if this model applied, after which it should develop in a self-reinforcing manner. So why deliberate attempts fail so frequently, while clusters appear in other, unforeseen locations? >Most such attempts have >failed, because governments' powers aren't unlimited; Dublin is a good >example of this strategy succeeding. I'm not sure if this is correlation, but not causation; perhaps except in a wider sense, like creating other good reasons for foreign companies to invest in Ireland at all. I see the "clustering" forces as a sort of derived factor: first, there are fundamental issues that make the company set up in that place or not - see it as "mass" in a physical analogy. Inter-dependency issues, or "gravity" in a physical analogy, comes only later. I do not claim that they can't have the influence at all, by no means. I'm just skeptical of claims if they are of primary importance. >No matter WHY the good infrastructure is there, the tax breaks, the >thriving community of high-tech workers, etc, a firm deciding where to >set up may perfectly well find it rational to have all of these >advantages overwhelm the issues of rents, congestion, competition for >good workers. In other words, my disagreement with your thesis that, >because the government lowered taxes, taking advantage of that is NOT in >the best interests of a firm's stockholders, is now maximal: I find your >thesis not just wrong, but by now outright silly. Huh? Of course it is in the interest of the company and stockholders and they will most likely do it! The point here is much more subtle: what I mean is that this cluster has been created not so much by "gravity" and "repulsion" forces as simple rational choice unrelated to inter-dependency issues - so companies clustering in that place is definitely a rational choice, given that Dublin is 2 million people city in a 5 million people country, they simply won't find workers elsewhere; however, I'd hold this correlation as just correlation (with exception of simple ability of finding most educated workers) and not necessarily causation. That those were _other_ economic factors - like Irish being highly educated, speaking English, and living in a relatively inexpensive member country of EU - as the decisive factors of that decision and not necessarily the typical clustering factors like "being close to your customers". Speaking in such terms, maybe Ireland as a whole country has been such a "cluster", but then again, is such a cluster result of "interdependency" issues or more fundamental factors, such as historical circumstances, govt decisions, political stability, secure property rights, corruption, etc? If the latter, I'd argue that "clustering" in Ireland is a correlation, not causation. >> To me, the issue of manager having to face their superiors >> asking him a question - "why on Earth have you decided >> to locate our branch in the middle of nowhere in this country? >> Why not in capital city? Can't you look at the map? Read some >> stats how many inhabitants this city has and what is the >> income level there?" is overwhelming: it would take long >> time to explain for this manager who e.g. may have already >You are wrong, because the same decisions get rationally made by >sole-owner sole-manager companies where these considerations cannot >apply. Deciding where to site an imporant branch is a BIG decision: of >course it takes a long time, *DUH*, and all sorts of factors are taken >into consideration. Then you have had a good luck of interacting with much, much more reasonable managers than I have had. And that includes some managers in some big multinationals, and not just in this country. Sure, many managers I've seen were careful, insightful and wanted to understand this issue well before making the decision; but I have met equally many decisionmakers who tended to be rash, careless and too quick in their judgments, and really not prone to reconsidering their opinion if the new evidence came in. Sometimes I was scared silly to see how carelessly the important decisions were made, because I knew I may have to live with the consequences. >> got his hands dirty in this industry in that country to know >> that say, there's little revenue increase to be gained in >> locating the facility in capital city, the needed workers are >> actually hard to find there, etc. >So all of these factors are folded into a huge pile of reports in >companies where such decisions are at all likely to be challenged later, >and sign-off on the folders is carefully obtained for cover-up purposes. >If the local development agencies of the "middles of nowhere in that >country" don't do their job, including showering managers planning such >decisions with supporting materials, that's a bad sign: maybe due to >cultural influences foreign capital, professionals, and managers are NOT >welcome there as they would be in a relative metropolis, for example. That was not a factor here really. Most of that has to do with the fact that regional and local branches of govt are exceptionally clueless and lazy (and corrupt), at least when compared to govt in capital city. However, I've observed that they're learning, esp. in the north to north-western part of the country. The East, as usual, is a no-man's-land. It's also the poorest part. >> To me, this is much like decision whether do much of >> development in Python or MS VS / VB. "But everybody's >> using VisualStudio / VB" is a simple and compelling argument: >> "so many people can't be wrong", while explanations that >> going Python may actually be better decision in this context >> requires long and complex explanations and managers oft can >> not even be bothered to read executive summaries. >The issue of parallels or otherwise is by now totally secondary, to me, >to the main issue that I find your approach to explaining regional >clustering problems across industries totally, irredeemably, and >horribly WRONG. So, I'm not going to make the post even longer by even >trying to address this part. Few, besides the two of us, can be left >reading by now, and clearly our disagreements on economics are so total >that it's unlikely we can get anywhere by our discussions anyway. I prefer to think that those are contrived issues and we rather had some disagreements. As usual, when you leave the trivia, and start on more complicated issues, it's not simple anymore. >> I feel econ models frequently are elegantly designed >> abstractions of elegantly designed problems; the problem >> is how close those are to the real-world problems. At >> the end of the day, it's "human action" that gets all >> of that implemented. I've seen too much resources >> going down the drain in completely idiotic projects >> and decisions to believe managers are rational beings. >When you claim managers are acting rationally (if selfishly) to avoid >risk to themselves, you can't then justify this claim by adding that >they aren't rational at all. But that was my attempt of (poor) sarcasm actually... I did not mean that literally. Sorry for that. >Economics does cover, in its modern form, >both issues of agency problems (misalignment of incentives between agent >and owner) AND ones of "bounded rationality" (all the way from >asymmetric information, to transaction costs relating to acquiring and >processing information). Trying to throw economics overboard because >you can't be bothered to understand it is a kind of behavior that >reminds me closely of the "leftists" you excoriate in your signature. I forgot to change this sig when switching to here from political ng, sorry.. It's just a sig but still OT given the nature of the group. Re "throwing the economics overboard" - perish the thought! I don't know why you came to this conclusion, perhaps I did not indicate clearly enough I meant the last paragraph in an ironic way. On the contrary, I have the impression that I belong to the small minority of people who consider economics as science. Au contraire, people oft perceive me as believing too much in relevance of economics! That doesn't mean I have to seee _particular economic model_ as relevant. The history of economics is scattered with such examples, like Phillips curve or Bowley's law (my favorite book by Mark Blaug, "Methodology of Economics", worth a ton of gold, quotes a long litany of such broken models). There's nothing wrong in principle about it: science is about falsification (or at least Karl Popper told us so). I'm just wary of what I see as excessive stressing one factor (like physical proximity) over other, possibly neglected factors. -- It's a man's life in a Python Programming Association. From tim.golden at viacom-outdoor.co.uk Sat Jan 8 14:36:57 2005 From: tim.golden at viacom-outdoor.co.uk (Tim G) Date: 8 Jan 2005 11:36:57 -0800 Subject: Installing IPython on win2k In-Reply-To: References: Message-ID: <1105213017.820231.67050@c13g2000cwb.googlegroups.com> Dave Merrill wrote: > Hi, I'm new to python, and ipython, but not to programming, having trouble > getting ipython installed on windows 2000, python 233. Any help would be > much appreciated; I'm sure I'm being some basic flavor of dense... First of all, rest assured that it does work (and quite easily) so welcome to Python and iPython and I hope the going's a bit smoother as you go along. > Then downloaded ipython-0.6.6.zip and unzipped it. When I double-click > setup.py, I get only a brief wait cursor; nothing else happens, and > importing ipython as a test fails. First of all, ipython isn't really an import into python; you run it and it runs python (if you understand me). So when you've installed it, I think it puts an item on your start menu. On linux, it puts an executable ipython onto your path. I've just downloaded and run the setup.py, and it does create a Start Menu item which will start iPython. Look out for that and see if it does the business. > Both files in the scripts dir, ipython and pycolor, have no filename > extension, which seems odd to my newbie eye. I tried renaming them to .py, > still no difference. This is a unixism. Some unix types decry the use of file extensions because the information the extension gives -- which executable program to use -- is already embedded in the first line of a file. > > My apologies for this basic question, and my no doubt ignorant flailing > about. Very much looking forward to getting this working. > > Thanks, > > Dave Merrill Good luck and happy hunting TJG From rff_rff at remove-yahoo.it Sun Jan 2 09:02:43 2005 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Sun, 02 Jan 2005 14:02:43 GMT Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> Message-ID: <7aTBd.11928$H%6.521997@twister1.libero.it> Mike Thompson ha scritto: > > 'Seaside' is a Smalltalk framework for what might be called "Modal Web > Development" or "Synchronous Web Programming", or even "Continuation > Based Web Apps". > > http://www.beta4.com/seaside2/ > > Very sexy it looks too. And it seems to be generating a lot of interest > - Ruby and Java variants have already sprung up: > > http://rubyforge.org/projects/borges/ > http://lakeshore.sourceforge.net/ actually, there are also implementations in Scheme, Common Lisp (UnCommonWeb) and Cocoon-FLOW has similar concepts. And somewhere (I think on the portland pattern repository) I recall reading that Viaweb (aka "the first web app") was written in CPS. Also notice that the Wee project in ruby is more advanced that Borges. > I googled for the python spin-off but didn't find one. Closest I found > was Imposter (http://csoki.ki.iif.hu/~vitezg/impostor/) which looks like > an earlier, partially failed attempt to do what Seaside now seems to be > delivering. I think "independent" more than earlier, it seem many people are reinventing this from time to time. Anyway, I just wanted to point out that IIRC something on this lines appeared recently in the nevow svn tree, maybe you can take a look. From steven.bethard at gmail.com Fri Jan 7 15:49:15 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 13:49:15 -0700 Subject: Display Function Code Body? In-Reply-To: <1105130263.788520.96710@f14g2000cwb.googlegroups.com> References: <1105130263.788520.96710@f14g2000cwb.googlegroups.com> Message-ID: Haibao Tang wrote: > What I would like to do is to write a function like disp(), when typed, > it can give you the code infomation. Check the docs entitled "Retrieving source code": http://docs.python.org/lib/inspect-source.html Depending on what you want, you may be able to use inspect.getsource: py> import inspect py> import string py> print inspect.getsource(string.split) def split(s, sep=None, maxsplit=-1): """split(s [,sep [,maxsplit]]) -> list of strings Return a list of the words in the string s, using sep as the delimiter string. If maxsplit is given, splits at no more than maxsplit places (resulting in at most maxsplit+1 words). If sep is not specified or is None, any whitespace string is a separator. (split and splitfields are synonymous) """ return s.split(sep, maxsplit) However, this won't work for functions you've defined interactively I don't think. On the other hand, if you defined them interactively, you can just scroll up. ;) Steve From ncoghlan at iinet.net.au Sat Jan 29 03:14:39 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 29 Jan 2005 18:14:39 +1000 Subject: Who should security issues be reported to? In-Reply-To: <7xu0p0yin0.fsf@ruckus.brouhaha.com> References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <7xu0p0yin0.fsf@ruckus.brouhaha.com> Message-ID: <41FB45EF.2010409@iinet.net.au> Paul Rubin wrote: >>More significantly, any security problem is likely to be with a >>specific function or object that has been implemented in C. > > > False; the Cookie module example we talked about was caused by an > unforeseen interaction between pure Python modules (Cookie and pickle). Fair cop on the C thing, but that example otherwise illustrates my point perfectly. Unpickling untrusted data is just as dangerous as evaluating or executing untrusted data. This is *still* dangerous, because there *is no patch* to fix the problem. There are only documentation changes to highlight the security risks associated with unpickling, and Deprecation Warnings on the Cookie classes which use this unsafe feature. So, the only effective mechanism is to get the word out to Python *users* that the feature is unsafe, and should be used with care, which basically requires telling the world about the problem. Any time Python has a problem of this sort, there is going to be at least one solution, and only possibly two: 1. Avoid the feature that represents a security risk 2. Eliminate the security risk in a maintenance update. The first solution applies regardless of whether the security risk is inherent in Python's design or not. Some obvious examples (given above) relate to execution of untrusted code. The second solution applies only to bugs in the CPython implementation and extension modules. And often, tweaking the application's Python code to avoid the dangerous features is going to be faster (and safer) than changing over to a new Python version. By keeping the process public, and clearly identifying the problematic features, application developers can immediately start working on protecting themselves, in parallel with the CPython developers (possibly) working on a new maintenance release. To go with the 72 hours + 8 example you gave - what if you could work around the broken feature in 6? I suspect we'll have to agree to disagree on this point. Where we can agree is that I certainly wouldn't be unhappy if SF had a feature like Bugzilla's security flag. Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From peter at engcorp.com Fri Jan 14 23:25:21 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 14 Jan 2005 23:25:21 -0500 Subject: Com port interrupts again In-Reply-To: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> References: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> Message-ID: engsol wrote: > I didn't fully think through my application before posting my > question. Async com port routines to handle com port interrups > only work well if one has access to the low level operating > system. In that case the receive buffer interrupt would cause > a jump to an interrupt service routine.. I don't believe that > Python provides that capabilty directly. The solution then would > be to write a C extention? Maybe, but I doubt that you can or would really want to do this with modern operating systems anyway. With DOS, and similar primitive things, glomming onto an interrupt or hooking yourself into the interrupt table was pretty easy. I don't think either Windows or Linux is structured such that you just "write a C extension" to intercept interrupts. Instead, you must write relatively complicated drivers which have to be loaded at system startup (more or less) and be tied into the kernel at a relatively low level. Think "rocket science", at least in comparison to writing a simple C extension. :-) > The suggestions offered by respondents to my original post > were almost all of a "Use threads, and poll as needed" flavor. > You're right...I need to learn threads as applied to com ports. At least on Windows, I'm fairly sure you can configure the read timeouts so that you get behaviour on reads that for all intents and purposes is about as good as an interrupt, without the difficulties inherent in that approach, but provided you are willing to dedicate a thread to the task. On Linux, it's possible the read timeouts capabilities are a little less flexible (but I've only just barely glanced at this area), but as I recall you were on Windows anyway. BTW, another post pointed you to USPP. As far as I know, it hasn't been updated recently and, while I can't say how it compares to PySerial, I believe it's fair to say at this point in time that PySerial is the _de facto_ standard way to do serial port stuff in Python. If it doesn't do what you need, it's probably a good idea to at least point that out in its mailing list so that it can be improved. -Peter From dbickett at gmail.com Mon Jan 24 00:45:08 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Mon, 24 Jan 2005 00:45:08 -0500 Subject: how to write a tutorial In-Reply-To: References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106531824.833549.28720@c13g2000cwb.googlegroups.com> Message-ID: <1d6cdae305012321452fb71ca6@mail.gmail.com> Chris Mattern wrote: > alex23 wrote: > > > Having read your comments on women, > > I hadn't looked at that part of his site until now. I can only say: > gah. Haven't seen something like that since Dave Sim's infamous > "Tangent" essay. It's painfully obvious that it is all for the sole purpose of negative attention. You guys are just begging for a YHBT ;-) Daniel Bickett From skip at pobox.com Fri Jan 28 15:09:46 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 28 Jan 2005 14:09:46 -0600 Subject: some kind of LFU dict... In-Reply-To: <63b5e209.0501280739.3887d82@posting.google.com> References: <63b5e209.0501280739.3887d82@posting.google.com> Message-ID: <16890.39946.399821.436142@montanaro.dyndns.org> Joh> so i wondered if i can not use some kind of cache, i googled and Joh> found information on LRU, LFU, and LFU interested me : keep only Joh> most frequently used items inside dict (and memory) and writing Joh> others on disk for a possible future reuse. I have a Cache class that you might subclass to provide different behavior: http://www.musi-cal.com/~skip/python/Cache.py What it does now is throw out keys that match the desired criteria. You could subclass it to stuff those items in a DB file (probably using the anydbm module) and read them from the DB file if an attempt to access a key in the cache fails. Skip From rakesh_usenet at yahoo.com Mon Jan 17 03:20:24 2005 From: rakesh_usenet at yahoo.com (Rakesh) Date: 17 Jan 2005 00:20:24 -0800 Subject: nntplib: abstraction of threads In-Reply-To: <41EAA458.1020501@holdenweb.com> References: <1105840367.526347.110160@c13g2000cwb.googlegroups.com> <41EAA458.1020501@holdenweb.com> Message-ID: <1105950024.112707.286290@z14g2000cwz.googlegroups.com> Steve Holden wrote: > Werner Amann wrote: > > > Rakesh schrieb: > > > > > >>What I want is to *group the messages belonging to each thread* . > > > > > > Hello > > > > Why not sort with Message-ID and References? > > Attention - it is a Newbie-Solution. > > > > import nntplib > > > > hamster = nntplib.NNTP('127.0.0.1', 119, 'user', 'pass') > > resp, count, first, last, name = hamster.group('comp.lang.python') > > resp, items = hamster.xover(first,last) > > > > start_dic = {} > > re_dic = {} > > numb = 1 > > > > for id,subject,author,date,message_id,references,size,lines in items: > > if 'Re:' not in subject: > > start_dic[subject] = (author, message_id) > > else: > > re_dic[numb] = (subject, author, references) > > numb += 1 > > > > resp = hamster.quit() > > > > for a in start_dic: > > print a > > print start_dic[a][0] > > for b in re_dic: > > if start_dic[a][1] in re_dic[b][2]: > > print '|' > > print ' ->', re_dic[b][0] > > print ' ', re_dic[b][1] > > print > > > Better still, do a Google search on "mail threading algorithm", > implement the algorithm described in > > http://www.jwz.org/doc/threading.html Thanks a lot for the link. > > and post your implementation back to the newsgroup :-) Sure I would. I would definitely do the same. I am a python newbie and am reading nntp spec (rfc) right now. Once I get a working version I would definitely post the same. From peter at engcorp.com Wed Jan 5 15:14:33 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 Jan 2005 15:14:33 -0500 Subject: OT: spacing of code in Google Groups In-Reply-To: References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> Message-ID: Jacek Generowicz wrote: > Peter Hansen writes: >>Grant Edwards wrote: >> >>>I always rather liked line numbers (a-la 'can -n'). That also >>>makes discussion of the code easier: >> >>That, unfortunately, is somewhat harder to remove without >>using a regular expression... > > You mean to say that your editor does not have rectangle operations ? > :-) I wouldn't know.** I try quite hard to limit the features that I have to learn and remember to a very, very small list. Why the heck would I ever have to do "rectangle operations" on a regular basis? ;-) -Peter ** I'm using Scite; it probably has it. It has quite a few features -- far more than I'll ever use. Remarkable how simple an editor could be and still be effective... for some people. From fredrik at pythonware.com Mon Jan 31 14:19:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 20:19:02 +0100 Subject: Relocatable binary installs.... References: <1107195180.462949.222980@z14g2000cwz.googlegroups.com> <41FE7F26.1090209@holdenweb.com> Message-ID: Steve Holden wrote: >>>Is there a way to make a relocateable python binary... that is... a >>>python installation that won't care where it is on the machine... and >>>won't care if it gets put somewhere else besides / ? >> >> >> the standard CPython interpreter is 100% "relocatable". If you think >> it isn't, you have to be a bit more specific. >> > Is it possible that you are using "relocatable" in the standard sense of "code can be located > anywhere in physical memory", where the OP is using the same term to mean "can live anywhere in > the filestore"? nope. > I suspect the problem the OP is seeing is because the --prefix configuration parameter will cause > an interpreter to look in a specific place for standard libraries. Clearly if you "relocate" the > libraries to another directory entirely then an interpreter without any further nouse (and no > symbolic links to help it) is going to crap out badly. clearly? [fredrik at brain build] mv python2.3 /tmp [fredrik at brain build] mkdir /tmp/lib [fredrik at brain build] mv lib /tmp/lib/python2.3 [fredrik at brain build] cd /tmp [fredrik at brain tmp]$ ./python2.3 >>> import sys >>> sys.prefix '/tmp' >>> sys.path ['', '/tmp/lib/python23.zip', '/tmp/lib/python2.3', ...] >>> [fredrik at brain tmp]$ mkdir spam [fredrik at brain tmp]$ mv python2.3 spam [fredrik at brain tmp]$ mv lib spam [fredrik at brain tmp]$ cd spam/ [fredrik at brain spam]$ ./python2.3 >>> import sys >>> sys.prefix '/tmp/spam' >>> sys.path ['', '/tmp/spam/lib/python23.zip', '/tmp/spam/lib/python2.3', ...] >>> [fredrik at brain spam]$ mkdir bin [fredrik at brain spam]$ mv python2.3 bin [fredrik at brain spam]$ bin/python2.3 >>> import sys >>> sys.prefix '/tmp/spam' >>> [fredrik at brain spam]$ cd bin [fredrik at brain bin]$ ./python2.3 >>> import sys >>> sys.prefix '/tmp/spam' [fredrik at brain fredrik]$ export PATH=/tmp/spam/bin:$PATH [fredrik at brain bin]$ cd [fredrik at brain fredrik]$ python2.3 >>> import sys >>> sys.prefix '/tmp/spam' >>> and so on... From fuzzyman at gmail.com Tue Jan 25 04:02:45 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2005 01:02:45 -0800 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: Message-ID: <1106643765.733317.27440@f14g2000cwb.googlegroups.com> An implementation of the core language semantics - without any modules or file operations would be dead useful. It could replace some of the function of the long dead rexec modules as well as support projects like this. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From hat at se-126.se.wtb.tue.nl Tue Jan 4 11:03:17 2005 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Tue, 4 Jan 2005 16:03:17 +0000 (UTC) Subject: Parallelization with Python: which, where, how? References: Message-ID: On Mon, 20 Dec 2004 14:03:09 +0100, Mathias wrote: > Can someone recommend a parallelization approach? Are there examples or > documentation? Has someone got experience with stability and efficiency? If you think a light-weight approach of distributing work and collecting the output afterwards (using ssh/rsh) fits your problem, send me an email. Albert -- Unlike popular belief, the .doc format is not an open publically available format. From joshway_without_spam at myway.com Wed Jan 12 17:23:30 2005 From: joshway_without_spam at myway.com (JCM) Date: Wed, 12 Jan 2005 22:23:30 +0000 (UTC) Subject: reference or pointer to some object? References: Message-ID: Torsten Mohr wrote: ... > I still wonder why a concept like "references" was not > implemented in Python. I think it is (even if small) > an overhead to wrap an object in a list or a dictionary. > Isn't it possible to extend Python in a way to use > real references? Or isn't that regarded as necessary? Some think it's unwise. The ability to modify local variables in your caller's scope can lead to messiness, especially if the modifiability isn't evident to the caller (eg. via C's "&"). From rkern at ucsd.edu Mon Jan 3 21:02:27 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 03 Jan 2005 18:02:27 -0800 Subject: Howto Extract PNG from binary file @ 0x80? In-Reply-To: <1104802606.806575.178870@c13g2000cwb.googlegroups.com> References: <1102753727.706459.105920@f14g2000cwb.googlegroups.com> <1104797038.407042.32580@z14g2000cwz.googlegroups.com> <1104802606.806575.178870@c13g2000cwb.googlegroups.com> Message-ID: Don't seek to position 97. Seek to 96. You're off by one. That's why there's the test for the header (which you removed). Files (and Python strings for that matter) are 0-indexed. The first character is 0, the second 1, and so on. If you want the 97th character, you have to seek to position 96. -- 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 phil at riverbankcomputing.co.uk Fri Jan 28 08:47:21 2005 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Fri, 28 Jan 2005 13:47:21 -0000 (GMT) Subject: example needed: sip + Qt In-Reply-To: References: Message-ID: <39688.82.68.80.137.1106920041.squirrel@82.68.80.137> > Hi, > > can someone provide me with a running example for subclassing QWidget (or > something similarly simple) in C++ and then creating SIP (4.x+) bindings > for in for Python (2.3+)? > > I am looking for something I can start of with and work my way towards > more > complicated stuff (with Qt). > > The QLabel example in the SIP reference manual yields syntax errors for > me. What syntax errors? If there is a documentation bug then I'll fix it. Phil From apardon at forel.vub.ac.be Fri Jan 14 04:55:06 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Jan 2005 09:55:06 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-01-14, Fredrik Lundh schreef : > Paul Rubin wrote: > >>> > Huh? Expressions are not statements except when they're "expression >>> > statements"? What kind of expression is not an expression statement? >>> >>> any expression that is used in a content that is not an expression statement, >>> of course. >> >> Come on, that is vacuous. The claim was "expressions are not >> statements". But it turns out that expressions ARE statements. > > no, expressions CAN BE USED as statements. that doesn't mean > that they ARE statements, unless you're applying belgian logic. No I am applying set logic. Any string that is in the set of valid expressions is also in the set of valid statements. Like any animal that is in the set of dogs is also in the set of mamals. -- Antoon Pardon From philippecmartin at sbcglobal.net Wed Jan 5 09:14:44 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Wed, 05 Jan 2005 15:14:44 +0100 Subject: smtp question - using email module Message-ID: <1104934484.6869.13.camel@localhost> Thank you all for your help - an yes! the email module is _very_ nice. Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From bulba at bulba.com Thu Jan 6 20:13:28 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 02:13:28 +0100 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <10trej2fl8dip65@corp.supernews.com> Message-ID: <7lmrt0tf6lgdj70klbsti1r8uougm4tf9n@4ax.com> On Thu, 06 Jan 2005 14:27:55 -0800, Jeff Shannon wrote: >>>That's generally the goal of the Free Software Foundation: they think >>>all users should have the freedom to modify and/or distribute your code. >> >> You have the freedom of having to wash my car then. ;-) >A more accurate analogy would be, "You're free to borrow my car, but >if you do, you must wash it and refill the gas tank before you return it." That analogy is an equivalent of LGPL. Not GPL. GPL in analogy would require you to donate whatever you created thanks to studying the construction of that car in the meantime. And yes, again, sure that is what the borrower agreed to do, sure that NOT using it at all does not result in such obligations, and again - that is not the point. >Note that the so-called 'viral' nature of GPL code only applies to >*modifications you make* to the GPL software. The *only* way in which >your code can be 'infected' by the GPL is if you copy GPL source. >Given the standard usage of closed-source software, you never even >have access to the source. Which means that standard closed-source software does not impose itself on your software - except those detestable cases where Stefan Axelsson pointed out, it prevents you from developing smth similar if you agreed to such a pre-condition in EULA of this thing. It would appear that such a software attempts to economically lock the user in using the only binary in the world that implements this functionality; and FSF attempts to economically, indirectly lock the developers - and indirectly users - in "being pressured to give away" on the rationale of sharing being so good for everyone. Now, this may not be what they INTENDED - but from my viewpoint it seems like that is the RESULT. Not only I see this as unfair, but also as counter-effective in getting more of people into both using and developing software with publicly available source code ("free software" guys tend to get hot under the collar when they hear "open source"). Trying to bully people into this thing _for their own good_ tends to have the effect opposite to the intended. You achieve more by showing positive attitude rather than via conspiracy theories and paranoia. It is also this mostly friendly and relaxed aspect of Python community that I like so much. Again, agreeing / not agreeing and resulting use / walking away _are not the issue_. I don't see MS defended like "well if you don't like whatever MS does, just don't use their software, so shut up about whatever licenses MS actually has and about whatever it does!". >If you use GPL software in the same way >that you use closed-source software, then the GPL cannot 'infect' >anything you do. True, but that abstracts from source code issues, doesn't it? >The 'infective' nature of the GPL *only* comes when you make use of >the *extra* privelidges that open source grants. Those extra privileges are the only way of _building_ large software systems, isn't it? So I would define it as "normal". Yes, closed-source is sort of "crippled" in this regard. >So yes, those extra >privelidges come with a price (which is that you share what you've >done); but if you don't want to pay that price, you have the choice of >not using those privelidges. This does not, in any way, prevent you >from using GPL'ed software as a user. Obviously; but while what you wrote is true, it is not the crux of the problem. >(Problems may come if someone licenses a library under the GPL; that's >what the LGPL was invented for. But the issue here is not that the >GPL is bad, it's that the author used the wrong form of it.) >Personally, I'm not a big fan of the GPL. I'm much more likely to use >BSD-ish licenses than [L]GPL. Personally, I think that LGPL in abstract sense does make sense: if you use and modify this thing, you should return back the _modified_ part - and this should apply regardless whether you keep it in private or not, release in binary or in source to anybody. However, it's definitely safer and since it also FEELS more benign, BSD-like licenses are probably more productive in terms of motivating people to cooperate, so I agree with you on that point. > But it still bugs me to see the GPL >misrepresented as some plot to steal the effort of hardworking >programmers -- it is, instead, an attempt to *encourage* hardworking >programmers to share in a public commons, by ensuring that what's >donated to the commons remains in the commons. OK, a quick sanity check: does Python not remain "in the commons" because some people use it in closed-source applications? I would say that ALL of software released under GPL, LGPL or other free / open source licenses remains in the commons. All of the controversies seem to be about the derived works, don't they? -- It's a man's life in a Python Programming Association. From Prikryl at skil.cz Thu Jan 20 03:36:08 2005 From: Prikryl at skil.cz (Petr Prikryl) Date: Thu, 20 Jan 2005 09:36:08 +0100 Subject: list item's position Message-ID: > On Wed, 19 Jan 2005 22:04:44 -0500, Bob Smith wrote: > > [...] how to find an element's numeric value (0,1,2,3...) > > in the list. Here's an example of what I'm doing: > > > > for bar in bars: > > if 'str_1' in bar and 'str_2' in bar: > > print bar > > > > This finds the right bar, but not its list position. The reason I need > > to find its value is so I can remove every element in the list before it > > so that the bar I found somewhere in the list becomes element 0... does > > that make sense? I have borrowed the bars list example from "Bill Mill"s solutions and here are the two solutions... bars = ['str', 'foobaz', 'barbaz', 'foobar'] # Solution 1: The enumerate(). for idx, bar in enumerate(bars): if 'bar' in bar and 'baz' in bar: break bars_sliced = bars[idx:] print bars_sliced # Solution 2: Low level approach, testing and removing combined. In situ. while bars: # some prefer len(bars) > 0, which is less magical, IMHO bar = bars.pop(0) # get and remove the first element if 'bar' in bar and 'baz' in bar: bars.insert(0, bar) # insert the tested back break # and finish print bars The result is ['barbaz', 'foobar'] in both cases. Petr -- Petr Prikryl (prikrylp at skil dot cz) From drewp at bigasterisk.com Mon Jan 3 13:14:13 2005 From: drewp at bigasterisk.com (drewp at bigasterisk.com) Date: 3 Jan 2005 10:14:13 -0800 Subject: Is Python good for graphics? In-Reply-To: <10s1bdaj7gbin8e@corp.supernews.com> References: <10s1bdaj7gbin8e@corp.supernews.com> Message-ID: <1104776053.962423.112510@f14g2000cwb.googlegroups.com> Esmail Bonakdarian wrote: > > Basically, I would like to be able to create some basic animations > where I can help visualize various sorting algorithms (for instance > http://ciips.ee.uwa.edu.au/~morris/Year2/PLDS210/sorting.html#insert_anim) > or graph searches (coloring nodes as each gets visited). (Something > like this: http://cs.smith.edu/~thiebaut/java/graph/Welcome.html) For the sorting algorithms, at least, check out Demo/tkinter/guido/sortvisu.py in the standard distribution. I'd recommend Tk for all the other demos you described, too. From pythongnome at hotmail.com Fri Jan 14 08:06:17 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Fri, 14 Jan 2005 13:06:17 GMT Subject: porting C code In-Reply-To: <0NidnetRONZTgHrcRVn-oQ@powergate.ca> References: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> <0NidnetRONZTgHrcRVn-oQ@powergate.ca> Message-ID: Peter Hansen wrote: > Lucas Raab wrote: > >> I have the statement: "typedef unsigned long int word32" and later >> on: "word32 b[3]" referencing the third bit of the integer. > > > If that's really exactly what you have, then you actually have > something defining an array of three unsigned long integers > named "b". And even if you didn't have precisely "word32 b[3]", > but merely a "b[3]" reference somewhere, it would be referencing > the third element of an array called "b", which is possibly a byte, > maybe a long, but definitely not a bit. > > Maybe showing it as code rather than inline in your text > would avoid the possibility of confusion. > > -Peter Sorry, the third "byte" is what I meant. As for code samples, I hope the following will work: typedef unsigned long int word32 ; void mu(word32 *a) { int i ; word32 b[3] ; b[0] = b[1] = b[2] = 0 ; for( i=0 ; i<32 ; i++ ) { b[0] <<= 1 ; b[1] <<= 1 ; b[2] <<= 1 ; if(a[0]&1) b[2] |= 1 ; if(a[1]&1) b[1] |= 1 ; if(a[2]&1) b[0] |= 1 ; a[0] >>= 1 ; a[1] >>= 1 ; a[2] >>= 1 ; } a[0] = b[0] ; a[1] = b[1] ; a[2] = b[2] ; } The "a[#]" and "b[#]" are the parts that are giving me trouble. From klachemin at comcast.net Sun Jan 23 09:04:26 2005 From: klachemin at comcast.net (Kamilche) Date: 23 Jan 2005 06:04:26 -0800 Subject: Reload Tricks In-Reply-To: <1gqsb7j.1tbzcqn1f431kdN%aleaxit@yahoo.com> References: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> <1gqsb7j.1tbzcqn1f431kdN%aleaxit@yahoo.com> Message-ID: <1106489066.098048.212390@z14g2000cwz.googlegroups.com> Well, I look forward to seeing the new version. I have the old version of the Python cookbook, it was very useful! From aleaxit at yahoo.com Mon Jan 31 08:16:38 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 31 Jan 2005 14:16:38 +0100 Subject: how do i create such a thing? References: <7vGdnTsopcKl-GDcRVn-rw@comcast.com> Message-ID: <1gr9b2q.1dlgnok1ayt2zsN%aleaxit@yahoo.com> Steven Bethard wrote: > Of if you only want to deal with the case where the attribute doesn't > exist, you can use getattr, which gets called when the attribute can't > be found anywhere else: > > py> class DefaultAttr(object): > ... def __init__(self, default): > ... self.default = default > ... def __getattr__(self, name): > ... return self.default > ... > py> x = DefaultAttr(99) > py> x.a > 99 > py> x.a = 10 > py> x.a > 10 This is a good approach, but it's fragile regarding specialnames. >>> class DefaultAttr(object): ... def __init__(self, default): self.default = default ... def __getattr__(self, name): return self.default ... >>> import copy >>> copy.copy(DefaultAttr(99)) Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.4/copy.py", line 87, in copy rv = reductor(2) TypeError: 'int' object is not callable There are many more, worse example for classic classes, but even in newstyle classes you must consider that once in a while a system routine will try a getattr(someinst, '__aspecialname__', None) or the like -- and your class is making its instances claim to have ANY special name that may be introspected for in this way. This can be a pernicious lie, since your class in fact has no idea whatsoever what that specialname and the corresponding value might be for. It's HIGHLY advisable to have your __getattr__ methods raise AttributeError for any requested name that starts and ends with double underscores, possibly with some specific and specifically designed exceptions. Alex From hgk at et.uni-magdeburg.de Mon Jan 17 06:18:35 2005 From: hgk at et.uni-magdeburg.de (Hans Georg Krauthaeuser) Date: Mon, 17 Jan 2005 12:18:35 +0100 Subject: platform independent kbhit() Message-ID: Hey all, this is probably a FAQ, but I didn't found the answer... I use msvcrt.kbhit() to check for a user keyboard event on windows. But now, I would prefer to make the module independent from the platform used. I already know that I can use curses (on linux/unix) or Tkinter. Also, I found this http://my.execpc.com/~geezer/software/kbhit.c C source that has a kbhit() and a getch() for linux/unix that I can SWIG to python. Are there other (more simple, pure python, true platform independent) possibilities? Best regards Hans Georg Krauthaeuser -- www.uni-magdeburg.de/krauthae From http Tue Jan 11 12:30:12 2005 From: http (Paul Rubin) Date: 11 Jan 2005 09:30:12 -0800 Subject: Time script help sought! References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> Message-ID: <7x4qhn7u1n.fsf@ruckus.brouhaha.com> "kpp9c" writes: > These are analog tapes that were digitized (on to CD or a digital tape) > that have now been exported as individual files that are meant to be > part of an on-line audio archive. ... > I was hoping and > praying that some one here was feeling generous and show me the way... Is this online archive going to be accessible by the public for free? What's in the archive? If you're asking for volunteer labor it's generally appropriate to say precisely what that the labor is for. From ralobao at gmail.com Thu Jan 6 16:47:22 2005 From: ralobao at gmail.com (ralobao at gmail.com) Date: 6 Jan 2005 13:47:22 -0800 Subject: Download .jpg from web In-Reply-To: References: Message-ID: <1105048042.103907.158870@f14g2000cwb.googlegroups.com> You could try using: urlllib.urlretrieve ...it may be faster. From fredrik at pythonware.com Fri Jan 28 07:00:03 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 28 Jan 2005 13:00:03 +0100 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> <41FA22DA.2090402@iinet.net.au> Message-ID: Nick Coghlan wrote: >> I'm sorry, but this isn't really good enough. If Open Source wants to >> say that they are better than these proprietary companies, they need >> to deal with these sorts of things more professionally and establish >> decent channels of communications for dealing with it. > > Is that the sound of a volunteer I hear? > > All you have to do is put your hand up, and the problem will be solved. If not you, who? oh, please. this is a security issue. it needs a little more coordination than an ordinary bug report. From exarkun at divmod.com Sat Jan 8 10:44:53 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sat, 08 Jan 2005 15:44:53 GMT Subject: "A Fundamental Turn Toward Concurrency in Software" In-Reply-To: Message-ID: <20050108154453.32125.797079096.divmod.quotient.2429@ohm> On Sat, 08 Jan 2005 14:22:30 GMT, Lee Harr wrote: >>> [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that the > >> continous CPU performance gain we've seen is finally over. And that future > >> gain would primary be in the area of software concurrency taking advantage > >> hyperthreading and multicore architectures. > >> > > > Well, yes. However, it's not as bad as it looks. I've spent a good part > > of my professional life with multiprocessors (IBM mainframes) and > > I have yet to write a multi-thread program for performance reasons. > > All of those systems ran multiple programs, not single programs > > that had to take advantage of the multiprocessor environment. > > Your typical desktop is no different. My current system has 42 > > processes running, and I'd be willing to bet that the vast majority > > of them aren't multi-threaded. > > > > Exactly. If every one of your processes had its own 2 Ghz processor > running nothing else, I think you would be pretty happy. Your OS > had better be well-written to deal with concurrent access to > memory and disks, but I think for general application development > there will be huge speed boosts with little need for new > programming paradigms. Not likely. How often do you run 4 processes that are all bottlenecked on CPU? It's not a common usage pattern. If you have 16 CPUs, and 15 of them are running mostly idle processes and that *one* process you'd wish would hurry the heck up and finish has the 16th pegged at 100% usage, you are not a happy camper. For the case where you do have a lot of competing unrelated processes, no doubt SMP is a big win automatically, but there will still need to be language innovations to make it easier to develop software which can benefit from the additional hardware for the more common case of individual CPU hungry processes. Jp From martin at v.loewis.de Sun Jan 23 18:24:59 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 24 Jan 2005 00:24:59 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> Message-ID: <41f4324a$0$1547$9b622d9e@news.freenet.de> Paul Rubin wrote: > If he understood how Python is actually used, he'd understand that any > C module is a lot more useful in the core than out of it. This is non-sense. I have been distributing C modules outside the core for quite some time now, and I found that the modules are quite useful. distutils makes it really easy for anybody to use them. > There are already tons of > 3rd party crypto modules outside the core, and the module I was > writing wouldn't add anything useful to those. Why do you think these are not part of the core? It's not because they contain crypto code, or because they had been rejected. They are primarily not included in Python because they have not been contributed to Python, yet. If they were contributed, a number of things still would need to be considered, e.g. what is the size of the code, including libraries, is the contributor really the author, is the code likely going to be maintained, and so on. However, it never got that far. > Where does Frederik get > off lecturing me about wanting to get a module into the core, when > Guido had invited me to do precisely that with that very module? I know that *I* am very opposed to any contribution of a larger module that has not seen any real users, yet. So if the module was primarily written to be included in the core, I would initially reject it for that very reason. After one year or so in its life, and a recognizable user base, inclusion can be considered. > I did release a replacement for the rotor module that's written in > Python, which means it's reasonably useable without being in the core. > However, while its security should be ok, to provide reasonable > performance it had to use a nonstandard algorithm and therefore isn't > good for interoperating with anything. To be both acceptably fast and > interoperable with other applications, a C module is needed. I fail to see the problem you seem to have with C modules. They are very easy to use if written properly. Regards, Martin From andre.roberge at gmail.com Sat Jan 22 19:04:50 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 22 Jan 2005 16:04:50 -0800 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> Message-ID: <1106438690.420574.247510@f14g2000cwb.googlegroups.com> Steven Bethard wrote: > If you have access to the user module's text, something like this might > be a nicer solution: > > py> class Robot(object): > ... def __init__(self): > ... self.name = None > ... def move(self): > ... print "robot %r moved" % self.name > ... > py> class RobotDict(dict): > ... def __setitem__(self, name, value): > ... if isinstance(value, Robot): > ... value.name = name > ... super(RobotDict, self).__setitem__(name, value) > ... > py> user_code = """\ > ... alex = Robot() > ... anna = Robot() > ... alex.move() > ... anna.move()""" > py> robot_dict = RobotDict() > py> robot_dict['Robot'] = Robot > py> exec user_code in robot_dict > robot 'alex' moved > robot 'anna' moved > > Note that I provide a specialized dict in which to exec the user code -- > this allows me to override __setitem__ to add the appropriate attribute > to the Robot as necessary. > I have tried this exact example (using Python 2.3 if it makes any difference) and what I got was: robot None moved robot None moved I checked what I wrote, used cut & paste on your code, removing the leading "junk", tried it again ... to no avail. :-( Andr? From wittempj at hotmail.com Mon Jan 3 10:22:14 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 3 Jan 2005 07:22:14 -0800 Subject: removing comments form a file In-Reply-To: <5b617$41d956df$53e8229a$22273@freeler.nl> References: <5b617$41d956df$53e8229a$22273@freeler.nl> Message-ID: <1104765734.888089.279470@f14g2000cwb.googlegroups.com> You cold do something like this: >>> import re >>> commentpattern = re.compile('.*(?=//)|.*(?!//)') >>> stringwithcomment = 'Blah di blah // some comment' >>> match = commentpattern.match(stringwithcomment) >>> match.group() 'Blah di blah ' >>> stringwithoutcomment = 'Blah di blah' >>> match = commentpattern.match(stringwithoutcomment) >>> match.group() 'Blah di blah' >>> blankline = '\n' >>> match = commentpattern.match(blankline) >>> match.group() '' >>> and put this in a loop where you iterate over your file. Martin (The Netherlands, Amsterdam, bij Diemen) Noud Aldenhoven wrote: > Hello everyone, > > I was wondering how to remove comments away form a file. > So that's why I made this script. > > =============================== > #!/usr/bin/env python > > import sys > import string > import time > > helptext = "usage: python rmcomment [oldfile] [newfile] [comment]" > > def rmcomment(oldfile, newfile, comment): > oldfile = open(oldfile, 'r') > newfile = open(newfile, 'w') > ccount = 0 > lcount = 0 > for line in oldfile.readlines(): > splitline = string.split(line) > pstest = 0 > fileline = "" > for word in splitline: > if word[:2] == comment: > pstest = -1 > ccount += 1 > pass > elif pstest == -1: > pass > else: > fileline += word + " " > if len(fileline) == 0: > pass > else: > newfile.write(fileline + "\n") > lcount += 1 > print "Done... in %s seconds\nRemoved comment from %s lines\nWrote % > lines to %s" % (time.time()-start , ccount, lcount, newfile) > raw_input("Push the enter button to quit>") > > if __name__ == "__main__": > if sys.argv[1] == "-h" or sys.argv[1] == "-help": > print helptext > else: > start = time.time() > oldfile = sys.argv[1] > newfile = sys.argv[2] > comment = sys.argv[3] > rmcomment(oldfile, newfile, comment) > > > ======================================== > > This script works fine with standard text files. An example is this one: > > example.txt: > > Hello Fuckin' World //how are you doing today > //I think it delete this sentence and the next sentence too! > > But this one not! #Even not this comment > > end example.txt > > If I use my script, named rmcomment.py I get this: > > jwaixs at linux:~/programmeren/python/rmcomment$ cat example.txt > Hello Fuckin' World //how are you doing today > //I think it delete this sentence and the next sentence too! > > But this one not! #Even not this comment's > jwaixs at linux:~/programmeren/python/rmcomment$ python rmcomment.py > example.txt newexample.txt // > Done... in 0.00104999542236 seconds > Removed comment from 2 lines > Wrote 2nes to > Push the enter button to quit> > jwaixs at linux:~/programmeren/python/rmcomment$ cat newexample.txt > Hello Fuckin' World > But this one not! #Even not this comment > jwaixs at linux:~/programmeren/python/rmcomment$ > > works fine... but here's my problem. If I use rmcomment.py also the > whitelines will be removed. And I don't want that to happen. Here's another > example: > > jwaixs at linux:~/programmeren/python/rmcomment$ cat otherexample.txt > //This shows what whitelines are doing here > left from me is a nice white line tabs > and here left are at least 3 white line tabs > > //and ofcourse, comments will be deleted > jwaixs at linux:~/programmeren/python/rmcomment$ python rmcomment.py > otherexample.txt newotherexample.txt // > Done... in 0.0011351108551 seconds > Removed comment form 2 lines > Wrote 2nes to > Push the enter button to quit> > jwaixs at linux:~/programmeren/python/rmcomment$ cat newotherexample.txt > left from me is a nice white line tabs > and here left are at least 3 white line tabs > jwaixs at linux:~/programmeren/python/rmcomment$ > > My beautiful whitelines are gone! And I don't want that! > I've thaught how to fix this for a time, but I can't make it on my own. Too > less programming experiance, I'm afraid. > Could someone help me with this problem? Or fix the script or give a hint or > something? > > Thank you at least for reading this post, > > Noud Aldenhoven > The Netherlands (In de beurt bij Nijmegen, voor de nieuwschierigen) > > ps. Yes, I'm a Dyslextion and can't write correct english. I'm sorry for > that. From ajikoe at gmail.com Wed Jan 26 15:00:51 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 26 Jan 2005 12:00:51 -0800 Subject: access private field in python 2.4 In-Reply-To: <4prkc2-ini.ln1@pluto.i.infosense.no> References: <1106754371.637295.82160@z14g2000cwz.googlegroups.com> <4prkc2-ini.ln1@pluto.i.infosense.no> Message-ID: <1106769651.371856.107960@f14g2000cwb.googlegroups.com> Hello, if we want to access the private member of object we use the classname, it doesn't make sense. For example: I have class A: class A: def __init__(self, i): self.__i = i; pass __i = 0 a = A(22); b = A(33); How can I get field i in object a and how can I get field i in object b? Beside I try to call: print _A__i #fail this create error Please help. Pujo Aji From fumanchu at amor.org Tue Jan 25 13:25:00 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 25 Jan 2005 10:25:00 -0800 Subject: I want update one record using ADO,but I can't ,why? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398297@exchange.hqamor.amorhq.net> nightmarch wrote: > I want update one record ,but I can't ,why? > > code like following: > > ##------------------------------------------------- > import win32com.client as wc > > def main(): > conn = wc.Dispatch(r'ADODB.Connection') > rs = wc.Dispatch(r'ADODB.Recordset') > connStr = "Provider=MSDAORA.1;Password=jmpower;User > ID=jmpower;Data Source=jmgis_agps3;Persist Security Info=True" > tblName = r'wjtmp' > > conn.Open(connStr ) > > rs.Open( tblName, conn, wc.constants.adOpenKeyset, > wc.constants.adLockOptimistic ) > > if rs.Supports( wc.constants.adUpdate ): > rs.Fields.Item(0).Value = 11 > rs.Update() > else: > print "recordset can't update" > > rs.Close() > conn.Close() > > if __name__ == '__main__': > main() > ##------------------------------------------------- You almost give us enough information to help out ,but you don't quite ,why? What happens when you run the above? Is there any output? Error message? Does your update affect the membership of the record in the keyset? http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/ htm/mdconkeysetcursors.asp Why are you using keysets at all? Robert Brewer MIS Amor Ministries fumanchu at amor.org From martin at v.loewis.de Thu Jan 27 18:16:10 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 28 Jan 2005 00:16:10 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: <41f97630$0$11586$9b622d9e@news.freenet.de> phr at localhost.localdomain wrote: > I don't see why you can't make up your mind enough to issue simple > statements like "the Python lib should have a module that does > so-and-so I can say that assuming I know what so-and-so is. For the specific case of AES, I would say "I don't think the Python lib necessarily needs to have an AES module, but I would not object if it had one" (the latter part in consideration of consequences that inclusion of crypto code might have). > and it should meet such-and-such requirements I can only say such things if I know such-and-such in detail to specify requirements. For the specific case of AES, I don't know enough about it to specify requirements. I will have to trust others (and by that, I mean *multiple* others) > so if > someone submits one that meets the requirements and passes code review > and testing and doesn't have unexpected issues or otherwise fail to > meet reasonable expectations, we'll use it". Because I cannot specify requirements, I cannot make such a promise. In addition, for any new module, there is one primary requirement for acceptance that cannot be fulfilled in code quality: the contributor should promise to support the module in a foreseeable future (i.e. a couple of years). > Again, we're talking about straightforward modules whose basic > interface needs are obvious. You are talking about such a thing. I don't know enough about the functionality to specify what an obvious interface is, or to recognize one if I see it. > I don't know what OMG is, but there is no IETF requirement that any > implementations be available in any particular language. See RFC 2026, section 4.1.2. Two independent implementations are required for the document to advance to draft (!) standard. > However, the result of my not writing an AES module is that Python > doesn't have an AES module. That's not true. PyCrypto does have AES support. >>No, it's three steps >>1. decide that you want to do it >>2. do it >>3. decide whether you are pleased with the result, and only >> use it if you are >> >>IOW, there should not be a blanket guarantee to use it after step 1. > > > But, it's completely normal to say before step 1 that "if the result > of step 2 does so-and-so, then I'll be pleased in step 3", That's what I'm saying: If you distribute the module to users for a year, and users express interest and support for your choice of API, I'll support inclusion of the module. "do it" involves more than just writing the code. > You and > Frederik seem to think there's something inappropriate or > self-inflated about wanting that expectation before committing to do a > pile of work that's primarily for other people's benefit. It's very easy. If you are primarily do it for other people's benefit, and if you don't find any satisfaction in the process of doing it - THEN DON'T. I really mean that; this is how free software works. People *volunteer* to do things. If they don't volunteer - that's perfectly fine. > I think > your stated attitude is completely bizarre, that you can't really > believe anything so silly, so you're really just acting bureaucratic, > looking for excuses to say no instead of yes to worthwhile proposals. As I said above - for the specific feature in question, I don't care enough for the feature itself. Python will be just as useful to me with the feature as it is without. What I do care about is the effort that I will need to continue maintaining Python. I don't want to have to maintain an ill-designed, buggy module with no active maintainer, and I don't want to tell people that I had to rip the module out just because it doesn't work at all. Regards, Martin From kbk at shore.net Sat Jan 29 14:10:30 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Sat, 29 Jan 2005 14:10:30 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200501291910.j0TJAUhi007769@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 280 open ( +7) / 2747 closed ( +1) / 3027 total ( +8) Bugs : 803 open ( +6) / 4799 closed (+10) / 5602 total (+16) RFE : 167 open ( +1) / 141 closed ( +0) / 308 total ( +1) New / Reopened Patches ______________________ tarfile.ExFileObject iterators (2005-01-23) http://python.org/sf/1107973 opened by Mitch Chapman Allow slicing of any iterator by default (2005-01-24) http://python.org/sf/1108272 opened by Nick Coghlan fix .split() separator doc, update .rsplit() docs (2005-01-24) CLOSED http://python.org/sf/1108303 opened by Wummel type conversion methods and subclasses (2005-01-25) http://python.org/sf/1109424 opened by Walter D?rwald distutils dry-run breaks when attempting to bytecompile (2005-01-26) http://python.org/sf/1109658 opened by Anthony Baxter patch for idlelib (2005-01-26) http://python.org/sf/1110205 opened by sowjanya patch for gzip.GzipFile.flush() (2005-01-26) http://python.org/sf/1110248 opened by David Schnepper HEAD/PUT/DELETE support for urllib2.py (2005-01-28) http://python.org/sf/1111653 opened by Terrel Shumway Patches Closed ______________ fix .split() maxsplit doc, update .rsplit() docs (2005-01-24) http://python.org/sf/1108303 closed by rhettinger New / Reopened Bugs ___________________ "\0" not listed as a valid escape in the lang reference (2005-01-24) CLOSED http://python.org/sf/1108060 opened by Andrew Bennetts broken link in tkinter docs (2005-01-24) http://python.org/sf/1108490 opened by Ilya Sandler Cookie.py produces invalid code (2005-01-25) http://python.org/sf/1108948 opened by Simon Dahlbacka idle freezes when run over ssh (2005-01-25) http://python.org/sf/1108992 opened by Mark Poolman Time module missing from latest module index (2005-01-25) http://python.org/sf/1109523 opened by Skip Montanaro Need some setup.py sanity (2005-01-25) http://python.org/sf/1109602 opened by Skip Montanaro distutils argument parsing is bogus (2005-01-26) http://python.org/sf/1109659 opened by Anthony Baxter bdist_wininst ignores build_lib from build command (2005-01-26) http://python.org/sf/1109963 opened by Anthony Tuininga Cannot ./configure on FC3 with gcc 3.4.2 (2005-01-26) CLOSED http://python.org/sf/1110007 opened by Paul Watson recursion core dumps (2005-01-26) http://python.org/sf/1110055 opened by Jacob Engelbrecht gzip.GzipFile.flush() does not flush all internal buffers (2005-01-26) http://python.org/sf/1110242 opened by David Schnepper os.environ.update doesn't work (2005-01-27) CLOSED http://python.org/sf/1110478 opened by June Kim list comprehension scope (2005-01-27) CLOSED http://python.org/sf/1110705 opened by Simon Dahlbacka RLock logging mispells "success" (2005-01-27) CLOSED http://python.org/sf/1110998 opened by Matthew Bogosian csv reader barfs encountering quote when quote_none is set (2005-01-27) http://python.org/sf/1111100 opened by washington irving tkSimpleDialog broken on MacOS X (Aqua Tk) (2005-01-27) http://python.org/sf/1111130 opened by Russell Owen Bugs Closed ___________ bug with idle's stdout when executing load_source (2005-01-20) http://python.org/sf/1105950 closed by kbk "\0" not listed as a valid escape in the lang reference (2005-01-23) http://python.org/sf/1108060 closed by tim_one Undocumented implicit strip() in split(None) string method (2005-01-19) http://python.org/sf/1105286 closed by rhettinger split() takes no keyword arguments (2005-01-21) http://python.org/sf/1106694 closed by rhettinger Cannot ./configure on FC3 with gcc 3.4.2 (2005-01-26) http://python.org/sf/1110007 closed by loewis os.environ.update doesn't work (2005-01-27) http://python.org/sf/1110478 closed by loewis Scripts started with CGIHTTPServer: missing cgi environment (2005-01-11) http://python.org/sf/1100235 closed by loewis list comprehension scope (2005-01-27) http://python.org/sf/1110705 closed by rhettinger RLock logging mispells "success" (2005-01-27) http://python.org/sf/1110998 closed by bcannon README of 2.4 source download says 2.4a3 (2005-01-20) http://python.org/sf/1106057 closed by loewis New / Reopened RFE __________________ 'attrmap' function, attrmap(x)['attname'] = x.attname (2005-01-26) http://python.org/sf/1110010 opened by Gregory Smith From jnc at ecs.soton.ac.uk Mon Jan 10 09:14:24 2005 From: jnc at ecs.soton.ac.uk (John Carter) Date: Mon, 10 Jan 2005 14:14:24 +0000 Subject: Using ICL to compile C extensions References: <1104815892.984903.182190@f14g2000cwb.googlegroups.com> Message-ID: On 3 Jan 2005 21:18:13 -0800, dayzman at hotmail.com wrote: >Hi, > >Does anyone know how I can use "icl" (Intel C++) to compile C >extensions? I'm on Windows, and my Python is compiled using VS7.1 >(binary distribution). Right now, when I run setup.py install, it uses >cl.exe (MSVC++ Toolkit 2003), and I would like to use icl because >MSVC++ 2003 does not support C99. >Any help will be much appreciated. > >Cheers, >Michael I've not tried to do it using distutils yet, but when I was building extension modules with my own make files and nmake all I had to do was chance cl to icl and use the correct linker. You can tune the performance playing with switches, but I got a factor 3 improvement on a DCT type algorithm with out of the box settings. I can send you an example makefile if you want John Carter jnc at ecs.soton.ac.uk From reinhold-birkenfeld-nospam at wolke7.net Sat Jan 1 15:26:24 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 01 Jan 2005 21:26:24 +0100 Subject: Looping using iterators with fractional values In-Reply-To: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> References: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> Message-ID: <33ofbhF40asveU1@individual.net> drife wrote: > Hello, > > Making the transition from Perl to Python, and have a > question about constructing a loop that uses an iterator > of type float. How does one do this in Python? > > In Perl this construct quite easy: > > for (my $i=0.25; $i<=2.25; $i+=0.25) { > printf "%9.2f\n", $i; > } <=Py2.3: for i in [x/4.0 for x in xrange(1, 10)]: print "%9.2f" % i Py2.4: for i in (x/4.0 for x in xrange(1, 20)): print "%9.2f" % i Reinhold From aleaxit at yahoo.com Tue Jan 4 11:15:53 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 4 Jan 2005 17:15:53 +0100 Subject: Cookbook 2nd ed Credits (was Re: The Industry choice) References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> Message-ID: <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> wrote: > But then I have THREE published recipes!! > Does that mean that I get three free copies of the cookbook ? ;-) ...ti piacerebbe eh...?-) Sorry, "one each", even though you have _five_ credits. For the curious, here's the roster of most credited contributors (remember, significant comments we merged into other's recipes also count!-)...: 1: 42 u'Alex Martelli' 2: 26 u'Raymond Hettinger' 3: 25 u'Luther Blissett' 4: 22 u'Peter Cogolo' 5: 10 u'John Nielsen' 6: 10 u'Anna Martelli Ravenscroft' 7: 8 u'J\x9frgen Hermann' 8: 7 u'Scott David Daniels' 9: 7 u'Chris Perkins' 10: 6 u'S\x8ebastien Keim' 11: 6 u'Paul Prescod' 12: 6 u'Noah Spurrier' 13: 6 u'Jeff Bauer' 14: 6 u'Holger Krekel' 15: 6 u'Danny Yoo' 16: 6 u'Brent Burley' 17: 5 u'Paul Moore' 18: 5 u'Michele Simionato' 19: 5 u'Mark Nenadov' 20: 5 u'David Eppstein' 21: 5 u'Brian Quinlan' If you wished to count only _authored_ recipes (but that's a bit misleading, since in several recipes-as-published there is a merge of two or three separately submitted and accepted recipes, and here I'm counting only the first-listed-author per published-recipe...): 1: 25 u'Luther Blissett' 2: 21 u'Alex Martelli' 3: 9 u'John Nielsen' 4: 8 u'Raymond Hettinger' 5: 8 u'J\x9frgen Hermann' 6: 6 u'S\x8ebastien Keim' 7: 6 u'Peter Cogolo' 8: 6 u'Anna Martelli Ravenscroft' 9: 5 u'Scott David Daniels' 10: 5 u'Paul Prescod' 11: 5 u'Michele Simionato' 12: 5 u'Mark Nenadov' 13: 5 u'Jeff Bauer' 14: 5 u'Brent Burley' ...but each still gets ONE free copy...!-) Alex From marklists at mceahern.com Sat Jan 15 19:02:33 2005 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 15 Jan 2005 18:02:33 -0600 Subject: deleting from tarfile In-Reply-To: References: Message-ID: <41E9AF19.1020702@mceahern.com> Uwe Mayer wrote: >Hi, > >is it possible to delete a file from a tar-archive using the tarfile module? > >Thanks >Uwe > > It doesn't appear so. A workaround, of course, is to create a new file with the subset of files from the old file: #!/usr/bin/env python import tarfile import os def removeFile(filename, nameToDelete): """Remove nameToDelete from tarfile filename.""" prefix, ext = os.path.splitext(filename) newFilename = '%(prefix)s-modified%(ext)s' % locals() original = tarfile.open(filename) modified = tarfile.open(newFilename, 'w') for info in original.getmembers(): if info.name == nameToDelete: continue extracted = original.extractfile(info) if not extracted: continue modified.addfile(info, extracted) original.close() modified.close() // m From rbt at athop1.ath.vt.edu Wed Jan 26 17:43:33 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Wed, 26 Jan 2005 17:43:33 -0500 Subject: MSI Difficulties In-Reply-To: <1106775563.795954.50420@z14g2000cwz.googlegroups.com> References: <1106775563.795954.50420@z14g2000cwz.googlegroups.com> Message-ID: brolewis wrote: > I am trying to deploy Python onto a number of laptops and have been > trying to take advantage of Python 2.4's MSI installer. I have tried > using the following commands to install, but to no avail: > > msiexec /i python-2.4.msi /qb ALLUSERS=1 > -- and -- > msiexec /i python-2.4.msi /qb ALLUSERS=1 ADDLOCAL=ALL > > However both of these commands fail to update the Windows path to > include C:\Python24 and as such creates problems for me when trying to > actually use Python. How can I rectify this situation? Is there a > command I am missing? Do I need to manually update the Path, and if so, > is there a programatic way I can do this? Thanks in advance > I've always manually updated the path... but I suppose there may be a way to do this automatically during install or programatically (bat file or py script afterwards). Perhaps someone more knowledgeable can answer these questions? Best of luck! From alexs at advfn.com Thu Jan 13 07:56:38 2005 From: alexs at advfn.com (Alex Stapleton) Date: Thu, 13 Jan 2005 12:56:38 -0000 Subject: Debian says "Warning! you are running an untested version of Python." on 2.3 Message-ID: Whenever I run python I get "Warning! you are running an untested version of Python." prepended to the start of any output on stdout. This is with Debian and python 2.3 (running the debian 2.1 and 2.2 binaries doesn't have this effect) Does anyone have any idea how to stop this or have even seen it before? Google says Your search - "you are running an untested version" - did not match any documents :( From tundra at tundraware.com Sun Jan 23 13:58:20 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 23 Jan 2005 13:58:20 EST Subject: Insanity In-Reply-To: References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> <3sfcc2-b6v1.ln1@eskimo.tundraware.com> Message-ID: Fredrik Lundh wrote: > Tim Daneliuk wrote: > > >>Thanks - very helpful. One followup - your re works as advertised. But >>if I use: r'\[PROMPT:[^]].*\]' it seems not to. the '.*' instead of just '*' >>it matches the entire string ... > > > it's not "just '*'", it's "[^]]*". it's the "^]" set (anything but ]) that's repeated. > > "[^]].*\]" means match a single non-] character, and then match as many > characters as you possibly can, as long as the next character is a ]. > > "[^]]*\]" means match as many non-] characters as possible, plus a single ]. Got it - 'Makes perfect sense too > > >>which seems counterintutive to me. > > > then you need to study RE:s a bit more. > > (hint: an RE isn't a template, it's a language description, and the RE engine > is designed to answer the question "does this string belong to this language" > (for match) or "is there any substring in this string that belongs to this > language" (for search) as quickly as possible. things like match locations > etc are side effects). Yes, I understand this. But your clarification is most helpful. Thanks! ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From hcslmf at texlife.com Sat Jan 8 16:48:23 2005 From: hcslmf at texlife.com (brolewis) Date: 8 Jan 2005 13:48:23 -0800 Subject: Python Installation In-Reply-To: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> References: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> Message-ID: <1105220903.772101.298500@c13g2000cwb.googlegroups.com> For what its worth, I am running Windows XP Pro on all of these machines. From michele.simionato at gmail.com Thu Jan 27 03:24:23 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 27 Jan 2005 00:24:23 -0800 Subject: python without OO In-Reply-To: <1106694083.199064.240680@f14g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> Message-ID: <1106814263.835719.181360@z14g2000cwz.googlegroups.com> Davor wrote: > Thanks, > > I do not hate OO - I just do not need it for the project size I'm > dealing with - and the project will eventually become open-source and > have additional developers - so I would prefer that we all stick to > "simple procedural" stuff rather than having to deal with a developer > that will be convincing me that his 50 layers inheritance hierarchy is > good since it exists in some weird pattern that he saw somewhere on > some Java design patterns discussion board :-) and other "proper" OO > design issues... Once I opted for C++ in a very small project and > believed everyone will stick with C subset + better type checking > offered through C++ - but I simply could not manage to keep them off > using OO stuff which was just making program more complicated than it > should have been. (note, I am not an experienced developer, nor the > others I'll be working with (even though some think they are:-)), so I > prefer preemptively dealing with issue of everyone showing off their OO > design skills) > I think Davor is making an important point here: Python has grown in the last 14 years, and it is no more the simple scripting language it used to be. In particular, it evolved a lot of OOP "cruft" (static/classmethods, properties, the __new__ method, super, the new MRO, descriptors,metaclasses, etc.) and there is more than a learning curve issue coming with the added complexity. Davor is right: even if you do not want to use it, the stuff is *there* and somebody in your team will. So definitely there is an audience of programmers that just do not have an use for all the sophistication and actually are penalized by it. There is not much than can be done at the Python level. But I would see with interest a Python spinoff geared towards simplicity. Few months ago there was the Prothon proposal (by all means a terrible proposal) but the goal that motivated it (simplification, trying to remove classes) was in my opinion worthwhile. Now, *how* to remove (or simplify) classes is not at all clear to me, not I am convinced that prototypes are the right way to go, but still I feel that there is something wrong with inheritance. Maybe protocols are the solution, who knows? But in any case I think it is important to keep searching for semplicity. I do not believe Python is the definitive language, and it is probabily possible to introduce something better. It is just that nothing of the kind appeared until now, but I keep watching at the horizon ;) Michele Simionato From steve at holdenweb.com Wed Jan 19 12:17:59 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Jan 2005 12:17:59 -0500 Subject: Has apparent 2.4b1 bug been fixed? flatten in Lib\compiler\ast.py overloads 'list' name In-Reply-To: References: <41ede67e.1232456679@news.oz.net> Message-ID: Larry Bates wrote: > You have name clashing between Python's built in list function > and the variable called list that you pass into the function. > Change the passed in variable name to something else. > I believe Bengt was merely seeking confirmation that this was indeed a bug in a distributed library (which he then provided himself by finding a bug report). Hence his use of the phrase "overloads 'list' name" in the subject line! 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 sp1d3rx at gmail.com Tue Jan 11 14:21:06 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 11 Jan 2005 11:21:06 -0800 Subject: Time script help sought! In-Reply-To: <1105470872.613166.187800@f14g2000cwb.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> Message-ID: <1105471266.880133.318470@c13g2000cwb.googlegroups.com> Gosh Mark you must be a friggin genius or something. I can't even begin to read your code. Anyways, I think mine is easier to understand. My program has all the functions (save a couple) that you would need for your project. It's an exercise for you to copy and paste what you want where you want it and to form a basic program structure out of it. some of my comments spilled on to the next line (thanks google!) so you will have to clean it up a bit. From craig at postnewspapers.com.au Fri Jan 7 00:58:45 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 07 Jan 2005 13:58:45 +0800 Subject: curses is not imported under Linux (and Python 2.4) In-Reply-To: <41dd65bd.785984171@news.compuserve.de> References: <41dd65bd.785984171@news.compuserve.de> Message-ID: <1105077525.28776.71.camel@rasputin.localnet> On Fri, 2005-01-07 at 00:38, Konrad Koller wrote: > import curses > produces the ImportError: No module named _curses > ("from _curses import *" in line 15 in __init__.py) > Of course imp.find_module ("_curses") reports the same error. > How can I make use of the curses package for writing a Python script > with curses? What Linux distro? Is the Python version you're running one you compiled, one that shipped with the distro, or a 3rd party RPM? At a guess, I'd say you compiled it yourself and you don't have the ncurses development packages (providing the ncurses header files and static libs) installed. -- Craig Ringer From bvande at po-box.mcgill.ca Wed Jan 26 14:53:04 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed, 26 Jan 2005 14:53:04 -0500 Subject: how to write a tutorial In-Reply-To: References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106723545.429728.308620@f14g2000cwb.googlegroups.com> Message-ID: <41F7F520.8040706@po-box.mcgill.ca> Terry Reedy said unto the world upon 2005-01-26 14:08: > Xah the arrogant wrote, among other things, > However, there are several errors in the above that would mislead a Python > learner. I advise any such to ignore Xah's writings. > > Terry J. Reedy Hi all, here's a thought: There isn't any doubt that these 'tutorials' are generally unwelcome and unhelpful. Numerous people have kindly taken the time to flag some of the problems. So much so that any competent google of the archives would quickly reveal the group consensus on their instructional merit. I submit that continued corrections and advice of this sort are counter-productive. I understand the good intentions behind the corrections. (Indeed, my own level of Python-fu is such that it is possible that I might have been mislead the 'tutorials' without these corrections; I thus appreciate the correctors' efforts.) But, such corrections are troll-food and make it unlikely that the 'game' of posting such tutorials will soon loose its magical power to amuse the OP. They all but ensure that there will be more such 'tutorials' to correct. Could we try to ignore them in the hopes that without the light of attention they will wither, meanwhile trusting the many extant reviews and google to do their work? (In case it isn't obvious: none of this is intended as a criticism of Terry or any of the others who have been 'fighting the good fight'; I just think a change of strategy might be in order.) Best to all Brian vdB From fredrik at pythonware.com Mon Jan 24 11:09:06 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 17:09:06 +0100 Subject: Right place for third party modules (here: fixedpoint) References: <35kj2iF4n6sokU1@news.dfncis.de> Message-ID: >> I suppose fixedpoint is no package as described in the tutorial and so "site-packages" might not >> be the right place for it. > > site-packages sure works on my windows xp / python 2.4 configuration. ah, forget what I said. you need to put the fixedpoint.py *file* under site-packages, not the entire directory. as that "python -v -v" would have told you: > more out ... # trying C:\python24\lib\site-packages\fixedpoint.pyd # trying C:\python24\lib\site-packages\fixedpoint.dll # trying C:\python24\lib\site-packages\fixedpoint.py # trying C:\python24\lib\site-packages\fixedpoint.pyw # trying C:\python24\lib\site-packages\fixedpoint.pyc Traceback (most recent call last): File "", line 1, in ? ImportError: No module named fixedpoint ... From elephantum at dezcom.mephi.ru Tue Jan 11 05:38:25 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Tue, 11 Jan 2005 13:38:25 +0300 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <34frdmF42p2jrU1@individual.net> Message-ID: <34hol1F4ajrmmU1@individual.net> > So of the four keywords suggested so far ('where', 'with', 'in', > 'using'), I'd currently vote for 'using' with 'where' a fairly close > second. My vote goes to 'using' because it has a fairly clear meaning > ('execute the statement using this extra information'), and doesn't have > the conflicting external baggage that 'where' does. I should agree with you =) Though I love "with" for historical reasons and addiction to functional languages "using" is not that bad and I do not mind using it. =) From jdhunter at ace.bsd.uchicago.edu Fri Jan 28 14:47:13 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 28 Jan 2005 13:47:13 -0600 Subject: Installing Numeric with ATLAS and LAPACK In-Reply-To: <1106940704.164253.134630@c13g2000cwb.googlegroups.com> ("drife"'s message of "28 Jan 2005 11:31:44 -0800") References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> <1106940704.164253.134630@c13g2000cwb.googlegroups.com> Message-ID: >>>>> "drife" == drife writes: drife> Thanks John. Those are the steps I followed, and to no drife> avail. Make sure you get a clean build by rm -rf ing the build dir before you build again. Then capture the output of your build to a file. When you say "to no avail" what do you mean -- that the calculation was slower. If you still have troubles, post again to the numpy-discussion list listing what you did and the output of the build process. Good luck! JDH From case.nelson at gmail.com Wed Jan 12 00:02:48 2005 From: case.nelson at gmail.com (snoe) Date: 11 Jan 2005 21:02:48 -0800 Subject: Help Optimizing Word Search In-Reply-To: <1105492347.701890.124830@f14g2000cwb.googlegroups.com> References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> <1105492347.701890.124830@f14g2000cwb.googlegroups.com> Message-ID: <1105506168.801091.282350@z14g2000cwz.googlegroups.com> First of all thank you very much for the reply. I hope I'm not too verbose here, just hope that if someone else runs into a similar problem they can find an answer here. > This appears to be a Computer Science 101 Data Structures and > Algorithms question, not a Python question, but here's an answer > anyway Heh, it's been awhile since I took data structures 101 but I asked here after reading about python generators, and although I can't quite get my head around them, I have a sense that they could help me check all mutations (is this the right word?) of the candidate strings. Thanks for the ideas on finding matches, I will have to try the bit filter out to see if its faster. The trie works similar to this in that it will return a 3 if the substring is not in the dictionary so that you don't have to check any superset of the mutation. Although to clarify, the reason I posted was mostly for help on my weak wildcard algorithm. > If "aa" is in your dictionary, what queries would retrieve it? Any query that contains either "a" and "a" or "a" and "?" or "?" and "?". So some examples would be: "aa", "a?", "aba", "baa", "bbbaba", "b?b?", "bab?", "?abbbbb" etc... > Searching with wild cards: your example of query == "??" seems to yield > all two-letter words. I'd like to see what you expect for "a?", "?a", > "ab?", and "aa?" before suggesting how to tackle wild cards. > Reverse-engineering requirements out of other folks' code is not > something I do for fun :-) My apologies, in my haste my example of what query == "??" yields was unclear. Every list of candidate letters should yield every unique (if possible) mutation, of length 1 to len(candidate). Heh, exactly what each of those strings would yield is pretty much the root of my problem: ?? yields (the order of the results dont matter): a, b, c, d, e, f, ..., x, y, z, aa, ab, ac, ..., ax, ay, az, ba, bb, bc, ..., ya, yb, yc, ..., yx, yy, yz, za, zb, zc, ..., zx, zy, zz a? yields a, b, c, d, ..., x, y, z, aa, ab, ac, ..., ax, ay, az, ba, ca, da, ..., xa, ya, za ?a yields same as a? ab? yields a, b, c, d, ..., x, y, z, aa, ab, ac, ..., ax, ay, az, ba, bb, bc, ..., bx, by, bz, ca, cb, da, db, ea, eb, ..., xa, xb, ya, yb, za, zb, aba, abb, abc, abd, ..., abx, aby, abz, baa, bab, bac, ..., bax, bay, baz, aab, acb, adb, ..., axb, ayb, azb, bba, bca, bda, ... bxa, bya, bza, cba, dba, eba, xba, yba, zba HTH, basically every possible string out of the given pool of up to 10 letters. Ok writing these out just gave me an idea on how I could try and write this another way. Ok done. Wow, this program actually ran much much slower than my original 135 seconds vs 9 seconds!! I'm not sure if I made a huge mistake or if it's because in the original I can stop searching superset-candidates if the candidate is not a substring of a dictionary word (in the same way the mask would reject impossible mutations). This produces the correct mutations however (although not unique as I wrote out above): -- begin code -- !def getmutations(pool): ! ! for i, letter in enumerate(pool): ! pool2 = pool[:] ! pool2.pop(i) ! ! for mutation in getmutations(pool2): ! if letter != '?': ! yield letter + mutation ! else: ! for c in alpha: ! yield c + mutation ! ! yield "" !letters = list('abae?s?') !s = time.time() !output = open('words.log','w') !for candidate in getmutations(letters): ! # Check if word is valid ! result = mytrie.query(candidate) ! ! # Found a word, add it to the database ! if result == 1: ! words[candidate] = 1 ! !print time.time() - s --- end code --- From mirko-lists at zeibig.net Tue Jan 4 04:40:54 2005 From: mirko-lists at zeibig.net (Mirko Zeibig) Date: Tue, 04 Jan 2005 10:40:54 +0100 Subject: python 3000 and removal of builtin callable Message-ID: <33v6l6F40l7hqU1@individual.net> Hello everybody, I recently stumbled across the proposal of removing `callable` in Python 3000 (http://python.org/peps/pep-3000.html) catching an exception instead, maybe something like this: --- snip --- [mize at lxmize mize]$ python2.3 Python 2.3.3 (#1, Apr 6 2004, 01:47:39) [GCC 3.3.3 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> i = 5 >>> i() Traceback (most recent call last): File "", line 1, in ? TypeError: 'int' object is not callable >>> --- snap --- This is not an option for e.g. IDEs as some functions might actually do something when called ;-) and I like `callable` for introspection. Other ways would be to check for the `__call__` attribute or use several methods of the `inspect`-Module, both of which are not better than `callable` IMHO. Regards Mirko -- Insert a sig please. From mnations at gmail.com Tue Jan 18 17:21:37 2005 From: mnations at gmail.com (Mudcat) Date: 18 Jan 2005 14:21:37 -0800 Subject: How to fill available screen size then scroll Message-ID: <1106086897.788340.267550@f14g2000cwb.googlegroups.com> Hi all, I am writing a gui that expands depending on the number of interefaces a user decides to use with Win 2k, Tkinter, and Pmw. So with normal use the gui window will expand to the screen size and then clip without scrolling. If I use Pmw.ScrolledFrame, the clipping frame is set based on the size of the first child frame and never expands to fill the screen. It just expands the size of the inside frame inside the clipping frame. I need a tweener solution. I need the gui to expand until it reaches the width of the available viewing screen. THEN the scroll bar kicks in with a clipping frame the width of the screen to allow the user to see as many interfaces as possible. Does anyone know how to do this? Thanks ahead of time, Marc From ncoghlan at iinet.net.au Sat Jan 22 00:59:05 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 22 Jan 2005 15:59:05 +1000 Subject: Print a string in binary format In-Reply-To: <41f1b14a.1480920561@news.oz.net> References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> <41f1b14a.1480920561@news.oz.net> Message-ID: <41F1EBA9.5010903@iinet.net.au> Bengt Richter wrote: > On Sat, 22 Jan 2005 00:45:19 +1000, Nick Coghlan wrote: >>Here's an interesting twiddle, though (there's probably already something along >>these lines in the cookbook): > > Looks like you also played with this problem, after Alex posted a request for alternative > one-liner solutions to a question on an Italian newsgroup last October? ("show_base" reminded me > of "number_in_base") > > http://groups-beta.google.com/groups?hl=en&lr=&q=number_in_base&qt_s=Search+Groups See, I knew I wouldn't be the first one to think of it :) I stole some ideas from that thread to add to the new version down below (I did not, however, try to make the function expressible as a one-liner, since, after the function has been defined, *using* it is a one-liner!) > Hm, learn something every day ;-) > It didn't occur to me that a string multiplied by a negative number would default > nicely to the same result as multiplying by zero. Where'd I learn that trick?. . . oh, that's right, Facundo used it when working out the string representation for Decimal. It certainly makes padding to a desired minimum field width pretty easy. > Of course, this is the prefixed-sign and absolute value representation, > which is no good if you are using base 2, 8, or 16 to get an idea of > underlying bits in a negative two-s complement representation. Dealing with negative numbers isn't really needed for printing a string as binary , since ord() returns only positive results. However, we should be able to add complement formatting fairly easily: Py> def show_base(val, base, min_digits=1, complement=False, ... digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"): ... if base > len(digits): raise ValueError("Not enough digits for base") ... negative = val < 0 ... val = abs(val) ... if complement: ... sign = "" ... max = base**min_digits ... if (val >= max) or (not negative and val == max): ... raise ValueError("Value out of range for complemented format") ... if negative: ... val = (max - val) ... else: ... sign = "-" * negative ... val_digits = [] ... while val: ... val, digit = divmod(val, base) ... val_digits.append(digits[digit]) ... result = "".join(reversed(val_digits)) ... return sign + ("0" * (min_digits - len(result))) + result ... Py> show_base(10, 2) '1010' Py> show_base(-10, 2) '-1010' Py> show_base(10, 2, 8) '00001010' Py> show_base(-10, 2, 8) '-00001010' Py> show_base(10, 2, 8, complement=True) '00001010' Py> show_base(-10, 2, 8, complement=True) '11110110' Py> show_base(10, 16, 2, complement=True) '0A' Py> show_base(-10, 16, 2, complement=True) 'F6' Py> show_base(127, 16, 2, complement=True) '7F' Py> show_base(-127, 16, 2, complement=True) '81' Py> show_base(255, 16, 2, complement=True) 'FF' Py> show_base(-255, 16, 2, complement=True) '01' Py> show_base(256, 16, 2, complement=True) Traceback (most recent call last): File "", line 1, in ? File "", line 10, in show_base ValueError: Value out of range for complemented format Py> show_base(-256, 16, 2, complement=True) '00' Py> Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ncoghlan at iinet.net.au Fri Jan 14 22:44:47 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 15 Jan 2005 13:44:47 +1000 Subject: import keyword behaviour - performance impact if used multiple times? In-Reply-To: <1105721512.379401.266490@c13g2000cwb.googlegroups.com> References: <41a87cd9$0$25779$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <1105721512.379401.266490@c13g2000cwb.googlegroups.com> Message-ID: <41E891AF.8010900@iinet.net.au> neophyte wrote: > Nick Coghlan wrote: > >> > Is >> > this something to do with system modules being singletons? >> >>They aren't singletons in the GoF design pattern sense. However, > > Python's import > >>machinery operates in such a way that it takes effort to get multiple > > version of > >>the same module into memory at the same time (it *can* be done, but > > you have to > >>work at it). > > Given that this is exactly what I want, how can you do it? > If you just want to reload an existing module, use the builtin "reload" function. Getting multiple versions of a module into sys.modules at the same time isn't something I've ever actually wanted to do, but the following will do it: Py> import sys Py> sys.modules["sys1"] = sys Py> del sys.modules["sys"] Py> import sys Py> import sys1 Py> sys is sys1 False However: 1. Doing this at all is probably a bad idea (since you may end up duplicating objects that are meant to be unique within the process, and any C-extension code will still be shared between the multiple versions of the module) 2. Doing it to 'sys' like I just did is an even worse idea, since you *definitely* end up doing 1 :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From news at NOwillmcguganSPAM.com Wed Jan 26 11:21:59 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Wed, 26 Jan 2005 16:21:59 +0000 Subject: Help With Python In-Reply-To: References: Message-ID: <41f7c3a7$0$7777$db0fefd9@news.zen.co.uk> Judi Keplar wrote: > I am currently taking a course to learn Python and was looking for > some help. I need to write a Python statement to print a comma- > separated repetition of the word, "Spam", written 511 times ("Spam, > Spam, ? Spam"). > > Can anybody help me get started? I am completely new to programming! > > Thanks in advance! >>> print "Spam, " * 510 + "Spam" Will McGugan From jdhunter at ace.bsd.uchicago.edu Fri Jan 28 13:59:11 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 28 Jan 2005 12:59:11 -0600 Subject: handling xls with pyuno Message-ID: Does anyone have any example scripts using the OpenOffince python-bridge module pyuno to load xls, extract the data, and/or save to another format such as xsc or csv. Thanks, JDH From fb at frank-buss.de Fri Jan 21 10:03:45 2005 From: fb at frank-buss.de (Frank Buss) Date: Fri, 21 Jan 2005 15:03:45 +0000 (UTC) Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <0n7Id.135415$Xk.80179@pd7tw3no> Message-ID: drewc wrote: > What does this have to do with Lisp? (i'm in c.l.l). he is a troll, but one who confess this fact: http://www.xahlee.org/Netiquette_dir/troll.html -- Frank Bu?, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From salvafg at terra.es Sat Jan 29 14:52:34 2005 From: salvafg at terra.es (Salvador Fandino) Date: Sat, 29 Jan 2005 19:52:34 GMT Subject: ASPy package Message-ID: <6QRKd.53675$A7.97046@telenews.teleline.es> Hello, I have been trying to download ASPy (an old jython package implementing ASP pages support) from the Internet but it is not available anymore from its home page. Does anybody have it and could link it in some public place? Best Regards - Salvador From deetsNOSPAM at web.de Sun Jan 23 07:06:50 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 23 Jan 2005 13:06:50 +0100 Subject: debugging xmlrpc servers References: <1106442233.305138.24790@f14g2000cwb.googlegroups.com> Message-ID: I have difficulties understanding your probelem - is your own method giving you trouble (and the 'exceptions.ValueError:too many values to unpack') error or is it the remote debugger? Or do you simply not understand the error message itself. The error itself is raised in cases like this: a,b,c = (1,2,3,4) Now to see where that sort of statement fails, it would help if you'd give us the actual code for your result-method. -- Regards, Diez B. Roggisch From aleaxit at yahoo.com Sat Jan 15 14:56:54 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 15 Jan 2005 20:56:54 +0100 Subject: hash patent by AltNet; Python is prior art? References: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> Message-ID: <1gqg78x.1pugljnc5awhmN%aleaxit@yahoo.com> GerritM wrote: > How can this type of fundamental knowledge be patented? I am afraid this is > again an example of a total failure of the current patent system. As a European citizen, you have a chance to make a difference to software patentability in Europe -- think globally, act locally. The Netherlands are a crucial country in the ongoing battle against software patents. Get active! -- we have won major battles over the last 4+ years and we'll need to win quite a few more to break the back of this ugly beast forever. A future where the US and other major SW development countries such as India have saddled themselves with this absurdity, and Europe has freed itself of it, is THE best competitive hope to make Europe into the hotbed of software development and IT innovation in the next generation. Personally, I'm neither patriotic nor competitive, so I'd rather look forward to a world entirely free of this blight -- but hey, where I can make a difference is HERE, so, HERE is where I act. Alex From craig at postnewspapers.com.au Fri Jan 7 00:43:29 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 07 Jan 2005 13:43:29 +0800 Subject: Python C Object Comparison In-Reply-To: <41DD1428.1030503@esi-india.com> References: <41DD1428.1030503@esi-india.com> Message-ID: <1105076609.28776.56.camel@rasputin.localnet> On Thu, 2005-01-06 at 18:34, Anand K Rayudu wrote: > Here is my python code > > import myModule > > a=myModule.myAPI1("1") > b=myModule.myAPI2("name") > > # basically both above functions return same C pointer. > # so i want to compare > if(a==b): print "They are same" > else : print "They are different" > > python always prints they are different, > I guess this is because in python layer we create PythonCObject for > every C pointer, and that is how it is exposed to python. Though both > the APIs are returning the same C pointer, they are different instances > of PythonCObject. That sounds likely to me. > So i guess that is the reason comparison is failing. > How ever is it possible to make python to compare actual C pointer, > rather than the PythonCObject Pointer. You might be able to subclass PyCObject and work with your subclassed version (that adds a __eq__ method). In the end, though, I don't think that's the right path to proceed down. My understanding is that CObjects are for passing pointers through Python code in a safe way. I don't think they're really intended for uses where the Python code is actually working with the objects, only pass them around as opaque objects. If you want to actually work with the objects you're passing around, I'd think about implementing my own type that better fits the API my extension module wants to present to Python code. I'm using PyCObjects as a temporary ugly hack in an embedded app I'm working on... but it's seriously ugly. What I should do, and will soon do now that I've tested the concept of what I'm doing and it works, is move all my functions into a class and make the class own and manage the C++ object (and pointer to it) that it owns. Perhaps that's a better solution for you too? If you want any opinions from folks here about the best way to solve your problem, you'll probably need to explain a bit more of your problem - like what your extension module is doing that makes it have to pass PyCObjects around and get Python code to work with them. -- Craig Ringer From sp1d3rx at gmail.com Fri Jan 14 17:22:24 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 14 Jan 2005 14:22:24 -0800 Subject: win32net help In-Reply-To: References: Message-ID: <1105741344.058696.161980@z14g2000cwz.googlegroups.com> Have you tried using UDP instead of TCP? Also, it is common practice to choose a random port over 1024 for opening a connection to a remote server. From tjreedy at udel.edu Sun Jan 2 21:52:04 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Jan 2005 21:52:04 -0500 Subject: Calling Function Without Parentheses! References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> Message-ID: "Kamilche" wrote in message news:1104715584.407505.190910 at f14g2000cwb.googlegroups.com... > What a debug nightmare! I just spent HOURS running my script through > the debugger, sprinkling in log statements, and the like, tracking down > my problem. Did you try PyChecker? (Don't know if > I called a function without the ending parentheses. Which means you didn't call, and that was your problem ;-) In Python, the (...) pair in the appropriate context (where an operator is expected) *is* the infix/postfix call operator. It is equivalent to the call or gosub prefix in some other languages. The call operator works with any callable, not just function objects. >I sure do WISH Python would trap it when I try to do the following: trap = raise an exception? nooooh. > MyFunc > instead of: > MyFunc() In Python, non-keyword names resolve at runtime to the objects they are then bound to. This simple, uniform rule is, to me, part of the beauty of Python. There are lots of times that one wants to refer to a callable without calling it. Indeed, because Python separates referring to an object from calling the object, it can and does have a broader notion of 'callable' than other languages. This includes the option of making instances of any user class callable (by including a __call__ method). Terry J. Reedy From agriff at tin.it Mon Jan 10 02:31:02 2005 From: agriff at tin.it (Andrea Griffini) Date: Mon, 10 Jan 2005 07:31:02 GMT Subject: Speed revisited References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> <1105237556.402188.126980@c13g2000cwb.googlegroups.com> <1105303172.147395.63580@c13g2000cwb.googlegroups.com> <36c3u0tpbg6f98ta6cm4fkj2kn0dkv624m@4ax.com> <1105315414.432202.249470@c13g2000cwb.googlegroups.com> Message-ID: On 9 Jan 2005 16:03:34 -0800, "John Machin" wrote: >My wild guess: Not a common use case. Double-ended queue is a special >purpose structure. > >Note that the OP could have implemented the 3-tape update simulation >efficiently by reading backwards i.e. del alist[-1] Note that I was just trying to say that it's not obvious that list insertion at the first element is O(n); because there are "less naive" implementation that can do better. For a lower level language O(n) is probably what 99% of programmers indeed would expect, but for a VHLL like python this is IMO not the case. I remember when a few years ago working with PowerBuilder (a RAD environment for client-server applications) to my great surprise I found that even adding at the end of a list was O(n) in that language... where is the line ? After all "smart" reallocation is still a tradeoff (extra "wasted" space traded for diminshed copying) ... Andrea From mike at lookdirect.com.au Mon Jan 31 17:42:11 2005 From: mike at lookdirect.com.au (mike) Date: 31 Jan 2005 14:42:11 -0800 Subject: Microsoft Visual C++ and pyton In-Reply-To: References: <1107126726.533325.104300@z14g2000cwz.googlegroups.com> Message-ID: <1107211331.830565.238150@c13g2000cwb.googlegroups.com> Thanks Chris.. I was also advised to build the python core (pythoncore.vcproj) with my C++ program. By that way I would not have to load the python core anymore during runtime. Is this a good approach? I am currently using VC++ 7 and python 2.4. - mike Christopher De Vries wrote: > On Sun, Jan 30, 2005 at 03:12:06PM -0800, mike wrote: > > I am new with python. Is it possible to have an MFC application and > > develop some module using python? what are the steps in doing this? can > > anybody give me a url or some documentation for this.. thanks.. > > It is possible to embed python in a C or C++ application, enabling you to call > python functions from C. I would recommend reading "Extending and Embedding the > Python Interpreter" at http://docs.python.org/ext/ext.html for more > information. If you are currently using Visual C++ 6.0, either stick with > Python 2.3 or read this: http://www.vrplumber.com/programming/mstoolkit/ to > learn how to build extensions for python 2.4 with the free VC++ toolkit > compiler. If you are already using version 7 of the Microsoft C++ compiler then > you should have no problems with Python 2.4. > > I usually do not embed the interpreter, but I have written some extension > modules... well, I should say I have used SWIG (http://www.swig.org/) to create > wrappers around some C libraries. For information (read: rants) on extending > versus embedding see http://twistedmatrix.com/users/glyph/rant/extendit.html > and http://c2.com/cgi/wiki?EmbedVsExtend . > > You can also use win32 python extensions to make your module available through > COM, but I don't know anything about that. > > Chris From ncoghlan at iinet.net.au Tue Jan 4 05:46:55 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 04 Jan 2005 20:46:55 +1000 Subject: why does UserDict.DictMixin use keys instead of __iter__? In-Reply-To: References: Message-ID: <41DA741F.5050406@iinet.net.au> Steven Bethard wrote: > Sorry if this is a repost -- it didn't appear for me the first time. > > > So I was looking at the Language Reference's discussion about emulating > container types[1], and nowhere in it does it mention that .keys() is > part of the container protocol. Because of this, I would assume that to > use UserDict.DictMixin correctly, a class would only need to define > __getitem__, __setitem__, __delitem__ and __iter__. So why does > UserDict.DictMixin require keys() to be defined? Because it's a DictMixin, not a ContainerMixin? .keys() is definitely part of the standard dictionary interface, and not something the mixin can derive from the generic container methods. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From exarkun at divmod.com Thu Jan 6 09:09:00 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 06 Jan 2005 14:09:00 GMT Subject: get the IP address of a host In-Reply-To: Message-ID: <20050106140900.25734.752673503.divmod.quotient.3700@ohm> On Thu, 06 Jan 2005 14:35:16 +0100, J Berends wrote: > > From several approached I came up with the following code: > > def getipaddr(hostname='default'): > """Given a hostname, perform a standard (forward) lookup and return > a list of IP addresses for that host.""" > if hostname == 'default': > hostname = socket.gethostname() > ips = socket.gethostbyname_ex(hostname)[2] > ips = [i for i in ips if i.split('.')[0] != '127'] > if len(ips) != 0: > # check if we have succes in determining outside IP > ip = ips[0] > elif len(ips) == 0 and hostname == socket.gethostname(): > # when we want to determine local IP and did not have succes > # with gethostbyname_ex then we would like to connect to say... > > # google.com and determine the local ip address bound to the > # local socket. > try: > s = socket.socket() > s.connect(('google.com', 80)) > print ('___ connecting to internet to determine local ip') > ip = s.getsockname()[0] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('1.2.3.4', 56)) ip = s.getsockname()[0] > del s > except: > print ('*** cannot connect to internet in order to \ > determine outside IP address') > raise Exception > if len(ip) != 0: > return ip > else: > print ('*** unable to determine outside IP address') > raise Exception > > It returns the IP address with which it connects to the world (not lo), > might be a pvt LAN address or an internet routed IP. Depend on where the > host is. > > I hate the google trick actually, so any suggestions to something better > is always welcome. Jp From francis.girard at free.fr Fri Jan 21 11:16:28 2005 From: francis.girard at free.fr (Francis Girard) Date: Fri, 21 Jan 2005 17:16:28 +0100 Subject: need help on need help on generator... In-Reply-To: <1106322141.19065.42.camel@bucket.localnet> References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501211605.40696.francis.girard@free.fr> <1106322141.19065.42.camel@bucket.localnet> Message-ID: <200501211716.28459.francis.girard@free.fr> Really, thank you Craig Ringer for your great answer. > I'm afraid I can't help you with that. I tend to take the view that side > effects in lazily executed code are a bad plan, and use lazy execution > for things where there is no reason to care when the code is executed. I completly agree with this. But this is much more true in theory than in practice. In practice you might end up with big big memory usage with lazy constructs as the "system" has to store intermediate results (the execution context in the case of Python). These kinds of phenomena happen all the time in a language like Haskell -- at least for a beginner like me -- if you don't pay attention to it ; and this makes the language a lot more difficult to master. Thus you have to keep an eye on performance even though, in FP, you shoould just have to "declare" your intentions and let the system manage the execution path. > http://gnosis.cx/publish/programming/metaclass_1.html > http://gnosis.cx/publish/programming/metaclass_2.html Thank you, I'll read that. Francis Girard FRANCE Le vendredi 21 Janvier 2005 16:42, Craig Ringer a ?crit?: > On Fri, 2005-01-21 at 16:05 +0100, Francis Girard wrote: > > I recently read David Mertz (IBM DeveloperWorks) about generators and > > got excited about using lazy constructs in my Python programming. > > Speaking of totally great articles, and indirectly to lazyness (though > not lazyily evaluated constructs), I was really impressed by this > fantastic article on metaclasses: > > http://gnosis.cx/publish/programming/metaclass_1.html > http://gnosis.cx/publish/programming/metaclass_2.html > > which shows that they're really just not that hard. That saved me an > IMMENSE amount of utterly tedious coding just recently. > > > But besides the fact that generators are either produced with the new > > "yield" reserved word or by defining the __new__ method in a class > > definition, I don't know much about them. > > They can also be created with a generator expression under Python 2.4. A > generator expression works much like a list comprehension, but returns a > generator instead of a list, and is evaluated lazily. (It also doesn't > pollute the outside namespace with its working variables). > > >>> print [ x for x in range(1,10)] > > [1, 2, 3, 4, 5, 6, 7, 8, 9] > > >>> print ( x for x in xrange(1,10) ) > > > > >>> print list(( x for x in xrange(1,10) )) > > [1, 2, 3, 4, 5, 6, 7, 8, 9] > > Not the use of xrange above for efficiency in the generator expressions. > These examples are trivial and pointless, but hopefully get the point > across. > > > In particular, I don't know what Python constructs does generate a > > generator. > > As far as I know, functions that use yield, and generator expressions. I > was unaware of the ability to create them using a class with a __new__ > method, and need to check that out - I can imagine situations in which > it might be rather handy. > > I'm not sure how many Python built-in functions and library modules > return generators for things. > > > I know this is now the case for reading lines in a file or with the > > new "iterator" package. But what else ? Does Craig Ringer answer mean > > that list comprehensions are lazy ? > > Nope, but generator expressions are, and they're pretty similar. > > > Where can I find a comprehensive list of all the lazy constructions > > built in Python ? (I think that to easily distinguish lazy from strict > > constructs is an absolute programmer need -- otherwise you always end > > up wondering when is it that code is actually executed like in > > Haskell). > > I'm afraid I can't help you with that. I tend to take the view that side > effects in lazily executed code are a bad plan, and use lazy execution > for things where there is no reason to care when the code is executed. > > -- > Craig Ringer From steve at holdenweb.com Fri Jan 14 17:22:20 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 17:22:20 -0500 Subject: (objects as) mutable dictionary keys In-Reply-To: References: Message-ID: Antoon Pardon wrote: > Op 2005-01-14, Peter Maas schreef : > >>I have summarized the discussion about the usability of lists (and >>and other mutable types) as dictionary keys and put it into the >>Python wiki.URL: http://www.python.org/moin/DictionaryKeys. >> >>This summary might be used as a reference should the 'mutable >>dictionary keys' issue come up again in c.l.py. >> > > I had a look and I think you should correct the followingr: > > Dictionary lookup with mutable types like lists is a source of > unpleasant surprises for the programmer and therefore impossible in > Python. > Better, perhaps, to say: Dictionary lookup with mutable types like lists can be a source of unpleasant surprises for the programmer and therefore not recommended in Python. > > It is not impossible in Python. It may be discouraged but it is not > impossible since I have already done so. > If I discouraged you from shooting yourself in the foot would you do that too? some-people-just-won't-be-told-ly y'rs - 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 a at a.invalid Thu Jan 27 03:32:37 2005 From: a at a.invalid (Timo Virkkala) Date: Thu, 27 Jan 2005 08:32:37 GMT Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> Message-ID: Davor wrote: > Timo Virkkala wrote: >> This guy has got to be a troll. No other way to understand. > > not really - it was not my intention at all - but it seems people get > upset whenever this OO stuff is mentioned - and what I did not expect at > all at this forum as I believed Python people should not be so OO > hardcore (seems not all as quite a few have indicated in their > replies)... Nevertheless, I think the discussion has several quite good > points! Yes, sorry about that. I posted too soon. After posting I read more of your posts and realized that you really mean it, so I tried to cancel my message, but apparently it got through (news message canceling has never been that reliable..). I believe that if you take the time to do some Python programming, you can find out that OO, when used correctly, is not the huge monster your previous languages had led you to believe it is. In Python, you can use just the right amount of OO to make things easier and more sensible, without complicating things with huge inheritance trees and unnecessary polymorphism. Again, sorry about my premature judgement. -- Timo Virkkala From __peter__ at web.de Fri Jan 28 04:33:30 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Jan 2005 10:33:30 +0100 Subject: get list of member variables from list of class References: Message-ID: Oliver Eichler wrote: > what will be the fastest solution to following problem > > class a: > def __init__(self): > self.varA = 0 > self.varB = 0 > s.o. ... > > > listA = [a]*10 > > > varA = [] > varB = [] > > for l in listA: > varA.append(l.varA) > varB.append(l.varB) > s.o. ... > > > I could think of: > [varA.append(l.varA) for l in listA] > [varB.append(l.varB) for l in listA] > s.o. ... > > But is this faster? After all I have to iterate over listA several times. > > Any better solutions? A different approach, a "virtual list" could even be faster if client code must access only a fraction of the items in the virtual list. If you are lucky, you never have to iterate over the complete list. >>> class A: ... def __init__(self, a): ... self.a = a ... def __repr__(self): ... return "A(%r)" % self.a ... >>> items = map(A, range(10)) >>> items [A(0), A(1), A(2), A(3), A(4), A(5), A(6), A(7), A(8), A(9)] >>> class List: ... def __init__(self, items, getter): ... self.items = items ... self.getter = getter ... def __getitem__(self, index): ... return self.getter(self.items[index]) ... def __iter__(self): ... return imap(self.getter, self.items) ... >>> from operator import attrgetter >>> from itertools import imap >>> items_a = List(items, attrgetter("a")) >>> items_a <__main__.List instance at 0x402ae2cc> >>> items_a[2] 2 >>> list(items_a) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> items[2] = A(42) >>> items [A(0), A(1), A(42), A(3), A(4), A(5), A(6), A(7), A(8), A(9)] >>> items_a[2] 42 Peter From steve at holdenweb.com Mon Jan 17 06:32:10 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 06:32:10 -0500 Subject: [perl-python] 20050117, filter, map In-Reply-To: References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: <41EBA23A.2010005@holdenweb.com> Erik Max Francis wrote: > Steven Bethard wrote: > >> Is there any chance you could post these all as part of the same >> thread? That would be really nice for those of us who aren't >> interested -- then we could just ignore the thread... > You are looking for evidence of cluefulness where it seems unlikely to ever appear. > > Or, better yet, not posting it at all. He's got his mailing list, what > does he need to post it here for? > As I may have mentioned before, egotism can be the only possible reason. 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 kent3737 at yahoo.com Thu Jan 20 15:23:01 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Thu, 20 Jan 2005 15:23:01 -0500 Subject: Overloading ctor doesn't work? In-Reply-To: References: <35ab8oF4idc25U1@individual.net> <41effd30$1_1@newspeer2.tds.net> Message-ID: <41f010b5$1_1@newspeer2.tds.net> Paul McGuire wrote: > "Kent Johnson" wrote in message > news:41effd30$1_1 at newspeer2.tds.net... > >>>Martin H?cker wrote: >>> >>> >>>>Hi there, >>>> >>>>I just tried to run this code and failed miserably - though I dunno >>>>why. Could any of you please enlighten me why this doesn't work? >> >>Here is a simpler test case. I'm mystified too: >> >>from datetime import datetime >> >>class time (datetime): >> def __init__(self, hours=0, minutes=0, seconds=0, microseconds=0): >> datetime.__init__(self, 2001, 10, 31, hours, minutes, seconds, > > microseconds) > >>print time(1,2,3,4) # => 0001-02-03 04:00:00 >>print time() # => TypeError: function takes at least 3 arguments (0 > > given) > >> >>What happens to the default arguments to time.__init__? What happens to > > the 2001, 10, 31 arguments > >>to datetime.__init__? >> >>I would expect the output to be >>2001-10-31 01:02:03.000004 >>2001-10-31 00:00:00.000000 >> >>Kent > > > I can't explain this behavior, but this version does work (uses > datetime.combine instead of ctor) > > -- Paul > > > from datetime import datetime, date as dt_date, time as dt_time > > class time_d (datetime): > def __new__(cls, *args): > # default to no microseconds > if len(args)==3: > args = args + (0,) > if len(args)==4: > tmpdate = datetime.today() > h, mi, s, ms = args > return datetime.combine(tmpdate, dt_time(h,mi,s,ms)) > elif len(args)==7: > y,m,d,h,mi,s,ms = args > return datetime.combine(dt_date(y,m,d), dt_time(h,mi,s,ms)) > else: > raise TypeError, "wrong number of args" > > print time_d(2001,10,31,1,2,3,4) > print time_d(1,2,3,4) > print time_d(1,2,3) Ah, right. The light turns on... datetime is immutable so overriding the constructor doesn't change the constructed object. You have to override __new__ instead. http://www.python.org/2.2.1/descrintro.html#__new__ This works: from datetime import datetime class time (datetime): def __new__(cls, hours=0, minutes=0, seconds=0, microseconds=0): return datetime.__new__(cls, 2001, 10, 31, hours, minutes, seconds, microseconds) print time(1,2,3,4) # => 2001-10-31 01:02:03.000004 print time() # => 2001-10-31 00:00:00 Kent > > > From sam.wun at authtec.com Mon Jan 24 01:26:58 2005 From: sam.wun at authtec.com (sam) Date: Mon, 24 Jan 2005 14:26:58 +0800 Subject: compile python to binary In-Reply-To: References: <1d6cdae3050123080242bf8994@mail.gmail.com> Message-ID: <41F49532.5040307@authtec.com> Fredrik Lundh wrote: > Daniel Bickett wrote: > > >>I believe Sam was talking about "frozen" python scripts using tools >>such as py2exe: > > > oh, you mean that "python compiler" didn't mean "the python compiler". > > here are links to some more tools, btw: > > http://effbot.org/zone/python-compile.htm > Thanks for the link. It is what I exactly looking for. Thanks Sam > > > > From marc_a_poulin at yahoo.com Fri Jan 28 19:04:48 2005 From: marc_a_poulin at yahoo.com (Marc Poulin) Date: Fri, 28 Jan 2005 17:04:48 -0700 Subject: Where can I find sample "beginner" programs to study? References: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> Message-ID: <41fad2f9$0$206$75868355@news.frii.net> Todd_Calhoun wrote: > I'm trying to learn Python (and programming), and I'm wondering if there > are any places where I can find small, simple programs to study. > > Thanks. Look at http://www.livewires.org.uk/python/ Good projects and tutorials for beginners. From get at bent.com Wed Jan 26 02:59:35 2005 From: get at bent.com (nobody) Date: Wed, 26 Jan 2005 17:59:35 +1000 Subject: MySQLdb References: Message-ID: <1106726373.519886@chloe.intranet> > How many indices? Just the primary key (id). From benn at cenix-bioscience.com Thu Jan 20 05:55:11 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Thu, 20 Jan 2005 11:55:11 +0100 Subject: [Fwd: Re: Oddity is shutil.copyfileobj] Message-ID: <41EF8E0F.2070401@cenix-bioscience.com> -------------- next part -------------- An embedded message was scrubbed... From: Neil Benn Subject: Re: Oddity is shutil.copyfileobj Date: Thu, 20 Jan 2005 11:41:40 +0100 Size: 2267 URL: From firstname.lastname at iki.fi-spam Wed Jan 12 09:03:07 2005 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 12 Jan 2005 16:03:07 +0200 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <1105509379.301556.178130@z14g2000cwz.googlegroups.com> Message-ID: <87wtui4uec.fsf@sme.intra.citec.fi> michele.simionato at gmail.com writes: > This is a bizarre idea if you want to make Python run faster. It is > not so bizarre if what you want is to have access to Python from > Lisp/Scheme in the same sense Jython has access to Java. And it sounds very nice if you prefer writing Lisp code (or resort to it if needed) and run it on a cross-platform environment that's available almost everywhere, and access a large standard library of modern utilities. br, S From steven.bethard at gmail.com Wed Jan 26 12:46:45 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 10:46:45 -0700 Subject: inherit without calling parent class constructor? In-Reply-To: References: Message-ID: Christian Dieterich wrote: > Hi, > > I need to create many instances of a class D that inherits from a class > B. Since the constructor of B is expensive I'd like to execute it only > if it's really unavoidable. Below is an example and two workarounds, but > I feel they are not really good solutions. Does somebody have any ideas > how to inherit the data attributes and the methods of a class without > calling it's constructor over and over again? > > Thank, > > Christian > > Here's the "proper" example: > > class B: > def __init__(self, length): > size = self.method(length) > self.size = size > def __str__(self): > return 'object size = ' + str(self.size) > def method(self, length): > print 'some expensive calculation' > return length > > class D(B): > def __init__(self, length): > B.__init__(self, length) > self.value = 1 > > if __name__ == "__main__": > obj = D(7) > obj = D(7) I'm confused as to how you can tell when it's avoidable... Do you mean you don't want to call 'method' if you don't have to? Could you make size a property, e.g. class B(object): def __init__(self, length): self._length = length def _get_size(self): print 'some expensive calculation' return self._length size = property(fget=_get_size) class D(B): def __init__(self, length): super(B, self).__init__(length) self.value = 1 if __name__ == "__main__": obj = D(7) obj = D(7) Then 'size' won't be calculated until you actually use it. If 'size' is only to be calculated once, you might also look at Scott David Daniels's lazy property recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363602 Steve From ug at algonet.se Tue Jan 25 03:26:50 2005 From: ug at algonet.se (=?ISO-8859-1?Q?Ulf_G=F6ransson?=) Date: Tue, 25 Jan 2005 09:26:50 +0100 Subject: Open Folder in Desktop In-Reply-To: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> References: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> Message-ID: Kamilche wrote: > Is there a command you can execute in Python that will open a window on > the desktop, such as 'My Documents'? Kind of like 'system', but for > folder names, not just programs. I'm running on Windows 2000. Maybe this is good enough? os.system("explorer " + folder_path) /ug From strombrg at dcs.nac.uci.edu Mon Jan 3 16:23:23 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Mon, 03 Jan 2005 13:23:23 -0800 Subject: Zope newsgroups? Need help with POSKeyError References: <41d5e51d$0$4095$afc38c87@news.optusnet.com.au> Message-ID: On Sat, 01 Jan 2005 10:47:41 +1100, richard wrote: > Bob Horvath wrote: >> I have a Zope/Plone combination that I have been having POSKeyErrors >> with for a while now. Are there any newsgroups that deal with Zope? > > No, but there is a mailing list - see zope.org > > Also, try google searching for POSKeyError. > > > Richard You could also see if the zeop mailing list is gatewayed to nntp on gmane. They have a huge number of FLOSS development mailing lists on that nntp server. Google should be able to find it easily. From fredrik at pythonware.com Sun Jan 23 13:39:52 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 19:39:52 +0100 Subject: on the way to find pi! References: <20050123182847.74790.qmail@web61009.mail.yahoo.com> Message-ID: Ali Polatel wrote: > I found a code which calculates pi with an interesting algorithm the programme code is below: > [code snipped] > This code gives the number in an unusual format like "3.1415'None'" it has > a number part and a string part. are you sure? $ python pi.py How many digits? :5 3.1415 $ python pi.py How many digits? :10 3.141592653 $ python pi.py How many digits? :20 3.1415926535897932384 > Any idea how to seperate this 'None' from the number and make it a real > normal number on which I can do operations like +1 -1 or like that :) what's the point of that? the math module already contains pi with as many decimals as you can put in a Python float: $ python >>> pi = 3.1415926535897932384 >>> pi 3.1415926535897931 >>> import math >>> math.pi 3.1415926535897931 >>> pi = math.pi True From fredrik at pythonware.com Tue Jan 25 20:10:44 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Jan 2005 02:10:44 +0100 Subject: string.atoi and string.atol broken? References: Message-ID: Mike Moum wrote: > s.atoi('4',3) should result in 11 > > s.atoi('13',4) should result in 31 > > s.atoi('12',4) should result in 30 > > s.atoi('8',4) is legitimate, but it generates an error. > > Is this a bug, or am I missing something obvious? the function's named "atoi", not "atoitoa". From brian.bird at securetrading.com Wed Jan 5 04:21:41 2005 From: brian.bird at securetrading.com (brian.bird at securetrading.com) Date: 5 Jan 2005 01:21:41 -0800 Subject: Keyword arguments - strange behaviour? References: <1103622331.247762.161750@f14g2000cwb.googlegroups.com> <1103637176.450940.243500@c13g2000cwb.googlegroups.com> <1103640442.940168.246130@c13g2000cwb.googlegroups.com> <1103801690.093414.72370@f14g2000cwb.googlegroups.com> <1gpal5s.crzm5p1oal62zN%aleaxit@yahoo.com> Message-ID: <1104916901.552008.195950@z14g2000cwz.googlegroups.com> Thanks. In case anyone else is looking, the recipe is at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303440 (which also shows how to make it work with python2.3 and below since they don't support decorators) Brian From foo.bar at freesurf.ch.invalid Sat Jan 1 14:39:50 2005 From: foo.bar at freesurf.ch.invalid (Thomas Rast) Date: Sat, 01 Jan 2005 20:39:50 +0100 Subject: Python equivalent of script(1) References: <1104607982.132310.181560@c13g2000cwb.googlegroups.com> Message-ID: <87d5wprla1.fsf@thomas.local> cepl at surfbest.net writes: > I would love to have a record of all what I've done, so I can edit > this record into final script. You can save the current input history with >>> import readline >>> readline.write_history_file("python.log") If you want to log your whole session, including output, try using the 'screen' utility. HTH - Thomas -- If you want to reply by mail, substitute my first and last name for 'foo' and 'bar', respectively, and remove '.invalid'. From ovazquez at gmail.SPAM.com Sun Jan 23 07:12:56 2005 From: ovazquez at gmail.SPAM.com (Orlando Vazquez) Date: Sun, 23 Jan 2005 12:12:56 GMT Subject: re Insanity In-Reply-To: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> Message-ID: Tim Daneliuk wrote: > For some reason, I am having the hardest time doing something that should > be obvious. (Note time of posting ;) > > Given an arbitrary string, I want to find each individual instance of > text in the form: "[PROMPT:optional text]" > > I tried this: > > y=re.compile(r'\[PROMPT:.*\]') > > Which works fine when the text is exactly "[PROMPT:whatever]" but > does not match on: > > "something [PROMPT:foo] something [PROMPT:bar] something ..." > > The overall goal is to identify the beginning and end of each [PROMPT...] > string in the line. > > Ideas anyone? If I understand correctly, this is what you are trying to achieve: >>> import re >>> temp = "something [PROMPT:foo] something [PROMPT:bar] something ..." >>> prompt_re = re.compile(r"\[PROMPT:.*?\]") >>> prompt_re.findall(temp) ['[PROMPT:foo]', '[PROMPT:bar]'] >>> HTH, -- Orlando From pedro.werneck at terra.com.br Sun Jan 30 17:49:01 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Sun, 30 Jan 2005 20:49:01 -0200 Subject: is this sort method the same as the one in python 2.4 In-Reply-To: References: Message-ID: <20050130204901.69a7ef73.pedro.werneck@terra.com.br> What about this ? # if sys.version_info >= (2,4): def sorted(iterable, *args, **kwds): seq = list(iterable) seq.sort(*args, **kwds) return seq # It worked against the TestSorted in lib/test/test_builtins.py On Sun, 30 Jan 2005 08:30:17 +0100 "Fredrik Lundh" wrote: > Raymond Hettinger wrote: > > >> I'm trying to emulate the sorted() method introduced in python 2.4. The > >> only difference is that it takes a sequence as one of its arguments > >> rather than being a method of the sequence class. Does my method do the > >> same as the sorted()? > > > > Almost. This is closer to the mark: > > > > def sorted(iterable, cmp=None, key=None, reverse=False): > > "return a sorted copy of its input" > > if sys.version_info >= (2,4): > > return sorted(iterable, cmp, key, reverse) > > with your code > > print sorted([1, 2, 3]) > > gives me a traceback that ends with > > File "test.py", line 6, in sorted > return sorted(iterable, cmp, key, reverse) > File "test.py", line 6, in sorted > return sorted(iterable, cmp, key, reverse) > File "test.py", line 6, in sorted > return sorted(iterable, cmp, key, reverse) > File "test.py", line 5, in sorted > if sys.version_info >= (2,4): > RuntimeError: maximum recursion depth exceeded in cmp > > the recursion isn't really that hard to explain, but the runtime error doesn't > really seem right... > > ::: > > to fix the recursion, move the if-statement so you only define the function > if needed: > > if sys.version_info < (2,4): > def sorted(...): > .... > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From jacek.generowicz at cern.ch Tue Jan 4 10:02:16 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 04 Jan 2005 16:02:16 +0100 Subject: Optional Static Typing References: <1103795375.843649.286620@c13g2000cwb.googlegroups.com> <1103895045.561695.293330@c13g2000cwb.googlegroups.com> <41cc686a$1@nntp0.pdx.net> <1103992000.641659.48940@z14g2000cwz.googlegroups.com> <10t0fkn2kng8803@corp.supernews.com> <1gpgws6.11jticrb4ah8mN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > I've always liked the (theoretical) idea that assertions (including of > course contracts) could be used as axioms used to optimize generated > code, rather than (necessarily) as a runtime burden. E.g. (and I don't > know of any implementation of this concept, mind you), inferring (e.g. > from such assertions) that x>=0, and that y<0, the compiler could simply > cut away a branch of dead code guarded by "if x warning, in this case;-)... A few months ago, a troll challenged the denizens of comp.lang.lisp to write a Lisp implementation of some some code which he posted in C++, which would be competitive in terms of speed with his C++ version. The c.l.lers duly obliged, and, IIRC, it so happened that the improvement that made the Lisp version overtake the C++ one was the declaration of some variable to be of type "floating point number in the range 0 to two Pi". Of course, in CL type declarations are not contracts, but promises to the compiler ... but it's still an examlpe of a situation where more specific type information allowed the compiler to produce more efficient code, in practice. From fredrik at pythonware.com Mon Jan 24 16:43:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 22:43:38 +0100 Subject: Looking for Form Feeds References: <41F5696D.9030100@novasyshealth.com> Message-ID: Greg Lindstrom wrote: > I have a file generated by an HP-9000 running Unix containing form feeds signified by ^M^L. I am > trying to scan for the linefeed to signal certain processing to be performed but can not get the > regex to "see" it. Suppose I read my input line into a variable named "input" > > The following does not seem to work... > input = input_file.readline() > if re.match('\f', input): print 'Found a formfeed!' > else: print 'No linefeed!' hint: >>> line = "\r\f" >>> re.match("\f", line) (nothing) >>> re.search("\f", line) <_sre.SRE_Match object at 0x00B380C8> >>> re.match("\r\f", line) <_sre.SRE_Match object at 0x00B38988> in this case, it's probably better to use the "in" operator: if "\f" in line: print "found a line feed" From chris.stromberger at gmail.com Thu Jan 27 13:06:39 2005 From: chris.stromberger at gmail.com (chris) Date: 27 Jan 2005 10:06:39 -0800 Subject: urllib and proxy References: Message-ID: <1106849199.450771.314960@f14g2000cwb.googlegroups.com> This was helpful. After reading this, I realized you can also just add this atop whatever script imports urllib. Just add after "import urllib": # Disable proxy use. urllib.getproxies = lambda x = None: {} -Chris http://www.fetidcascade.com/ From pedro.werneck at terra.com.br Thu Jan 27 18:55:06 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Thu, 27 Jan 2005 21:55:06 -0200 Subject: tkinter socket client ? In-Reply-To: References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> <1106318469.311179.126140@c13g2000cwb.googlegroups.com> <1106319270.932204.180590@c13g2000cwb.googlegroups.com> <1106659122.977876.234250@z14g2000cwz.googlegroups.com> Message-ID: <20050127215506.18ba5a76.pedro.werneck@terra.com.br> On Tue, 25 Jan 2005 13:44:32 +0000 Martin Franklin wrote: > > thanks for this info - I had to abandon the createfilehandler() method > > as it is not supported in windows and the GUI "might" be used there at > > some time ... Take a look here: http://www.pythonbrasil.com.br/moin.cgi/MonitorandoSocketsComTkinter From JoshuaACohen at gmail.com Mon Jan 31 15:10:41 2005 From: JoshuaACohen at gmail.com (Josh) Date: 31 Jan 2005 12:10:41 -0800 Subject: Handling MySQL connection Message-ID: <1107202241.789216.224920@c13g2000cwb.googlegroups.com> Hi, First off, I am a newbie to Python and so far I must say that we're getting along pretty well. My schooling was is C/C++, but have been writing code in, dare I say it, VB, for the past 4 years. Here is the problem I have run across. I am using SPE w/WXGlade to setup the GUI, so it handled the initial formatting of my python code as two seperate classes, one for the APP and one for the Frame. I'll be the first to admit I haven't gotten a good grasp on how things should flow within a python program. Anyway, what I have done is created a few functions using the DEF statement to handle the action of the widgets. Part of the program is accessing a MySQL database. Once a button is pushed, part of it's function is to open the database, check to see if a value exists, and then close the connection. Running this locally on my PC, which is also where MySQL resides, returns results instantly. The flow is a) Open a connection to the database b) Execute a simple Select statement to verify the field c) Close the connection. All done within a single DEF This works fine and dandy on my Windows 2000 PC that is also acting as the MySQL server, but when I transfer the program to a Linux box running Fedora, there is a very noticable lag when this action takes place. So my thought is rather than connecting to the database, fetching the data, then closing out the connection every time, it may be a better idea to connect to the database upon starting the program, leaving the connection open, making the transactions as needed, and then closing the connection upon leaving the program. Doing this, however, has proved to be a little more difficult than I thought, and I'm sure it's just because of my lack of knowledge of Python. So I put the question out, how do I accomplish this? Do I need some sort of Global(such an evil word) object to work off of? In the Def __init__ I would like to open the connection eg: connection = MySQLdb.connect(host="localhost", user="root", passwd="blah", db="data") In a Sepeate Function I would like to make the transactions on it. eg: cursor = connection.cursor() cursor.execute( "SELECT * FROM tags WHERE tags.tag_no = %s" %temp_tag ) self.data = cursor.fetchall() cursor.close() Finally in another Function I would like to be able to close the connection eg: connection.close() All of these Def's would fall under the same Frame class. Am I going about this incorrectly? Thanks for your help and patience. Josh From aurora00 at gmail.com Fri Jan 7 16:35:46 2005 From: aurora00 at gmail.com (aurora) Date: Fri, 07 Jan 2005 13:35:46 -0800 Subject: "A Fundamental Turn Toward Concurrency in Software" Message-ID: Hello! Just gone though an article via Slashdot titled "The Free Lunch Is Over: A Fundamental Turn Toward Concurrency in Software" [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that the continous CPU performance gain we've seen is finally over. And that future gain would primary be in the area of software concurrency taking advantage hyperthreading and multicore architectures. Perhaps something the Python interpreter team can ponder. From ian at cottee.org Tue Jan 4 21:49:37 2005 From: ian at cottee.org (Ian J Cottee) Date: Wed, 05 Jan 2005 11:49:37 +0900 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><7xmzvu1ycn.fsf@ruckus.brouhaha.com><7xd5wqd14y.fsf@ruckus.brouhaha.com><7xfz1lal5d.fsf@ruckus.brouhaha.com><7xekh423b6.fsf@ruckus.brouhaha.com> <_rTBd.66275$Jk5.46@lakeread01> Message-ID: <171sa2-t79.ln1@suse.zobbo.org> Peter Hansen wrote: > I know that I've started many one-man projects over the years, > and only slowly (I'm a little thick, you see) came to realize > that while it's incredibly easy to start something, seeing it > through to the end is rather more difficult. > > At this point, perhaps largely as a result of a new world-view > inspired by the agile movement, I rarely start anything... > and when I do, it's driven by a strong, recurring need, and I > only do just enough to meet that need, in the simplest way > I can find. (Often, that ends up not involving a computer.) So here we are, in our wisdom. Never starting anything grandiose for fear of failure :). Personally I'm trying to get back some of that old stupidity but I'm very thick :) Ian From apardon at forel.vub.ac.be Fri Jan 14 10:41:44 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Jan 2005 15:41:44 GMT Subject: (objects as) mutable dictionary keys References: Message-ID: Op 2005-01-14, Peter Maas schreef : > I have summarized the discussion about the usability of lists (and > and other mutable types) as dictionary keys and put it into the > Python wiki.URL: http://www.python.org/moin/DictionaryKeys. > > This summary might be used as a reference should the 'mutable > dictionary keys' issue come up again in c.l.py. > I had a look and I think you should correct the followingr: Dictionary lookup with mutable types like lists is a source of unpleasant surprises for the programmer and therefore impossible in Python. It is not impossible in Python. It may be discouraged but it is not impossible since I have already done so. -- Antoon Pardon From cdieterich at geosci.uchicago.edu Wed Jan 26 12:29:48 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Wed, 26 Jan 2005 11:29:48 -0600 Subject: inherit without calling parent class constructor? Message-ID: Hi, I need to create many instances of a class D that inherits from a class B. Since the constructor of B is expensive I'd like to execute it only if it's really unavoidable. Below is an example and two workarounds, but I feel they are not really good solutions. Does somebody have any ideas how to inherit the data attributes and the methods of a class without calling it's constructor over and over again? Thank, Christian Here's the "proper" example: class B: def __init__(self, length): size = self.method(length) self.size = size def __str__(self): return 'object size = ' + str(self.size) def method(self, length): print 'some expensive calculation' return length class D(B): def __init__(self, length): B.__init__(self, length) self.value = 1 if __name__ == "__main__": obj = D(7) obj = D(7) Here's a workaround: class B: def __init__(self, length): size = self.method(length) self.size = size def __str__(self): return 'object size = ' + str(self.size) def method(self, length): print 'some expensive calculation' return length class D(B): def __init__(self, object): for key, value in object.__dict__.iteritems(): setattr(self, key, value) self.value = 1 if __name__ == "__main__": tmp = B(7) obj = D(tmp) obj = D(tmp) Here's another workaround: Bsize = 0 class B: def __init__(self, length): size = self.method(length) self.size = size global Bsize Bsize = self.size def __str__(self): return 'object size = ' + str(self.size) def method(self, length): print 'some expensive calculation' return length class D(B): def __init__(self, length): self.size = Bsize self.value = 1 if __name__ == "__main__": B(7) obj = D(9) obj = D(9) From apardon at forel.vub.ac.be Mon Jan 24 06:31:29 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Jan 2005 11:31:29 GMT Subject: Wrapping functions in modules or packages. Message-ID: I'm writing some utilty functions for use with gtk. But in order to use them correctly I have to know whether they are called in the gtk-thread or an other. So my idea was to wrap the gtk.main function so that it would registrate the thread_id that called it. So I was thinking about doing something like the following. import gtk import thread _gtkmain = gtk.main def main(): global _gtkthread _gtk_thread = thread.get_ident() _gtkmain() gtk.main = main Is this acceptable? Are there better ways to do things like this? From annaraven at gmail.com Fri Jan 7 06:54:50 2005 From: annaraven at gmail.com (Anna) Date: 7 Jan 2005 03:54:50 -0800 Subject: Securing a future for anonymous functions in Python References: Message-ID: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Okay, I tried to post this previously but ran into the new Google groups system which appears to have sent my original response into the ether... Oops. Trying again. Alan Gauld wrote: > On Thu, 30 Dec 2004 23:28:46 +1000, Nick Coghlan > wrote: > > > GvR has commented that he want to get rid of the lambda keyword for Python 3.0. > > Getting rid of lambda seems like a worthy goal, > > Can I ask what the objection to lambda is? > 1) Is it the syntax? > 2) Is it the limitation to a single expression? > 3) Is it the word itself? > > I can sympathise with 1 and 2 but the 3rd seems strange since a > lambda is a well defined name for an anonymous function used in > several programming languages and originating in lambda calculus > in math. Lambda therefore seems like a pefectly good name to > choose. > > So why not retain the name lambda but extend or change the syntax > to make it more capable rather than invent a wholly new syntax > for lambdas? > > Slightly confused, but since I only have time to read these > groups regularly when I'm at home I have probably missed the bulk > of the discussion over the years. > > Alan G. > Author of the Learn to Program website > http://www.freenetpages.co.uk/hp/alan.gauld Hi Alan: Having taken some calculus (derivatives, limits, some integrals) but never even heard of lambda calculus, to me, lambda means absolutely NOTHING. Less than nothing. Actually, in my encounters with others code in Python (including reading near 1000 recipes for the recent edition of the Cookbook), what I've discovered is that what lambda mostly means to me is: "I don't wanna write clear, elegant Python - I wanna write fancy, clever, obfuscated code, and lambda lets me do that!" I've seen maybe 1 case in 10 where lambda appears, to me, to allow clearer, cleaner code than defining a function. Most cases-it's an ugly, incomprehensible hack. So, if people really need anonymous functions in Python (and apparently, they do), then at least lets get a word that actually *means* something. Every other word in Python has an obvious meaning. lambda doesn't. So, I guess I don't like the word itself - any more than I like how it's (mostly) used. Anna Martelli Ravenscroft From fuzzyman at voidspace.org.uk Wed Jan 12 04:47:49 2005 From: fuzzyman at voidspace.org.uk (Fuzzyman) Date: Wed, 12 Jan 2005 09:47:49 +0000 Subject: PyCrypto 2.0, pysco 1.4 - Windows Binaries for 2.4 Message-ID: <41E4F245.5060709@voidspace.org.uk> The location of the prebuilt windows installer for PyCypto 2.0 (for python 2.4) has changed. Apologies for any confusion, this is because of a website reorganisation at Voidspace. The new location is : http://www.voidspace.org.uk/python/modules.shtml#pycrypto There is also a prebuilt windows installer for psyco 1.4 (for python 2.4). This is because there isn't yet a prebuilt binary available from sourceforge. http://www.voidspace.org.uk/python/modules.shtml#psyco Both built using the free, Microsoft, optimizing compiler. Following instructions from : http://www.vrplumber.com/programming/mstoolkit/index.html Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From this at is.invalid Tue Jan 18 08:23:24 2005 From: this at is.invalid (John Field) Date: 18 Jan 2005 13:23:24 GMT Subject: [wxpython] exclude files in a wx.FileDialog? Message-ID: <41ed0dcc$0$73526$abc4f4c3@news.wanadoo.nl> Hello, Is it possible to exclude certain files in a wx.FileDialog, so that the user won't see them and can't select them with the mouse in de File open window? I was thinking of somehow extending the class FileDialog(Dialog) in the wx module _windows.py to a subclass, but I'm not sure how to do that (if feasible). cheers From ram at forefront-tech.No.Lunch.meat.com Wed Jan 12 18:47:13 2005 From: ram at forefront-tech.No.Lunch.meat.com (Rick Morrison) Date: Wed, 12 Jan 2005 23:47:13 GMT Subject: dict.updated References: Message-ID: <5GiFd.8571$Vj3.3354@newssvr17.news.prodigy.com> I could live with creating a new dict, sure (although it seems wasteful). I realize that something like this probably doesn't stand a chance of ever making it into the std library for what might be called "philosophical" reasons. I just want it for me (my personal philosophy runs more to the pragmatic -- well at least for coding). I suppose the in-place version would be more along the lines of: >>> def updated(d, updates): ... d.update(updates) ... return d ... >>> [updated(d, {'c':3}) for d in [{'a':1, 'b':2}, {'x':10, 'y':'11'}]] [{'a': 1, 'c': 3, 'b': 2}, {'y': '11', 'x': 10, 'c': 3}] But I'd like to put the "updated" method on the "dict" object, which is what I can't seem to figure out. Yeah I know that's "bad", but to my mind so is polluting the global namespace with the "updated" function. -- Or maybe I'm just lazy and picked up too many bad habits from Javascript. Rick "Steven Bethard" wrote in message news:dvKdnWal2sVXAXjcRVn-2g at comcast.com... > Rick Morrison wrote: > > Would there be any way to add a method to all dict objects that operated > > like the .update() method, but also returned a reference to the updated > > dict? > > Are you looking for updated() to parallel sorted(), where sorted() > returns a *new* list? I doubt you'll be able to rally much support for > a method that changes an object and returns a reference to it -- check > the archives to see these kind of things getting rejected over and over. > > Could you do something like: > > py> import itertools > py> d1 = dict(a=1, b=2) > py> d2 = dict(c=3, d=4) > py> d3 = dict(itertools.chain(d1.iteritems(), d2.iteritems())) > py> d3 > {'a': 1, 'c': 3, 'b': 2, 'd': 4} > > Steve From rccharles at my-deja.com Fri Jan 28 13:50:57 2005 From: rccharles at my-deja.com (Robert) Date: Fri, 28 Jan 2005 13:50:57 -0500 Subject: installing tkiner Message-ID: I am trying to use tkinter on macos 10.2.6. I am not having any luck. I have tried this. python python2.4 after downloading downloaded TclTkAquaBI-8.4.6.1-Jaguar.dmg and installed python2.4 could not find tkiniter downloaded macpython 2.3.3 macphyton find tkinter but got an application exception. I was under the impression that macpython included tkinter, so I manually deleted TclTkAquaBI the best I could. macpython could not find tkinter. In the packages section of macpython, I saw... ('no', '_tkinter-2.3-binary', 'Enables Tkinter GUI building with Python.') Please advise. Robert From benn at cenix-bioscience.com Wed Jan 26 06:01:47 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Wed, 26 Jan 2005 12:01:47 +0100 Subject: python without OO In-Reply-To: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <41F7789B.7070702@cenix-bioscience.com> Davor wrote: >Is it possible to write purely procedural code in Python, or the OO >constructs in both language and supporting libraries have got so >embedded that it's impossible to avoid them? Also, is anyone aware of >any scripting language that could be considered as "Python minus OO >stuff"? (As you can see I'm completely new to Python and initially >believed it's a nice&simple scripting language before seeing all this >OO stuff that was added in over time) >Thanks, >Davor > > > Hello, Yes you can, that is a benefit and flaw of python in that you can mix up procedural and OO code, it allows for simple solutions - however it also allows for you to create all kinds of havoc. IMHO, there would have to be a very very small task to require procedural code. Especially if the code is gonna be open sourced (and presumably built upon) you will benefit from a proper design so that it can be developed and moved on in the future. One other thing, if your developers are proposing deep inheritance trees in _any_ language then they are designing incorrectly. In none of the languages I code in would I design a deep inheritance tree, the deep inheritance tree is a fault of the designer not the language (for example Java does not force you to design deep inheritance trees!) - 90% of the time. I say this because you do need to be aware of the 'mythical python wand' which will turn you from a bad programmer into a good programmer simply by typing 'class Klass(object):'. Rather than reading a GOF book, I'd pick up an introduction to OO programming book to take a refresher course - you thank yourself!! Language without OO at all - what about Logo - drive that little tortoise around!! Cheers, Neil From bearophileHUGS at lycos.com Sun Jan 16 10:55:10 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 16 Jan 2005 07:55:10 -0800 Subject: generator expressions: performance anomaly? References: <1105854381.117059.59940@c13g2000cwb.googlegroups.com> Message-ID: <1105890910.933744.143580@z14g2000cwz.googlegroups.com> Nick Coghlan: >There's a similar performance glitch associated with constructing a tuple from a generator expression (with vanilla 2.4, detouring via list is actually faster) You look right: .from time import clock .print "[x for x in l], list(x for x in l), aux = list(x for x in l); tuple(aux), tuple(x for x in l):" .for np in range(13, 21): . n = 1*2**np . print "n:", n, " s:", . l = xrange(n) . t1 = clock() . [x for x in l] . t2 = clock() . print round(t2-t1,3), . . t1 = clock() . list(x for x in l) . t2 = clock() . print round(t2-t1,3), . . t1 = clock() . aux = list(x for x in l) . tuple(aux) . t2 = clock() . print round(t2-t1,3), . . #l = tuple(l) useless . t1 = clock() . tuple(x for x in l) . t2 = clock() . print round(t2-t1,3) Output: [x for x in l], list(x for x in l), aux = list(x for x in l); tuple(aux), tuple(x for x in l): n: 8192 s: 0.01 0.007 0.01 0.013 n: 16384 s: 0.024 0.019 0.021 0.032 n: 32768 s: 0.054 0.042 0.049 0.113 n: 65536 s: 0.111 0.078 0.101 0.088 n: 131072 s: 0.196 0.155 0.183 0.177 n: 262144 s: 0.436 0.385 0.429 1.832 n: 524288 s: 0.921 0.744 0.877 8.271 n: 1048576 s: 1.86 1.546 1.866 33.154 The timings for tuple(x for x in l) seem to grow as len(n)**2. Bear hugs, Bearophile From peter at engcorp.com Thu Jan 13 16:49:59 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 16:49:59 -0500 Subject: News Reader In-Reply-To: References: Message-ID: Robert Kern wrote: > Robert Kern wrote: >> Daniel Bowett wrote: >>> Is anyone reading this list through thunderbird as news? If so - how >>> did you set it up? >> >> I subscribed to comp.lang.python under my USENET news server account. > > I guess I should add that that's all I did. There's nothing special to > set up. Having to add the news server by first selecting "File->New->Account" might qualify as important enough to mention too. ;-) -Peter From fuzzyman at gmail.com Mon Jan 17 04:24:45 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 17 Jan 2005 01:24:45 -0800 Subject: how to stop google from messing Python code In-Reply-To: References: <1105620098.878376.110250@z14g2000cwz.googlegroups.com> <1105704548.146263.229220@f14g2000cwb.googlegroups.com> Message-ID: <1105953885.661245.27570@c13g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Fuzzyman wrote: > > > I guess that most people use google to post to newsgroups is that they > > don't have nntp access. Telling htem to use a newsreader is facetious > > and unhelpful. > > if you have internet access, you have NNTP access. gmane.org provides access > to more than 6,500 mailing lists via NNTP, including all relevant Python forums. > Not if you're behind a censoring proxy that blocks everything except http. This is a situation many people find themselves in. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > From john at grulic.org.ar Thu Jan 13 19:06:27 2005 From: john at grulic.org.ar (John Lenton) Date: Thu, 13 Jan 2005 21:06:27 -0300 Subject: directory bug on linux; workaround? In-Reply-To: References: Message-ID: <20050114000627.GB3727@grulic.org.ar> On Thu, Jan 13, 2005 at 12:07:04PM -0800, Russell E. Owen wrote: > I stumbled across a really strange bug involving directories on linux. > > os.path.exists(path) can return 0 even after os.path.mkdir(path) > succeeds (well after; this isn't a timing issue). > > For the first file, the directory did not exist, so my code created the > directory (successfully) using os.path.mkdir(path). The next file > failed because os.path.exists(path) returned false, so my code tried to > create the directory again, which failed with "directory exists". > > It seems that the path was to a "fat" file partition and included a > directory name that was all uppercase. The directory was created, but > using lowercase. I'm not yet sure the version of python. > > The workaround for now is to not use fat file partitions. But I was > wondering if anyone had a better option? the bug is because os.path is assuming posix semantics, which fat doesn't have. Not using fat sounds like the best idea to me, but I'm probably strongly biased against that piece of crap. -- John Lenton (john at grulic.org.ar) -- Random fortune: A fox is a wolf who sends flowers. -- Ruth Weston -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From ncoghlan at iinet.net.au Thu Jan 6 07:11:22 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 06 Jan 2005 22:11:22 +1000 Subject: Python evolution: Unease In-Reply-To: <864d3709050106020568bd8b8e@mail.gmail.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> <1104982313.217034.308760@z14g2000cwz.googlegroups.com> <864d3709050106020568bd8b8e@mail.gmail.com> Message-ID: <41DD2AEA.2020301@iinet.net.au> Carlos Ribeiro wrote: > Couldn't a better document-writing interface be implemented? Such as: http://www.python.org/moin/Documentation Or AMK's annotatable docs: http://pydoc.amk.ca/frame.html Something like that? > The docs are great, but it took me some time to find them out after > searching inside Python docs. This is not a minor issue IMHO. Actually, this is a fair point - I work on isolated machines a lot (i.e. no net access), which means I can't get to any of these handy things. It would be nice if at least some of these things could be bundled with the CPython interpreter and linked to from the main documentation (rather than from the sidebar menu on the webpage). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From none.by.e-mail Wed Jan 5 23:49:21 2005 From: none.by.e-mail (Mike Thompson) Date: Thu, 06 Jan 2005 15:49:21 +1100 Subject: Python evolution: Unease In-Reply-To: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> References: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> Message-ID: <41dcc35a$0$3872$afc38c87@news.optusnet.com.au> Alex Martelli wrote: > Carlos Ribeiro wrote: > ... > >>>- IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than Pythonwin? >> >>I would like to seee Eric3, with some polish & opensourced on Win >>(which means solving the Qt licensing problem). Perhaps someone could >>convince Trolltech to release a special Qt Win version just for it >>(Eric3). Eclipse is also an interesting approach. > > > I love eric3, but if you're an eclipse fan, look at enthought's > "envisage" IDE -- it seems to me that it has superb promise. > I've tried both the SciPy and Enthought WWW sites and I can't find much on "Envisage". At SciPy.org there is one set of powerpoint slides on it but nothing more. Is it available for download somewhere? -- Mike From nelson at monkey.org Sun Jan 23 16:35:33 2005 From: nelson at monkey.org (Nelson Minar) Date: Sun, 23 Jan 2005 21:35:33 GMT Subject: What is print? A function? References: Message-ID: Frans Englich writes: > The reason I thinks about this is I need to implement a debug print for my > program; very simple, a function/print statement that conditionally prints > its message whether a bool is true. Not overly complex. As several folks have said, print is a statement, and Python doesn't really let you add statements to the language. You said you wanted to build a simple debugging function, so maybe this doesn't fit the bill, but for bigger pieces of code Python has a nice logging library. It's something like log4j or java.util.logging. http://www.python.org/doc/2.4/lib/module-logging.html From aleaxit at yahoo.com Sat Jan 22 18:06:51 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 23 Jan 2005 00:06:51 +0100 Subject: debugging process References: Message-ID: <1gqtexi.wxk0qn1oh6obbN%aleaxit@yahoo.com> wrote: ... > I think that this must have something to do with python expecting > itself to by in a TTY? Can anyone give any idea of where I should be > going with this? http://pexpect.sourceforge.net/ Alex From tjreedy at udel.edu Mon Jan 3 14:56:34 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 3 Jan 2005 14:56:34 -0500 Subject: emulating an and operator in regular expressions References: <1104750397.26918.1.camel@rasputin.localnet> Message-ID: "Craig Ringer" wrote in message news:1104750397.26918.1.camel at rasputin.localnet... > On Mon, 2005-01-03 at 08:52, Ross La Haye wrote: >> How can an and operator be emulated in regular expressions in Python? Regular expressions are designed to define and detect repetition and alternatives. These are easily implemented with finite state machines. REs not meant for conjunction. 'And' can be done but, as I remember, only messily and slowly. The demonstration I once read was definitely theoretical, not practical. Python was designed for and logic (among everything else). If you want practical code, use it. if match1 and match2: do whatever. Terry J. Reedy From qhfgva at gmail.com Mon Jan 17 16:08:50 2005 From: qhfgva at gmail.com (Dustin Lee) Date: Mon, 17 Jan 2005 14:08:50 -0700 Subject: python execution path Message-ID: I'm wondering if there is a way to get python to show each line as it is executed, sort of like sh -x does for shell programs. Seems like this would be a nice debugging aid. dustin From fredrik at pythonware.com Sun Jan 23 10:29:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 16:29:38 +0100 Subject: ANN: cElementTree 0.9.8 (january 23, 2005) Message-ID: effbot.org proudly presents release 0.9.8 of the cElementTree library, a fast and very efficient implementation of the ElementTree API, for Python 2.1 and later. On typical documents, it's 15-20 times faster than the Python version of ElementTree, and uses 2-5 times less memory. Here are some benchmark figures, using a number of popular XML tool- kits to parse a 3405k document-style XML file from disk: library memory time ------------------------------------------------------------ amara 20300k 6.4s minidom (python 2.4) 53000k 1.4s ElementTree 1.2.4 14500k 1.1s cDomlette 20500k 0.54s pyRXPU 10850k 0.175s libxml2 16000k 0.098s cElementTree 0.9 4900k 0.047s ------------------------------------------------------------ readlines (read as utf-8) 8850k 0.093s readlines (read as ascii) 5050k 0.032s ------------------------------------------------------------ This release also includes a new "iterparse" mechanism, which can be used to process the tree as it is being built. While not quite as fast as a full parse, it's over 4 times faster than Python's standard SAX interface, and even a bit faster than sgmlop. The library is available as C source code, and as Windows installers for all recent Python versions. Get your copy here: http://effbot.org/downloads#celementtree The cElementTree module uses some support functions from the standard ElementTree library, and will not work properly without it. If you haven't installed it already, you can get it from: http://effbot.org/downloads#elementtree enjoy /F "effbot.org -- not knowing how Python is used since 1995" From elephantum at dezcom.mephi.ru Sun Jan 16 07:04:53 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 16 Jan 2005 15:04:53 +0300 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> <41e6dc9b.771173178@news.oz.net> Message-ID: <34v3j5F49hm3uU1@individual.net> Nick Coghlan wrote: > # Anonymous functions > use res: > def f(x): > d = {} > exec x in d > return d > in: > res = [f(i) for i in executable] as for me, I found construction "use :" unobvious and confusing. Also there is great possibility to forget some of variables names. I think that syntax where: is more obvious. (and we already have defined semantics for it) we have two problems, that we try to solve 1) create method to nest scopes 2) create method to reverse execution order for better readability "using:" solves both at once. but your "use ... in ..." syntax shows, that you want to be able to solve 1) independently i.e. create nested scope without reversing execution order. so, I can suggest one more keyword "do:", which will create nested scope, just as "def f(): ... ; f()" do (and that could be just syntaxic sugar for it. so "use ... in ..." would look the following way: do: res = [f(i) for i in executable] #some more equations here using: def f(x): d = {} exec x in d return d that seems good for me. of course if you want to return something from the nest scope you must show that variable is from parent scope. // while writing that I realized that it's too complex to be implemented in python in that way. consider it as some type of brainstorming. From sjmachin at lexicon.net Tue Jan 4 05:55:52 2005 From: sjmachin at lexicon.net (John Machin) Date: 4 Jan 2005 02:55:52 -0800 Subject: why does UserDict.DictMixin use keys instead of __iter__? In-Reply-To: References: Message-ID: <1104836152.639270.196200@z14g2000cwz.googlegroups.com> Steven Bethard wrote: > Sorry if this is a repost -- it didn't appear for me the first time. > > > So I was looking at the Language Reference's discussion about emulating > container types[1], and nowhere in it does it mention that .keys() is > part of the container protocol. I don't see any reference to a "container protocol". What I do see is (1) """It is also recommended that mappings provide the methods keys(), ...""" (2) """The UserDict module provides a DictMixin class to help create those methods from a base set of __getitem__(), __setitem__(), __delitem__(), and keys(). """ > Because of this, I would assume that to > use UserDict.DictMixin correctly, a class would only need to define > __getitem__, __setitem__, __delitem__ and __iter__. So I can't see why would you assume that, given that the docs say in effect "you supply get/set/del + keys as the building blocks, the DictMixin class will provide the remainder". This message is reinforced in the docs for UserDict itself. > So why does > UserDict.DictMixin require keys() to be defined? Because it was a reasonable, documented, design? In any case, isn't UserDict past history? Why are you mucking about with it? From steven.bethard at gmail.com Fri Jan 21 19:46:46 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 17:46:46 -0700 Subject: finding name of instances created In-Reply-To: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> Message-ID: Andr? wrote: > Given the statement > >>>a = public_class() > > I would like to generate > >>>my_dict['a'] = private_class() > > so that one could write > >>>a.apparently_simple_method() > > and that, behind the scene, I could translate that as > >>>my_dict['a'].not_so_simple_method() > > as well as do things like > >>>for name in my_dict: >>> do_stuff(name) Why can't you just make public_class a factory, alias the method in PrivateClass and access the names through locals()? py> class PrivateClass(object): ... def not_so_simple_method(self): ... print "not so simple" ... apparently_simple_method = not_so_simple_method ... py> def public_class(): ... return PrivateClass() ... py> a = public_class() py> a.apparently_simple_method() not so simple py> # add 'name' and 'value' to locals() before iteration starts py> name, value = None, None py> for name, value in locals().iteritems(): ... if isinstance(value, PrivateClass): ... print name, value ... a <__main__.PrivateClass object at 0x01146D50> Steve From kartic.krishnamurthy at gmail.com Wed Jan 26 11:26:29 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 26 Jan 2005 08:26:29 -0800 Subject: Help With Python In-Reply-To: References: Message-ID: <1106756789.257980.256610@z14g2000cwz.googlegroups.com> Py>>> print "Spam, " * 115 Spam, Spam, Spam, Spam, Spam, ................. Spam, Multiplies (repeats) the string 115 times. To eliminate the last ", " (that is, a comma followed by space), you can do it using the slice notation and say: Py>>> print ("Spam, " * 115) [:-2] Spam, Spam, Spam, Spam, Spam, ................., Spam The [:-2] means that you asking Python to print everything from the beginning to the last but two characters of the string. You can also write this as [0:-2] [or [0:length_of_spam - 2] where length_of_spam = len("Spam, " * 115)] Since you are starting off, please read and follow the tuturial that available with your Python installation or on the Python.org site at http://docs.python.org/tut/tut.html Thank you, --Kartic From fredrik at pythonware.com Sat Jan 22 13:08:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 19:08:15 +0100 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com><41EE24F7.7030303@jessikat.fsnet.co.uk><7x1xchlpqv.fsf@ruckus.brouhaha.com><41efeb82$0$27807$9b622d9e@news.freenet.de><41f1a70b$0$25959$9b622d9e@news.freenet.de><7xbrbiqdhk.fsf@ruckus.brouhaha.com><7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > 2. "Would anyone except me have any use for this?" shows a lack of > understanding of how Python is used. Some users (call them > "application users" or AU's) use Python to run Python applications for > whatever purpose. Some other users (call them "developers") use > Python to develop applications that are intended to be run by AU's. "lack of understanding of how Python is used" wonderful. I'm going to make a poster of your post, and put it on my office wall. From http Sat Jan 22 07:50:30 2005 From: http (Paul Rubin) Date: 22 Jan 2005 04:50:30 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> Message-ID: <7xllalljah.fsf@ruckus.brouhaha.com> Nick Craig-Wood writes: > > No, unfortunately; the python-dev consensus was that encryption raised > > export control issues, and the existing rotor module is now on its way to > > being removed. > > I'm sure thats wrong now-a-days. Here are some examples of open > source software with strong crypto There's tons of such examples, but python-dev apparently reached consensus that the Python maintainers were less willing than the maintainers of those other packages to deal with those issues. You're right that this specifically says export control. I'm now thinking I saw some other messages, again from knowledgeable posters, saying that there was a bigger concern that including crypto in the distribution could make trouble for users in countries where having crypto at all was restricted. I'll see if I can find those. Martin, do you know more about this? I remember being disappointed about the decisions since I had done some work on a new block cipher API and I had wanted to submit an implementation to the distro. But when I heard there was no hope of including it, I stopped working on it. If there's an interest in it again, I can do some more with it. From rowen at cesmail.net Thu Jan 13 15:07:04 2005 From: rowen at cesmail.net (Russell E. Owen) Date: Thu, 13 Jan 2005 12:07:04 -0800 Subject: directory bug on linux; workaround? Message-ID: I stumbled across a really strange bug involving directories on linux. os.path.exists(path) can return 0 even after os.path.mkdir(path) succeeds (well after; this isn't a timing issue). For the first file, the directory did not exist, so my code created the directory (successfully) using os.path.mkdir(path). The next file failed because os.path.exists(path) returned false, so my code tried to create the directory again, which failed with "directory exists". It seems that the path was to a "fat" file partition and included a directory name that was all uppercase. The directory was created, but using lowercase. I'm not yet sure the version of python. The workaround for now is to not use fat file partitions. But I was wondering if anyone had a better option? -- Russell From sylvain.pasquet at gmail.com Wed Jan 26 09:16:50 2005 From: sylvain.pasquet at gmail.com (Tsubasa[Hokage]) Date: 26 Jan 2005 06:16:50 -0800 Subject: Freeze with wxpython on python 2.3 or python 2.4 on Win32 with Thread Message-ID: <549f320e.0501260616.7bc89f75@posting.google.com> first problem: With Idle environnement under Win32, all freeze after with bunch of code: #!/usr/bin/python import threading,time class T (threading.Thread) : def __init__(self,_a,_b) : threading.Thread.__init__(self) self.a = _a self.b = _b def run(self) : print "T(%d,%d)"%(self.a,self.b) time.sleep(3) print "T(%d,%d)=>%d"%(self.a,self.b,self.a+self.b) return self.a+self.b t = T(3,5) t.start() All freeze when sleep command are execute. Second part of this problem, I have a GUI in wxpython, when I create new thread i can't write new data in widget like a multibox when i am in a thread :( but i can retrieve data ( GetValue works but SetValue freeze ). Thanks From PPNTWIMBXFFC at spammotel.com Wed Jan 26 10:10:37 2005 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Wed, 26 Jan 2005 16:10:37 +0100 Subject: fast list lookup References: <3e96ebd7.0501260641.159e007f@posting.google.com> <8c7f10c60501260648c4a7c9a@mail.gmail.com> Message-ID: >> what is the fastest way to determine whether list l (with >> len(l)>30000) contains a certain element? Either a sorted list (in conjunction with the bisect-module) or a dictionary is your friend... Regards, Marco From as006d4848 at blueyonder.co.uk Mon Jan 24 00:15:07 2005 From: as006d4848 at blueyonder.co.uk (Philip Smith) Date: Mon, 24 Jan 2005 05:15:07 GMT Subject: Help with Threading Message-ID: Hi I am fairly new to Python threading and my needs are simple(!) I want to establish a number of threads each of which work on the same computationally intensive problem in different ways. I am using the thread module rather than the threading module. My problem is I can't see how (when one thread completes) to ensure that the other threads terminate immediately. Appreciate some simple advice Phil From helm.volker at gmx.de Tue Jan 4 15:10:33 2005 From: helm.volker at gmx.de (Volker Helm) Date: Tue, 04 Jan 2005 21:10:33 +0100 Subject: cxOracle for python 2.4 Message-ID: <340bheF44qhdtU1@individual.net> Hi there, does anybody knows where I can get the DB interface cx_Oracle for Python 2.4 with win32. On http://www.computronix.com/utilities.shtml exists only the version for Python 2.3. I would try to compile it myself, if I had a compiler and would know how to use it ;-) Thanks in advance, Volker From news at outbacklinux.com Wed Jan 12 06:25:43 2005 From: news at outbacklinux.com (Adrian Casey) Date: Wed, 12 Jan 2005 20:55:43 +0930 Subject: Command line and GUI tools : need a single threading solution References: <41e26e79@duster.adelaide.on.net> <34f9lfF4af717U1@individual.net> <41e38d8c@duster.adelaide.on.net> Message-ID: <41e50937@duster.adelaide.on.net> Adrian Casey wrote: > Diez B. Roggisch wrote: > >>> I'm thinking it may be possible to modify the command line tools to use >>> qt >>> threads instead of native python threads. Is this the way to go? Are >>> there other options? >> >> Why don't you use python threads in qt - I do so and so far it didn't >> make any troubles for me. And I would strongly advise against using >> qthreads with your commandline-tools, as these then would only run on >> machines where pyqt is installed - which opens a small part of >> "dependency hell" for your users. >> > I have a QThread which polls a queue object via queue.get(). The command > line tools spawn a number of threads each of which writes its output to > this queue using queue.put(). As soon as the gui gets something off the > queue, it creates a QCustomEvent and sets the data property with the data > read from the queue. My application has a customEvent() method which > reads the data item from the customEvent and processes it accordingly. > > The odd thing is, I have a non-threaded version of the command line tools > which work 100% with the gui. The multi-threaded version of the command > line tools all work OK at the console - just not with the gui. > > I will try your suggestion and replace my QCustomEvent mechanism with a > plain python queue. I tried replacing the QThread part with native python threads and, although it worked for a few minutes, I started to see XWindow errors and my application would then crash. On Phil Thompson's advice, I updated PyQt and sip. The problem appears to be fixed. Adrian. From aweinstein at vtr.net Tue Jan 4 18:40:50 2005 From: aweinstein at vtr.net (Alejandro Weinstein) Date: Tue, 04 Jan 2005 21:40:50 -0200 Subject: Reaching the real world In-Reply-To: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: <41DB0D62.559.2C107E@localhost> On 4 Jan 2005 at 6:55, Fuzzyman wrote: > What I'd like is an electronic interface that connects to several > relays and a python extension module to switch on and off the relays. > I've had a quick google and can't see anything too similar to what I > want. pyro (python robotics) seems to require expensive (relatively) > robotic equipment. Look at pyParallel (http://pyserial.sourceforge.net/pyparallel.html) to control the parallel port. From the parallel port you can control external devices. Please note that you will need to add a transistor to control a relay. There is also pySerial, (http://pyserial.sourceforge.net/) to control the serial port. If you know how to use a microcontroller (AVR, PIC, 8031, etc) you can communicate with it through the sereial port, and let the micro control the "real world". Regards, Alejandro. From timr at probo.com Tue Jan 25 03:18:44 2005 From: timr at probo.com (Tim Roberts) Date: Tue, 25 Jan 2005 00:18:44 -0800 Subject: is there better 32 clock() timing? References: Message-ID: Ray Schumacher wrote: > >I have a need for a time.clock() with >0.000016 second (16us) accuracy. >The sleep() (on Python 2.3, Win32, at least) has a .001s limit. > >Are they lower/better on other's platforms? You need to be careful about describing what you're seeing here. It is not that time.clock() is inaccurate. The problem is that the "time.clock()" statement takes several hundred microseconds to execute. >I had also considered forking a thread that would spin a loop checking >time.clock() and firing the TTL pulse after the appropriate interval, >but the real, ultimate resolution of time.clock() appears to be >~.00035s. If I increase process priority to real-time, it is ~.00028s >The alternative appears to be more C code... Are you seriously considering writing a real-time application in Python on Windows? The ONLY way to get small-integer microsecond responses in Windows is to write a kernel driver, and even then there are no guarantees. Windows is NOT a real-time system. If you have an environment where an unexpected delay of a millisecond or more is going to cause damage, then you need to redesign your application. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rowen at cesmail.net Tue Jan 25 13:29:16 2005 From: rowen at cesmail.net (Russell E. Owen) Date: Tue, 25 Jan 2005 10:29:16 -0800 Subject: tkinter socket client ? References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> <1106318469.311179.126140@c13g2000cwb.googlegroups.com> <1106319270.932204.180590@c13g2000cwb.googlegroups.com> <1106659122.977876.234250@z14g2000cwz.googlegroups.com> Message-ID: In article <1106659122.977876.234250 at z14g2000cwz.googlegroups.com>, "Tonino" wrote: >thanks for this info - I had to abandon the createfilehandler() method >as it is not supported in windows and the GUI "might" be used there at >some time ... > >So - I went the threading route - works well - for now - so I will >stick to it ... > >BUT - the next question: >In the Text() widget - why - when the text scrolls off the screen - >does the window not follow it ? > >I have added a scrollbar to it : > >self.center_frame = Frame(self.top_frame, background="tan", >relief=RIDGE) > >self.text=Text(self.center_frame,background='white') >scroll=Scrollbar(self.center_frame) >self.text.configure(yscrollcommand=scroll.set) > >self.text.pack(side=LEFT, fill=BOTH, expand=YES) >scroll.pack(side=RIGHT,fill=Y) >self.center_frame.pack(side=RIGHT, expand=YES, fill=BOTH) > > >but the window does not scroll to follow the text ? >Any ideas ? That's just how it works. But when you append text you can easily tell the text widget to display it, e.g. using "see". Here is the code I use (from RO.Wdg.LogWdg.py), which has these useful features: - auto-scrolls only if the user is already scrolled to the of text (so if a user is staring at some older data, it won't be jerked out from under them) - deletes excess text. def addOutput(self, astr, category=None): """Add a line of data to the log. Inputs: - astr: the string to append. If you want a newline, specify the \n yourself. - category: name of category or None if no category """ # set auto-scroll flag true if scrollbar is at end # there are two cases that indicate auto-scrolling is wanted: # scrollPos[1] = 1.0: scrolled to end # scrollPos[1] = scrollPos[0]: window has not yet been painted scrollPos = self.yscroll.get() doAutoScroll = scrollPos[1] == 1.0 or scrollPos[0] == scrollPos[1] if category: self.text.insert("end", astr, (category,)) else: self.text.insert("end", astr) extraLines = int(float(self.text.index("end")) - self.maxLineIndex) if extraLines > 0: self.text.delete("1.0", str(extraLines) + ".0") if doAutoScroll: self.text.see("end") -- Russell From jceasar at example.org Sat Jan 29 15:53:23 2005 From: jceasar at example.org (Jceasar) Date: Sat, 29 Jan 2005 14:53:23 -0600 Subject: Registration is accepted Message-ID: An HTML attachment was scrubbed... URL: -------------- next part -------------- The file Jol03.cpl attached to this message posed a potential virus risk to the network and has been removed. If you need to receive a .zip file from an external source, you may request an exception by emailing opssec at qwest.com. Thank you, Risk Mgmt-Info Sec From ptmcg at austin.rr._bogus_.com Fri Jan 21 17:22:03 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 21 Jan 2005 22:22:03 GMT Subject: why am I getting a segmentation fault? References: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> Message-ID: "Jay donnell" wrote in message news:1106330476.419418.46920 at f14g2000cwb.googlegroups.com... > I have a short multi-threaded script that checks web images to make > sure they are still there. I get a segmentation fault everytime I run > it and I can't figure out why. Writing threaded scripts is new to me so > I may be doing something wrong that should be obvious :( > Here is a code excerpt from your link (the main routine, omits the class definition for ImageChecker, which extends threading.Thread): db = MySQLdb.connect(host="localhost", user="xxx", passwd="xxx", db="xxx") cursor = db.cursor() query = "select * from item order by rand() limit 0, 100" #query = "select * from item" cursor.execute(query) result = cursor.fetchall() maxThreads = 5 for r in result: while(threading.activeCount() > maxThreads): pass flag='good' #pass #print str(r[0]) + ', ' + str(r[7]) tmp = r[7].split('/') filename = tmp[-1] #print 'filename ' + filename filename = '/tmp/'+filename threadList = [] #r[7] is the url of the image #r[0] is the id for the row imageChecker = ImageChecker(r[7], filename, r[0]) imageChecker.start() threadList.append(imageChecker) ---------------------------------------------- 1. What happens after you fall out of the loop "for r in result"? Shouldn't you wait for the remaining threads to finish? Perhaps you need another busy-loop to wait for the threads to finish, something like while threading.activeCount() > 0: pass 2. Is this the best way to busy-wait? What about some kind of thread.join()? At least throw a sleep call in there or something, or this loop will churn and churn, diverting CPU from your threads that are actually trying to do some real work. 3. I find it easier to work with named variables than numeric subscripts. At the top of your for loop, try something like: id,height,width,numBytes,whatever,slkdjf1,slkdjf2,url = r This way you have much more meaningful names than r[0] and r[7], which you later have to comment to explain whats going on! 4. filename=r[7].split('/')[-1] is not terribly portable. See if there is a standard module for parsing filespecs (I'll bet there is). -- Paul From cdieterich at geosci.uchicago.edu Thu Jan 27 18:50:47 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Thu, 27 Jan 2005 17:50:47 -0600 Subject: inherit without calling parent class constructor? In-Reply-To: <10vii1r91ovdv91@corp.supernews.com> Message-ID: <44845B34-70BE-11D9-B56C-000A9582377C@geosci.uchicago.edu> On D?ardaoin, Ean 27, 2005, at 14:05 America/Chicago, Jeff Shannon wrote: > True, in the sense that B is instantiated as soon as a message is sent > to D that requires B's assistance to answer. If the "decision" is a > case of "only calculate this if we actually want to use it", then this > lazy-container approach works well. If the decision requires Yes, I see this advantage of a lazy container. Seems perfect to do something on request. See also below. > the descriptor approach does. In either case, the calculation happens > as soon as someone requests D.size ... Agreed. The calculation happens as soon as someone requests D.size. So far so good. Well, maybe I'm just not into it deep enough. As far as I can tell, In your class D the calculation happens for every instantiation of D, right? For my specific case, I'd like a construct that calculates D.size exactly once and uses the result for all subsequent instantiations. > If it will work for numerous D instances to share a single B instance > (as one of your workarounds suggests), then you can give D's > __init__() a B parameter that defaults to None. This sounds as if B needs to instantiated only once. In your example self._B is None for every new instantiation of D and then __getattr__() makes a new instances of self.B. > (However, from your other descriptions of your problem, it does sound > like a property / descriptor is a better conceptual fit than a > contained class is. I mostly wanted to point out that there are other > ways to use OO than inheritance...) I appreciate your input anyway. Thinking of how I could use containers it became clear, that I'm going to use them for something else, where I want something to be calculated upon request only. Christian From skip at pobox.com Wed Jan 12 06:37:17 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 12 Jan 2005 05:37:17 -0600 Subject: "Architecture of Python" was removed ? In-Reply-To: References: <004801c4f7cb$f62d1d30$1d02a8c0@cr> Message-ID: <16869.3053.896410.298943@montanaro.dyndns.org> Someone> Does anyone here have a copy of that document? Or who can tell Someone> me what is the email address of Jim Jackson or Kar-Han Tan. Nick> http://web.archive.org/web/20031222201953/http://wiki.cs.uiuc.edu/cs427/PYTHON Gerrit> This is again a nice document, and an example of a document that Gerrit> presumably has been removed because of maintenance Gerrit> reasons. Shouldn't we have a collection (archive) of these Gerrit> documents at python.org? Yes, perhaps. Note that it doesn't appear that the Wayback Machine contains the meat of the essay, just the front page. It came from a wiki. Perhaps the sysadmin folks at UIUC can dredge the content up from backup, though I suspect they'd be unlikely to do that. Ah, wait... Google to the rescue yet again. Try Googling for python cs427 site:uiuc.edu then pull the pages of interest out of Google's cache. 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? -- Skip Montanaro skip at mojam.com http://www.mojam.com/ From mcfletch at rogers.com Sun Jan 23 17:40:43 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 23 Jan 2005 17:40:43 -0500 Subject: Weakref.ref callbacks and eliminating __del__ methods Message-ID: <41F427EB.3000200@rogers.com> I'm looking at rewriting parts of Twisted and TwistedSNMP to eliminate __del__ methods (and the memory leaks they create). Looking at the docs for 2.3's weakref.ref, there's no mention of whether the callbacks are held with a strong reference. My experiments suggest they are not... i.e. I'm trying to use this pattern: class Closer( object ): """Close the OIDStore (without a __del__)""" def __init__( self, btree ): """Initialise the closer object""" self.btree = btree def __call__( self, oldObject=None ): """Regular call via self.close or weakref deref""" if self.btree: self.btree.close() self.btree = None class BSDOIDStore(oidstore.OIDStore): def __init__( self, filename, OIDs = None ): """Initialise the storage with appropriate OIDs""" self.btree = self.open( filename ) self.update( OIDs ) self.close = Closer( self.btree ) weakref.ref( self, self.close ) but the self.close reference in the instance is going away *before* the object is called. So, this approach doesn't *seem* to work (the Closer doesn't get called), so I can gather that the callbacks don't get incref'd (or they get decref'd during object deletion). I can work around it in this particular case by defining a __del__ on the Closer, but that just fixes this particular instance (and leaves just as many __del__'s hanging around). I'm wondering if there's a ready recipe that can *always* replace a __del__'s operation? I know I heard a rumour somewhere about Uncle Timmy wanting to eliminate __del__ in 2.5 or thereabouts, so I gather there must be *some* way of handling the problem generally. The thing is, weakref callbacks trigger *after* the object is deconstructed, while __del__ triggers before... must be something clever I'm missing. Throw an old doggie a bone? Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From bokr at oz.net Fri Jan 14 06:06:41 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 14 Jan 2005 11:06:41 GMT Subject: finding/replacing a long binary pattern in a .bin file References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> <41e6293f.725257715@news.oz.net> <10udjc3fmnhro9d@corp.supernews.com> Message-ID: <41e7a190.821594009@news.oz.net> On Thu, 13 Jan 2005 11:40:52 -0800, Jeff Shannon wrote: >Bengt Richter wrote: > >> BTW, I'm sure you could write a generator that would take a file name >> and oldbinstring and newbinstring as arguments, and read and yield nice >> os-file-system-friendly disk-sector-multiple chunks, so you could write >> >> fout = open('mynewbinfile', 'wb') >> for buf in updated_file_stream('myoldbinfile','rb', oldbinstring, newbinstring): >> fout.write(buf) >> fout.close() > >What happens when the bytes to be replaced are broken across a block >boundary? ISTM that neither half would be recognized.... > >I believe that this requires either reading the entire file into >memory, to scan all at once, or else conditionally matching an >arbitrary fragment of the end of a block against the beginning of the >oldbinstring... Given that the file in question is only a few tens of >kbytes, I'd think that doing it in one gulp is simpler. (For a large >file, chunking it might be necessary, though...) > Might as well post this, in case you're interested... warning, not very tested. You want to write a proper test? ;-) ----< sreplace.py >------------------------------------------------- def sreplace(sseq, old, new, retsize=4096): """ iterate through sseq input string chunk sequence treating it as a continuous stream, replacing each substring old with new, and generating a sequence of retsize returned strings, except that the last may be shorter depedning on available input. """ inbuf = '' endsseq = False out = [] start = 0 lenold = len(old) lennew = len(new) while not endsseq: start, endprev = old and inbuf.find(old, start) or -1, start if start<0: start = endprev # restore find start pos for chunk in sseq: inbuf+= chunk; break else: out.append(inbuf[start:]) endsseq = True else: out.append(inbuf[endprev:start]) start += lenold out.append(new) if endsseq or sum(map(len, out))>=retsize: s = ''.join(out) while len(s)>= retsize: yield s[:retsize] s = s[retsize:] if endsseq: if s: yield s else: out = [s] if __name__ == '__main__': import sys args = sys.argv[:] usage = """ Test usage: [python] sreplace.py old new retsize [rest of args is string chunks for test] where old is old string to find in chunked stream and new is replacement and retsize is returned buffer size, except that last may be shorter""" if not args[1:]: raise SystemExit, usage try: args[3] = int(args[3]) args[0] = iter(sys.argv[4:]) print '%r\n-----------\n%s\n------------' %(sys.argv[1:], '\n'.join(sreplace(*args[:4]))) except Exception, e: print '%s: %s' %(e.__class__.__name__, e) raise SystemExit, usage -------------------------------------------------------------------- As mentioned, not tested very much beyond what you see: [ 2:43] C:\pywk\ut>py24 sreplace.py x _XX_ 20 This is x and abcxdef 012x345 zzxx zzz x ['x', '_XX_', '20', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] ----------- Thisis_XX_andabc_XX_ def012_XX_345zz_XX__ XX_zzz_XX_ ------------ [ 2:43] C:\pywk\ut>py24 sreplace.py x _XX_ 80 This is x and abcxdef 012x345 zzxx zzz x ['x', '_XX_', '80', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] ----------- Thisis_XX_andabc_XX_def012_XX_345zz_XX__XX_zzz_XX_ ------------ [ 2:43] C:\pywk\ut>py24 sreplace.py x _XX_ 4 This is x and abcxdef 012x345 zzxx zzz x ['x', '_XX_', '4', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] ----------- This is_X X_an dabc _XX_ def0 12_X X_34 5zz_ XX__ XX_z zz_X X_ ------------ [ 2:44] C:\pywk\ut>py24 sreplace.py def DEF 80 This is x and abcxdef 012x345 zzxx zzz x ['def', 'DEF', '80', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] ----------- ThisisxandabcxDEF012x345zzxxzzzx ------------ If you wanted to change a binary file, you'd use it something like (although probably let the default buffer size be at 4096, not 20, which is pretty silly other than demoing. At least the input chunks are 512 ;-) >>> from sreplace import sreplace >>> fw = open('sreplace.py.txt','wb') >>> for buf in sreplace(iter(lambda f=open('sreplace.py','rb'):f.read(512), ''),'out','OUT',20): ... fw.write(buf) ... >>> fw.close() >>> ^Z [ 3:00] C:\pywk\ut>diff -u sreplace.py sreplace.py.txt --- sreplace.py Fri Jan 14 02:39:52 2005 +++ sreplace.py.txt Fri Jan 14 03:00:01 2005 @@ -7,7 +7,7 @@ """ inbuf = '' endsseq = False - out = [] + OUT = [] start = 0 lenold = len(old) lennew = len(new) @@ -17,21 +17,21 @@ start = endprev # restore find start pos for chunk in sseq: inbuf+= chunk; break else: - out.append(inbuf[start:]) + OUT.append(inbuf[start:]) endsseq = True else: - out.append(inbuf[endprev:start]) + OUT.append(inbuf[endprev:start]) start += lenold - out.append(new) - if endsseq or sum(map(len, out))>=retsize: - s = ''.join(out) + OUT.append(new) + if endsseq or sum(map(len, OUT))>=retsize: + s = ''.join(OUT) while len(s)>= retsize: yield s[:retsize] s = s[retsize:] if endsseq: if s: yield s else: - out = [s] + OUT = [s] if __name__ == '__main__': import sys Regards, Bengt Richter From mike at hobbshouse.org Thu Jan 13 12:21:30 2005 From: mike at hobbshouse.org (Michael Hobbs) Date: Thu, 13 Jan 2005 17:21:30 -0000 Subject: why are people still using classic classes? References: Message-ID: <10udbgqh32a2901@corp.supernews.com> Simon Wittber wrote: > I've noticed that a few ASPN cookbook recipes, which are recent > additions, use classic classes. > > I've also noticed classic classes are used in many places in the > standard library. > > I've been using new-style classes since Python 2.2, and am suprised > people are still using the classic classes. > > Is there a legitimate use for classic classes that I am not aware of? > Is there a project to specifically migrate standard library classes to > new-style classes? I'm guessing that the biggest contributor to the continued prevalence of classic classes is the official Python Tutorial: http://docs.python.org/tut/node11.html#SECTION0011300000000000000000 I came into Python around the 2.2 timeframe and used the tutorial as my starting point. I had often read people referring to "classic classes" but assumed that it was some old pre-2.2 thing that I need not worry about. For the longest time, I had assumed that I was using new style classes because I created them exactly as prescribed in the 2.2 tutorial (which still hasn't changed for 2.3 or 2.4). Now, classic classes are my habit and I see no compelling reason to put in the effort to change my habits. Regards, - Mike From chris.lasher at gmail.com Thu Jan 13 11:14:01 2005 From: chris.lasher at gmail.com (Chris Lasher) Date: 13 Jan 2005 08:14:01 -0800 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> Message-ID: <1105632841.461042.68310@c13g2000cwb.googlegroups.com> >Others have probably solved your basic problem, or pointed >the way. I'm just curious. >Given that the information content is 2 bits per character >that is taking up 8 bits of storage, there must be a good reason >for storing and/or transmitting them this way? I.e., it it easy >to think up a count-prefixed compressed format packing 4:1 in >subsequent data bytes (except for the last byte which have >less than 4 2-bit codes). My guess for the inefficiency in storage size is because it is human-readable, and because most in-silico molecular biology is just a bunch of fancy string algorithms. This is my limited view of these things at least. >I'm wondering how the data is actually used once records are >retrieved. This one I can answer. For my purposes, I'm just organizing the sequences at hand, but there are all sorts of things one could actually do with sequences: alignments, BLAST searches, gene annotations, etc. From tchur at optushome.com.au Wed Jan 12 01:29:49 2005 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 12 Jan 2005 17:29:49 +1100 Subject: Python.org, Website of Satan Message-ID: <200501120629.j0C6TnHI022666@mail28.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From floydophone at gmail.com Mon Jan 3 20:08:00 2005 From: floydophone at gmail.com (floydophone at gmail.com) Date: 3 Jan 2005 17:08:00 -0800 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <1gprtcx.7y2fb7b25id2N%dial#####$#$#NOSPAM####$$##$tone@gmail.com> References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <1gprtcx.7y2fb7b25id2N%dial#####$#$#NOSPAM####$$##$tone@gmail.com> Message-ID: <1104800880.259621.60100@f14g2000cwb.googlegroups.com> Hi... I'm Peter Hunt. I've implemented stuff like this for a variety of different frameworks. I authored nevow.wolf and the more recent CherryFlow (http://trac.cherrypy.org/cgi-bin/trac.cgi/wiki/CherryFlow). I came up with this idea after looking at Cocoon FlowScript examples. Python generators suit continuation-based web development very nicely. If you take a look at CherryFlow version 1, the core of it is just about 15 lines. I'm constantly updating CherryFlow. I'll keep you posted. Also, if anyone wants to assist me with Subway, my Ruby-on-Rails clone, let me know :) From sjmachin at lexicon.net Sun Jan 9 19:03:34 2005 From: sjmachin at lexicon.net (John Machin) Date: 9 Jan 2005 16:03:34 -0800 Subject: Speed revisited In-Reply-To: <36c3u0tpbg6f98ta6cm4fkj2kn0dkv624m@4ax.com> References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> <1105237556.402188.126980@c13g2000cwb.googlegroups.com> <1105303172.147395.63580@c13g2000cwb.googlegroups.com> <36c3u0tpbg6f98ta6cm4fkj2kn0dkv624m@4ax.com> Message-ID: <1105315414.432202.249470@c13g2000cwb.googlegroups.com> Andrea Griffini wrote: > On 9 Jan 2005 12:39:32 -0800, "John Machin" > wrote: > > >Tip 1: Once you have data in memory, don't move it, move a pointer or > >index over the parts you are inspecting. > > > >Tip 2: Develop an abhorrence of deleting data. > > I've to admit that I also found strange that deleting the > first element from a list is not O(1) in python. My wild > guess was that the extra addition and normalization required > to have insertion in amortized O(1) and deletion in O(1) at > both ends of a random access sequence was going to have > basically a negligible cost for normal access (given the > overhead that is already present in python). > > But I'm sure this idea is too obvious for not having been > proposed, and so there must reasons for refusing it > (may be the cost to pay for random access once measured was > found being far from negligible, or that the extra memory > overhead per list - one int for remembering where the live > data starts - was also going to be a problem). > My wild guess: Not a common use case. Double-ended queue is a special purpose structure. Note that the OP could have implemented the 3-tape update simulation efficiently by reading backwards i.e. del alist[-1] Suggested projects for you, in increasing order of difficulty: 1. Grab the source code (listobject.c) and report back on how you would implement your proposal. 2. Convince folk that your implementation is faster and more robust and has beter internal documentation than anything the timbot could ever write. 3. Write a PEP that didn't cause a flamewar. From fuzzyman at gmail.com Tue Jan 25 03:11:30 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2005 00:11:30 -0800 Subject: Help on project, anyone? In-Reply-To: References: <35ienhF4lu88lU1@individual.net> <1106561458.167373.303270@c13g2000cwb.googlegroups.com> Message-ID: <1106640690.817073.248670@c13g2000cwb.googlegroups.com> Miki Tebeka wrote: > Hello Fuzzyman, > > > 3) Simple Version Control program for single programmer. A very simple > > way of doing version control/releases for small projects with only a > > single programmer. [3] > Subversion (and CVS) are dead simple to install and use. I've heard *lots* of people say exactly the opposite. > IMO in the long run you'll find yourself implementing most of their > features anyway. > > > [3] I think lots of people would find this useful. A version control > > system for projects where CVS/Subversion is overkill. This would be > > based on DirWatcher/FSDM ( > > http://www.voidspace.org.uk/python/programs.shtml#dirwatcher ) - All > > the code for finding which files have changed is already there, and > > there is an existing Tkinter GUI for Dirwatcher. > Adding changes to version control should be done as an explicit action by > the developer. Anything else is on the road to disaster, you'll find > yourself spending too much time backing out of changes you didn't want in. Yeah, my idea is pretty flexible. You could snapshot a 'release state', and roll back changes on individual files in between releases. You basically maintain it on your file system in the normal way and keep an archive of releases/changes. I think this probably works well with the may most small projects are actually managed. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > > Bye. > -- > ------------------------------------------------------------------------ > Miki Tebeka > http://tebeka.bizhat.com > The only difference between children and adults is the price of the toys From apardon at forel.vub.ac.be Mon Jan 24 08:35:31 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Jan 2005 13:35:31 GMT Subject: finding name of instances created References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> <1106397218.724722.172660@c13g2000cwb.googlegroups.com> Message-ID: Op 2005-01-24, Nick Coghlan schreef : > Steven Bethard wrote: >> That is, you can just keep track of all the names of a Robot in the >> Robot object. In the simple case, where there's only one name, you can >> display it as such. In the more complicated case, where there's some >> aliasing, you can display the multiple aliases. This means you don't >> have to teach about aliasing right off the bat, but if a student >> accidentally discovers it on their own, the machinery's there to explain >> it... > > Incidentally, this discussion made me realise the real reason why using a lambda > to create a named function is evil: It is not a named function, it is just a lamda that is assigned to a name. > > Py> def f(): pass > ... > Py> f.func_name > 'f' > Py> f = lambda: None > Py> f.func_name > '' > > I think I've heard that explanation before, but it never really clicked. I just don't see what is so evil about it. Why is it so trouble some that a function wouldn't have a name, while most objects don't have a name. Why is it a problem doing something like: f = lambda: None But isn't it a problem doing something like v = None. Why don't we demand something like Py> assign v: None Py> v.obj_name 'v' -- Antoon Pardon From ionel.mc at gmail.com Sat Jan 15 10:58:41 2005 From: ionel.mc at gmail.com (ionel) Date: Sat, 15 Jan 2005 17:58:41 +0200 Subject: where can i fins some good pywin32 tutorials? Message-ID: need somethin to get started with mfc on python -- ionel. From oglycans at yahoo.com Thu Jan 13 16:07:18 2005 From: oglycans at yahoo.com (oglycans at yahoo.com) Date: 13 Jan 2005 13:07:18 -0800 Subject: how to control the mouse pointer with python? Message-ID: <1105650438.311153.167410@f14g2000cwb.googlegroups.com> Hi. Anybody know a way to control the mouse pointer (move it around and click on things) using python? Thanks. From martin at v.loewis.de Mon Jan 31 18:14:30 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 01 Feb 2005 00:14:30 +0100 Subject: msvcp71.dll and Python 2.4 C++ extensions In-Reply-To: References: Message-ID: <41FEBBD6.4010402@v.loewis.de> Matthias Baas wrote: > are there any guidelines about what to do if a Windows extension for > Python 2.4 requires the C++ runtime (msvcp71.dll)? No; it should "just work fine". The standard guidelines apply, of course: never try to mix different versions of similar DLLs. > If I want to > distribute a binary installer of an extension that contains C++ code, > should I really include the msvcp71.dll in the package? If you cannot expect your users to have that file, you should distribute it. Make sure you have read and understood the Microsoft license concerning the file. > It doesn't > sound like a good idea to me if every package places another copy of > this dll somewhere in the Python directory. Why not? If your installer follows Windows logo compliance rules, it should check whether the DLL is already present; if it is, it should check whether the version installed is newer than the one it would install, and if so, should skip installation. > Python 2.4 does install the C runtime (msvcr71.dll) in the Windows > system32 directory, doesn't it? It depends. If this is an allusers installation, it does so. For a per-user installation, the user might not have sufficient privileges to install into system32, so the installer won't install it there. > (btw, shouldn't this be installed in > the Python directory instead?) No. If you install the DLL into the Python directory, Python will not work anymore because python24.dll (installed into system32) will not find this DLL. If you then also move python24.dll into the Python directory, COM components that require python24.dll will fail to run. > So would it be possible that future > Python releases would also install the C++ runtime? Why should it? Nothing in the Python distribution requires C++. > I think it's > better if the dll would only be installed once by Python instead of > several times by every extension that uses C++. Why is that better? The DLL versioning rules, and the shared DLL refcounting mechanisms will make sure that the installation works just fine. > Currently, I do not package the C++ runtime and leave it up to the > user to install the dll if it isn't already somewhere on his system. > But this really is not a satisfying solution... Then you should probably include the DLL, or rewrite your extension to not use C++. Regards, Martin From ncoghlan at iinet.net.au Tue Jan 11 09:18:24 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 12 Jan 2005 00:18:24 +1000 Subject: [Python-Dev] PEP 246, redux In-Reply-To: <6EA3D69F-63B7-11D9-ADA4-000A95EFAE9E@aleax.it> References: <5.1.1.6.0.20050110113559.02bc2350@mail.telecommunity.com> <5.1.1.6.0.20050110113559.02bc2350@mail.telecommunity.com> <5.1.1.6.0.20050110132407.0344a9d0@mail.telecommunity.com> <6EA3D69F-63B7-11D9-ADA4-000A95EFAE9E@aleax.it> Message-ID: <41E3E030.3000209@iinet.net.au> Alex Martelli wrote: > "I really wish the language had > private inheritance because I'm using Abstract as a base just for code > reuse" Funny you should say that. . . what about a __nonconformant__ entry that accepts a list of base classes that is used to indicate inheritance without a proper is-a relationship? So if the isinstance check succeeds and there is no '__nonconformant__' entry, then adapt() just returns the object. If, on the other hand, __nonconformant__ is supplied, then adapt() can check the list of base classes that remains after removing the entries in __nonconformant__ to see if the object would *still* be an instance a subtype, even after removing the noncomformant bases, and if it is, return it. Otherwise, continue on to the rest of the adaptation process. This should give a better idea what I mean: # The 'fast path' if isinstance(obj, protocol): if not hasattr(obj, "__nonconformant__"): return obj conformant_bases = set(obj.__bases__) - set(obj.__nonconformant__) for base in conformant_bases: if issubtype(base, protocol): return obj # Continue on with the other adaptation possibilities (including __conform__) Then you can get 'discreet' inheritance (you have the methods, but you don't brag about the fact) by writing: class Dubious(Abstract): __noncomformant__ = [Abstract] # etc rather than: class Dubious(Abstract): def __comform__(self, protocol): if issubtype(protocol, Abstract): raise LiskovViolation # etc Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From stephen.thorne at gmail.com Thu Jan 13 01:47:05 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 16:47:05 +1000 Subject: newbie q In-Reply-To: <34mgq0F4dq4buU1@individual.net> References: <34mgq0F4dq4buU1@individual.net> Message-ID: <3e8ca5c8050112224720b5585c@mail.gmail.com> On Thu, 13 Jan 2005 15:55:10 +1000, Egor Bolonev wrote: > how to get rid of 'for' operator in the code? > > import os, os.path > > def _test(): > src = 'C:\\Documents and Settings\\????\\My Documents\\My Music\\' > > for i in [x for x in os.listdir(src) if os.path.isfile(os.path.join(src, > x)) and len(x.split('.')) > 1 and x.split('.')[-1].lower() == 'm3u']: > os.remove(os.path.join(src, i)) > > if __name__ == '__main__': > _test() import glob for x in glob.glob("*.m3u"): os.remove(x) Regards, Stephen Thorne From lkirsh at cs.ubc.ca Thu Jan 20 04:48:41 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Thu, 20 Jan 2005 01:48:41 -0800 Subject: why are these not the same? In-Reply-To: References: Message-ID: D'oh I should've caught that myself. Thanks. Fredrik Lundh wrote: > Lowell Kirsh wrote: > >>On a webpage (see link below) I read that the following 2 forms are not the same and that the >>second should be avoided. They look the same to me. What's the difference? > > >>def functionF(argString="abc", argList = None): >> if argList is None: argList = [] >> ... >> >>def functionF(argString="abc", argList=None): >> argList = argList or [] >> ... > > > "is None" tests for None, "argList or" tests for a false value. None is > false, but many non-None objects are also false. > > "should be avoided" sounds like overly zealous advice to me; use the > latter form if you understand it. > > > > > From mahs at telcopartners.com Sat Jan 22 14:38:49 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sat, 22 Jan 2005 11:38:49 -0800 Subject: default value in a list In-Reply-To: <1gqs9gb.1mmtpcit05ruwN%aleaxit@yahoo.com> References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> <1gqs9gb.1mmtpcit05ruwN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: [explanation and the following code:] > >>> a, b, c = it.islice( > ... it.chain( > ... line.split(':'), > ... it.repeat(some_default), > ... ), > ... 3) > ... > ... > >>> def pad_with_default(N, iterable, default=None): > ... it = iter(iterable) > ... for x in it: > ... if N<=0: break > ... yield x > ... N -= 1 > ... while N>0: > ... yield default > ... N -= 1 Why not put these together and put it in itertools, since the requirement seems to crop up every other week? >>> line = "A:B:C".split(":") ... >>> def ipad(N,iterable, default = None): ... return it.islice(it.chain(iterable, it.repeat(default)), N) ... >>> a,b,c,d = ipad(4,line) >>> a,b,c,d ('A', 'B', 'C', None) Michael From nick at craig-wood.com Wed Jan 19 05:30:02 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 19 Jan 2005 10:30:02 GMT Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: > Paul Rubin wrote: > > "Reed L. O'Brien" writes: > > > >>I see rotor was removed for 2.4 and the docs say use an AES module > >>provided separately... Is there a standard module that works alike or > >>an AES module that works alike but with better encryption? > > > > > > If you mean a module in the distribution, the answer is no, for > > political reasons. > > > .....I'm also missing the rotor module and regret that something useful > was warned about and now removed with no plugin replacement. > > I had understood that this was because rotor was insecure, but you > mention politics. Are other useful modules to suffer from politics? > > What exactly are/were the political reasons for rotor removal? Presumably he is talking about crypo-export rules. In the past strong cryptography has been treated as munitions, and as such exporting it (especially from the USA) could have got you into very serious trouble. However I believe those restrictions have been lifted (the cat having been let out of the bag somewhat ;-), and its easy to do this for open source encryption software. A wade through http://www.bxa.doc.gov/Encryption/enc.htm Might be interesting. A case in point: the linux 2.6 kernel is chock full of crypo and comes with implementations of AES, ARC4, Blowfish, Cast5+6, DES, Serpent, Twofish, TEA, etc. The linux kernel+source surely goes everywhere python does so I don't think adding strong crypto modules to python is a problem now-a-days. AES in the core python library would be very useful and it would discourage people from writing their own crypto routines (looks easy but isn't!) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From lescault91967 at aol.com Thu Jan 6 22:41:06 2005 From: lescault91967 at aol.com (MIke) Date: Thu, 6 Jan 2005 22:41:06 -0500 Subject: This Program Realy Works Message-ID: MAKE LOTS OF MONEY QUICKLY, GUARANTEED 100%, NO SCAM! Turn 6.00 into 42,000! This is true!!.... Read this carefully to find out how!!.... READING THIS WILL CHANGE YOUR LIFE! I found this on a bulletin board and decided to try it. A little while back, I was browsing through newsgroups, and came across an article similar to this that said you could make thousands of cash within weeks with only an initial investment of .00! So I thought, "Yeah right, this must be a scam", but like most of us, I was curious, so I kept reading. Before you get skeptical, just take a few minutes to finish reading. HERE'S HOW IT WORKS WITH THIS PLAN, YOU REALLY CAN MAKE TONS OF TOTALLY LEGAL, FAST AND EASY CASH MONEY!! IT WORKS!!! BUT YOU HAVE TO FOLLOW IT CAREFULLY FOR IT TO WORK CORRECTLY AND IN YOUR FAVOR!!!! WITH ALL THE MONEY YOU ARE GONNA MAKE, YOU WILL SOON GET EVERYTHING YOU'VE ALWAYS DREAMED OF!!!! ALL YOU DO IS... All you do is send $1.00 to each of the 6 names and address stated in the article. You then place your own name and address in the bottom of the list at #6, and post the article in at least 200 newsgroups. (There are thousands.) No catch, that was it . So after thinking it over, and talking to a few people first, I thought about trying it. I figured, what have I got to lose except 6 stamps and 6.00, right? Like most of us I was a little skeptical and a little worried about the legal aspects of it all. So I checked it out with the U.S. Post Office (1-800-725-2161) and they confirmed that it is indeed legal! AND THEN GUESS WHAT... Then I invested the measly 6.00. Well, GUESS WHAT!!... Within 7 days, I started getting money just kept coming in. In my first week, I made about 25. By the end of the second week I had made a total of over 1,000! In the third week I had over 10,000 and it's still growing. This is now my fourth week and I have made a total of just over 42000, and it's still coming in rapidly. It's certainly worth 6. and 6 stamps. By the way, I have spent more than that on the lottery in the last month!! Let me tell you how this works and most importantly, why it works.... also, make sure you print a copy of this article NOW, So you can get the information off of it, as you need it. SO LET'S GET STARTED AND SEE WHAT HAPPENS STEP 1: Get 6 separate pieces of paper and write the following on eash piece of paper, "PLEASE PUT MY NAME ON YOUR MAILING LIST." Also, be sure to include your name and address. Now, get 6 U.S. $1.00 bills and place ONE inside EACH of the 6 pieces of paper so the bill will not be seen through the envelope, to prevent thievery. Next, place one paper in each of the 6 envelopes and seal them. You should now have 6 sealed envelopes, each with a piece of paper stating the above phrase, your name and address email , and a $1.00 bill. What you are doing is creating a service by this. THIS IS ABSOLUTELY LEGAL! STEP 2 : Mail the 6 envelopes to the following addresses: #1 John Christensen 5446 Santa Barbara Sparks, NV 89436 #2 Randall Hines 22 Stature Dr. Newark DE 19713 #3 Mike Sharrer 921 West State St. Coopersburg PA 18036 #4 Travis Montgomery 2211 Elmers Lane Norfolk NE 68701 #5 James Adair the third 22 Over Rd. Feasterville PA 19053 #6 Michael Lescault 123 Rhode Island Ave. Pawtucket, RI. 02860 STEP 3: Now take the #1 name off the list that you see above, move the other names up (6 becomes 5, 5 becomes 4, etc.) and add YOUR Name as number 6 on the list. STEP 4: Change anything you need to, but try to keep this article as close to original as possible. If you do not live in the U.S. or there is a foreign address, you must put an international stamp on your envelopes. Now, post your amended article to at least 200 newsgroups. ( I think there are close to 24,000 groups in all.) All you need is 200, but remember, the more you post, the more money you make!! DIRECTIONS FOR POSTING TO NEWSGROUP BULLETINS STEP 1: You do not need to re-type this entire letter to do your own posting. Simply put you cursor at the beginning of this letter and drag your cursor to the bottom of this letter. Then select 'copy' from the edit menu. This will copy the entire letter into the computer's temporary memory. STEP 2: Open a blank 'notepad' or word processor file and place your cursor at the top of the blank page. From the 'edit' menu select 'paste'. This will paste a copy of the letter into notepad so that you can add your name to the list. STEP 3: Save your new notepad file as a *.txt file. If you want to do your postings in different sittings, you'll always have this file to fo back to. STEP 4: Use your Internet provider and search engines to find various newsgroups (on-line forums, message boards, chat sites, discussions). STEP 5: Visit these message boards and post this article as a new message by higlighting the text of this letter and selecting paste from the edit menu. Fill in the Subject, and this will be the header that everyone sees as they scroll through the list of postings in a particular group. Then click the post message button. You're done with your first one! Congratulations... THAT'S IT! All you have to do is jump to different newsgroups and post away. After you get the hang of it, it will only take about 30 seconds for each posting!! ** REMEMBER, THE MORE NEWSGROUPS YOU POST IN, THE MORE MONEY YOU WILL MAKE!! ----BUT YOU HAVE TO POST A MINIMUM OF 200**----- That's it! You will begin receiving money from around the world within days! You may eventually want to rent a P.O. Box due to the large amount of mail you will receive. If you wish to stay anonymous, you can invent a name to use , as long as the postal service will deliver it. *JUST MAKE SURE ALL THE ADDRESSES ARE CORRECT* WITH 200 POSTINGS Out of 200 postings, say I receive only 5 replies ( a very low example). So then I made 5.00 with my name at #6 on the letter. Now, each of the 5 persons who just sent me $1.00 make the MINIMUM 200 postings, each with my name at #5, and only 5 persons repond to each of the original 5, that is another 25. Then those 25 each make 200 MINIMUM posts with my name at #4, and only 5 relies to each, and I will bring in an additional125! Now, those 125 persons turn around and post the MINIMUM 200 with my name at #3 and only receive 5 replies each, and I will make an additional 625! OK, now here is the fun part... Each of those 625 persons post a MINIMUM 200 letters with my name at #2, and they each only receive 5 replies, that just made me 3125!!! Those 3,125 persons will all deliver this message to 200 newsgroups with my name at #1, and if still 5 persons per 200 newsgroups react, I will receive an amazing 15625! With an original investment of only 6! AMAZING! DO IT OVER AND OVER When your name is no longer on the list, you just take the latest posting in the newsgroups, and send out another 6 to names on the list, putting your name at #6 again. Then start posting again. That's it! Do you realize that thousands of honest people just like you all over the world are joining the Internet and reading these articles everday? So can you afford 6 and see if it really works?? I think so.. People have said, "what if the plan is played out and no one sends you the money?" So what! What are the chances of that happening when there are tons of new honest users who are joining the Internet and newsgroups everyday? So, are you willing to give it a try? Estimates are about 20,000 to 50,000 new bulletin board users everyday, with thousands of those joining the Internet itself. ---Remember please play FAIRLY! This ensures a huge circle of wealth that grows with the Internet audience!!! Everyone benefits!!! Remember To Send The Six Envelopes To The Above Addresses, In Order To Create The Legal Service. At first I was scared to try this, but once I research it, I found that it is totally legal. When you send the six envelopes out, you create a service, a legal service. The Internet audience is expanding all the time. The audience is like an equity stock on the stock market, continuously going up. If you still think this is a fraud, take a few minutes to check it out, then.... you can start raking in the cash!! THIS CAN WORK IF WE ARE ALL IN IT TOGETHER!!!! From tundra at tundraware.com Wed Jan 12 04:28:28 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 12 Jan 2005 04:28:28 EST Subject: [ANN]: twander 3.160 Released And Available Message-ID: <41E4ED3E.2030900@tundraware.com> 'twander' Version 3.160 is now released and available for download at: http://www.tundraware.com/Software/twander The last public release was 3.146. Existing users are encouraged to upgrade to this release as it has a number of bug fixes and several nice new features including: - Mouse popups for all the menus (except Help). - Ability to force Unix-style paths under Windows when doing substitutions in command macros. (Very helpful for cygwin users.) - A smarter "adaptive" directory refresh mechanism. - A new "Shortcut" menu for fast navigation around the filesystem. Complete details of all fixes, changes, and new features can be found in the WHATSNEW.txt file included in the distribution. Users are strongly encouraged to join the twander-users mailing list as described in the documentation. What Is 'twander'? ------------------ 'twander' is a macro-programmable Filesystem Browser that runs on both Unix-like systems as well as Win32 systems. It embraces the best ideas of both similar GUI-driven programs (Konqueror, Windows Explorer) as well as text-based interfaces (Midnight Commander, List, Sweep). Or, If You Prefer The "Elevator Pitch" -------------------------------------- 'twander' is: - A better file browser for Unix and Win32. (Tested on FreeBSD, Linux, Win32.) - A way to make browsing the same on all the OSs you use. - A macro-programmable tool that lets *you* define the features. - A GUI navigation front-end for your shell. - A way to "can" workflows for your technically-challenged colleagues. - A way to free yourself from the shackles of the mouse. - A way to significantly speed up your day-to-day workflow. - A Python/Tkinter application - about 3100/1300 lines of code/comments - A RCT (Really Cool Tool) that will have you addicted in a day or two See the web page for more information, a screen shot, and the complete documentation. ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From a at b.c Sun Jan 23 02:27:38 2005 From: a at b.c (Doug Holton) Date: Sun, 23 Jan 2005 01:27:38 -0600 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> Message-ID: Steve Holden wrote: > Yet again I will interject that XML was only ever intended to be wriiten > by programs. Hence its moronic stupidity and excellent uniformity. Neither was HTML, neither were URLs, neither were many things used the way they were intended. YAML, however, is specifically designed to be easier for people to write and to read, as is Python. From neil.benn at arcor.de Wed Jan 12 14:43:04 2005 From: neil.benn at arcor.de (Neil Benn) Date: Wed, 12 Jan 2005 20:43:04 +0100 Subject: Excel module for Python In-Reply-To: References: Message-ID: <41E57DC8.5030400@arcor.de> sam wrote: > Simon Brunning wrote: > >> On Wed, 12 Jan 2005 15:18:09 +0800, sam wrote: >> >>> I m wondering which Excel module is good to be used by Python? >> >> >> >> If you are on Windows, and you have Excel, then the Python for Windows >> extensions[1] are all you need to drive Excel via COM. O'Reilly's >> "Python Programming on Win32" covers COM scripting extensively - and >> by good fortune, driving Excel is the example they use, and the COM >> scripting chapter is on-line[2]. >> >> You'll also need to know the objects and methods that Excel exposes. >> These are documented on Microsoft's web site[3], or in the Excel VBA >> help, which is an optional part of they Office installation. >> > > No, I don't use MS windows. I need to generate Excel file by printing > data to it, just like Perl module Spreadsheet::WriteExcel. > > thanks > Sam Hello, If you can use jython then there is something that does this in java - it's called POI (search for POI HSSF Excel) in google. If you can't use jython and are desperate then you could set up a WebService/cgi/ and send the information back and forth. I spose you can do this with perl as well (don't know any perl so this bit is only a guess!). However the last time I looked (about a year ago) POI does have limitations with excel graphs. Cheers, Neil From pdemb at illx.org Mon Jan 3 09:38:50 2005 From: pdemb at illx.org (Peter Dembinski) Date: Mon, 03 Jan 2005 15:38:50 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1> <7x8y7cjo57.fsf@ruckus.brouhaha.com> <87zmzsax12.fsf@hector.domek> <87pt0na5zf.fsf@hector.domek> <87llbba55t.fsf@hector.domek> Message-ID: <87y8fah91h.fsf@hector.domek> Peter Hansen writes: > Roy Smith wrote: >> "Terry Reedy" wrote: >> >>> None has been reserved because there is no known good use for >>> overriding it. >> Should I infer from the above that there's a known bad use? > > Yes: making None equal to the integer 3. That's one of > six known bad uses.... it's possible there are more. ;-) Binding user variables to these names should raise exception (eg. AreYouInsaneException or WhatAreYouDoingException) :> From Marc.Poinot at onera.fr Fri Jan 21 11:09:16 2005 From: Marc.Poinot at onera.fr (Marc Poinot) Date: Fri, 21 Jan 2005 17:09:16 +0100 Subject: MPI and python+threads on IRIX Message-ID: <41F1292C.703EF3FE@onera.fr> Hi, I'm trying to add a dynamic module using MPI on a 2.3.4 Python with threads (posix). The interpreter blocks into the dlopen (dynload_shlib.c) if any reference to the IRIX libmpi.so (actually SGI/IRIX 6.5) appears. The docs say that the use of MPI+dlopen requires a call to MPI_Init_thread before the dlopen. I wonder how I can build a shared module using mpi if it blocks inside the dlopen ! It looks like the dlopen itself blocks at the time it reads the libmpi.so (is it possible). The MPI modules I've found are not ported on SGI (yes I know...) Any hints ? Help ? Piece of advice ? Idea ? Patch ? Coconut ? -MP- ----------------------------------------------------------------------- Marc POINOT Alias: marcvs Email: poinot at onera.fr ONERA -MFE/DSNA/ELSA Tel: 01.46.73.42.84 Info: elsa-info at onera.fr 29, Div. Leclerc Fax: 01.46.73.41.66 Site: 92322 Chatillon FRANCE Project: elsA Web: http://www.onera.fr From b at b.b Sat Jan 8 15:23:01 2005 From: b at b.b (Roose) Date: Sat, 08 Jan 2005 20:23:01 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> Message-ID: > Is an OS written in Lisp also ludicrous? Because it's been done. Can you point me to this? I'd like to see how "truly" Lisp it is. My first guess would be -- not very. And I'd like to install it on my PC. From ptmcg at austin.rr._bogus_.com Tue Jan 11 18:08:17 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 11 Jan 2005 23:08:17 GMT Subject: Time script help sought! References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> <1105477084.525279.312970@f14g2000cwb.googlegroups.com> <1105479292.689762.155510@f14g2000cwb.googlegroups.com> <1105480151.431987.327080@c13g2000cwb.googlegroups.com> Message-ID: "kpp9c" wrote in message news:1105480151.431987.327080 at c13g2000cwb.googlegroups.com... > still working on it and also fixing the input data. I think for > simplicity and consistency's sake i will have *all* time values input > and output as hh:mm:ss maybe that would be easier.... but i have a few > thousand find and replaceeseseses to do now (yes i am doing them by > hand) > > grr... this is hard! > Oh, I wasn't going to chime in on this thread, your data looked so well-formed that I wouldn't recommend pyparsing, but there is enough variability going on here, I thought I'd give it a try. Here's a pyparsing treatment of your problem. It will accommodate trailing comments or none, leading hours or none on timestamps, and missing end times, and normalizes all times back to the item start time. Most of your processing logic will end up going into the processVals() routine. I've put various examples of how to access the parsed tokens by field name, and some helper methods for converting to and from seconds and hh:mm:ss or mm:ss times. -- Paul from pyparsing import * data = """ Item_1 TAPE_1 1 00:23 8:23 Item_2 TAPE_1 2 8:23 9:41 Item_3 TAPE_1 3 9:41 10:41 Item_3 TAPE_1 4 10:47 11:19 Item_3 TAPE_1 5 11:21 11:55 Item_3 TAPE_1 6 11:58 12:10 Item_3 TAPE_1 7 12:15 12:45 Defect in analog tape sound. Item_3 TAPE_1 8 12:58 24:20 Defect in analog tape sound. Item_4 TAPE_1 9 24:33 Item_4 TAPE_1 10 25:48 Item_4 TAPE_1 11 29:48 Item_4 TAPE_1 12 31:46 Item_4 TAPE_1 13 34:17 Electronic sounds. Item_4 TAPE_1 14 35:21 Item_4 TAPE_1 15 36:06 Item_4 TAPE_1 16 37:01 01:37:38 """ def toSecs(tstr): fields = tstr.split(":") secs = int(fields[-1]) secs += int(fields[-2])*60 if len(fields)>2: secs += int(fields[-3])*60*60 return secs def secsToTime(secs): s = secs % 60 m = ((secs - s) / 60 ) % 60 h = (secs >= 3600 and (secs - s - m*60 ) / 3600 or 0) return "%02d:%02d:%02d" % (h,m,s) # globals for normalizing timestamps lastItem = "" itemStart = 0 # put logic here for processing various parse fields def processVals(s,l,t): global lastItem,itemStart print t.item,t.tape,t.recnum if not t.item == lastItem : lastItem = t.item itemStart = toSecs(t.start) startSecs = toSecs(t.start) print secsToTime(startSecs),"(%s)" % secsToTime(startSecs-itemStart) if t.end: endSecs = toSecs(t.end) print secsToTime(endSecs),"(%s)" % secsToTime(endSecs-itemStart) print endSecs-startSecs,"elapsed seconds" print secsToTime(endSecs-startSecs),"elapsed time" else: print "" print t.comment print # define structure of a line of data - sorry about the clunkiness of the optional trailing fields integer = Word(nums) timestr = Combine(integer + ":" + integer + Optional(":" + integer)) dataline = ( Combine("Item_"+integer).setResultsName("item") + Combine("TAPE_"+integer).setResultsName("tape") + integer.setResultsName("recnum") + timestr.setResultsName("start") + Optional(~LineEnd() + timestr, default="").setResultsName("end") + Optional(~LineEnd() + empty + restOfLine,default="-").setResultsName("comment") ) # set up parse handler that will process the actual fields dataline.setParseAction(processVals) # now parse the little buggers OneOrMore(dataline).parseString(data) will print out: Item_1 TAPE_1 1 00:00:23 (00:00:00) 00:08:23 (00:08:00) 480 elapsed seconds 00:08:00 elapsed time - Item_2 TAPE_1 2 00:08:23 (00:00:00) 00:09:41 (00:01:18) 78 elapsed seconds 00:01:18 elapsed time - Item_3 TAPE_1 3 00:09:41 (00:00:00) 00:10:41 (00:01:00) 60 elapsed seconds 00:01:00 elapsed time - Item_3 TAPE_1 4 00:10:47 (00:01:06) 00:11:19 (00:01:38) 32 elapsed seconds 00:00:32 elapsed time - Item_3 TAPE_1 5 00:11:21 (00:01:40) 00:11:55 (00:02:14) 34 elapsed seconds 00:00:34 elapsed time - ... From andre.roberge at gmail.com Fri Jan 21 19:13:19 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 21 Jan 2005 16:13:19 -0800 Subject: finding name of instances created Message-ID: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> Short version of what I am looking for: Given a class "public_class" which is instantiated a few times e.g. a = public_class() b = public_class() c = public_class() I would like to find out the name of the instances so that I could create a list of them e.g. ['a', 'b', 'c'] I've read the Python Cookbook, Python in a Nutshell, Programming Python, Learning Python, ... googled (probably missed something obvious), all to no avail. ===== Longer version: If I can do the above, I believe I could do the following thing which is what I am really after eventually. Given the statement >> a = public_class() I would like to generate >> my_dict['a'] = private_class() so that one could write >> a.apparently_simple_method() and that, behind the scene, I could translate that as >> my_dict['a'].not_so_simple_method() as well as do things like >> for name in my_dict: >> do_stuff(name) Any help, pointers, sketches or outline of solution would be greatly appreciated. Andr? From sridharinfinity at gmail.com Sun Jan 2 03:19:01 2005 From: sridharinfinity at gmail.com (Sridhar) Date: 2 Jan 2005 00:19:01 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <1104653941.732418.15900@c13g2000cwb.googlegroups.com> You need Twisted - http://twistedmatrix.com --- : http://en.wikipedia.org/wiki/User:Sridharinfinity From claird at lairds.us Tue Jan 4 11:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 04 Jan 2005 16:08:03 GMT Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1104511661.928284.10200@z14g2000cwz.googlegroups.com> Message-ID: <31rqa2-c2b.ln1@lairds.us> In article , Alan Gauld wrote: >On Sat, 01 Jan 2005 16:08:07 GMT, claird at lairds.us (Cameron >Laird) wrote: > >> I argue that it's a false opposition to categorize projects in >> terms of use of single languages. Many projects are MUCH better >> off with a mix > >In practice I have *never* worked on an industrial scale project >that only used one language. The nearest I came was a small >protocol convertor that only used C, SQL and some shell and >awk - but that's still 4 languages! And the whole project was >only 40,000 lines of code in about 20 files. > >And most projects use many more, I'd guess around 5-8 on an >"average project" of around 300-500kloc. The biggest project I >worked on had about 3.5Mloc and used: > >Assembler (680x0 and Sparc), >C >C++ >Lisp(Flavors) >awk >Bourne shell >C shell - this was a mistake discovered too late to "fix" >PL/SQL >???? - A UI description language for a tool called TeleUse... >Pascal - No, I don't know why... >ASN.1 - with a commercial compiler > >We also had some IDL but since it was tool generated I'll ignore >it... > >We also had an experimental version running on a NeXt box so it >used Objective C for the UI instead of ???? and C++... > >A total of 13 languages... with 5 geographically dispersed teams >comprising a total of 200 developers (plus about 40 testers). >Interesting times...in the Chinese sense! . . . D. The TeleUSE language is "D". And I suspect your count is a lower bound. If you worked with TeleUSE, somebody probably was doing Motif configuration, which arguably is a(n impoverished configuration) language itself. From drinkmyjesus at aol.com Sat Jan 15 02:51:56 2005 From: drinkmyjesus at aol.com (drinkmyjesus at aol.com) Date: 14 Jan 2005 23:51:56 -0800 Subject: New computer Message-ID: <1105775516.246393.171850@f14g2000cwb.googlegroups.com> Hey- Check out this great site that is giving away totally FREE Desktop PCs! I've joined and I think you should as well. It's a completely legitimate offer, and this company has already given away $4 million in FREE stuff! All you have to do is join, complete an online offer, and refer friends to do the same. That's it! Here is my referral link. To help me get my Desktop PC, click this exact link to join, or copy and paste it into a browser: http://www.FreeDesktopPC.com/?r=13995904 this is my second free computer. Its awesome. Get it and sell it or use it. Its free. Who cares. From mikybNO at SPAMinterfree.it Fri Jan 28 18:09:09 2005 From: mikybNO at SPAMinterfree.it (Michele) Date: Fri, 28 Jan 2005 23:09:09 GMT Subject: boa constructor & mysql Message-ID: <2005012900090816807%mikybNO@SPAMinterfreeit> I've search a lot to found how visualize a mysql table in a gui (wxpython). I think to use wxgrid to visualize this table...but I don't know how... Anyone help me? Thanks a lot for the patience. Michele From pycon at python.org Sun Jan 23 16:07:00 2005 From: pycon at python.org (Steve Holden) Date: Sun, 23 Jan 2005 22:07:00 +0100 (CET) Subject: Microsoft to Provide PyCon Opening Keynote Message-ID: <20050123210700.EF4E41E4015@bag.python.org> Dear Python Colleague: The PyCon Program Committee is happy to announce that the opening keynote speech, at 9:30 am on Wednesday March 23 will be: Python on the .NET Platform, by Jim Hugunin, Microsoft Corporation Jim Hugunin is well-known in the Python world for his pioneering work on JPython (now Jython), and more recently for the IronPython .NET implementation of Python. Jim joined Microsoft's Common Language Runtime team in August last year to continue his work on Iron Python and further improve the CLR's support for dynamic languages like Python. I look forward to hearing what Jim has to say, and hope that you will join me and the rest of the Python community at PyCon DC 2005, at George Washington University from March 23-25, with a four-day sprint starting on Saturday March 19. Early bird registration rates are still available for a few more days. Go to http://www.python.org/moin/PyConDC2005/Schedule for the current schedule, and register at http://www.python.org/pycon/2005/ regards Steve Holden Chairman, PyCON DC 2005 -- PyCon DC 2005: The third Python Community Conference http://www.pycon.org/ http://www.python.org/pycon/ The scoop on Python implementations and applications From http Thu Jan 27 23:25:57 2005 From: http (Paul Rubin) Date: 27 Jan 2005 20:25:57 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> Message-ID: <7xu0p2dvsa.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > > I don't see why you can't make up your mind enough to issue simple > > statements like "the Python lib should have a module that does > > so-and-so > > I can say that assuming I know what so-and-so is. For the specific > case of AES, I would say "I don't think the Python lib necessarily > needs to have an AES module, but I would not object if it had one" Well, ok, you're changing your tune a little bit now, and getting more reasonable. Before, you were making blanket statements of any modules written for the Python stdlib. Now you're limiting it to AES and basing it on some AES-specific things. > (the latter part in consideration of consequences that inclusion > of crypto code might have). I would say the first thing I'd request would be your sense of how plausible it is that the current no-crypto policy might be relaxed. And I think this is about totally up to Guido, since (reading between the lines of those python-dev messages) he's concerned about the Dutch crypto restrictions, which makes some sense because he's Dutch and still has to deal with the Dutch government from time to time, while you or I might not care what the Dutch government thinks. I was about to mention that Rop Gongrijp has been operating a crypto company in Holland (www.nah6.com) but I now see that it's moved to Germany, and I wonder if those Dutch restrictions might be the reason. I don't know any details though. > > and it should meet such-and-such requirements > > I can only say such things if I know such-and-such in detail > to specify requirements. For the specific case of AES, I don't > know enough about it to specify requirements. I will have to > trust others (and by that, I mean *multiple* others) OK. If it helps, I can tell you that the Python crypto crowd hangs out on a mailing list called python-crypto and has discussed this module at some length. > > so if someone submits one that meets the requirements and passes > > code review and testing and doesn't have unexpected issues or > > otherwise fail to meet reasonable expectations, we'll use it". > > Because I cannot specify requirements, I cannot make such a promise. Again OK. I had thought from earlier discussions that you were a crypto developer and familiar with this stuff; no problem if you're not. However, in that case, you probably wouldn't be using the module if it got included. I think the best policy if you don't feel comfortable supporting including some module (whether it's crypto or something else) that you're not personally going to use, is don't support inclusion, but also don't obstruct it. If there's some other stdlib maintainers who are knowledgeable about that kind of module and have an opinion about it, then go along with them unless there's a clear reason not to. Like, if I were a stdlib maintainer and somebody submitted a fancy multigrid PDE solver, that's outside my expertise and I'd go along with whatever Tim recommended. > In addition, for any new module, there is one primary requirement > for acceptance that cannot be fulfilled in code quality: the > contributor should promise to support the module in a foreseeable > future (i.e. a couple of years). That's not too unreasonable, though I don't think I've heard it mentioned as a requirement before. > You are talking about such a thing. I don't know enough about the > functionality to specify what an obvious interface is, or to > recognize one if I see it. The thing to do then is just defer the whole issue to someone on the core team who uses that type of function. Only if no one on the team has an opinion do you start having to look for stuff like wide use of the module in the outside community. > > I don't know what OMG is, but there is no IETF requirement that any > > implementations be available in any particular language. > > See RFC 2026, section 4.1.2. Two independent implementations > are required for the document to advance to draft (!) standard. That says nothing about the implementation languages. Both might be in Python, or one might be in VHDL and the other in Ada, or whatever. This particular module we're discussing is a straightforward implementation of AES, DES, and FIPS 81, for which there are thousands of implementations in both hardware and software. For the specific Python API, there's a Python implementation and the proposed new module is a C implementation that does the exact same thing only faster. So that's two implementations, though not independent in the IETF sense, because they'd both be written by the same person. I've never heard of any requirement before that there be two separate implementations of every Python stdlib module, by the way. That would be silly. > > However, the result of my not writing an AES module is that Python > > doesn't have an AES module. > > That's not true. PyCrypto does have AES support. That's not in any Python distro that I know of. I'm talking about modules in the stdlib, not external modules. "Batteries included", you know. > That's what I'm saying: If you distribute the module to users for > a year, and users express interest and support for your choice of > API, I'll support inclusion of the module. "do it" involves more than > just writing the code. Well, that's nice of you to offer to support inclusion of a module that you're not likely to use yourself and whose functionality you don't really understand (I'm not being sarcastic). If you're going to offer such support it makes sense to impose an unusually high standard for offering it. I myself would probably never support including any such module no matter how long it was distributed, but rather would just defer the whole question to people experienced with such modules and trust their sense of what the acceptance criteria should be for a specific module. That is, I'd abstain from any decision. > It's very easy. If you are primarily do it for other people's > benefit, and if you don't find any satisfaction in the process > of doing it - THEN DON'T. I really mean that; this is how > free software works. People *volunteer* to do things. If they > don't volunteer - that's perfectly fine. That doesn't map well onto the real world. Say I'm a professional cook and I have a good recipe for spam, eggs, sausage, and spam. I write the PyCon organizers and ask if they'd like me to cook up a big batch to serve for breakfast for PyCon attendees (this is as a volunteer, all ingredients provided at my own expense, etc). Reasonable answers might be: 1) No, we don't want to serve breakfast at PyCon, we thought about it but decided against it. => OK, fine, I don't cook it. 2) Hey, that sounds good--cook enough for 500 people and bring it to the site before the conference starts, and we'll put it on the menu unless it's below expectations. => OK, fine, I start cooking. Nobody has made an ironclad promise, but the organizers have told me their basic intentions, which is good enough for me. 3) Hmm, that recipe sounds interesting, why don't you send one or two portions to the organizers, we'll try them and let you know. => OK, this is basically a prototype implementation, like the pure-Python version of the AES module, that's fine for testing but not fast enough to serve (e.g.) 500 web connections. I send the small batch and wait for an answer before deciding to start the much bigger job of making a 500-person batch. Your answer is more like "make enough for 500 people and bring it to the conference site and only then will we even THINK about whether to serve it for breakfast. Serving it at PyCon shouldn't matter to you, what are you, some kind of egotist? You like cooking, so if you make the 500 portions and then the organizers decline them, you can always hand them out in the street. If you don't find any satisfaction in that, THEN DON'T DO IT." If the cook's goal is not just to feed Python users in the street, but to actually improve PyCon itself by providing for PyCon to serve breakfast to attendees, I hope you can see why he might not think much of your answer. > As I said above - for the specific feature in question, I don't > care enough for the feature itself. Python will be just as useful > to me with the feature as it is without. I'm sure that's true of lots of modules. If you're the sole maintainer of the Python distro, then you have to evaluate every module that anyone submits. But since you're part of a reasonable sized group, I think it's best to examine the modules you care about, but don't feel that you have to have your hands in everything. From korimort at aon.at Wed Jan 12 08:13:00 2005 From: korimort at aon.at (Thomas Korimort) Date: Wed, 12 Jan 2005 14:13:00 +0100 Subject: how to visualize symbol table? Message-ID: <41e5220c$0$15240$91cee783@newsreader01.highway.telekom.at> Hi, how can i visualize the content of the symbol table in Python? Sometimes i want to know which symbols are imported from apackage and such kind of things Greetings, THomas Korimort From michele.simionato at gmail.com Tue Jan 11 04:15:00 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 11 Jan 2005 01:15:00 -0800 Subject: Python & unicode In-Reply-To: <1105434532.132061.24030@f14g2000cwb.googlegroups.com> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> <1105434532.132061.24030@f14g2000cwb.googlegroups.com> Message-ID: <1105434900.511862.54740@f14g2000cwb.googlegroups.com> I forgot to add the following: >>> setattr(C, "?", u"The letter ?") >>> getattr(C, "?") u'The letter \xe8' >>> print getattr(C, "?") The letter ? Python identifiers can be generic strings, including Latin-1 characters; they cannot be unicode strings, however: >>> setattr(C, u"?", "The letter ?") Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 0: ordinal not in range(128) So you are right after all, but I though most people didn't know that you can have valid identifiers with accented letters, spaces, and non printable chars. > setattr(C, " ", "this works") > getattr(C, " ") Michele Simionato From google-groups at slippytoad.com Thu Jan 13 16:57:56 2005 From: google-groups at slippytoad.com (Nick Atkins) Date: 13 Jan 2005 13:57:56 -0800 Subject: Pygtk: How to remove title bar from a window Message-ID: <1105653476.254139.58810@f14g2000cwb.googlegroups.com> Hi all, I am writing an application using pyGTK that has several pop-up dialogs that show and hide in succession. I would like to prevent the user from closing the dialog and if possible I'd like to use a "title bar-less" window with a normal border so the X is not even available to click. Is this possible? I have tried using window.set_decorated(FALSE) but this also removes the border making the window look quite strange. Thanks, Nick. From ken at switchboard.ericsson.se Fri Jan 28 09:09:27 2005 From: ken at switchboard.ericsson.se (Kenneth Johansson) Date: Fri, 28 Jan 2005 15:09:27 +0100 Subject: Profiling python 2.3 References: Message-ID: On Fri, 28 Jan 2005 10:02:33 +0000, Stephen Kellett wrote: > In message , Kenneth > Johansson writes >>I wonder what would be a good way to profile a python program where the >>main thread starts two worker threads that do all the work. >> >>I get no infomation at all from the threads. > > Python Performance Validator (beta) > > http://www.softwareverify.com/pythonPerformanceValidator/index.html > > Stephen I develop on linux. Nice to see I do not have to recompile and relink to use the tool that's a real problem with other python stuff ;) From bokr at oz.net Sun Jan 9 16:12:08 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 09 Jan 2005 21:12:08 GMT Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> Message-ID: <41e19e14.427486833@news.oz.net> On 09 Jan 2005 03:10:15 -0800, Paul Rubin wrote: >Nick Coghlan writes: >> Trying to push it a level further (down to expressions) would, IMO, be >> a lot of effort for something which would hurt readability a lot. > >I think we should just try to do things in a simple and general way >and not try to enforce readability. For example, the >slightly-overcomplex code that I proposed might have been generated by >a macro, or even by a compiler from some other language. No human >would ever have to look at it, so it doesn't matter whether it's >easily readable. There's no reason to add needless constraints on the >language just to make writing ugly code difficult. The main goal >should be to make writing clear code easy, not to worry about whether >someone might also write ugly code. +1 ;-) Regards, Bengt Richter From pythongnome at hotmail.com Tue Jan 11 17:29:29 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Tue, 11 Jan 2005 22:29:29 GMT Subject: Game programming in Python In-Reply-To: References: Message-ID: Baza wrote: > I'm looking for any books or on-line resources on game programming using > Python. Does anyone have any advice? > -- > Computer says, 'no' > > www.panda3d.com, www.pygame.org, www.blender3d.com ... From skip at pobox.com Thu Jan 20 09:26:12 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 20 Jan 2005 08:26:12 -0600 Subject: Zen of Python In-Reply-To: <972ec5bd0501191641166972b0@mail.gmail.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> Message-ID: <16879.49028.243445.847968@montanaro.dyndns.org> >> The gist of "Flat is better than nested" is "be as nested as you have >> to be, no more," because being too nested is just a mess. Tim> Which I agree with, and which makes sense. However your "gist" is a Tim> different meaning. Not if you conflate "Flat is better than nested" with "Namespaces are one honking great idea -- let's do more of those!". seek-balance-in-all-things-my-son-ly, y'rs, Skip From mesteve_bpleaseremovethis at hotmail.com Sun Jan 2 17:16:50 2005 From: mesteve_bpleaseremovethis at hotmail.com (StvB) Date: Sun, 02 Jan 2005 22:16:50 GMT Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: The way that Paul Graham sees Lisp: ($$$$$$$$$$$$)))yes!))))) ) "Roy Smith" wrote in message news:roy-D9F00D.12570402012005 at reader1.panix.com... > In article , > Ron Garret wrote: > >> In article <1104657461.868175.252380 at c13g2000cwb.googlegroups.com>, >> "Erik Bethke" wrote: >> >> > >> > I have NEVER experienced this kind of programming joy. >> >> Just wait until you discover Lisp! >> >> ;-) >> >> rg > > Shouldn't that be ;-)))))))))))))) ? From python at hope.cz Mon Jan 17 14:12:09 2005 From: python at hope.cz (python at hope.cz) Date: 17 Jan 2005 11:12:09 -0800 Subject: How to prevent the script from stopping before it should In-Reply-To: References: <1105981979.853318.269300@c13g2000cwb.googlegroups.com> <1105982387.852448.298900@c13g2000cwb.googlegroups.com> Message-ID: <1105989129.404687.140070@c13g2000cwb.googlegroups.com> Steve Holden wrote: > wittempj at hotmail.com wrote: > > > #import urllib, sys > > #pages = ['http://www.python.org', 'http://xxx'] > > #for i in pages: > > # try: > > # u = urllib.urlopen(i) > > # print u.geturl() > > # except Exception, e: > > # print >> sys.stderr, '%s: %s' % (e.__class__.__name__, e) > > will print an error if a page fails opening, rest opens fine > > > More generally you may wish to use the timeout features of TCP sockets. > These were introduced in Python 2.3, though Tim O'Malley's module > "timeoutsocket" (which was the inspiration for the 2.3 upgrade) was > available for earlier versions. > > You will need to import the socket module and then call > socket.setdefaulttimeout() to ensure that communication with > non-responsive servers results in a socket exception that you can trap. > > 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 Thank you wittempj at hotmail.com and Steve for some ideas.Finding the fact that the script hanged is not a big problem . I,however, would need a solution that I will not need to start again the script but the script re-start by itself. I am thinking about two threads, the main(master) that will supervise a slave thread.This slave thread will download the pages and whenever there is a timeout the master thread restart a slave thread. Is it a good solution? Or is there a better one? Thanks for help Lad From sjmachin at lexicon.net Mon Jan 24 15:56:04 2005 From: sjmachin at lexicon.net (John Machin) Date: 24 Jan 2005 12:56:04 -0800 Subject: "bad argument type for built-in operation" References: Message-ID: <1106600164.016115.24660@c13g2000cwb.googlegroups.com> Gilles Arnaud wrote: > Hello, > > I've got a nasty bug and no idea to deal with : > > here is the method : Big snip. The Python code is unlikely to be your problem. > and the trace > > in None [(-2.0, 2.0), (-2.0, 2.0)] [0.1385039192456847, > 0.87787941093093491] 2 2 > [0.1385039192456847, 0.87787941093093491] That's a very mangled trace! > the first call of the methode succeed > all following call failed. So the first call is leaving a bomb behind. > > I've got different scenario which call this low level methode, > many succeed, some failed this way. > > what's happened ? > If someone got an idea ? > what can raise this exception ? At this stage, without the benefit of look-ahead, one could only blame gamma rays or pointy-eared aliens :-) > > My program is written partially in python and partially in C. > the top level is in python which call a C optimisation routine > which use a callback (PyObject_CallMethod) to evaluate the cost in > python again. Aha! *Now* you tell us. *You* have "denormalised" the stack. Read your C code carefully. Use a debugger, or put some "printf()" in it. With PyObject_CallMethod, do the format descriptors and the arguments match? Are you testing the returned value for NULL and acting accordingly? Is the called-from-C Python method ever executed? Try putting a print statement (that shows the args) at the top. More generally, are you testing the returned value from each and every C API call? Are you testing for the correct error value (some return NULL, some -1, ...)? Are you doing the right thing on error? A catalogue of the different ways of messing things up using C would take forever to write. If you can't find your problem, post the code, either on the newsgroup or as a web page. Hope this helps, John From sjmachin at lexicon.net Tue Jan 11 20:47:36 2005 From: sjmachin at lexicon.net (John Machin) Date: 11 Jan 2005 17:47:36 -0800 Subject: SciTe In-Reply-To: <58%Ed.4827$C52.2609@newsread2.news.atl.earthlink.net> References: <58%Ed.4827$C52.2609@newsread2.news.atl.earthlink.net> Message-ID: <1105494456.015733.275590@f14g2000cwb.googlegroups.com> Lucas Raab wrote: > I didn't want to go through the rigamole of adding myself to the SciTe > mailing list, so I'm asking my question here. How do I choose a > different C/C++ compiler to compile in?? I don't use the g++ compiler; I > use the VC 7 compiler. > > TIA, > Lucas How the @#$% should we know? Don't be lazy; join the SciTe mailing list!!! From bulba at bulba.com Sat Jan 8 20:48:49 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 09 Jan 2005 02:48:49 +0100 Subject: windows mem leak References: <41XDd.70234$Jk5.40626@lakeread01> Message-ID: On Sat, 08 Jan 2005 15:00:05 -0500, Steve Holden wrote: >> Does the Win32 port of Python have a memory leak? I have some code that >> runs flawlessly on Linux, but bombs after a few hours on Windows. It's >> threaded and uses a lot of memory. >Yes, that's a well-known problem. Code that runs with a few errors will >port without any trouble at all to Windows, but once it runs flawlessly >on Linux it starts to leak memory on Windows. The PSU suspects a plot in >Redmond, the basic details of which ar You have my nomination for SOTW*. :-) * skit of the week / short story of the week -- It's a man's life in a Python Programming Association. From http Mon Jan 10 19:35:46 2005 From: http (Paul Rubin) Date: 10 Jan 2005 16:35:46 -0800 Subject: Writing huge Sets() to disk References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <7xmzvgren6.fsf@ruckus.brouhaha.com> Message-ID: <7xis64ree5.fsf@ruckus.brouhaha.com> Paul Rubin writes: > handle with builtin Python operations without putting some thought > into algorithms and data structures. From "ribosome" I'm guessing > you're doing computational biology. If you're going to be writing > code for these kinds of problems on a regular basis, you probably > ought to read a book or two on the topic. "CLRS" is a good choice: > > http://theory.lcs.mit.edu/~clr/ > http://mitpress.mit.edu/algorithms/ Correction to unclarity: I meant a book on the topic of algorithms and data structures (e.g. CLRS). Since you're presumably already a biologist, I wouldn't presume to suggest that you read a book on biology ;-). From godoy at ieee.org Wed Jan 19 10:45:23 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Wed, 19 Jan 2005 13:45:23 -0200 Subject: Accessing MDB files on Windows Message-ID: <1635068.ZTfiooUzB4@strongwill.g2ctech> Hi, What is the best way to deal with MDB files? I was thinking on using ODBC... I'll need to read and write some information to it. The load won't be so high, but there might be a lot of data. Any advices? Will my approach work? I'm not a Windows guy... :-) -- Godoy. From abpillai at gmail.com Thu Jan 6 05:24:35 2005 From: abpillai at gmail.com (Anand) Date: 6 Jan 2005 02:24:35 -0800 Subject: Contributor's List In-Reply-To: <1105006211.527899.318740@c13g2000cwb.googlegroups.com> References: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> <1105006211.527899.318740@c13g2000cwb.googlegroups.com> Message-ID: <1105007075.090543.47370@c13g2000cwb.googlegroups.com> I have no idea. I am just another contributor like you. Just doing a service to the Python community by providing the list at my site. However, I am not responsible for its content. Please direct your queries to the editors, if any. Thanks -Anand From sjmachin at lexicon.net Thu Jan 20 19:34:51 2005 From: sjmachin at lexicon.net (John Machin) Date: 20 Jan 2005 16:34:51 -0800 Subject: why no time() + timedelta() ? In-Reply-To: References: Message-ID: <1106267691.485671.45380@c13g2000cwb.googlegroups.com> Tim Peters wrote: > [josh] > > Why can't timedelta arithmetic be done on time objects? > > Obviously, because it's not implemented . > > > (e.g. datetime.time(5)-datetime.timedelta(microseconds=3) > > > > Nonzero "days" of the timedelta could either be ignored, or > > trigger an exception. > > And if the result is less than 0, or >= 24 hours, it could raise > OverflowError, or wrap around mod 24*60*60*1000000 microseconds, and > so on. There are so many arbitrary endcases that no agreement could > be reached on what they "should" do. So it's not supported at all. > In contrast, it was much easier to reach consensus on what datetime > arithmetic should do, so that was supported. Reminds me of the debate at the time whether "add months" functionality should be provided. Disagreement, including someone who shall remain nameless opining that Jan 31 + one month should return Mar 3 (or Mar 2 in a leap year). Not supported at all. Those of us who dabble in arcane esoterica like payrolls, pensions, mortgages, insurance, and government bloody regulations had a quick ROTFL and started typing: class RealWorldDateFunctionality(datetime.date): ... From steve at holdenweb.com Mon Jan 10 05:28:44 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Jan 2005 05:28:44 -0500 Subject: Python serial data aquisition In-Reply-To: References: <41e1b833$1_3@omega.dimensional.com> Message-ID: Flavio codeco coelho wrote: > mfuhr at fuhr.org (Michael Fuhr) wrote in message news:<41e1b833$1_3 at omega.dimensional.com>... > >>If the actual byte and/or bit order is different then you'll have >>to modify the expression, but this should at least give you ideas. > > > Thanks Michael and Steve, > > I'll put your Ideas to the test ASAP, meanwhile, could you point me to > references to these bit operations in Python? I am new to this stuff, > and might need to do more of this to support other hardware... > > I havent been able to find anything about this on the python > documentation.. > > Thanks a lot!! > > Flavio ord() is documented in section 2.1 of the library reference manual (Built-in Functions) - see http://docs.python.org/lib/built-in-funcs.html#l2h-53 for further information. Bitstring operations are at http://docs.python.org/lib/bitstring-ops.html#l2h-150 Hope this helps. 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 sjmachin at lexicon.net Sun Jan 2 21:28:52 2005 From: sjmachin at lexicon.net (John Machin) Date: 2 Jan 2005 18:28:52 -0800 Subject: Calling Function Without Parentheses! References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> Message-ID: <1104719332.876804.193020@c13g2000cwb.googlegroups.com> Kamilche wrote: > What a debug nightmare! I just spent HOURS running my script through > the debugger, sprinkling in log statements, and the like, tracking down > my problem. > > I called a function without the ending parentheses. I sure do WISH > Python would trap it when I try to do the following: > MyFunc > > instead of: > > MyFunc() > > aaaaaaaaaaaah. Aaaaaaaaaaaah indeed. You must be using an extremely old version of pychecker. The version I have in my Python22 directory gave the same results as the current one; see below. C:\junk>type noparens.py [bangs inserted to defeat Google's lstrip() !def bar(): ! foo !def foo(): ! alist = [] ! alist.sort C:\junk>pychecker noparens.py C:\junk>c:\python24\python.exe c:\python22\Lib\site-packages\pychecker\checker.py noparens.py Processing noparens... Warnings... noparens.py:2: Statement appears to have no effect noparens.py:5: Statement appears to have no effect From tom at dtsam.com Tue Jan 18 18:33:14 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Tue, 18 Jan 2005 17:33:14 -0600 Subject: simultaneous multiple requests to very simple database References: Message-ID: "Eric S. Johansson" wrote in message news:mailman.871.1106087623.22381.python-list at python.org... > 99.9 percent of what I do (and I suspect this could be true for others) > could be satisfied by a slightly enhanced super dictionary with a record > level locking. BUT - Did you not mention! : > Estimated number of records will be in the ballpark of 50,000 to 100,000 in his > early phase and 10 times that in the future. Each record will run about > 100 to 150 bytes. . And > The very large dictionary must be accessed from > multiple processes simultaneously And > I need to be able to lock records > within the very large dictionary when records are written to And > although I must complete processing in less than 90 seconds. And - the hole in the bottom of the hull - all of the above using "a slightly enhanced super dictionary". *Super* dictionary??? *Slightly* enhanced??? Have you attempted any feasability tests? Are you running a Cray? There are many database systems available, and Python (probably) has free bindings to every one of them. Whichever one might choose, it would add simplicity, not complexity to what you are attempting. The problems you mention are precisely those that databases are meant to solve. The only tough (impossible?) requirement you have is that you don't want to use one. When you write that "super dictionary", be sure to post code! I could use one of those myself. Thomas Bartkus From deetsNOSPAM at web.de Thu Jan 13 07:36:36 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 13 Jan 2005 13:36:36 +0100 Subject: Unclear On Class Variables References: Message-ID: <34n8a5F4dec78U2@individual.net> Tim Daneliuk wrote: > I am a bit confused. I was under the impression that: > > class foo(object): > x = 0 > y = 1 > > means that x and y are variables shared by all instances of a class. > But when I run this against two instances of foo, and set the values > of x and y, they are indeed unique to the *instance* rather than the > class. > > It is late and I am probably missing the obvious. Enlightenment > appreciated ... Without actual code how you set the vars, no one can answer that question. -- Regards, Diez B. Roggisch From aleaxit at yahoo.com Sun Jan 2 17:25:47 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 2 Jan 2005 23:25:47 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> Message-ID: <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> Roy Smith wrote: > Stefan Axelsson wrote: > > Yes, ignoring most of the debate about static vs. dynamic typing, I've > > also longed for 'use strict'. > > You can use __slots__ to get the effect you're after. Well, sort of; it > only works for instance variables, not locals. And the gurus will argue > that __slots__ wasn't intended for that, so you shouldn't do it. There's a simple, excellent recipe by Michele Simionato, on both the online and forthcoming 2nd edition printed Cookbook, showing how to do that the right way -- with __setattr__ -- rather than with __slots__ . Alex From tmj at SPAMLESSjarmania.com Sun Jan 2 17:14:08 2005 From: tmj at SPAMLESSjarmania.com (Tim Jarman) Date: Sun, 02 Jan 2005 22:14:08 +0000 Subject: How to make executable file ? References: <33r5gcF449bt0U1@individual.net> <41d868ff@news.unimelb.edu.au> Message-ID: <33ra0eF42g7qiU1@individual.net> Maurice LING wrote: > Hi all, > > This may be OT but is there a way to do the same for *nix type of > system? Like cast a python interpreter with scripts together? > > I'm running Mac OSX here. > For OSX, google for py2app - for *nix in general, I believe freeze is your mman, although so many *nixen ship with Python these days it's not such an issue. -- Website: www DOT jarmania FULLSTOP com From kp8 at mac.com Tue Jan 11 15:15:24 2005 From: kp8 at mac.com (kpp9c) Date: 11 Jan 2005 12:15:24 -0800 Subject: Time script help sought! In-Reply-To: <1105471266.880133.318470@c13g2000cwb.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> Message-ID: <1105474524.083536.129220@f14g2000cwb.googlegroups.com> Thanks for this Everyone! Trying to work with all the stuff folks are giving me on this i a have come across a problem... down the line i notice that some of the times will also have an hour as well as in H:M:S (e.g. 1:22:40) so in some cases i would need to convert H:M:S to sec and some just M:S or should there just be a fun that passes all the times and converts them to H:M:S first and just appends a 00: ((e.g. 00:02:07) if there is no hour value? cheers, -kp From __peter__ at web.de Tue Jan 11 08:40:14 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Jan 2005 14:40:14 +0100 Subject: Exception not captured References: Message-ID: Miki Tebeka wrote: > Hello All, > > Can someone please explain how is the following code fragment possible? > (If you're interested I can place the whole project somewhere). > > def checkout(dest, log): > '''Get latest version from SCM > > client - SCM client to use > dest - Destination directory > ''' > try: > SCM.checkout(dest, log) > except SCMError, e: > raise NightlyError("Checkout") > except Exception, e: > import inspect > file = inspect.getsourcefile(e.__class__) > line = inspect.getsourcelines(e.__class__)[1] > print "%s:%d" % (file, line) > file = inspect.getsourcefile(SCMError) > line = inspect.getsourcelines(SCMError)[1] > print "%s:%d" % (file, line) > print SCMError is e.__class__ > raise SystemExit > > I get to the second "except" clause, and the printout is: > /home/mikit/work/nightly/scm/common.py:3 > /home/mikit/work/nightly/scm/common.py:3 > False > > How is this possible? Some kind of duplicate import, maybe? E.g.: >>> import sys >>> import inspect >>> getsource = inspect.getsource >>> del sys.modules["inspect"] >>> import inspect >>> getsource is inspect.getsource False Peter From apardon at forel.vub.ac.be Thu Jan 13 07:53:55 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 12:53:55 GMT Subject: lambda References: Message-ID: Op 2005-01-13, Tim Leslie schreef : > Because if it takes more than a single line it deserves a name. So if I have a call with an expression that takes more than one line, I should assign the expression to a variable and use the variable in the call? But wait if I do that, people will tell me how bad that it is, because it will keep a reference to the value which will prevent the garbage collector from harvesting this memory. Besides python allows more than one statement on the same line. -- Antoon Pardon From philippecmartin at sbcglobal.net Tue Jan 11 01:32:26 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Tue, 11 Jan 2005 07:32:26 +0100 Subject: fetching method names from a class, and the parameter list from a methodRe: fetching method names from a class, and the parameter list from a method Message-ID: <1105425146.6920.3.camel@localhost> >>> import inspect >>> help(inspect) Thanks, I have not seen the func params yet, but the default values are so .... Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From aahz at pythoncraft.com Mon Jan 31 16:20:59 2005 From: aahz at pythoncraft.com (Aahz) Date: 31 Jan 2005 16:20:59 -0500 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> Message-ID: In article <1gr98se.102e9b1qnsknwN%aleaxit at yahoo.com>, Alex Martelli wrote: > >Some people claim a language should change the way you think -- a >frequent poster, excellent Python contributor, and friend, even has that >claim in his signature. Generally speaking, I change my .sig either when I get bored or when someone references it. So here's the new one. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. 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 From frans.englich at telia.com Mon Jan 31 23:17:10 2005 From: frans.englich at telia.com (Frans Englich) Date: Tue, 1 Feb 2005 04:17:10 +0000 Subject: Python's idiom for function overloads Message-ID: <200502010417.10481.frans.englich@telia.com> Hello, Since Python doesn't have static typing, how is the same result as traditional function overloads results in acheived? With function overloads the "selection of code path depending on data type" is transparent and automatic since the typing system figure out what goes to what. 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? Cheers, Frans From peter at somewhere.com Thu Jan 13 09:58:03 2005 From: peter at somewhere.com (Peter Maas) Date: Thu, 13 Jan 2005 15:58:03 +0100 Subject: [perl-python] 20050112 while statement In-Reply-To: References: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> Message-ID: brianr at liffe.com schrieb: > "Xah Lee" writes: [...] > (As a matter of interest, is this sequence of posts intended to > demonstrate ignorance of both languages, or just one?) :) This sequence of posts is intended to stir up a debate just for the sake of a debate. It's a time sink. It's up to you wether you want to post to this thread or do something useful. :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From andreasp at qbcon.com Fri Jan 28 02:16:38 2005 From: andreasp at qbcon.com (Andreas Pauley) Date: Fri, 28 Jan 2005 09:16:38 +0200 (SAST) Subject: Point of Sale In-Reply-To: <41F9193B.7090801@tokenexchange.com> References: <41F9193B.7090801@tokenexchange.com> Message-ID: On Thu, 27 Jan 2005, Evan Simpson wrote: > You may want to check out the Spread Toolkit, at www.spread.org, whose Python > wrapper lives at http://www.python.org/other/spread/doc.html. It's used by > the Zope Replication Service, for example. > > Cheers, > > Evan @ 4-am Thanks a lot, I need components like these desperately. I've also seen ICE from ZeroC (www.zeroc.com) and OSE (http://ose.sourceforge.net/browse.php?group=python-manual&entry=modules.htm) I haven't tried any of them yet, will have to do that a bit later. Andreas From itsme at yahoo.com Fri Jan 14 16:32:09 2005 From: itsme at yahoo.com (It's me) Date: Fri, 14 Jan 2005 21:32:09 GMT Subject: Why would I get a TypeEror? References: <34ql1vF4dqd9pU1@individual.net> Message-ID: Say again??? "Reinhold Birkenfeld" wrote in message news:34ql1vF4dqd9pU1 at individual.net... > It's me wrote: > > Sorry if my question was a little "lazy" and yes, I was asking about the > > "lazy evaluation". :=) > > > > I am surprised about this (and this can be dangerous, I guess). > > > > If this is true, I would run into trouble real quick if I do a: > > > > (1/x,1.0e99)[x==0] > > > > and that's not good. > > > > Something to keep in mind. :-( > > Lazy evaluation: use the (x==0 and 1e99 or 1/x) form! > > Reinhold From itsme at yahoo.com Mon Jan 3 13:56:20 2005 From: itsme at yahoo.com (It's me) Date: Mon, 03 Jan 2005 18:56:20 GMT Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: "Richards Noah (IFR LIT MET)" wrote in message news:crbur8$edu$1 at athen03.muc.infineon.com... > > Begging your pardon, but a better resource would be the brochure available > (http://www.pti-us.com/PTI/company/brochures/PSSE.pdf). It appears that the > program was probably (originally) written in C/C++ (using MFC for the GUI), > and now employs Python for adding modules and scripting support. Very > interesting stuff :) > > It was actually developed in Fortran some 35 years ago. Then migrated to F77. Then added a C/C++ layer to sit ontop. Then converted to API based. Then added a Python layer on top. The only thing unfortunate is that they went with MFC on the newest version. Yuck! From ville at spammers.com Mon Jan 17 07:35:02 2005 From: ville at spammers.com (Ville Vainio) Date: 17 Jan 2005 14:35:02 +0200 Subject: OCAMl a more natural extension language for python? References: Message-ID: >>>>> "Jelle" == Jelle Feringa // EZCT / Paris writes: Jelle> After reading about extending python with C/Fortran in the Jelle> excellent Python Scripting for Computational Science book Jelle> by Hans Langtangen, I'm wondering whether there's not a Jelle> more pythonic way of extending python. And frankly I think Jelle> there is: OCAML For many tasks the point of "extending" python is to gain access to libraries that have a C/C++ API. Extensions that merely provide a faster way to do something are much rarer. -- Ville Vainio http://tinyurl.com/2prnb From philippecmartin at sbcglobal.net Mon Jan 17 15:28:17 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 17 Jan 2005 21:28:17 +0100 Subject: how to find site-packages path (Michael Hoffman) - use distutils Message-ID: <1105993697.6720.3.camel@localhost> >>The flawless way would be to use distutils. In fact you shouldn't even >>need your own install script--it should do most of the work for you. The reason I have not so far is I have not found a way to get what I want done: 1) create directories in site-packages (I gather this shoudl be easy enough) 2) copy already compiled (.pyc) and source (.py) files to those directories 3) create directories and copy files in a directory kept in an environment variable Can distutils do this for me ? Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From lonetwin at gmail.com Sat Jan 29 08:35:55 2005 From: lonetwin at gmail.com (Steve) Date: Sat, 29 Jan 2005 19:05:55 +0530 Subject: The next Xah-lee post contest Message-ID: <5a309bd305012905357e14df62@mail.gmail.com> Hi All, For sometime now, I have just been a passive lurker on this list. Of late I saw an increase in the number of posts by Xah Lee, and I have to admit, what he lacks in understanding of the various programming languages he talks about, he makes up for in creativity. So, I was wondering, how would it be to be Mr Lee. That got me thinking of his next post. Well, I know through my days of lurking around, a lot of people here love creative challenges ...so here's one for you. Write up the next Xah Lee post ! The requirement are: a) The post should talk about a single language, although the example code needn't adhere to that restriction. b) It should explain the style, structure and design of some code snippet/program, though not necessarily of the same code snippet/program mentioned in the post. c) Should be written in English ... respect to English grammar is not mandatory. d) It *must* be flammable. Here's my contribution (tho' I'm not really in my most creative frame of mind): -------------------------------------------------- perl is fucked ! Its a language named with a word that can't even pass through spell-checker. What kind of programming language has a scalar variable but the array is not called vector ...it is array. Also the list comprehension feature of the language is entirely anal. Example $list = { i for i in range(100) } now is $list a function ?? No it's is an array ..... -------------------------------------------------- ..phew, this is hard !! I'll have another go later. You are welcomed to participate. Regards Steve From http Thu Jan 13 18:06:35 2005 From: http (Paul Rubin) Date: 13 Jan 2005 15:06:35 -0800 Subject: newbie ?s References: <1105656971.768148@sj-nntpcache-5> Message-ID: <7xekgpgc90.fsf@ruckus.brouhaha.com> "Venkat B" writes: > I'm looking build a CGI-capable SSL-enabled web-server around Python 2.4 on > Linux. > It is to handle ~25 hits possibly arriving "at once". Content is non-static > and built by the execution of py cgi-scripts talking to a few backend > processes. > > 1) I was wondering if anyone has opinions on the ability of CGIHTTPServer (a > forking variant) to be able to handle this. Why not use apache? > 2) If so, would something like pyOpenSSL be useful to make such a webserver > SSL-enabled. I haven't used pyOpenSSL but I don't see any other way to do it. Well maybe mxCrypto which I haven't used either. The SSL socket library doesn't understand certificates. From franco.fiorese at tin.it Fri Jan 28 15:53:42 2005 From: franco.fiorese at tin.it (Franco Fiorese) Date: Fri, 28 Jan 2005 20:53:42 GMT Subject: Pystone benchmark: Win vs. Linux (again) Message-ID: Hi all, I am relatively new about Python benchmarks. After some experiments I found that Python on my PC Windows XP has a relevant higher performance than on Linux. The simple test using pystone.py shows this: * Windows XP Pro: 16566.7 pystones/second * Linux (kernel 2.6.9 NPTL): 12346.2 pystones/second I have repeated the test, on Linux, also with other distributions and kernel but a relevant difference still exists with Windows offering a better performance. Is there any way, that you know, to get better performance under Linux? regards Franco From ark at acm.org Sat Jan 22 11:55:45 2005 From: ark at acm.org (Andrew Koenig) Date: Sat, 22 Jan 2005 16:55:45 GMT Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <7xu0p9lk4h.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xu0p9lk4h.fsf at ruckus.brouhaha.com... > It's really irrelevant whether anyone is using a feature or not. If > the feature is documented as being available, it means that removing > it is an incompatible change that can break existing code which > currently conforms to the spec. If the "feature" is described as the > bug that it is, anything that relies on it is nonconformant. In this case, I think the right solution to the problem is two-fold: 1) from __future__ import lexical_comprehensions 2) If you don't import the feature, and you write a program that depends on a list-comprehension variable remaining in scope, the compiler should issue a diagnostic along the lines of Warning: This program should be taken out and shot. From cbfalconer at yahoo.com Sun Jan 23 05:47:10 2005 From: cbfalconer at yahoo.com (CBFalconer) Date: Sun, 23 Jan 2005 10:47:10 GMT Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: <41F37E6D.296D9EB1@yahoo.com> Xah Lee wrote: > ... snip ... > > the first paragraph of 9.1 "A Word About Terminology" is epitome > of masturbation. The entire 9.1 is not necessary. > > Large part of 9.2 "Python Scopes and Name Spaces" is again > masturbatory. PLONK for excessive OT crossposting and trolling. -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson From eurleif at ecritters.biz Mon Jan 10 18:40:11 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 10 Jan 2005 18:40:11 -0500 Subject: Python & unicode In-Reply-To: <10u6347j23enuc3@news.supernews.com> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> Message-ID: <34gi0fF4c1lntU1@individual.net> John Roth wrote: > It doesn't work because Python scripts must be in ASCII except for > the contents of string literals. Having a function name in anything > but ASCII isn't supported. To nit-pick a bit, identifiers can be in Unicode; they're simply confined to digits and plain Latin letters. From bulba at bulba.com Sun Jan 2 12:23:13 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 02 Jan 2005 18:23:13 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <63bgt0dsj237t5j08jo895emj15p2tkl2s@4ax.com> On Fri, 31 Dec 2004 21:08:02 GMT, claird at lairds.us (Cameron Laird) wrote: >Let me add a cautionary note, though: Big Companies, >including Oracle, Software AG, IBM, Cisco, and so on, have >adopted Tcl over and over. All of them still rely on Tcl >for crucial products. All of them also have employees who >sincerely wonder, "Tcl? Isn't that dead?" >I offer this as a counter-example to the belief that Adop- >tion by a heavyweight necessarily results in widespread >acceptance. It's a quiet adoption. It's not a firework show a la Java combined with blowing all those truckloads of money on it (I've read this good comment in one of the IT periodicals that in future Java will be cited as an example of work of genius - not a genius of computing, though, but of marketing). There is a rational element in this craziness: people around watch and see that $$$ has been sunk in this, so they know that this who sank all those $$$ has very, very much of motivation not to let this thing wither away. No guarantee, of course, but a much better chance they just won't drop it. The problem of Python is not that it's not used, but because some company like IBM didn't decide to blow $1 bln on it or smth. Using it alone and even announcing it is not enough. "put your money where your mouth is", or so the thinking goes. -- It's a man's life in a Python Programming Association. From letsgoloslos at yahoo.com Fri Jan 14 21:24:15 2005 From: letsgoloslos at yahoo.com (chrisg) Date: 14 Jan 2005 18:24:15 -0800 Subject: Threading Or Other Suggestions?!? References: Message-ID: <1105755855.294024.98420@c13g2000cwb.googlegroups.com> You could also use os.spawnl to launch it in a separate process. From fumanchu at amor.org Fri Jan 7 18:02:07 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 7 Jan 2005 15:02:07 -0800 Subject: Exception report library Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339813B@exchange.hqamor.amorhq.net> Ian Bicking wrote: > I've been using one of several systems to catch unexpected > exceptions and log them (e.g., write to a file, display on > web page, email me, etc). But many are built into a > particular system, or have an interesting but incomplete > set of features... > I feel like there must be something out there, since every Python > programmer has to deal with this sort of thing to some degree...? And I replied: > I feel that way, too, but haven't found it...If we could put our > many heads together, I think this would be doable for the stdlib. Ian: > I'm not optimistic about a good exception handler in the standard > library; development slows down a lot at that point, and it's not a > reasonable candidate until it is designed and used Sure; I understand it's a long process, and should start independently. Me again: > Here are the pieces of the framework, by the way, which might also > benefit from some standardization: > > 1. Thread-safe application state > 2. Logging (+ exception handling) > 3. Configuration data (reading from various sources) > 4. Registry of Workers for getting things done on a schedule, > possibly recurring > 5. Registry of startup/shutdown functions > 6. Registry of active user interfaces > > I think the first three are all good candidates for a standard. > If we had a standard, thread-safe Application object, the rest > could be registerable plugins for that. You'd basically register > callbacks for app.startup and .shutdown methods to iterate over. Ian: > Hmm... I'm confused by these bits. Are you talking about > libraries for other parts of a web framework, besides exception > handling? If so, you might want to look into WSGI... Those are the bits I pulled out as specifically non-web-specific, which could be used for any kind of app (and tend to get rewritten for every framework). If your app is single-process, multi-threaded, it needs a state manager so two threads don't load or destroy global resources simultaneously. Most apps need logging and uncaught exception handling (as you noticed). Etcetera. One way to meet these needs once-and-for-all would be to have a (eventually standard) library for them, where you could mix and match the pieces you needed. So, you could write WSGI consumers of them, but they wouldn't be WSGI-specific in my mind. If they were, they'd just add to the "several systems" you were lamenting... ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org From fredrik at pythonware.com Sun Jan 30 02:30:17 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Jan 2005 08:30:17 +0100 Subject: is this sort method the same as the one in python 2.4 References: Message-ID: Raymond Hettinger wrote: >> I'm trying to emulate the sorted() method introduced in python 2.4. The >> only difference is that it takes a sequence as one of its arguments >> rather than being a method of the sequence class. Does my method do the >> same as the sorted()? > > Almost. This is closer to the mark: > > def sorted(iterable, cmp=None, key=None, reverse=False): > "return a sorted copy of its input" > if sys.version_info >= (2,4): > return sorted(iterable, cmp, key, reverse) with your code print sorted([1, 2, 3]) gives me a traceback that ends with File "test.py", line 6, in sorted return sorted(iterable, cmp, key, reverse) File "test.py", line 6, in sorted return sorted(iterable, cmp, key, reverse) File "test.py", line 6, in sorted return sorted(iterable, cmp, key, reverse) File "test.py", line 5, in sorted if sys.version_info >= (2,4): RuntimeError: maximum recursion depth exceeded in cmp the recursion isn't really that hard to explain, but the runtime error doesn't really seem right... ::: to fix the recursion, move the if-statement so you only define the function if needed: if sys.version_info < (2,4): def sorted(...): .... From gabriel.barros at gmail.com Sat Jan 29 19:38:55 2005 From: gabriel.barros at gmail.com (Gabriel B.) Date: Sat, 29 Jan 2005 22:38:55 -0200 Subject: naive doc question Message-ID: <5175a81c050129163826fcd734@mail.gmail.com> Is it just me that can't find a full reference in the docs? I wanted a list of all the methods of dict for example... where can i find it? Thanks, and sorry if this question is just dumb, i really can't find it From PeterMayne at ap.spherion.com Wed Jan 12 19:21:29 2005 From: PeterMayne at ap.spherion.com (PJDM) Date: 12 Jan 2005 16:21:29 -0800 Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> Message-ID: <1105575689.335040.174490@c13g2000cwb.googlegroups.com> John Machin wrote: > > 1. Octal notation is of use to systems programmers on computers where > the number of bits in a word is a multiple of 3. Are there any still in > production use? AFAIK word sizes were 12, 24, 36, 48, and 60 bits -- > all multiples of 4, so hexadecimal could be used. The PDP-11 was 16 bit, but used octal. With eight registers and eight addressing modes in instructions, octal was a convenient base. (On the 11/70, the front switches were marked in alternate pink and purple groups of three. ) > I don't see any mention of octal in GvR's "Python Regrets" or AMK's > "PEP 3000". Why not? Is it not regretted? I suspect that, as in other places, Python just defers to the underlying implementation. Since the C libraries treat "0n" as octal, so does Python. (So does JavaScript.) More "it sucks, but it's too late to change" than regrets. Maybe P3K will have an integer literal like "n_b" for "the integer n in base b". PJDM From b_b at net.hr Mon Jan 24 11:06:52 2005 From: b_b at net.hr (Brane) Date: Mon, 24 Jan 2005 17:06:52 +0100 Subject: how to ncurses on win32 platform Message-ID: <3nkds3kzc9mp.18yfed1y3vo9d$.dlg@40tude.net> please advice regards brane From http Wed Jan 12 15:49:32 2005 From: http (Paul Rubin) Date: 12 Jan 2005 12:49:32 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> <7xekgr7lpy.fsf@ruckus.brouhaha.com> <7x4qhn9q3g.fsf@ruckus.brouhaha.com> <7xr7kq1rk6.fsf@ruckus.brouhaha.com> <7xvfa2toed.fsf@ruckus.brouhaha.com> Message-ID: <7xpt0a4bkz.fsf@ruckus.brouhaha.com> Ian Bicking writes: > That sounds like you'd be implementing your own filesystem ;) Yes, this shouldn't be any surprise. Implementing a special purpose file system what every database essentially does. > If you are just trying to avoid too many files in a directory, another > option is to put files in subdirectories like: > > base = struct.pack('i', hash(page_name)) > base = base.encode('base64').strip().strip('=') > filename = os.path.join(base, page_name) Using subdirectories certainly keeps directory size down, and it's a good idea for MoinMoin given the way MoinMoin uses the file system. But for really big wikis, I think using the file system like that isn't workable even with subdirectories. Plus, there's the issue of how to find backlinks and how to do full text search. From sjmachin at lexicon.net Sat Jan 15 19:42:55 2005 From: sjmachin at lexicon.net (John Machin) Date: 15 Jan 2005 16:42:55 -0800 Subject: How to del item of a list in loop? In-Reply-To: References: <34rvjqF4f6l70U1@individual.net> <34s7omF4emdsaU1@individual.net> Message-ID: <1105836175.289357.158650@z14g2000cwz.googlegroups.com> Nick Coghlan wrote: > > I think this is about the best you can do for an in-place version: > for i, x in enumerate(reversed(lst)): > if x == 2: > del lst[-i] Don't think, implement and measure. You may be surprised. Compare these two for example: !def method_del_bkwds(lst, x): ! for inx in xrange(len(lst) - 1, -1, -1): ! if lst[inx] == x: ! del lst[inx] ! return lst !def method_coghlan(lst, x): ! for i, obj in enumerate(reversed(lst)): ! if obj == x: ! del lst[-i] ! return lst > > The effbot's version is still going to be faster though: > lst = [x for x in lst if x != 2] Have you measured this? From belred at gmail.com Sun Jan 30 14:58:58 2005 From: belred at gmail.com (Bryan) Date: Sun, 30 Jan 2005 11:58:58 -0800 Subject: The next Xah-lee post contest In-Reply-To: <20050130114008.797088857.whereU@now.com> References: <20050130114008.797088857.whereU@now.com> Message-ID: Eric Pederson wrote: >>From: Arthur > > >>Not sure how Xah got himself into all this. > > > > One can easily see that Java programmers are geeks who secretly wanted to make the football team and are now trying to conform, ignoring their language's critical lack of Prolog syntax. Python coders, similarly, do not recognize that they may be violating several open source patents each time they write: "class(Object):", and both languages may become unusable when the Government changes the inheritance tax. > > Rather than throw stones or make fun, all but the closet Republicans should examine how poor Xah came to such a state of misunderstanding IPv8, and try to help him. > >>From Aahz tag line we have a clue: > > "19. A language that doesn't affect the way you think about programming,is not worth knowing." --Alan Perlis > > Further understanding will require research. Was it Perl that did this to Mr. Lee's brain, or perhaps it was trying to ascertain the web services "standard"? Was it a massive PHP program that simply grew beyond comprehendability and blew all normal circuits? Or perhaps an attempt to jump straight from Fortran 77 into Ruby? > > Perhaps we will never know the cause, but surely when the ill come to us we must prescribe something. > > Ah, perhaps if he will join us in a song we will all be OK: > > Python Choir: > Lee's a lumberjack, and he's OK, > He codes all night and he posts all day. > > XL: > I cut down trees, I eat my lunch, > I go to the lavatory. > On Wednesdays I go shopping, > And have buttered scones for tea. > > Python Choir: > Lee cuts down trees, He eats his lunch, > He goes to the lavatory. > On Wednesdays he goes shopping, > And have buttered scones for tea. > > Lees a lumberjack, and he's OK, > He codes all night and he posts all day. > > XL: > I cut down trees, I skip and jump, > I like to press wild flowers. > I put on women's clothing, > And hang around in bars. > > Python Choir: > Lee cuts down trees, he skips and jumps, > He likes to press wild flowers. > He puts on women's clothing > And hangs around.... In bars??????? > > > Well. At least I feel better. For now. > > > > /Eric - sentenced to re-learn and write an application in Perl 5.0 > What will that do to my mind? > > > 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 > ::::::::::::::::::::::::::::::::::: > oh great... now you just legend-ized him on this group forever :( From samantha7395 at hotmail.com Tue Jan 18 13:57:18 2005 From: samantha7395 at hotmail.com (Samantha) Date: Tue, 18 Jan 2005 10:57:18 -0800 Subject: Print to Windows default Printer References: Message-ID: <1e-dnYx8z5eTwXDcRVn-3g@adelphia.com> Thanks for he quick response. This is small sample code from a PSP script to get Exit Info of a digital image. I want to print to the printer rather than the screen. ------- Info = App.Do( Environment, 'ReturnImageInfo' ) print print 'Input Device Information' for key in InputDeviceKeys: if OnlyExistingData == 0 or Info[key] != '': print key, ': ', Info[key] print print 'Artist Information' for key in ArtistKeys: if OnlyExistingData == 0 or Info[key] != '': print key, ': ', Info[key] print ------ Is there an easy way to do it. Right now I copy and paste to a txt file then print the file? S "Peter Hansen" wrote in message news:v46dnZlNecChxXDcRVn-3A at powergate.ca... > Samantha wrote: >> I am new to Python and I am having considerable trouble trying to print >> (using a simple script) to the default printer rather than the screen. >> Thanks for any help. > > Please show some example code, and explain in more detail > what you are trying to do. There are perhaps *dozens* > of different ways to do printing under Windows, and we > can't guess which approach you are trying, nor which > might be suitable for your needs. > > -Peter From itoakya at yahoo.co.jp Sat Jan 8 17:12:30 2005 From: itoakya at yahoo.co.jp (AkioIto) Date: 8 Jan 2005 14:12:30 -0800 Subject: Ranting about the state of Python IDEs for Windows References: Message-ID: <1105222350.906941.83130@c13g2000cwb.googlegroups.com> Carlos Ribeiro wrote: > Oh well. A mailing list is not the most appropriate place for rants (a > blog is better), but it's still better than keeping it for myself. > > I'm frustrated. My search for a good IDE to support my activities -- > doing development for Python in the Windows environment -- are not > being succesful as I had originally dreamt. I have big constraints on > what can I do now; money is not an option, and my current machine is > still useful but it's below par for more advanced stuff. It's my > fault? Probably. But it's all that I have -- a 500MHz PC with 64MB and > Win98 SE. It has to be Windows, for reasons beyond my control (read > wife and kids :-). > Look at http://www.pspad.com/en/index.html. Very good and smart editor for Python and other languages. You even can set menu for brazillian portuguese! And it's free... "A dica vem com um certo atrazo, mas espero que seja util". From FBatista at uniFON.com.ar Mon Jan 17 12:20:13 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 17 Jan 2005 14:20:13 -0300 Subject: How to prevent the script from stopping before it should Message-ID: [python at hope.cz] #- I have a script that downloads some webpages.The problem is that, #- sometimes, after I download few pages the script hangs( stops). What do you mean with "hangs"? It raises an error and quit? It just stops doing nothing? If the latter, what prints if you hit ctrl-c? . 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 bulba at bulba.com Thu Jan 6 19:27:30 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 01:27:30 +0100 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <7xhdluxh4i.fsf@ruckus.brouhaha.com> Message-ID: On 06 Jan 2005 15:38:53 -0800, Paul Rubin wrote: >> Making derived work proprietary in no way implies that the base >> work is publicly unavailable anymore. >Since you want to be able to incorporate GPL code in your proprietary >products, Nope. That is not what I'm arguing. Really, I think you have jumped to conclusion about that: I merely pointed out that I don't like what I perceive as end effect of what GPL license writers are attempting to achieve: vendor lock-in. I think I stated that clearly. > and say there's no problem since the base work is still >available from the same places it was available from before, fairness >would say you shouldn't mind that people incorporate code from your >products into THEIR products, since your version is still available >from you. I merely pointed out that previous poster's argument about "hijacking" the OSS product: that it's just not possible as long as this person is not in legal position to make _base_ work proprietary. I think I stated clearly: base work is still available regardless of whatever derived work creators do or don't do - esp. that they tend to release only binaries, thus making it impossible to create further derived works! >From the viewpoint of looking at availability of source code A, it's completely irrelevant if those guys are fishmongers or make derived work A' and redistribute only binary of A'. Not a single line of publicly available source code appeared or disappeared as the result of whatever they do. Amounts of binaries - yes, that is affected. But not the source code. >Really, you're just a freeloader looking for handouts. Rest assured this is not my motivation, esp. that I attempt not to use the GPL-ed software whenever I reasonably can (e.g. it's rather hard to abstain from using gcc sometimes, as you oft have a hard time compiling this damn thing with anything else -- see, the beginnings of vendor lock-in appear). And I thought I stated clearly that basically I have no problem with LGPL - which requires distributing modifications of the _base_ work, but not _your_ code. Oh, and "freeloading" argument really doesn't make much sense: since that software is available to EVERYONE, its availability / unavailability in the economic sense it is merely reducing / increasing costs equally for everyone (ceteris paribus, assuming both vendor A and B find that OSS product equally useful). I like to think of OSS as a "tide that rises all boats". -- It's a man's life in a Python Programming Association. From aisaac0 at verizon.net Sat Jan 22 22:07:22 2005 From: aisaac0 at verizon.net (David Isaac) Date: Sun, 23 Jan 2005 03:07:22 GMT Subject: problems with duplicating and slicing an array References: <7cffadfa05012017337858d171@mail.gmail.com> <1106325711.782439.305360@c13g2000cwb.googlegroups.com> Message-ID: Yun Mao wrote: >a[ [1,0], [0,1] ] , which should give me >[[4, 5], [1,2]] Numeric: take(take(a,[1,0]),[0,1],1) fwiw, Alan Isaac From timr at probo.com Sat Jan 15 02:55:57 2005 From: timr at probo.com (Tim Roberts) Date: Fri, 14 Jan 2005 23:55:57 -0800 Subject: from __future__ import decorators References: Message-ID: Jacek Generowicz wrote: > >I have some code, which makes copious use of the @decorator syntax I'm very curious to know what kind of application you are writing in which "copious use of the @decorator syntax" actually solved a problem productively. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steven.bethard at gmail.com Sat Jan 1 20:04:06 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 02 Jan 2005 01:04:06 GMT Subject: PEP 288 ponderings Message-ID: PEP 288 was mentioned in one of the lambda threads and so I ended up reading it for the first time recently. I definitely don't like the idea of a magical __self__ variable that isn't declared anywhere. It also seemed to me like generator attributes don't really solve the problem very cleanly. An example from the PEP[1]: def mygen(): while True: print __self__.data yield None g = mygen() g.data = 1 g.next() # prints 1 g.data = 2 g.next() # prints 2 I looked in the archives but couldn't find a good discussion of why setting an attribute on the generator is preferable to passing the argument to next. Isn't this example basically equivalent to: class mygen(object): def next(self, data): print data return None g = mygen() g.next(1) # prints 1 g.next(2) # prints 2 Note that I didn't even define an __iter__ method since it's never used in the example. Another example from the PEP: def filelike(packagename, appendOrOverwrite): data = [] if appendOrOverwrite == 'w+': data.extend(packages[packagename]) try: while True: data.append(__self__.dat) yield None except FlushStream: packages[packagename] = data ostream = filelike('mydest','w') ostream.dat = firstdat; ostream.next() ostream.dat = firstdat; ostream.next() ostream.throw(FlushStream) This could be rewritten as: class filelike(object): def __init__(self, packagename, appendOrOverwrite): self.data = [] if appendOrOverwrite == 'w+': self.data.extend(packages[packagename]) def next(self, dat): self.data.append(dat) return None def close(self): packages[packagename] = self.data ostream = filelike('mydest','w') ostream.next(firstdat) ostream.next(firstdat) ostream.close() So, I guess I have two questions: (1) What's the benefit of the generator versions of these functions over the class-based versions? (2) Since in all the examples there's a one-to-one correlation between setting a generator attribute and calling the generator's next function, aren't these generator attribute assignments basically just trying to define the 'next' parameter list? If this is true, I would have expected that a more useful idiom would look something like: def mygen(): while True: data, = nextargs() print data yield None g = mygen() g.next(1) # prints 1 g.next(2) # prints 2 where the nextargs function retrieves the arguments of the most recent call to the generator's next function. With a little sys._getframe hack, you can basically get this behavior now: py> class gen(object): ... def __init__(self, gen): ... self.gen = gen ... def __iter__(self): ... return self ... def next(self, *args): ... return self.gen.next() ... @staticmethod ... def nextargs(): ... return sys._getframe(2).f_locals['args'] ... py> def mygen(): ... while True: ... data, = gen.nextargs() ... print data ... yield None ... py> g = gen(mygen()) py> g.next(1) 1 py> g.next(2) 2 Of course, it's still a little magical, but I think I like it a little better because you can see, looking only at 'mygen', when 'data' is likely to change value... Steve [1] http://www.python.org/peps/pep-0288.html From http Thu Jan 6 10:32:25 2005 From: http (Paul Rubin) Date: 06 Jan 2005 07:32:25 -0800 Subject: Embedding a restricted python interpreter References: Message-ID: <7xbrc2a7zq.fsf@ruckus.brouhaha.com> Jp Calderone writes: > A Python sandbox would be useful, but the hosting provider's excuse > for not allowing you to use mod_python is completely bogus. All the > necessary security tools for that situation are provided by the > platform in the form of process and user separation. But mod_python is an apache module and runs in the same apache process with other users' scripts. From JoshuaACohen at gmail.com Thu Jan 6 15:57:29 2005 From: JoshuaACohen at gmail.com (Josh) Date: 6 Jan 2005 12:57:29 -0800 Subject: File Handling Problems Python I/O In-Reply-To: <1105044049.815913.17830@z14g2000cwz.googlegroups.com> References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> <1105034789.700445.291380@z14g2000cwz.googlegroups.com> <1105043692.497106.315270@z14g2000cwz.googlegroups.com> <1105044049.815913.17830@z14g2000cwz.googlegroups.com> Message-ID: <1105045049.653794.96490@z14g2000cwz.googlegroups.com> Micheal, Thanks for the advice as the programming I am doing will be run on both Windows and Linux based PC's, that being the main reason for my venture into Python. I'm glad to see that people are willing to help out even the newbie's. Josh From jdhunter at ace.bsd.uchicago.edu Fri Jan 28 18:00:23 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 28 Jan 2005 17:00:23 -0600 Subject: LinearAlgebra incredibly slow for eigenvalue problems In-Reply-To: <1106952951.834888.65430@f14g2000cwb.googlegroups.com> ("drife"'s message of "28 Jan 2005 14:55:51 -0800") References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> <1106952951.834888.65430@f14g2000cwb.googlegroups.com> Message-ID: >>>>> "drife" == drife writes: drife> Hi David, I performed the above check, and sure enough, drife> Numeric is --not-- linked to the ATLAS libraries. drife> I followed each of your steps outlined above, and Numeric drife> still is not linking to the ATLAS libraries. drife> My setup.py file is attached below. Are you sure that you 1) 'rm -rf build' before rebuilding 2) are using the python / Numeric that you think you are, eg, might you have one python in /usr/bin and another in /usr/local. root paths can differ from user paths which may effect which python is used at install time versus run time From daranrife at yahoo.com Tue Jan 11 17:15:44 2005 From: daranrife at yahoo.com (drife) Date: 11 Jan 2005 14:15:44 -0800 Subject: Rotation of eigenvector matrix using the varimax method Message-ID: <1105481744.502108.19930@f14g2000cwb.googlegroups.com> Hello, Has anyone a Python script for rotating an eigenvector matrix using the varimax (or quartimax or other) methods? Thanks in advance for your help. Daran From "j.p.t.j.berends\" at (none)student.tudelft.nl Wed Jan 5 10:59:11 2005 From: "j.p.t.j.berends\" at (none)student.tudelft.nl (none) Date: Wed, 05 Jan 2005 16:59:11 +0100 Subject: get the IP address of a host Message-ID: I want to determine the outside (non local, a.k.a. 127.0.0.x) ip addresses of my host. It seems that the socket module provides me with some nifty tools for that but I cannot get it to work correctly it seems. Can someone enlightened show a light on this: import socket def getipaddr(hostname='default'): """Given a hostname, perform a standard (forward) lookup and return a list of IP addresses for that host.""" if hostname == 'default': hostname = socket.gethostname() ips = socket.gethostbyname_ex(hostname)[2] return [i for i in ips if i.split('.')[0] != '127'][0] It does not seem to work on all hosts. Sometimes socket.gethostbyname_ex only retrieves the 127.0.0.x ip adresses of the local loopback. Does someone has a more robust solution? Targetted OS'es are Windows AND linux/unix. From hancock at anansispaceworks.com Mon Jan 24 18:01:33 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 24 Jan 2005 17:01:33 -0600 Subject: Looking for Form Feeds In-Reply-To: <41F5696D.9030100@novasyshealth.com> References: <41F5696D.9030100@novasyshealth.com> Message-ID: <200501241701.33232.hancock@anansispaceworks.com> On Monday 24 January 2005 03:32 pm, Greg Lindstrom wrote: > I also tried to create a ^M^L (typed in as Q M L) but that > gives me a syntax error when I try to run the program (re does not like > the control characters, I guess). Is it possible for me to pull out the > formfeeds in a straightforward manner? I suspect you should convert that to hexadecimal codes: '\x0c\x0b' (at least I *think* those are the characters you mean, I'm not really familiar with the ^X notation). That would be the simplest solution, probably. Anytime I get into unprintable characters, I like to switch to hex. So you could just do something like: pages = open('myfile.dat', 'rb').read().split('\x0c\x0b') to load each page into a list, for example. HTH, Terry -- -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From kent3737 at yahoo.com Thu Jan 20 09:01:01 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Thu, 20 Jan 2005 09:01:01 -0500 Subject: xml parsing escape characters In-Reply-To: <359o5cF4il48kU1@individual.net> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> Message-ID: <41efb72d$1_2@newspeer2.tds.net> Luis P. Mendes wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > this is the xml document: > > > <DataSet> > ~ <Order> > ~ <Customer>439</Customer> > (... others ...) > ~ </Order> > </DataSet> This is an XML document containing a single tag, , whose content is text containing entity-escaped XML. This is *not* an XML document containing tags , , , etc. All the behaviour you are seeing is a consequence of this. You need to unescape the contents of the tag to be able to treat it as structured XML. Kent From abpillai at gmail.com Thu Jan 6 05:22:41 2005 From: abpillai at gmail.com (Anand) Date: 6 Jan 2005 02:22:41 -0800 Subject: Contributor's List In-Reply-To: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> References: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> Message-ID: <1105006961.413793.40760@c13g2000cwb.googlegroups.com> Please direct any query to the Cookbook editors. Thanks -Anand From kent3737 at yahoo.com Tue Jan 25 15:40:13 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Tue, 25 Jan 2005 15:40:13 -0500 Subject: Help with saving and restoring program state In-Reply-To: <85b54e91.0501241556.d281f90@posting.google.com> References: <85b54e91.0501241556.d281f90@posting.google.com> Message-ID: <41f6ac25$1_3@newspeer2.tds.net> Jacob H wrote: > Hello list... > > I'm developing an adventure game in Python (which of course is lots of > fun). One of the features is the ability to save games and restore the > saves later. I'm using the pickle module to implement this. Capturing > current program state and neatly replacing it later is proving to be > trickier than I first imagined, so I'm here to ask for a little > direction from wiser minds than mine! > > When my program initializes, each game object is stored in two places > -- the defining module, and in a list in another module. The following > example is not from my actual code, but what happens is the same. > > (code contained in "globalstate" module) > all_fruit = [] > > (code contained in "world" module) > class Apple(object): # the class hierarchy goes back to object, anyway > def __init__(self): > self.foo = 23 > self.bar = "something" > globalstate.all_fruit.append(self) > apple = Apple() > > I enjoy the convenience of being able to refer to the same apple > instance through world.apple or globalstate.all_fruit, the latter > coming into play when I write for loops and so on. When I update the > instance attributes in one place, the changes are reflected in the > other place. But now comes the save and restore game functions, which > again are simplified from my real code: My understanding of pickle is that it will correctly handle shared references in the saved data. So if you pack all your global dicts into one list and pickle that list, you will get what you want. See code changes below: > > (code contained in "saveload" module) > import pickle > import world import globalstate > def savegame(path_to_name): > world_data = {} > for attr, value in world.__dict__.items(): > # actual code is selective about which attributes > # from world it takes -- I'm just keeping this > # example simple > world_data[attr] = value the_whole_shebang = [ world_data, globalstate.all_fruit, globalstate.all_items ] > fp = open(path_to_name, "w") pickle.dump(the_whole_shebang, fp) > fp.close() > > def loadgame(path_to_name): > fp = open(path_to_name, "r") the_whole_shebang = pickle.load(fp) world_data, globalstate.all_fruit, globalstate.all_items = the_whole_shebang > for attr, value in world_data.items(): > setattr(world, attr, value) > fp.close() Kent From rkern at ucsd.edu Mon Jan 31 02:12:06 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 30 Jan 2005 23:12:06 -0800 Subject: Image stats - going from Matlab to Python In-Reply-To: <1107153660.431217.145160@f14g2000cwb.googlegroups.com> References: <1107153660.431217.145160@f14g2000cwb.googlegroups.com> Message-ID: tjv at hotmail.com wrote: > Hi all, > I am working with images in python using PIL. I come from a MATLAB > background so I am finding it to be sometimes frustrating to do things > correctly and quickly. Yup. That's the curse of changing toolsets. > All I need to do is load an image and store a > list of pixel coordinates at which the alpha channel is set to 1. > In Matlab this would be easy...Lets say we have a 2x2x4 array that > represents the image. I would just type something like: > > indices = find(im(:,:,3)==1); > > then work with indices to get xy coords. Is there a similar way to > accomplish the same thing in python and PIL without having a nested for > loop and checking every pixel? > I would appreciate advice. Thanks very much for your attention! One way would be to use Numeric or numarray, which you will probably want anyway if you are doing Matlab-type stuff. If you are dealing with large images or are dealing with raw data on disk (as opposed to PNGs or GIFs), numarray might be best for you. A mildly tested example: import Numeric as N import Image filename = 'heavy_1.gif' img = Image.open(filename).convert('RGBA') data = img.tostring() arr = N.fromstring(data, N.UInt8) arr.shape = (img.size[1], img.size[0], 4) mask = (arr[:,:,3] == 255).flat idx = N.indices(arr.shape[:2]) idx.shape = (2, len(mask)) pixels = N.compress(idx, mask) # for all i, arr[pixels[0,i], pixels[1,i], 3] == 255 I'm sure there's some code floating around that makes these kinds of operations simpler. -- 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 Wed Jan 5 11:48:02 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 08:48:02 -0800 Subject: Image capture In-Reply-To: References: <1104939479.011181.147650@f14g2000cwb.googlegroups.com> Message-ID: <1104943682.530470.113770@f14g2000cwb.googlegroups.com> Hi Catalin, Here are the modifications to your code. I am emailing you the complete file back to your email address. Please note that you need PIL (Python Imaging Library) to grab the window. I included a step to save the image, but you can do whatever you want with it. Thanks, --Kartic -------------- Unified Diff --------------- --- Catalin.txt Wed Jan 05 11:43:38 2005 +++ frmDesign.py Wed Jan 05 11:43:17 2005 @@ -1,7 +1,7 @@ from wxPython.wx import * from wxPython.grid import * from win32api import SendMessage -import win32ui +import win32ui, win32gui, ImageGrab WM_PAINT = 0xf WM_PRINT = 0x317 @@ -47,6 +47,10 @@ dc = wxMemoryDC() dc.SelectObject(bmp) dc.Clear() + win_sz = win32gui.GetWindowRect(self.grd.GetHandle()) + print win_sz + im = ImageGrab.grab((win_sz[0],win_sz[1],win_sz[2],win_sz[3])) + im.save('C:/TEMP/grid.jpg') SendMessage(self.grd.GetHandle(), WM_PAINT, dc.GetHDC(), 0) SendMessage(self.grd.GetHandle(), WM_PRINT, dc.GetHDC(), PRF_CHILDREN|PRF_CLIENT|PRF_OWNED) From stephen.thorne at gmail.com Sat Jan 29 10:11:32 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Sun, 30 Jan 2005 01:11:32 +1000 Subject: limited python virtual machine In-Reply-To: <16891.41849.882856.527798@montanaro.dyndns.org> References: <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> <16891.41849.882856.527798@montanaro.dyndns.org> Message-ID: <3e8ca5c805012907114062470c@mail.gmail.com> On Sat, 29 Jan 2005 08:53:45 -0600, Skip Montanaro wrote: > > >> One thing my company has done is written a ``safe_eval()`` that uses > >> a regex to disable double-underscore access. > > Alex> will the regex catch getattr(object, > Alex> 'subclasses'.join(['_'*2]*2)...?-) > > Now he has two problems. ;-) I nearly asked that question, then I realised that 'getattr' is quite easy to remove from the global namespace for the code in question, and assumed that they had already thought of that. Stephen. From fredrik at pythonware.com Wed Jan 19 16:10:05 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 19 Jan 2005 22:10:05 +0100 Subject: a question References: <797fe3d405011912511a609c1c@mail.gmail.com> Message-ID: Bill Mill wrote: > You've got a couple problems. First, you need to end the string before > putting a continuation in. >>> "no\ ... pe" 'nope' >>> "however\ File "", line 1 "however\ ^ SyntaxError: EOL while scanning single-quoted string (in the second case, the ^ is trying to point out that I added some whitespace after the backslash) From a at a.invalid Thu Jan 6 05:11:49 2005 From: a at a.invalid (Timo Virkkala) Date: Thu, 06 Jan 2005 10:11:49 GMT Subject: Why tuples use parentheses ()'s instead of something else like <>'s? In-Reply-To: <1104356661.326757.84590@f14g2000cwb.googlegroups.com> References: <1104299822.394489.161500@z14g2000cwz.googlegroups.com> <1gpjrru.wgin5135kfkvN%aleaxit@yahoo.com> <1104356661.326757.84590@f14g2000cwb.googlegroups.com> Message-ID: seberino at spawar.navy.mil wrote: > I can't thank you enough for your reply and for everyones' great info > on this thread. The end of your email gave a rock solid reason why it > is impossible to improve upon ()'s for tuples.... Actually, you missed the point. The parentheses don't have anything to do with the tuple. They are just used for disambiguation. It's the commas that define the tuple. -- Timo Virkkala From elbertlev at hotmail.com Mon Jan 24 23:40:03 2005 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 24 Jan 2005 20:40:03 -0800 Subject: smtplib bug with Windows XP In-Reply-To: References: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> Message-ID: <1106628003.054231.139170@z14g2000cwz.googlegroups.com> > Try manually, but think about these options: a firewall that > has suddenly been enabled, an SMTP server that now requires > authentication, some kind of proxy like what virus scanners > use (though why they would intercept outgoing mail I don't > know)... > > -Peter I bet it was the firewall on XP. From noreply at python.org Wed Jan 19 03:18:37 2005 From: noreply at python.org (Mail Administrator) Date: Wed, 19 Jan 2005 09:18:37 +0100 Subject: MDaemon Warning - virus found: Delivery reports about your e-mail Message-ID: <20050119081921.627281E4004@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 ---------------------------------------------------------------------- message.pif I-Worm.Mydoom.m Removed ********************************************************************** This message was undeliverable due to the following reason: Your message could not be 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 3 days: Server 127.15.40.10 is not responding. The following recipients did not receive this message: Please reply to postmaster at python.org if you feel this message to be in error. From cam.ac.uk at mh391.invalid Fri Jan 14 06:16:59 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 14 Jan 2005 11:16:59 +0000 Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: Peter Renzland wrote: > What is the simplest/fastest Python program to determine how many > IP addresses sum up to 666? > > The simplest/fastest enumerator? > > The simplest/fastest that determines which ones of them are home pages? This seems to work although it could be made more efficient or elegant. Also, the failed gethostbyaddr() calls take forever. from socket import gethostbyaddr, herror for a in xrange(256): if a < 666-255*3: continue for b in xrange(256): if a+b < 666-255*2: continue for c in xrange(256): if a+b+c < 666-255: continue for d in xrange(256): if a + b + c + d == 666: ip_address = "%d.%d.%d.%d" % (a, b, c, d) try: hostname, aliaslist, ipaddrlist = gethostbyaddr(ip_address) except herror: hostname = "NONE" print hostname, ip_address break -- Michael Hoffman From bulba at bulba.com Sun Jan 2 12:15:36 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 02 Jan 2005 18:15:36 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: On Sat, 01 Jan 2005 13:28:16 -0600, "Rob Emmons" wrote: >> For managers of companies it's worse: the company makes >> VERY substantial investments into any technology it "marries", >> and that means big losses if it goes. Long-term stability >> of this technology in terms of "we're not going to be left out >> in cold alone with this technology to feed it" means a lot >> to them. Even a poor technology with external backing >> of big, stable vendor is better than the excellent technology >> without ...... >There is the stability issue you mention... but also probably the fear >issue. If you choose a solution from a major company -- then it fails for >some reason or they drop the product -- it's their fault -- you've got an >automatic fall guy. True. I have a bit of interest in economics, so I've seen e.g. this example - why is it that foreign branches of companies tend to cluster themselves in one city or country (e.g. China right now)? According to standard economics it should not happen - what's the point of getting into this overpriced city if elsewhere in this country you can find just as good conditions for business. The point is obviously "cover your ass" attitude of managers: if this investment fails, this manager can defend himself "but everybody invested in that particular place, too, so you see, at the time it was not a bad decision, we could not predict... yadda yadda". -- It's a man's life in a Python Programming Association. From steven.bethard at gmail.com Thu Jan 13 13:28:27 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 13 Jan 2005 11:28:27 -0700 Subject: sorted (WAS: lambda) In-Reply-To: <7x7jmh1eek.fsf@ruckus.brouhaha.com> References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <7x7jmh1eek.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > > That completely depends on the objects in question. Compare > > temp = all_posters[:] > temp.sort() > top_five_posters = temp[-5:] > > to: > > top_five_posters = all_posters.sorted()[-5:] > > which became possible only when .sorted() was added to Python 2.4. I believe you mean "when sorted() was added to Python 2.4": py> ['d', 'b', 'c', 'a'].sorted() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'list' object has no attribute 'sorted' py> sorted(['d', 'b', 'c', 'a']) ['a', 'b', 'c', 'd'] Note that sorted is a builtin function, not a method of a list object. It takes any iterable and creates a sorted list from it. Basically the equivalent of: def sorted(iterable): result = list(iterable) result.sort() return result Steve From steven.bethard at gmail.com Fri Jan 7 13:17:39 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 11:17:39 -0700 Subject: python3: 'where' keyword In-Reply-To: <3480qqF46jprlU1@individual.net> References: <3480qqF46jprlU1@individual.net> Message-ID: Andrey Tatarinov wrote: > Hi. > > It would be great to be able to reverse usage/definition parts in > haskell-way with "where" keyword. Since Python 3 would miss lambda, that > would be extremly useful for creating readable sources. > > Usage could be something like: > > >>> res = [ f(i) for i in objects ] where: > >>> def f(x): > >>> #do something > > or > > >>> print words[3], words[5] where: > >>> words = input.split() > > - defining variables in "where" block would restrict their visibility to > one expression How often is this really necessary? Could you describe some benefits of this? I think the only time I've ever run into scoping problems is with lambda, e.g. [lambda x: f(x) for x, f in lst] instead of [lambda x, f=f: for x, f in lst] Are there other situations where you run into these kinds of problems? > - it's more easy to read sources when you know which part you can skip, > compare to > > >>> def f(x): > >>> #do something > >>> res = [ f(i) for i in objects ] > > in this case you read definition of "f" before you know something about > it usage. Hmm... This seems very heavily a matter of personal preference. I find that your where clause makes me skip the 'res' assignment to read what the 'res' block contains. I had to read it twice before I actually looked at the list comprehension. Of course, I'm sure I could be retrained to read it the right way, but until I see some real benefit from it, I'd rather not have to. TOOWTDI-ily-yrs, Steve From fccoelho at gmail.com Tue Jan 11 03:09:46 2005 From: fccoelho at gmail.com (Flavio codeco coelho) Date: 11 Jan 2005 00:09:46 -0800 Subject: Python serial data aquisition References: <41e1b833$1_3@omega.dimensional.com> Message-ID: mfuhr at fuhr.org (Michael Fuhr) wrote in message news:<41e1b833$1_3 at omega.dimensional.com>... > If the actual byte and/or bit order is different then you'll have > to modify the expression, but this should at least give you ideas. Hi Michael, It all looks pretty god but there is a couple of things I still don't understand, 1) in Steve's solution (which seems equivalent to your own), he does the masking, shifts by seven, and then sums the two numbers while you, instead of summing, use a logical or. How can these operations be equivalent? or are they? Is the logical or equivalent to a concatenation? 2) why 7? why do we have shift 7 bits? is that so the 8th bit on byte one is aligned with the first bit on the second byte? thanks: From michele.simionato at gmail.com Tue Jan 4 10:32:07 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 4 Jan 2005 07:32:07 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> Message-ID: <1104852727.673212.40060@z14g2000cwz.googlegroups.com> Yep, I did the same and got confused :-/ Michele From remi at cherrypy.org Wed Jan 19 13:15:02 2005 From: remi at cherrypy.org (Remi Delon) Date: 19 Jan 2005 10:15:02 -0800 Subject: ANN: Free Trac/Subversion hosting at Python-Hosting.com Message-ID: <585c0de9.0501191015.290eb537@posting.google.com> Hello everyone, To celebrate its second anniversary, Python-Hosting.com is happy to announce that it is now offering free Trac/Subversion hosting. This offer is limited to open-source, python projects. Trac and Subversion make a great combination for project management. More information about Trac can be found here: http://www.edgewall.com/trac The free offer includes: - Your own Trac site with HTTP and HTTPS access - Your own Subversion repository with HTTP and HTTPS access - Access to trac-admin through a web interface - Access to Trac and Subversion user configuration through a web interface - Web usage statistics of your Trac site - Nightly backups of your data to external servers If you want to know more about this offer and find out how to sign up, check out the following page: http://www.python-hosting.com/freetrac Remi. From __peter__ at web.de Tue Jan 11 10:23:34 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Jan 2005 16:23:34 +0100 Subject: Importing Problem on Windows References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> Message-ID: brolewis wrote: > I have a directory that has two files in it: > > parse.py > parser.py > > parse.py imports a function from parser.py and uses it to parse out the > needed information. On Linux, the following code works without a > problem: > > parse.py, line 1: > from parser import regexsearch > > However, when I run the same command in Windows, I get the following > error: > > ImportError: cannot import name regexsearch > Any suggestions on why this would work on Linux but not on Windows? This has nothing to do with Linux vs. Windows. Depending on sys.path and your current working directory either your own parser.py or the parser.py module in the library is imported. If you want to play it safe, rename your parser.py to myparser.py or another name that is not already used by the standard library and avoid the confusion between the two modules. If you do that, don't forget to delete the compiled module parser.pyc or parser.pyo, too. Peter From steven.bethard at gmail.com Mon Jan 24 12:56:40 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Jan 2005 10:56:40 -0700 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) Message-ID: Philippe C. Martin wrote: > class Debug_Stderr: > __m_text = '' > __m_log_text = None > __m_dbg = None > __m_refresh_count = 0 I don't see the benefit in 99.9% of cases for making class variables like this "private". If you don't want people to use them, simply use the standard convention[1] for non-public variables: class Debug_Stderr: _text = '' _log_text = None _dbg = None _refresh_count = 0 A lot of the time, it actually makes sense to make (at least some of) the attributes public, e.g.: class Debug_Stderr: text = '' log_text = None dbg = None refresh_count = 0 I don't know what all the variables in this specific example are intended to be, but it certainly seems like something like 'refresh_count' might be useful to clients of the class. Name mangling is there to keep you from accidentally hiding such an attribute in a subclass, but how often is this really a danger? Can someone give me an example of where __-mangling really solved a problem for them, where a simple leading underscore wouldn't have solved the same problem? Steve [1] http://www.python.org/peps/pep-0008.html From irmen at -nospam-remove-this-xs4all.nl Thu Jan 20 13:14:19 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 20 Jan 2005 19:14:19 +0100 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> Message-ID: <41eff4fa$0$6209$e4fe514c@news.xs4all.nl> Istvan Albert wrote: > XML with elementtree is what makes me never have think about XML again. +1 QOTW -Irmen From bokr at oz.net Tue Jan 25 03:27:44 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 25 Jan 2005 08:27:44 GMT Subject: Retrieving modification time of file class was declared in References: <1106627951.152900.135310@z14g2000cwz.googlegroups.com> Message-ID: <41f601d4.1763682581@news.oz.net> On 24 Jan 2005 20:39:11 -0800, nathan_kent_bullock at yahoo.ca wrote: >Assume I am using a class Foo. I want to find out the modification time >of the file that that class was defined in. How would I go about this? > >If I could find out the name of the file that Foo was defined in then >it is easy, I could use os.path.getmtime(), but I can't even figure >that out. > >I realize that this wouldn't be a completely accurate way to tell the >last time this class was modified because it could inherit info from >other classes, or use functions from other modules that have been >modified, etc. > >Nathan Bullock > try this for about any object you can pass to finfo: ----< finfo.py >---------------- import sys, os def finfo(obj): if not hasattr(obj, '__name__'): obj = type(obj) name = '<%s instance>'%obj.__name__ else: name = obj.__name__ if type(obj) == type(sys): # module type modname = name else: # not module type, but be class now modname = obj.__module__ mod = sys.modules[modname] if modname == '__builtin__' or repr(mod) == ""%modname: path = sys.executable else: path = vars(sys.modules[modname]).get('__file__','??') if path != '??': tmod = os.path.getmtime(path) else: tmod = '???' return name, modname, path, tmod -------------------------------- Not very tested, but seems to retrieve info. The file in question for builtins is the interpreter executable, I supposed. Ignore the "ut." here, that's just my utilities grabbag [ 0:25] C:\pywk\sovm>py24 Python 2.4b1 (#56, Nov 3 2004, 01:47:27) [GCC 3.2.3 (mingw special 20030504-1)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from ut.finfo import finfo >>> finfo(finfo) ('finfo', 'ut.finfo', 'c:\\pywk\\ut\\finfo.pyc', 1106641080) >>> import time >>> time.ctime(finfo(finfo)[-1]) 'Tue Jan 25 00:18:00 2005' HIH Regards, Bengt Richter From drjonfox at gmail.com Mon Jan 17 10:36:55 2005 From: drjonfox at gmail.com (drjonfox at gmail.com) Date: 17 Jan 2005 07:36:55 -0800 Subject: Central New Jersey PIG Meeting -- Python Interest Group In Princeton PIG/IP Message-ID: <1105976215.038859.72730@z14g2000cwz.googlegroups.com> Central New Jersey PIG Meeting -- Python Interest Group In Princeton PIG/IP PIG/IP will hold its first meeting on Jan 19, 2005 at the Lawrenceville Library (Room #3). Jon Fox will speak about Python's 2.4 release and then open discussion about Python will be encouraged. When: Wednesday, January 19, 2005 at 7:00 PM Where: Mercer County Library Lawrenceville Branch 2751 Brunswick Pike Lawrenceville, NJ 08648 882-9246 Map and directions at http://www.lugip.org/meeting/location/ For more information about this group http://python.meetup.com/156/ or email Jon Fox at drjonfox at gmail.com From strombrg at dcs.nac.uci.edu Fri Jan 21 21:10:06 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Fri, 21 Jan 2005 18:10:06 -0800 Subject: pure python code to do modular-arithmetic unit conversions? Message-ID: Is there already a pure python module that can do modular-arithmetic unit conversions, like converting a huge number of seconds into months, weeks... or a bandwidth measure into megabits/s or gigabits/s or megabytes/s or gigabytes/s, whatever's the most useful (ala df -h)? Thanks! From a at a.invalid Thu Jan 27 03:38:48 2005 From: a at a.invalid (Timo Virkkala) Date: Thu, 27 Jan 2005 08:38:48 GMT Subject: python without OO In-Reply-To: <1106798140.896125.187850@f14g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> <1106798140.896125.187850@f14g2000cwb.googlegroups.com> Message-ID: beliavsky at aol.com wrote: > I think the OO way is slightly more obscure. It's obvious what x = > reverse(x) does, but it is not clear unless you have the source code > whether x.reverse() reverses x or if it returns a reversed list. If > x.reverse() does the former, a disadvantage relative to the procedural > approach is that a function can be used in an expression. It is clearer > and more concise to write Sure, it's clear if in written code you see x = reverse(x) To me it would also be clear to see x.reverse() But what if you just see in some list that there is a reverse(sequence) function, or that a sequence has a reverse() method? To me, neither of these is clear. Do they return a new, reversed sequence or reverse in place? When creating a new API, I would probably use a convention where reverse does it in place and reversed returns a new. So, in my API, reverse(x) y = reversed(x) x.reverse() y = x.reversed() -- Timo Virkkala From a at b.c Wed Jan 5 12:22:24 2005 From: a at b.c (Doug Holton) Date: Wed, 05 Jan 2005 11:22:24 -0600 Subject: How do I make Windows Application with Python ? In-Reply-To: <1r9ydq5jsele7.1c45eb2jskpli.dlg@40tude.net> References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> <1r9ydq5jsele7.1c45eb2jskpli.dlg@40tude.net> Message-ID: BOOGIEMAN wrote: > Thanks all for very detailed answers. BTW I tried this one but it seems > that it doesn't use VS'es visual designer. Also it doesn't have "build" > option so it is basicly only usefull to higlight Python syntax. > Active Sate Komodo looks like much better choice I don't know of any python IDE with a visual designer and a build to exe option. But since you are familiar with Visual Studio and you are developing on Windows, you might check out the free SharpDevelop IDE: http://www.icsharpcode.net/OpenSource/SD/ Then unzip this boo add-in into the SharpDevelop folder under Program Files: http://coedit.net/boo/BooBinding.zip Then you can start up SharpDevelop, create a new boo project, press the green play button, and your exe will be built and executed (the one below is only 4kb in size). We are working on adding support for SharpDevelop's visual form designer soon. To show a Windows message box instead of printing to the console like you were asking earlier, you can use code like this: import System.Windows.Forms MessageBox.Show("your message") Or for a more complete windows app: import System.Drawing import System.Windows.Forms class MainForm(Form): def constructor(): self.Text = "My Window" b = Button(Text: "Click Me") b.Location = Point(100,75) b.Click += def(): MessageBox.Show("Button clicked") #or: #b.Click += OnButtonClick self.Controls.Add(b) def OnButtonClick(): MessageBox.Show("Button clicked") f = MainForm() Application.Run(f) From markscottwright at gmail.com Tue Jan 18 12:11:06 2005 From: markscottwright at gmail.com (markscottwright at gmail.com) Date: 18 Jan 2005 09:11:06 -0800 Subject: makepy crashing Message-ID: <1106068266.402828.301030@f14g2000cwb.googlegroups.com> Has anyone sucessfully run makepy and Microsoft Word Object Library (9.0)? Mine crashes under XP Pro and Python 2.4. It only seems to be word that has the problem, though. I get a dialog that says that pythonwin.exe has crashed: AppName: pythonwin.exe AppVer: 0.0.0.0 ModName: ntdll.dll ModVer: 5.1.2600.1217 Offset: 000096f9 From fredrik at pythonware.com Mon Jan 31 11:41:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 17:41:50 +0100 Subject: import doesn't work as i want References: <41fe5438$0$18865$8fcfb975@news.wanadoo.fr> <41fe5cfd$0$6597$8fcfb975@news.wanadoo.fr> Message-ID: Olivier Noblanc wrote: > how to move in function ? how to put code in a function? the same way you put code in a method. change if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MyFrame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() #startb = time.time() - starta #print startb app.MainLoop() to def main(): app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MyFrame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() #startb = time.time() - starta #print startb app.MainLoop() and call it from your main program: import inc.wxgrid inc.wxgrid.main() if you have trouble sorting out the imports, this might help: http://docs.python.org/ref/import.html http://www.python.org/doc/essays/packages.html http://effbot.org/zone/import-confusion.htm From snacktime at gmail.com Wed Jan 26 14:55:43 2005 From: snacktime at gmail.com (snacktime) Date: Wed, 26 Jan 2005 11:55:43 -0800 Subject: Set parity of a string In-Reply-To: <1f060c4c05012611503090c261@mail.gmail.com> References: <1f060c4c05012611503090c261@mail.gmail.com> Message-ID: <1f060c4c05012611554f727d29@mail.gmail.com> Correction on this, ETX is ok, it seems to be just STX with the data I am using. Chris On Wed, 26 Jan 2005 11:50:46 -0800, snacktime wrote: > I'm trying to figure out why the following code transforms ascii STX > (control-b) into "\x82". The perl module I use returns a value of > "^B", and that is also what the application I am communicating with > expects to see. Some ascii characters such as FS and GS come through > fine, but STX and ETX get transformed incorrectly (at least for what I > need they do). From http Sun Jan 9 06:42:36 2005 From: http (Paul Rubin) Date: 09 Jan 2005 03:42:36 -0800 Subject: Old Paranoia Game in Python References: <2005010903390916807%spk00@coxnet> Message-ID: <7x3bxau8ur.fsf@ruckus.brouhaha.com> Oh cool, I sort of remember that game from back in the day. I didn't play it very much so never got very far in it. I'll have to try your version. From rschroev_nospam_ml at fastmail.fm Thu Jan 6 10:44:03 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 06 Jan 2005 15:44:03 GMT Subject: The Industry choice In-Reply-To: <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> Message-ID: <71dDd.21829$En7.1635461@phobos.telenet-ops.be> Alex Martelli wrote: > Roel Schroeven wrote: > > >>Can you point to closed-source licenses that allow using the code *at >>all*? > > > As I recall, for example, Microsoft Visual C++ came with sources for > various libraries; all that the (closed-source) license for those > libraries forbade you from doing was to further distribute the _sources_ > themselves. You could do modifications big or small to those libraries > for whatever purposes, and redistribute the _compiled_ form of the code > as a DLL, or statically linked into your own programs, etc, etc. > > Is this what you mean by "allow using the code *at all*"? I think it's > a pretty common arrangement when the code being sold under closed-source > terms is a set of libraries, or a development system part of whose value > is a set of accompanying libraries. OK, I've been bitten by my exageration. There are indeed special cases such as some libraries. I was thinking more of end-user packages: if you somehow could lay your hands on the source code of Visual Studio itself, you're still not allowed to do anything with it. -- "Codito ergo sum" Roel Schroeven From skip at pobox.com Fri Jan 7 14:24:27 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 7 Jan 2005 13:24:27 -0600 Subject: Notification of PEP Updates In-Reply-To: <41DEC6C2.8030904@iinet.net.au> References: <41DEC6C2.8030904@iinet.net.au> Message-ID: <16862.57835.38948.120076@montanaro.dyndns.org> Nick> Let us know if it does anything odd (e.g. sending updates about Nick> other checkins) Note that the lone criterion for inclusion is the word "PEP" in the subject or the first few lines of the message. You might thus see the occasional checkin message that mentions "PEP" but isn't directly about a PEP. Nick> I believe the mail you receive should contain the checkin Nick> messages, along with a summary of the differences between the old Nick> version and the new version (handy if you can read a context diff, Nick> not so handy otherwise). I believe all the checkin messages come out as unified diffs these days, so they are a bit easier to read. Skip From eugene at boardkulture.com Sat Jan 29 07:17:37 2005 From: eugene at boardkulture.com (EuGeNe) Date: Sat, 29 Jan 2005 13:17:37 +0100 Subject: An mysql-python tutorial? In-Reply-To: References: Message-ID: Dfenestr8 wrote: > Hi. > > Been told by the admin of my (free!) server that he'd rather I should > learn to use mysql if I want to continue writing cgi scripts there. > > Not even sure exactly what mysql is. > > Is there a simple tutorial anywhere on the web about using python + mysql? http://www.devshed.com/c/a/Python/MySQL-Connectivity-With-Python/ that one put me on the right track (I think ;) -- EuGeNe [---- www.boardkulture.com www.actiphot.com www.xsbar.com ----] From ncoghlan at iinet.net.au Sun Jan 16 06:20:28 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 16 Jan 2005 21:20:28 +1000 Subject: generator expressions: performance anomaly? In-Reply-To: <1105854381.117059.59940@c13g2000cwb.googlegroups.com> References: <1105854381.117059.59940@c13g2000cwb.googlegroups.com> Message-ID: <41EA4DFC.1010301@iinet.net.au> John Machin wrote: > Background: There was/is a very recent thread about ways of removing > all instances of x from a list. /F proposed a list comprehension to > build the result list. Given a requirement to mutate the original list, > this necessitates the assignment to lst[:]. I tried a generator > expression as well. However while the listcomp stayed competitive up to > a million-element list, the genexp went into outer space, taking about > 20 times as long. The above timeit runs show a simpler scenario where > the genexp also seems to be going quadratic. > Comments, clues, ... please. Py> lc = [x for x in range(100)] Py> len(lc) 100 Py> ge = (x for x in range(100)) Py> len(ge) Traceback (most recent call last): File "", line 1, in ? TypeError: len() of unsized object It would be nice if unconditional ge's with known length inputs propagated __len__, but that is not currently the case. There's a similar performance glitch associated with constructing a tuple from a generator expression (with vanilla 2.4, detouring via list is actually faster) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From craig at postnewspapers.com.au Sat Jan 22 05:17:10 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 22 Jan 2005 18:17:10 +0800 Subject: need help on need help on generator... In-Reply-To: <1106387175.4103.16.camel@albert.localnet> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> <1106387175.4103.16.camel@albert.localnet> Message-ID: <1106389030.4103.21.camel@albert.localnet> On Sat, 2005-01-22 at 17:46 +0800, I wrote: > I'd be interested to know if there's a better solution to this than: > > .>>> inpath = '/tmp/msg.eml' > .>>> infile = open(inpath) > .>>> initer = iter(infile) > .>>> headers = [] > .>>> for line in initer: > .... if not line.strip(): > .... break > .... headers.append(tuple(line.split(':',1))) > .>>> data = ''.join(x for x in initer) > > because that seems like a pretty ugly hack (and please ignore the > variable names). Perhaps a way to get the file to seek back to the point > last read from the iterator when the iterator is destroyed? And now, answering my own question (sorry): Answer: http://tinyurl.com/6avdt so we can slightly simplify the above to: .>>> inpath = '/tmp/msg.eml' .>>> infile = open(inpath) .>>> headers = [] .>>> for line in infile: .... if not line.strip(): .... break .... headers.append(tuple(line.split(':',1))) .>>> data = ''.join(x for x in infile) at the cost of making it less clear what's going on and having someone later go "duh, why isn't he using read() here instead" but can't seem to do much more than that. Might it be worth providing a way to have file objects seek back to the current position of the iterator when read() etc are called? If not, I favour the suggestion in the referenced post - file should probably fail noisily, or at least emit a warning. What are others thoughts on this? -- Craig Ringer From nightmarch at gmail.com Tue Jan 25 22:06:51 2005 From: nightmarch at gmail.com (nightmarch) Date: Wed, 26 Jan 2005 11:06:51 +0800 Subject: I want update one record using ADO,but I can't ,why? In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3398297@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3398297@exchange.hqamor.amorhq.net> Message-ID: <31d9b15c05012519066a3dceca@mail.gmail.com> Sorry, I mean this code line " rs.Supports( wc.constants.adUpdate ) " got False result, So I can't update one record,i.e. I can't execute this code "rs.Fields.Item(0).Value = 11". And , if code is written like this: ##code------------------------- I got error msg like following: ##errorMsg---------------------------- On Tue, 25 Jan 2005 10:25:00 -0800, Robert Brewer wrote: > nightmarch wrote: > > I want update one record ,but I can't ,why? > > > > code like following: > > > > ##------------------------------------------------- > > import win32com.client as wc > > > > def main(): > > conn = wc.Dispatch(r'ADODB.Connection') > > rs = wc.Dispatch(r'ADODB.Recordset') > > connStr = "Provider=MSDAORA.1;Password=jmpower;User > > ID=jmpower;Data Source=jmgis_agps3;Persist Security Info=True" > > tblName = r'wjtmp' > > > > conn.Open(connStr ) > > > > rs.Open( tblName, conn, wc.constants.adOpenKeyset, > > wc.constants.adLockOptimistic ) > > > > if rs.Supports( wc.constants.adUpdate ): > > rs.Fields.Item(0).Value = 11 > > rs.Update() > > else: > > print "recordset can't update" > > > > rs.Close() > > conn.Close() > > > > if __name__ == '__main__': > > main() > > ##------------------------------------------------- > > You almost give us enough information to help out ,but you don't quite > ,why? > > What happens when you run the above? Is there any output? Error message? > > Does your update affect the membership of the record in the keyset? > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/ > htm/mdconkeysetcursors.asp > > Why are you using keysets at all? > > > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.org > From duncan.booth at invalid.invalid Fri Jan 28 10:22:05 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Jan 2005 15:22:05 GMT Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> <7x3bwlsqnj.fsf@ruckus.brouhaha.com> <7x8y6diu6k.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > The Cookie issue is discussed some in that bug thread. But more > relevant is bug 471893. Sorry. Thanks. There's an interesting comment in that thread: A.M. Kuchling (akuchling) wrote: > Date: 2003-02-06 09:29 > > The Cookie classes that use pickle have DeprecationWarnings in > 2.3, and should disappear in 2.4. Its a real pity that nobody seems to have remembered to actually remove them. >> I think its a bit borderline whether this really was a security bug in >> Python rather than just a problem with the way some people used Python. > > If using a module the way it's documented results in a security hole, > that's definitely a security bug. > > If using the module in an obvious and natural way that looks correct > results in a security hole, I'd say it's at least an issue needing > attention, even if some sufficiently hairsplitting reading of the > documentation says that usage is incorrect. Principle of least > astonishment. Agreed. Principle of least astonishment is definitely good. From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Tue Jan 11 17:50:23 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Tue, 11 Jan 2005 23:50:23 +0100 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <41e41633$1@nntp0.pdx.net> Message-ID: <41e458a9$0$7090$8fcfb975@news.wanadoo.fr> Hi ! >>> It is a least-common-denominator argument, not a "this is better" argument. I understand, but I have a feeling of attempt at hegemony. Is english language really least-common-denominator for a russian who writes into cyrillic, or not anglophone chinese? And, did you think of klingons? ;-) Michel Claveau From http Sun Jan 9 06:10:15 2005 From: http (Paul Rubin) Date: 09 Jan 2005 03:10:15 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> Message-ID: <7xr7ku26zs.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > Trying to push it a level further (down to expressions) would, IMO, be > a lot of effort for something which would hurt readability a lot. I think we should just try to do things in a simple and general way and not try to enforce readability. For example, the slightly-overcomplex code that I proposed might have been generated by a macro, or even by a compiler from some other language. No human would ever have to look at it, so it doesn't matter whether it's easily readable. There's no reason to add needless constraints on the language just to make writing ugly code difficult. The main goal should be to make writing clear code easy, not to worry about whether someone might also write ugly code. From http Tue Jan 4 22:25:12 2005 From: http (Paul Rubin) Date: 04 Jan 2005 19:25:12 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> Message-ID: <7xvfach813.fsf@ruckus.brouhaha.com> "Rob Emmons" writes: > Me personally, I believe in free software, but always talk about open > source. My answer regarding forcing people to share -- I like the GPL > -- and I am perfectly happy to have anyone who does not like the GPL > not to use any GPLed software. I don't feel compelled to share. I'd go further. It's not possible to force anyone to share, but the GPL aims to remove software from a system that instead aims to force people NOT to share. As the MPAA knows, people do want to share, and forcing them not to do so is impossible without turning the world into a police state. Maybe if Python were GPL, then Bulba wouldn't use it, but since it's not GPL, some people find themselves much less willing to contribute to it than if it were GPL. (I myself contribute bug reports and maybe small patches, but resist larger projects since there are GPL'd things that I can do instead). So catering to the wishes of Bulba and Microsoft may actually be impeding Python development. Yes, there are some people selfless enough to do long and difficult unpaid software tasks so that Bulba and Bill G can get richer by stopping people from sharing it, but others of us only want to do unpaid programming if we can make sure that the results stay available for sharing. From gandalf at geochemsource.com Wed Jan 26 02:39:42 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Wed, 26 Jan 2005 08:39:42 +0100 Subject: How to assign In-Reply-To: References: Message-ID: <41F7493E.9010100@geochemsource.com> Jan Rienyer Gadil wrote: >Sort of a newbie question: >How am i going to assign to a variable anything the user inputs on a wxTxtCtrl? > > I'm affraid you have to do it manually. I think the best solution is to use a property like this: import wx class FrameMain(wx.Frame): def __init__(self, *args,**kwargs): DEFAULT_VALUE = "Some string here" wx.Frame.__init__(self, *args,**kwargs) self.txt = wx.TextCtrl(self,value=DEFAULT_VALUE) self._value = DEFAULT_VALUE self._txt_updating = False self.txt.Bind( wx.EVT_TEXT, self.TextChanged ) self.value = "Test value" # This will set the property and the text control too def TextChanged(self,event): self._value = self.txt.GetValue() print "Property changed to %s" % self._value def _GetTextValue(self): return self._value def _SetTextValue(self,value): if not self._txt_updating: self._txt_updating = True try: self.txt.SetValue(value) finally: self._txt_updating = False value = property(_GetTextValue,_SetTextValue,'Your variable') app = wx.PySimpleApp() frame = FrameMain(None, -1, "TextValue") frame.Show(True) app.MainLoop() In this example, the frame has a property called "value" and that has the same cached value as the text in the textcontrol. From kentsin at yahoo.com Sun Jan 16 11:37:25 2005 From: kentsin at yahoo.com (kent sin) Date: Sun, 16 Jan 2005 08:37:25 -0800 (PST) Subject: iTools Message-ID: <20050116163725.83800.qmail@web40511.mail.yahoo.com> Where can I download python-itools? I found it in the python packages index but the site is not contactable. Thank you. From bulba at bulba.com Thu Jan 6 16:50:10 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 22:50:10 +0100 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> Message-ID: On Thu, 06 Jan 2005 15:44:03 GMT, Roel Schroeven wrote: >I was thinking more of end-user packages: if you somehow could lay your >hands on the source code of Visual Studio itself, you're still not >allowed to do anything with it. And why would anybody want to waste their time reading the source code of Visual Studio? ;-) No, honestly, after all most of the time what programmers learn is just API. The very point of having libraries after all is not having to learn the low-level mechs of this thing, but just using them in a push-button manner! My boss read the C-tree code. I was programming reports and other "peripheral" stuff, so I never had to do it. I was just using a subset of the C-tree functionality, and even that was a very small subset actually. Now I'm sure that B-trees used in there are a wonder of engineering - however, I simply have other goals and not enough time to learn them to appreciate that. Personally, I think that for most people the _direct_ benefits of access to source code are greatly exagerrated. I would place much, much more emphasis on indirect, derived benefits of availability of source code. Yes, you CAN read the source code. But the point is, you DON'T WANT TO. Because economically speaking, division of labor applies, and idealistically speaking, it's better to stand on the shoulders of giants. -- It's a man's life in a Python Programming Association. From ncoghlan at iinet.net.au Tue Jan 4 05:17:53 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 04 Jan 2005 20:17:53 +1000 Subject: Hlelp clean up clumpsy code In-Reply-To: References: Message-ID: <41DA6D51.40107@iinet.net.au> It's me wrote: > Another newbie question. > > There must be a cleaner way to do this in Python: > > #### section of C looking Python code #### > a = [[1,5,2], 8, 4] > a_list = {} > i = 0 > for x in a: > if isinstance(x, (int, long)): > x = [x,] > for w in [y for y in x]: > i = i + 1 > a_list[w] = i > print a_list > ##### > > The code prints what I want but it looks so "C-like". How can I make it > more Python like? Firstly, calling your dictionary "a_list" is evil. . . Secondly, explaining what you want the code to do in English is handy when asking for help cleaning up code (since we then know which features are deliberate, and which are accidental implementation artificacts). If I'm reading the code correctly, you want to flatten a data structure which may contain either substructures or actual elements. A custom generator will do nicely: Py> def flatten(seq): ... for x in seq: ... if hasattr(x, "__iter__"): ... for y in flatten(x): ... yield y ... else: ... yield x ... Py> data = [[1,5,2],8,4] Py> val_to_pos = {} Py> for i, x in enumerate(flatten(data)): ... val_to_pos[x] = i + 1 ... Py> print val_to_pos {8: 4, 1: 1, 2: 3, 4: 5, 5: 2} Not any shorter, but this version works correctly for any leaf elements which don't supply __iter__ (e.g. strings), and internal elements which do (e.g. tuples) and the depth is limited only by the maximum level of recursion. Don't try to flatten a circular structure, though :) You may not even need to write the generator, since if you have Tkinter, that already supplies a near-equivalent function: Py> from Tkinter import _flatten as flatten Py> data = [[1,5,2],8,4] Py> val_to_pos = {} Py> for i, x in enumerate(flatten(data)): ... val_to_pos[x] = i + 1 ... Py> print val_to_pos {8: 4, 1: 1, 2: 3, 4: 5, 5: 2} It even works with strings as leaf elements: Py> data = [["abc","def",2],8,"xyz"] Py> flatten(data) ('abc', 'def', 2, 8, 'xyz') Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From Noah.Richards at infineon.com Mon Jan 3 12:19:33 2005 From: Noah.Richards at infineon.com (Richards Noah (IFR LIT MET)) Date: Mon, 3 Jan 2005 12:19:33 -0500 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: > wrote in message > news:1104750017.235937.181370 at c13g2000cwb.googlegroups.com... > > Hello All, > > I am trying to convince my client to use Python in his new product. He > > is worried about the license issues. Can somebody there to point me any > > good commercial applications developed using python ?. The licence > > clearly says Python can be used for commercial applications. Is there > > any other implications like that of GPL to make the source open ? > > Thanks for any help. > > eeykay > > "It's me" wrote in message news:mBeCd.5832$5R.1770 at newssvr21.news.prodigy.com... > Shaw-PTI (www.pti-us.com) uses Python in their software. See: > http://www.pti-us.com/pti/news/index.cfm and search "2004 PSS/E User Group > Meeting" > Begging your pardon, but a better resource would be the brochure available (http://www.pti-us.com/PTI/company/brochures/PSSE.pdf). It appears that the program was probably (originally) written in C/C++ (using MFC for the GUI), and now employs Python for adding modules and scripting support. Very interesting stuff :) From mhartl at post.harvard.edu Wed Jan 12 14:50:39 2005 From: mhartl at post.harvard.edu (Michael Hartl) Date: 12 Jan 2005 11:50:39 -0800 Subject: counting items References: Message-ID: <1105559439.538736.87370@z14g2000cwz.googlegroups.com> There's a great function called "walk" at that iterates over arbitrary data (and is recursion-proof) at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/118845 It also supplies a recursion-proof way to flatten a list. (Once you can iterate over an arbitrary sequence, the flattened version is just [element for element in walk(sequence)].) I use both functions all the time. Adding a flatten function (along with walk) to Python sounds like a good idea to me. Having used Mathematica for many years, which uses Flatten[] all over the place, I was actually quite surprised to find that Python didn't have it. Michael From BOOGIEMANPN at YAHOO.COM Mon Jan 24 11:13:44 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Mon, 24 Jan 2005 17:13:44 +0100 Subject: Python 2.1 - 2.4 differences Message-ID: I found some e-book about Python 2.1, I want to print it but just to check first if sintax of Python 2.1 is same as 2.4 ? Also does anybody know where can I download any newer Python related e-book, because there isn't any published yet in my country. From tom at dtsam.com Mon Jan 31 14:34:11 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Mon, 31 Jan 2005 13:34:11 -0600 Subject: variable declaration References: Message-ID: "Alexander Zatvornitskiy" wrote in message news:MSGID_2=3A5025=2F3.131_41fde342 at fidonet.org... > 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! > > Even Visual Basic have 'Option Explicit' keyword! May be, python also have such > a feature, I just don't know about it? Exactly so! Python *does* require that your variables be declared and initialized before you use them. You did that with epsilon=0 and S=0 at the top. It is unfortunate, however, that the statement epselon=epsilon+1 also declares a new variable in the wrong place at the wrong time. Such mispellings are a *common* error caught instantly in languages that require a more formal declaration procedure. Another irksome sitiuation is that while Python does enforce strict type checking, you can re-declare variables and morph them in the middle of nowhere. S = 0 # It's an Integer! S = S + 'Hello' # No can do! Strong type checking forbids this. S = 'GoodBye' # Whoops - Now it's a string! Unfortunately legal! This seemingly demolishes all the good reasons one has for wanting strict type checking. That second example is just bad programming practice and easy to avoid. The problem you point out in your code, however, hurts! Was that an I, an l or a 1 in the variable name? Hey! - I like Python a lot. But nothings perfect Thomas Bartkus From bulba at bulba.com Tue Jan 4 13:26:14 2005 From: bulba at bulba.com (Bulba!) Date: Tue, 04 Jan 2005 19:26:14 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> On Mon, 03 Jan 2005 20:16:35 -0600, "Rob Emmons" wrote: >> This "free software" (not so much OSS) notion "but you can >> hire programmers to fix it" doesn't really happen in practice, >> at least not frequently: because this company/guy remains >> ALONE with this technology, the costs are unacceptable. >This certainly is the thinking, but I is the wrong thinking in many cases. >If companies could some how take a larger view and realize that by working >together here and there -- they enable and open development model which in >the end saves them money. AHHH but that's such a hard argument because it >takes vision, time, and trust. But the vision of what? Do we have clear, detailed, unambigous vision _of the process_ or just big ideological axes to grind? I'm afraid we're close to the latter situation - even though Python is remarkably different in this area than the "free software": clean, pragmatic, effective, free to include in closed-source. If Python were GPLed, I wouldn't use it: attempting to force people to share doesn't work. >It takes a whole vision change to work in this environment -- believing in >an economy of plenty rather than an economy of scarcity. Well, I'd say that lack of interchangeability in software is a big obstacle on this road: not that there's little source code, but that it's relatively hard (read: expensive) to combine the pieces. See: http://blogs.sun.com/roller/page/bmc/20040828#the_economics_of_software IMHO this: 'The problem is that for all of the rhetoric about software becoming a "commodity", most software is still very much not a commodity: one software product is rarely completely interchangeable with another.' ...hits the nail on the head. >> It depends on definition of "rational", on definition of your or >> company's goals and on the definitions of the situations that >> are the context. >I work for a very large company -- there is an internal culture that >defines what "rational" is: (a) Rational means outsourcing and doing less >inside the company, This could be made into a very strong argument for OSS: see the OSS developers as your "outsourced team" that works for almost nothing, i.e. "if we want to win them or get them to help, maybe we should contribute our bugfixes and enhancements to them". >(b) pretty much single sourcing commerical software, >(c) releasing nothing outside the company unless there is a direct >demonstratable significant business benifit related to our core products. That doesn't seem like a good idea to me. >I could argue these are not rational in the long run, but this is >the direction of the company as far as I know. This will change -- and >someone will get a big promotion for doing it -- but it will take a lot of >time. And of course someone already got a big promotion for outsourcing >and developing the single source stratagy -- bone headed as it is. As much as people tend to hate outsourcing, it frequently _does_ increase the efficiency of the industries, see this paper: http://econpapers.hhs.se/article/fipfednep/y_3A2003_3Ai_3Asep_3Ap_3A23-33_3An_3Av.9no.3.htm -- Real world is perfectly indifferent to lies that are the foundation of leftist "thinking". From jgrahn-nntq at algonet.se Wed Jan 12 16:38:01 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 12 Jan 2005 21:38:01 GMT Subject: Locale confusion References: <1105451372.655977.165250@f14g2000cwb.googlegroups.com> Message-ID: On 11 Jan 2005 05:49:32 -0800, Serge.Orlov at gmail.com wrote: > Jorgen Grahn wrote: > [snip] > >> >> frailea> cat foo >> import locale >> print locale.getlocale() >> locale.setlocale(locale.LC_CTYPE) >> print locale.getlocale() ... >> When I run it as a script it isn't though, and the setlocale() call > does not >> appear to fall back to looking at $LANG as it's supposed to(?), so my >> LC_CTYPE remains in the POSIX locale: ... >> So, is this my fault or Python's? I realize I could just adapt and > set >> $LC_CTYPE explicitly in my environment, but I don't want to > capitulate for a >> Python bug, if that's what this is. > > Try locale.setlocale(locale.LC_CTYPE,"") as in your C program. Oops, you are right. locale.setlocale(locale.LC_CTYPE,"") sets the locale from my environment (and gets it right!) while locale.setlocale(locale.LC_CTYPE) /returns/ the current locale. I don't know how I could have missed that, since it's clearly documented and also maps directly to C usage. > It would > be great if locale.setlocale with one parameter would be deprecated, > because it suddenly acts like getlocale. It's unpythonic. I dislike the term "unpythonic", but I tend to agree with you in practice here. Even better, but maybe not feasible, would be an approach to locales which doesn't involve changing a global state in this fashion. > By the way, since you took time to setup various LC_* variables there > is no need to play with LC_CTYPE category. Just use the standard idiom. > import locale > locale.setlocale(LC_ALL,"") Thanks for pointing that out. I picked out LC_CTYPE for my small program because I was in a hurry and didn't want to risk non-standard sorting elsewhere in the program. I hate what the LC_COLLATE=C does to swedish national characters, but I hate what LC_COLLATE=sv_SE does to non-alphabetic characters even more. To paraphrase Barbie: "i18n is hard". ;-) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From spam-trap-095 at at-andros.demon.co.uk Sun Jan 23 15:00:29 2005 From: spam-trap-095 at at-andros.demon.co.uk (Andrew McLean) Date: Sun, 23 Jan 2005 20:00:29 +0000 Subject: Fuzzy matching of postal addresses [1/1] References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: In case anyone is interested, here is the latest. I implemented an edit distance technique based on tokens. This incorporated a number of the ideas discussed in the thread. It works pretty well on my data. I'm getting about 95% matching now, compared with 90% for the simple technique I originally tried. So I have matched half the outstanding cases. I have spotted very few false positives, and very few cases where I could make a match manually. Although I suspect the code could still be improved. It took a bit of head scratching to work out how to incorporate concatenation of tokens into the dynamic programming method, but I think I got there! At least my test cases seem to work! -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: MinEditDistance5.py URL: -------------- next part -------------- -- Andrew McLean From bokr at oz.net Wed Jan 19 00:23:44 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 19 Jan 2005 05:23:44 GMT Subject: Has apparent 2.4b1 bug been fixed? flatten in Lib\compiler\ast.py overloads 'list' name References: <41ede67e.1232456679@news.oz.net> Message-ID: <41ededb0.1234298206@news.oz.net> On Wed, 19 Jan 2005 04:55:53 GMT, bokr at oz.net (Bengt Richter) wrote: >What am I missing? (this is from 2.4b1, so probably it has been fixed?) > I googled and found a bug report, but initial report kind of passes on it saying nested sequences will probably be tuples, so no panic (my paraphrased description). So I guess it's in the mill. So never mind. I should have googled first ;-/ > >def flatten(list): > l = [] > for elt in list: > ^^^^--must be expecting list instance or other sequence > t = type(elt) > if t is tuple or t is list: > ^^^^--looks like it expects to refer to the type, not the arg > for elt2 in flatten(elt): > l.append(elt2) > else: > l.append(elt) > return l > Regards, Bengt Richter From simonwittber at gmail.com Wed Jan 12 22:21:56 2005 From: simonwittber at gmail.com (Simon Wittber) Date: Thu, 13 Jan 2005 11:21:56 +0800 Subject: why are people still using classic classes? Message-ID: <4e4a11f805011219211feca15e@mail.gmail.com> I've noticed that a few ASPN cookbook recipes, which are recent additions, use classic classes. I've also noticed classic classes are used in many places in the standard library. I've been using new-style classes since Python 2.2, and am suprised people are still using the classic classes. Is there a legitimate use for classic classes that I am not aware of? Is there a project to specifically migrate standard library classes to new-style classes? Sw. From aleaxit at yahoo.com Sat Jan 1 11:28:55 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 1 Jan 2005 17:28:55 +0100 Subject: pickling a subclass of tuple References: <41d69113$0$14985$3a628fcd@reader2.nntp.hccnet.nl> Message-ID: <1gppyot.1rx6uz2fzk178N%aleaxit@yahoo.com> fedor wrote: > Hi all, happy new year, > > I was trying to pickle a instance of a subclass of a tuple when I ran > into a problem. Pickling doesn't work with HIGHEST_PROTOCOL. How should > I rewrite my class so I can pickle it? You're falling afoul of an optimization in pickle's protocol 2, which is documented in pickle.py as follows: # A __reduce__ implementation can direct protocol 2 to # use the more efficient NEWOBJ opcode, while still # allowing protocol 0 and 1 to work normally. For this to # work, the function returned by __reduce__ should be # called __newobj__, and its first argument should be a # new-style class. The implementation for __newobj__ # should be as follows, although pickle has no way to # verify this: # # def __newobj__(cls, *args): # return cls.__new__(cls, *args) # # Protocols 0 and 1 will pickle a reference to __newobj__, # while protocol 2 (and above) will pickle a reference to # cls, the remaining args tuple, and the NEWOBJ code, # which calls cls.__new__(cls, *args) at unpickling time # (see load_newobj below). If __reduce__ returns a # three-tuple, the state from the third tuple item will be # pickled regardless of the protocol, calling __setstate__ # at unpickling time (see load_build below). Essentially, and simplifying just a little...: you're inheriting __reduce_ex__ (because you're not overriding it), but you ARE overriding __new__ *and changing its signature* -- so, the inherited __reduce__ex__ is used, and, with this protocol 2 optimization, it essentially assumes that __new__ is similarly used -- or, at least, that a __new__ is used which does not arbitrarily change the signature! So, if you want to change __new__'s signature, and yet be picklable by protocol 2, you have to override __reduce_ex__ to return the right "args"... those your class's __new__ expects! For example, you could consider something like...: def __newobj__(cls, *args): return cls.__new__(cls, *args) class A(tuple): def __new__(klass, arg1, arg2): return super(A, klass).__new__(klass, (arg1, arg2)) def __reduce_ex__(self, proto=0): if proto >= 2: return __newobj__, (A, self[0], self[1]) else: return super(A, self).__reduce_ex__(proto) Note the key difference in A's __reduce_ex__ (for proto=2) wrt tuple's (which is the same as object's) -- that's after an "import a" where a.py has this code as well as an 'a = A(1, 2)'...: >>> a.a.__reduce_ex__(2) (, (, 1, 2)) >>> tuple.__reduce_ex__(a.a, 2) (, (, (1, 2)), {}, None, None) >>> Apart from the additional tuple items (not relevant here), tuple's reduce returns args as (, (1, 2)) -- two items: the class and the tuplevalue; so with protocol 2 this ends up calling A.__new__(A, (1,2))... BOOM, because, differently from tuple.__new__, YOUR override doesn't accept this signature! So, I suggest tweaking A's reduce so it returns args as (, 1, 2)... apparently the only signature you're willing to accept in your A.__new__ method. Of course, if A.__new__ can have some flexibility, you COULD have it accept the same signature as tuple.__new__ and then you wouldn't have to override __reduce_ex__. Or, you could override __reduce_ex__ in other ways, say: def __reduce_ex__(self, proto=0): if proto >= 2: proto = 1 return super(A, self).__reduce_ex__(proto) this would avoid the specific optimization that's tripping you up due to your signature-change in __new__. The best solution may be to forget __reduce_ex__ and take advantage of the underdocumented special method __getnewargs__ ...: class A(tuple): def __new__(klass, arg1, arg2): return super(A, klass).__new__(klass, (arg1, arg2)) def __getnewargs__(self): return self[0], self[1] This way, you're essentially choosing to explicitly tell the "normal" __reduce_ex__ about the particular arguments you want to be used for the __new__ call needed to reconstruct your object on unpickling! This highlights even better the crucial difference, due strictly to the change in __new__'s signature...: >>> a.a.__getnewargs__() (1, 2) >>> tuple.__getnewargs__(a.a) ((1, 2),) It IS, I guess, somewhat unfortunate that you have to understand pickling in some depth to let you change __new__'s signature and yet fully support pickling... on the other hand, when you're overriding __new__ you ARE messing with some rather deep infrastructure, particularly if you alter its signature so that it doesn't accept "normal" calls any more, so it's not _absurd_ that compensatory depth of understanding is required;-). Alex From hwlgw at hotmail.com Wed Jan 19 15:07:18 2005 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 19 Jan 2005 12:07:18 -0800 Subject: a question References: <3YvHd.80953$Jk5.28602@lakeread01> <6kwHd.48934$w62.45338@bgtnsc05-news.ops.worldnet.att.net> Message-ID: <1106165238.353672.272980@f14g2000cwb.googlegroups.com> Andrew Koenig wrote: > how about writing this instead? > > ('this is a ' > 'long string') Yes, nice. And to make that possible we have to write ('one-string-item',) instead of ('one-string-item') if we want a tuple with one string inside. Sometimes that feels like a wart to me, but now I know it, sometimes not. From fuzzyman at gmail.com Wed Jan 26 05:06:44 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 26 Jan 2005 02:06:44 -0800 Subject: python without OO In-Reply-To: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <1106734004.937008.46060@z14g2000cwz.googlegroups.com> It's perfectly possible to write good python code without using classes. (and using functions/normal control flow). You will have a problem with terrminology though - in python everything is an object (more or less). Common operations use attributes and methods of standard objects. For example : > somestring = 'fish' > if somestring.startswith('f'): > print 'It does' The above example uses the 'startswith' method of all string objects. Creating your own 'classes' of objects, with methods and attributes, is just as useful. You can certainly use/learn python without having to understand object oreinted programming straight away. On the other hand, Python's object model is so simple/useful that you *will* want to use it. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From rkern at ucsd.edu Fri Jan 7 05:50:47 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 07 Jan 2005 02:50:47 -0800 Subject: The Industry choice In-Reply-To: <1gq0k74.1epsxog1dgcgbsN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <10trej2fl8dip65@corp.supernews.com> <1gq0k74.1epsxog1dgcgbsN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Until some judge passes some judgment, the intent and effect of GPL must > remain a matter of opinion. But RMS's opinion is probably more > meaningful than mine or yours -- certainly regarding intent, given his > role in designing that license. But it may not have practical effect in an actual dispute. I believe that in some jurisdictions[1], the important piece of information in interpreting a license is the common understanding of what the license means between the disputing parties. The author of the license, if he is not one of the disputing parties, has no say in what the license means for that dispute. [1] IANAL; TINLA. This is from my memory of what I read in Lawrence Rosen's book[2] that I don't have in front of me right now. See his book, chapter 12, I think, for more details. [2] http://www.rosenlaw.com/oslbook.htm > If he's badly erred, and one day a > judge endorses your opinion and says that a program which copies no GPL > source cannot be infected by GPL, ah well -- then I guess GPL is badly > designed as to putting its intents into practice. But until there is > some strong basis to think otherwise, I believe it's prudent to assume > RMS is probably right, and your statement therefore badly wrong. I've always found, especially in light of what I wrote above, the best thing to do is to ask the author himself what he wants. If he subscribes to an unreasonable interpretation of the license, it's better that you found out quickly and avoid getting sued even though you might end up winning. You also avoid inadvertantly stepping on anyone's toes and garnering ill-will even if you never go to court. -- 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 b at b.b Sat Jan 8 15:28:03 2005 From: b at b.b (Roose) Date: Sat, 08 Jan 2005 20:28:03 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10u02s3deapvkd8@corp.supernews.com> Message-ID: Well can you describe what kind of things you want to do exactly? My guess is you are not out to develop a new algorithm for virtual memory or task scheduling. There are many parts to an OS shell. An example is the command line, i.e. bash and the like in Unix, and cmd.exe in Windows. In Windows, Windows Explorer could be considered part of the shell, as well as the start menu and all that user-specific stuff. Basically you need to pick your OS, and then find out what the API to program the shell to would be. e.g. in Windows you would do it with the Win32 API. This will let you do things like delete and create files, interact with user structures, the registry, etc. OR, as a first stab -- I would just write a prototype. i.e., don't tie it to a real OS. Just pretend you have your own "users", your own "file system", your own display space, etc. This will help you get a much better idea of what you want to do. "David Brown" wrote in message news:10u02s3deapvkd8 at corp.supernews.com... > So how would I make an OS Shell? > > From frans.englich at telia.com Mon Jan 17 15:55:33 2005 From: frans.englich at telia.com (Frans Englich) Date: Mon, 17 Jan 2005 20:55:33 +0000 Subject: Assigning to self In-Reply-To: References: Message-ID: <200501172055.33962.frans.englich@telia.com> On Monday 17 January 2005 19:02, Peter Otten wrote: > Frans Englich wrote: > > What the code attempts to do is implementing a, to the API user, > > transparent memory-saver by ensuring that no more than one instance of > > the class foo exists for a particular id. E.g, the user can simply > > "create" an instance and if one not already exists, it is created. > > By the time __init__() is called, a new Foo instance has already been > > created. Therefore you need to implement Foo.__new__(). E. g.: > >>> class Foo(object): > > ... cache = {} > ... def __new__(cls, id): > ... try: > ... return cls.cache[id] > ... except KeyError: > ... pass > ... cls.cache[id] = result = object.__new__(cls, id) > ... return result > ... def __init__(self, id): > ... self.id = id > ... def __repr__(self): > ... return "Foo(id=%r)" % self.id > ... I'm not sure, but I think this code misses one thing: that __init__ is called each time __new__ returns it, as per the docs Peter posted. Cheers, Frans From http Tue Jan 4 21:28:26 2005 From: http (Paul Rubin) Date: 04 Jan 2005 18:28:26 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> Message-ID: <7xoeg4txrp.fsf@ruckus.brouhaha.com> Jeremy Bowers writes: > So, nobody should have to write the docs because they should already be > there, but "somebody" should have to write the docs? > > You need to think more clearly about the pronouns you are slinging around. > Who is this "they" that should write the docs? The Python advocates who claim that Python is well-documented and take exception to when someone say it isn't. Their idea of "it's well-documented" seems to be "if there's parts that you think are poorly documented, feel free to document it". What kind of nonsense is that? "Python code runs just as fast as C code. If you think it's slower, feel free to speed it up". "Python's standard library includes a database module. If it isn't there, feel free to add one". "Programming in Python cures cancer. If your cancer doesn't clear up when you code in Python, feel free to submit a patch". Software advocacy, which Python has an awful lot of, involves extolling the virtues of a program as it exists in the present. Not as it could potentially exist if someone hypothetically added a bunch of work that hasn't yet been done. Python is good software, but its advocates are making claims that Python itself doesnt live up to. And no, I don't feel a responsibility to do the missing work, since I'm not the one making those advocacy claims. From snacktime at gmail.com Wed Jan 26 14:50:46 2005 From: snacktime at gmail.com (snacktime) Date: Wed, 26 Jan 2005 11:50:46 -0800 Subject: Set parity of a string In-Reply-To: References: Message-ID: <1f060c4c05012611503090c261@mail.gmail.com> I'm trying to figure out why the following code transforms ascii STX (control-b) into "\x82". The perl module I use returns a value of "^B", and that is also what the application I am communicating with expects to see. Some ascii characters such as FS and GS come through fine, but STX and ETX get transformed incorrectly (at least for what I need they do). What am I missing here? Chris > But here's one for you anyway. It raises an exception if any > input character is non-ASCII, otherwise when you call set_parity() > with a string and a parity parameter of 'even', 'mark', 'none', > 'odd', or 'space', it returns a string of the same length with > the high (parity) bits set appropriately. > > '''parity module for python''' > # Copyright 2005 Engenuity Corporation > # Released under the "MIT license" > # at http://www.opensource.org/licenses/mit-license.php > > import string > import operator > > def _makeTable(parity): > bitMap = {'even': [0,128], 'odd': [128,0], 'mark': [128,128]} > table = [] > for c in range(128): > even_odd = (sum(bool(c & 1< cp = chr(c | bitMap.get(parity, [0,0])[even_odd]) > table.append(cp) > table.extend(chr(c) for c in range(128, 256)) > table = ''.join(table) > return table, table[128:] > > _map = {} > for parity in 'even odd mark space none'.split(): > _map[parity] = _makeTable(parity) > > def set_parity(data, parity='none'): > '''return string with parity bits, accepting only ASCII characters > (0..127) as input''' > out = string.translate(data, *_map[parity.lower()]) > if len(out) != len(data): > raise ValueError('non-ASCII characters in input') > else: > return out > > if __name__ == '__main__': > print 'Running self-tests for parity.py' > > # check for invalid input handling > for input in [ '\xff', '\x80', 'test\xA0ing' ]: > try: > set_parity(input) > except ValueError: > pass > else: > assert False, 'no exception for non-ASCII input' > > # check for various valid inputs > for i, (parity, input, expected) in enumerate([ > ('space', 'test', 'test'), > ('SPACE', '\x00\x7f', '\x00\x7f'), > ('mark', 'test', '\xf4\xe5\xf3\xf4'), > ('Odd', '\x00test\x7f', '\x80\xf4\xe5s\xf4\x7f'), > ('even', '\x00\x01\x02\x03test\x7d\x7e\x7f', > '\x00\x81\x82\x03te\xf3t\x7d\x7e\xff'), > ]): > actual = set_parity(input, parity) > assert expected == actual, 'case %d: %r != %r' % (i, expected, actual) > > print 'All tests passed.' > -- > http://mail.python.org/mailman/listinfo/python-list > From philippecmartin at sbcglobal.net Wed Jan 12 10:27:43 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Wed, 12 Jan 2005 16:27:43 +0100 Subject: encryption/decryption help Message-ID: <1105543663.6716.8.camel@localhost> >>MD5 and SHA are by their very nature one way encryption. You cannot decrypt them. Indeed, the point of these algorithms is to sign data (like a fingerprint). In order to encrypt you may go for Symmetrical algos (AES, 3DES ....with those, the key must be known on both sides of the pipe) or Asymmetrical (RSA ... - where you get a private key on one side and a public key on the other - good but slow). Often you find hybrid methods: you start your session with a public/private style method just to exchange a symmetrical key that you'll use for the rest of the session. Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From apardon at forel.vub.ac.be Thu Jan 13 09:46:56 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 14:46:56 GMT Subject: Unclear On Class Variables References: Message-ID: > > Well I find this a confusing behaviour on python's part. The fact > that instance.field can mean something different, depending on > where in a statement you find it, makes the behaviour inconsistent. > > I know people in general here are against declarations, but declarations > could IMO provide more consistency here and thus more obvious behaviour. Well just to show how confusing python can be, the following piece of code. | class Spam: | eggs = [2, 3] | | | sp1 = Spam() | sp2 = Spam() | | print sp1.eggs, id(sp1.eggs) | print sp2.eggs, id(sp2.eggs) | print '--------------------' | | sp1.eggs += [4,] | | print sp1.eggs, id(sp1.eggs) | print sp2.eggs, id(sp2.eggs) | print '--------------------' | | Spam.eggs = [3,5] | | print sp1.eggs, id(sp1.eggs) | print sp2.eggs, id(sp2.eggs) | print '--------------------' Which produces: [2, 3] 1075958860 [2, 3] 1075958860 -------------------- [2, 3, 4] 1075958860 [2, 3, 4] 1075958860 -------------------- [2, 3, 4] 1075958860 [3, 5] 1075959084 -------------------- From invalidemail at aerojockey.com Mon Jan 10 06:50:39 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 10 Jan 2005 03:50:39 -0800 Subject: python3: 'where' keyword In-Reply-To: <7xis65a5w6.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> <1105355380.040837.189270@c13g2000cwb.googlegroups.com> <7xis65a5w6.fsf@ruckus.brouhaha.com> Message-ID: <1105357839.696387.309900@c13g2000cwb.googlegroups.com> Paul Rubin wrote: > "Carl Banks" writes: > > > So do you approve of the movement to get rid of the print statement? > > > > Any little incremental change in Python you could make by having or not > > having a print statement would be minor compared to the H-Bomb of > > ugliness we'd get if suites of statements were to be allowed inside > > Python expressions. Having or not having a print statement might > > violate some small aspect of the Zen, but it won't rape the whole list. > > How about macros? Some pretty horrible things have been done in C > programs with the C preprocessor. But there's a movememnt afloat to > add hygienic macros to Python. Got any thoughts about that? How about this: Why don't you go to a Python prompt, type "import this", and read the Zen of Python. Consider each line, and whether adding macros to the language would be going against that line or for it. After you've done that, make an educated guess of what you think I'd think about macros, citing various Zens to support your guess. Then I'll tell you what my my thoughts about it are. > > So I don't know what point you're trying to make. > > Why should you care whether the output of a macro is ugly or not, > if no human is ever going to look at it? I don't. > > But to answer your question, I would prefer a Python without a print > > statement, since a print method could do anything the print statement > > could. > > A print -method-?!! [snip example] > > I've heard of people wanting to replace print with a function, but > hadn't heard of replacing it with a method. Are you trying to turn > Python into Ruby? I'll give you the benefit of the doubt that you just didn't think it over thoroughly. I was thinkging would be a method of file like objects. stdout.print("hello") -- CARL BANKS From ncoghlan at iinet.net.au Sun Jan 9 01:58:24 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 16:58:24 +1000 Subject: python3: 'where' keyword In-Reply-To: <7xsm5b2m93.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> Message-ID: <41E0D610.1080803@iinet.net.au> Paul Rubin wrote: > Nick Coghlan writes: > >>I think having to keep the names unique within the statement you are >>currently writing is a reasonable request :) > > > Um, you could say the same thing about the function, the module, etc. ;) > And, indeed, that is what Python currently says. When writing code, the relevant namespaces are the builtins, the module, any containing functions and the current function. Inadvertent conflicts with any of those can have surprising side effects. The idea of 'where' is to push that down one level, and allow a namespace to be associated with a single statement. Trying to push it a level further (down to expressions) would, IMO, be a lot of effort for something which would hurt readability a lot. Compare: x = sqrt(a) + sqrt(b) where: a = 2.0 b = 3.0 This brings the operation we care about (add the sqrt's of 2 and 3) right up front. A folding code editor could actually hide the details quite easily. We can look inside the statement if we want to know what x & y actually are. Versus: x = (sqrt(a) where: a = 2.) \ + sqrt (a) where: a = 3. We haven't gotten rid of anything here - all the stuff we're interested in clearing out of the way is still embedded in the middle of our statement. Also not insignificantly, we're trying to put a suite inside an expression, which will be rejected for all the reasons that have kept lambda restricted to a single expression despite numerous complaints over time. Now, nothing in the idea of a statement local namespace actually *rules out* the prospect of an expression local namespace, so it could be added at a later date. However, doing so would require some actual use cases, and an expression-friendly syntax. Perhaps something that involves providing the namespace directly, like: x = (sqrt(a) where (a=2.0)) + (sqrt(b) where (a=3.0)) It seems to make more sense to try for statement local namespaces *first*, and then see if expression local namespaces are worth it. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From frans.englich at telia.com Mon Jan 24 21:42:19 2005 From: frans.englich at telia.com (Frans Englich) Date: Tue, 25 Jan 2005 02:42:19 +0000 Subject: Distutils: blurring the file==module borders In-Reply-To: <797fe3d40501241817765fd2b1@mail.gmail.com> References: <200501250215.58729.frans.englich@telia.com> <797fe3d40501241817765fd2b1@mail.gmail.com> Message-ID: <200501250242.19841.frans.englich@telia.com> On Tuesday 25 January 2005 02:17, Bill Mill wrote: > read this thread, it should help you: > > http://mail.python.org/pipermail/tutor/2005-January/035124.html Thanks, it did. Not optimally, but in the way I suspected it would be solved. In short, the solution, when translated to my case, is to in __init__.py do `from ClassA import ClassA`, and hence get the /class/ ClassA in the module's namespace. Note, I did not do `from foo.ClassA import ClassA` because that failed. To me, it is kinda hackish; it doesn't show up in the pydocs, and no idea if it shadows the actual module(assuming they have identical names, which they have) but it appears it can't be solved in a better way. Another approach would to do copy&paste with the build system at install time, but I will not sink that low.. Cheers, Frans From stuartm at mathworks.com Mon Jan 24 10:57:47 2005 From: stuartm at mathworks.com (Stuart McGarrity) Date: Mon, 24 Jan 2005 10:57:47 -0500 Subject: Memory Usage References: Message-ID: Do you have a page file? The Mem column should be RAM usage and not total working set. Some of it could be swapped to the page file. A free tool like process explorer can give you better informaton than the task manager. "rbt" wrote in message news:ct2v9f$k3t$1 at solaris.cc.vt.edu... > Would a Python process consume more memory on a PC with lots of memory? > > For example, say I have the same Python script running on two WinXP > computers that both have Python 2.4.0. One computer has 256 MB of Ram > while the other has 2 GB of Ram. On the machine with less Ram, the process > takes about 1 MB of Ram. On the machine with more Ram, it uses 9 MB of > Ram. > > Is this normal and expected behavior? > > Thanks, > > rbt From aleaxit at yahoo.com Sat Jan 22 03:50:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 09:50:36 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> Message-ID: <1gqsayh.th49i518ixczeN%aleaxit@yahoo.com> Dave Benjamin wrote: > Can we get a show of hands for all of those who have written or are > currently maintaining code that uses the leaky listcomp "feature"? "Have written": guilty -- basically to show how NOT to do things. "Currently maintaining": you _gotta_ be kidding!-) > I guess I've been peripherally aware of it, but I almost always use > names like "x" for my loop variables, and never refer to them > afterwards. If Python were to change in this regard, I don't think it > would break any Python code that I've ever written or maintained... If it changed the semantics of for-loops in general, that would be quite inconvenient to me -- once in a while I do rely on Python's semantics (maintaining the loop control variable after a break; I don't recall if I ever used the fact that the variable is also maintained upon normal termination). (musing...): I think the reason there's no real use case for using a listcomp's control variable afterwards is connected to this distinction: listcomps have no `break'... Alex From philippecmartin at sbcglobal.net Fri Jan 21 08:08:11 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Fri, 21 Jan 2005 07:08:11 -0600 Subject: What's the best python web-developer's editor Message-ID: <1106312891.7175.4.camel@localhost> >>Emacs >>For both discrete and mixed python and html code, and why? >>There's no reason to use anything else. Although I tested and will keep testing other editors/ide, I also went back to emacs and am quite happy with it. However, I sometimes use snavigator (http://sourceforge.net/projects/sourcenav) when I need to browse through a project (although I could use emacs TAGS, I find snavigator to be the best free solution out there to parse large projects) Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From wittempj at hotmail.com Tue Jan 18 14:16:40 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 18 Jan 2005 11:16:40 -0800 Subject: hex notation funtion In-Reply-To: References: Message-ID: <1106075800.825535.254540@c13g2000cwb.googlegroups.com> This will do it: >>> int('10000000', 2) 128 >>> hex(int('10000000', 2)) '0x80' >>> From __peter__ at web.de Tue Jan 11 07:37:19 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Jan 2005 13:37:19 +0100 Subject: [csv module] duplication of end of line character in output file generated References: Message-ID: simon.alexandre wrote: > I use csv module included in python 2.3. I use the writer and encouter the > following problem: in my output file (.csv) there is a duplication of the > end of line character, so when I open the csv file in Ms-Excel a blank > line is inserted between each data line. > > OS: W2k > > Someone has an idea ? > > thanks in advance > > the source code is the following: > > --------------------------------------------------> > import csv > > class CsvDumper: > > def __init__(self): > self.object = > [['la','mb','mc','md'],['ma','mb','mc','md'],['ma','mb','mc','md']] > self.writer = csv.writer(file("Test.csv", "w")) Try opening the file in binary mode: file("Test.csv", "wb") > def DumpCsvFile(self): > for row in self.object: > self.writer.writerow(row) > > c = CsvDumper() > c.DumpCsvFile() From timr at probo.com Tue Jan 25 03:23:39 2005 From: timr at probo.com (Tim Roberts) Date: Tue, 25 Jan 2005 00:23:39 -0800 Subject: Why can't use cursor.nextset() in adodbapi package? References: Message-ID: <790cv0l0kbqmcf9ltfpfp35npd71latt71@4ax.com> nightmarch wrote: >Thank you Dennis! > >You mean I should execute many select statement like this " rec = >crsr.fetchall() " ? No, you misunderstand. nextset() is used when you issue several SELECT statements in a single request. The first fetchall() gets the results of the first SELECT statement. To get the next one, you use nextset(). Your example only had one SELECT: >> > >>> sql = "select * from wjtmp" >> > >>> crsr.execute(sql) >> > >>> rec = crsr.fetchone() >> > >>> crsr.nextset() If you are only issuing one SELECT, like most applications, then nextset() serves no purpose. If you did something like this: sql = "select * from wjtmp; select count(*) from wjtmp;" That's when you need nextset(). Personally, I've never used it. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From esj at harvee.org Tue Jan 18 12:57:21 2005 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 18 Jan 2005 12:57:21 -0500 Subject: simultaneous multiple requests to very simple database In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E33981ED@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E33981ED@exchange.hqamor.amorhq.net> Message-ID: <41ED4E01.1040400@harvee.org> Robert Brewer wrote: > Eric S. Johansson wrote: > >>I have an application where I need a very simple database, >>effectively a very large dictionary. The very large >>dictionary must be accessed from multiple processes >>simultaneously. I need to be able to lock records within >>the very large dictionary when records are written to. > > > Just to clarify, you want shared-read until a write, at which point you > want to lock just the item being written? Or would page or table locking > be acceptable at that point? just the item/record. I'm doing arrival rate calculations. each record contains a set of arrival times and I am rewriting the record every time a new entry arrives. complete page or table locking will work in the sense that it will prevent collisions but it will have an increasing impact as load and simultaneous table but not record accesses increase. ---eric From hans at zephyrfalcon.org Sat Jan 1 17:23:32 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sat, 01 Jan 2005 17:23:32 -0500 Subject: UserDict deprecated In-Reply-To: References: Message-ID: Uwe Mayer wrote: >>>Why is the UserDict module is deprecated after Python 2.2. The >>>application of it I have in mind is, i.e. multiple inheritance from >>>"file" and "dic" - which is not possible. [...] > I was writing a class that read /writes some binary file format. I > implemented the functions from the file interface such that they are > refering to records. However, the file format has some header fields and > I'd wanted to grant access to those via the dict-interface. > > Another example: working with PyQt I have an instance of a QListView and > wanted to use the list-interface to get and set individual records. If it's just a matter of attribute access, implementing the relevant __getitem__ and __setitem__ methods will probably suffice. I don't think that deriving from dict or list will do you much good here... most of the methods will be irrelevant, or won't do what you want, so you have to override them anyway. -- Hans Nowak http://zephyrfalcon.org/ From pythongnome at hotmail.com Wed Jan 12 08:10:20 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 12 Jan 2005 13:10:20 GMT Subject: [OT] SciTe In-Reply-To: <41e4c577$0$6628$626a14ce@news.free.fr> References: <58%Ed.4827$C52.2609@newsread2.news.atl.earthlink.net> <41e4c577$0$6628$626a14ce@news.free.fr> Message-ID: <0l9Fd.4419$KJ2.747@newsread3.news.atl.earthlink.net> Fouff wrote: > I use Scintilla which is Scite with a lot of configurations files. > In directory exists a file "cpp.properties" and near the end of the file > is describe the command line use to compile, to link, ... > > I think you would be able to change here the compiler. > > regards > Fouff Thanks. From sp1d3rx at gmail.com Wed Jan 26 18:13:00 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 26 Jan 2005 15:13:00 -0800 Subject: Question Regarding SocketServer In-Reply-To: <1106692228.117977.104720@f14g2000cwb.googlegroups.com> References: <1106684900.771730.218060@f14g2000cwb.googlegroups.com> <1106688660.694617.290330@c13g2000cwb.googlegroups.com> <1106691478.621949.44020@z14g2000cwz.googlegroups.com> <1106692228.117977.104720@f14g2000cwb.googlegroups.com> Message-ID: <1106781180.062520.161800@c13g2000cwb.googlegroups.com> I am glad you were able to figure it out. It's strange that the pyc file didn't get updated... it should have automatically fixed itself. *shrug* that's one of those problems that aggrivate you to death... From peter at engcorp.com Fri Jan 21 09:01:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Jan 2005 09:01:00 -0500 Subject: Graph and Table implementation In-Reply-To: References: Message-ID: Jan Rienyer Gadil wrote: > could anyone please help me! > > what and how is the best implementation of creating a table based on What is a "table", to you? It could mean anything from something you intend to print, to a GUI-based representation similar to a spreadsheet, to a simple two-dimensional array of data in memory. > data coming from the serial port ? and also how would i be able to > create graphs (2D) based on these data? Platform? GUI framework, if you've chosen one? etc. etc. I might suggest using wxPython, with a wx.Grid and wxPyPlot, but given how little useful information you've provided, that could well be far from suitable. -Peter From gmuller at worldonline.nl Sat Jan 15 14:04:07 2005 From: gmuller at worldonline.nl (GerritM) Date: Sat, 15 Jan 2005 20:04:07 +0100 Subject: hash patent by AltNet; Python is prior art? Message-ID: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> ZDnet features an article about the had patent at AltNet http://news.zdnet.com/2100-9588_22-5534087.html . Apparantly this issue plays already for some time, now the p2p companies are threatened, becuase they use hashing to recognize files. As far as I know hasing is a very old technique used to quickly look up information. The use of hashing always requires an idnetity check, because the lookup is not unique (mapping a very big amount of possibilities on a limited amount of entries). This is a fast and robust way of finding information, if the right hashing function is used. How can this type of fundamental knowledge be patented? I am afraid this is again an example of a total failure of the current patent system. Unfortunately these ridiculous examples endanger smaller companies, open software activities amd innovation in general. kind regards, Gerrit -- Praktijk voor Psychosociale therapie Lia Charit? From jstroud at mbi.ucla.edu Fri Jan 7 22:28:09 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 7 Jan 2005 19:28:09 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: <7xvfa90w6g.fsf@ruckus.brouhaha.com> References: <7xvfa90w6g.fsf@ruckus.brouhaha.com> Message-ID: <200501071928.14651.jstroud@mbi.ucla.edu> On Friday 07 January 2005 01:24 pm, Paul Rubin wrote: > Nick Coghlan writes: > > Add in the fact that there are many, many Python programmers with > > non-CS backgrounds, and the term 'lambda' sticks out like a sore thumb > > from amongst Python's other English-based keywords. > > Richard Feynman told a story about being on a review committee for > some grade-school science textbooks. One of these book said something > about "counting numbers" and it took him a while to figure out that > this was a new term for what he'd been used to calling "integers". I think we should not try too hard to make everything "English" like. Its a crappy language anyway (though its the only one I speak good). Matt Neuberg, in _AppleScript: The Definitive Guide_, refers to "the English-likeness monster". His example is that instead of x = 4 you have to say copy 4 to x I think every reader of this list would prefer to look at the former. The point is that once we learn new symbolics of expression, they are as simple to decipher as plain old English if we format properly and gIvEnThAtwEiNcLuDEsOmEhElPfUlfORmaTtInGInOuRcOdEFroMtImEtOtiME. So I think that being fearful of new additions to the language (read "more ability for expression") is mainly fear of abuse by poor programmers--and that is akin to being afraid of the dark. James -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics 611 Charles E. Young Dr. S. MBI 205, UCLA 951570 Los Angeles CA 90095-1570 http://www.jamesstroud.com/ From itsme at yahoo.com Wed Jan 12 12:42:50 2005 From: itsme at yahoo.com (It's me) Date: Wed, 12 Jan 2005 17:42:50 GMT Subject: counting items Message-ID: Okay, I give up. What's the best way to count number of items in a list? For instance, a=[[1,2,4],4,5,[2,3]] I want to know how many items are there in a (answer should be 7 - I don't want it to be 4) I tried: b=len([x for y in a for x in y]) That doesn't work because you would get an iteration over non-sequence. I tried: g=lambda x: (1,len(x))[isinstance(x,(list,tuple,dict))] b=sum(lambda(x) for x in a) and that didn't work because I get a TypeError from the len function (don't know why) I can, of course: i=0 for x in a: if isinstance(x,(list,tuple,dict)): i += len(x) else: i += 1 but that's so C-like... Thanks, From hpk at trillke.net Tue Jan 4 17:08:38 2005 From: hpk at trillke.net (holger krekel) Date: Tue, 4 Jan 2005 23:08:38 +0100 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> Message-ID: <20050104220838.GA7646@solar.trillke.net> Hi Roman, On Wed, Jan 05, 2005 at 00:44 +0300, Roman Suzi wrote: > Python could have honest support of concepts. Everything else will be > available with them. > > That is the whole point that Python supports GP. It is only one step > to do concepts right (and GvR it seems want type-checking into Python 3.0 > anyway), so support for concepts/concept checking is very logical, > isn't it? As an innocent by-dropper into this thread: a) do you know Armin Rigo's "semantic model" page dealing with concepts? http://arigo.tunes.org/semantic_models.html b) do you have some concise definition of what you mean by "concept"? Myself, i appreciate the combination of testing and python's flexibility so much that i don't long for type declarations, at least not to the degree that would warrant syntax additions. Now for interfaces, for me this references more a documentation issue than a syntax one: I'd like to have a full-featured runtime browser that allows to quickly navigate cross-referenced life python objects. Back and forth in execution time, preferably. This probably requires the interpreter to help, track and record more information (which is one of the possibilities with PyPy). It doesn't neccessarily require any new syntax though. And I don't really see the point of adding interface hierarchies to already large frameworks. To me this adds to - what i call - "naming complexity", i.e. the number of names a programmer needs to remember to deal with a library or framework. For me, it's not really the syntax that is the problem with interfaces in Zope3 or twisted, but the sheer amount of names (each indicating certain concepts and behaviours) i am confronted with. Not sure why i am saying all this here but have fun, holger From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Jan 6 16:17:15 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Thu, 6 Jan 2005 22:17:15 +0100 Subject: Pb encodage & import Message-ID: <41ddaaef$0$2749$8fcfb975@news.wanadoo.fr> Bonsoir ! Hi ! My english is short, therefore, I do short. Two scripts, "i1.py" and "i2.py" : i1.py : import i2 print i2.GlobalA i2.py : GlobalA ="azerty" Like this, it's OK ; but : i1.py : import i2 print i2.GlobalA i2.py : GlobalA = "azerty" OK ============================== i1.py : import i2 print i2.GlobalA i2.py : # -*- coding: cp1252 -*- GlobalA = "azerty" SyntaxError ============================== i1.py : import i2 print i2.GlobalA i2.py : # -*- coding: utf-8 -*- GlobalA = "azerty" OK ============================== i1.py : # -*- coding: utf-8 -*- import i2 print i2.GlobalA i2.py : # -*- coding: utf-8 -*- GlobalA = "azerty" OK ============================== i1.py : # -*- coding: utf-8 -*- import i2 print i2.GlobalA i2.py : # -*- coding: cp1252 -*- GlobalA = "azerty" SyntaxError ============================== i1.py : # -*- coding: utf-8 -*- import i2 print i2.GlobalA i2.py : GlobalA = u"az?rty" #see unicode & accent OK ============================== i1.py : # -*- coding: utf-8 -*- import i2 print i2.GlobalA i2.py : # -*- coding: utf-8 -*- GlobalA = u"az?rty" #see unicode & accent UnicodeDecodeError ============================== All files are recorded in ANSI ; tests with Python 2.4 on Win-XP. Ideas, ou suggests ? @-salutations -- Michel Claveau From klachemin at comcast.net Fri Jan 7 15:56:33 2005 From: klachemin at comcast.net (Kamilche) Date: 7 Jan 2005 12:56:33 -0800 Subject: Calling Function Without Parentheses! In-Reply-To: <10tttc6vblse9@corp.supernews.com> References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> <41D8B5F4.1010903@mxm.dk> <1105113743.189469.115440@f14g2000cwb.googlegroups.com> <10tttc6vblse9@corp.supernews.com> Message-ID: <1105131393.355381.105800@c13g2000cwb.googlegroups.com> Uh, you're right! I wouldn't want to bog Python down with even more checking at run time. I guess I'm asking for syntax checks that are typically done only with compiled languages. It doesn't stop me from using Python, though! Since I don't have syntax checking, I find I have to test supporting routines thoroughly, to make sure it errs when it should err and runs when it should run. That's something that's always good to do, but it's especially useful in Python, which has no syntax checking before runtime. From bingham at cenix-bioscience.com Tue Jan 18 03:09:09 2005 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Tue, 18 Jan 2005 09:09:09 +0100 Subject: Fuzzy matching of postal addresses In-Reply-To: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <41ECC425.2000109@cenix-bioscience.com> Andrew McLean wrote: > I have a problem that is suspect isn't unusual and I'm looking to see if > there is any code available to help. I've Googled without success. > > Basically, I have two databases containing lists of postal addresses and > need to look for matching addresses in the two databases. More > precisely, for each address in database A I want to find a single > matching address in database B. I had a similar problem to solve a while ago. I can't give you my code, but I used this paper as the basis for my solution (BibTeX entry from http://citeseer.ist.psu.edu/monge00adaptive.html): @misc{ monge-adaptive, author = "Alvaro E. Monge", title = "An Adaptive and Efficient Algorithm for Detecting Approximately Duplicate Database Records", url = "citeseer.ist.psu.edu/monge00adaptive.html" } There is a lot of literature--try a google search for "approximate string match"--but very little publically available code in this area, from what I could gather. Removing punctuation, etc., as others have suggested in this thread, is _not_sufficient_. Presumably you want to be able to match typos or phonetic errors as well. This paper's algorithm deals with those problems quite nicely, -- -------------------------------------------------------------------- Aaron Bingham Application Developer Cenix BioScience GmbH -------------------------------------------------------------------- From michele.simionato at gmail.com Tue Jan 4 04:43:18 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 4 Jan 2005 01:43:18 -0800 Subject: Python evolution: Unease In-Reply-To: <7x652dk0gh.fsf@ruckus.brouhaha.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1104830276.579755.133870@f14g2000cwb.googlegroups.com> <7x652dk0gh.fsf@ruckus.brouhaha.com> Message-ID: <1104831798.408560.228940@c13g2000cwb.googlegroups.com> Maybe a PSF grant would help? I guess this has been considered ... Michele Simionato From aleaxit at yahoo.com Wed Jan 26 09:51:14 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 26 Jan 2005 15:51:14 +0100 Subject: fast list lookup References: <3e96ebd7.0501260641.159e007f@posting.google.com> Message-ID: <1gr06n6.170sqn1n6u0n4N%aleaxit@yahoo.com> Klaus Neuner wrote: > what is the fastest way to determine whether list l (with > len(l)>30000) contains a certain element? "if thecertainelement in l:" is the fastest way unless there are properties of l which you're not telling us about, or unless what you need is not just to determine whether l contains a certain element but rather something different (such as doing the same determination for several elements on an unchanging l). Alex From jeff at ccvcorp.com Thu Jan 27 13:59:22 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 27 Jan 2005 10:59:22 -0800 Subject: how to comment out a block of code In-Reply-To: <1106767695.572974.98920@z14g2000cwz.googlegroups.com> References: <1106767695.572974.98920@z14g2000cwz.googlegroups.com> Message-ID: <10vie53lfgid68a@corp.supernews.com> Xah Lee wrote: > is there a syntax to comment out a block of code? i.e. like html's > or perhaps put a marker so that all lines from there on are ignored? > thanks. Of course -- this feature is so important that all computer manufacturers worldwide have made a special button on the computer case just for this! Normally it's a large round button, with perhaps a green backlight. Press the button and hold it in for about 3 seconds, and the rest of your code/writing will be ignored just as it should be. Jeff Shannon Technician/Programmer Credit International From steven.bethard at gmail.com Fri Jan 21 20:57:58 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 18:57:58 -0700 Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) Message-ID: I wrote: > If you really want locals that don't contribute to arguments, I'd be > much happier with something like a decorator, e.g.[1]: > > @with_consts(i=1, deftime=time.ctime()) > def foo(x, y=123, *args, **kw): > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime > > Then you don't have to mix parameter declarations with locals > definitions. > > Steve > > [1] I have no idea how implementable such a decorator would be. I'd > just like to see function constants declared separate from arguments > since they mean such different things. I played around with this, and I think it's basically implementable: py> import new py> class with_consts(object): ... def __init__(self, **consts): ... self.consts = consts ... def __call__(self, func): ... return new.function(func.func_code, ... dict(globals(), **self.consts)) ... py> @with_consts(y=123) ... def f(x): ... return x*y, str ... py> f(2) (246, ) I just update the function globals with the keywords passed to the decorator. The only problem is that updates to globals() aren't reflected in the function's globals: py> str = 5 py> f(2) (246, ) Steve From flamesrock at gmail.com Fri Jan 7 20:17:52 2005 From: flamesrock at gmail.com (flamesrock) Date: 7 Jan 2005 17:17:52 -0800 Subject: EOF for binary? Message-ID: <1105147072.909665.242360@z14g2000cwz.googlegroups.com> Hi, So if I understand correctly, there are NO eof characters in any binary file. If so, is there an easier way to check for the end of the file than: os.path.getsize(infile) <= infile.tell() Because that returns the error: # File "/usr/lib/python2.3/posixpath.py", line 142, in getsize # return os.stat(filename).st_size #TypeError: coercing to Unicode: need string or buffer, file found for me. -thanks in advance flamesrock From ed at leafe.com Thu Jan 13 07:55:44 2005 From: ed at leafe.com (Ed Leafe) Date: Thu, 13 Jan 2005 07:55:44 -0500 Subject: py2exe Excludes In-Reply-To: References: Message-ID: <6FE0D374-6562-11D9-A18A-003065B11E84@leafe.com> On Jan 13, 2005, at 12:04 AM, vincent wehren wrote: > Just a guess: What happens if you remove everything that's in the > "build" directory before running setup.py? There may still be files > around from an earlier build that *did* include the Dabo modules. Ah, that was it! I didn't realize that it would still pull those things in there. I wiped out the build directory and re-ran setup, and it's now what I expected. Thanks! ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From ialbert at mailblocks.com Mon Jan 10 15:21:56 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 10 Jan 2005 15:21:56 -0500 Subject: Writing huge Sets() to disk In-Reply-To: References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> Message-ID: Martin MOKREJ? wrote: > But nevertheless, imagine 1E6 words of size 15. That's maybe 1.5GB of raw > data. Will sets be appropriate you think? You started out with 20E20 then cut back to 1E15 keys now it is down to one million but you claim that these will take 1.5 GB. On my system storing 1 million words of length 15 as keys of a python dictionary is around 75MB. I. From fredrik at pythonware.com Sat Jan 22 08:26:00 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 14:26:00 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com><797fe3d405011911465ab59acd@mail.gmail.com><1106177050.630141.33090@c13g2000cwb.googlegroups.com><972ec5bd0501191641166972b0@mail.gmail.com><7xis5szpdj.fsf@ruckus.brouhaha.com><7xekggbrns.fsf@ruckus.brouhaha.com><7x651rwbib.fsf@ruckus.brouhaha.com><7xfz0uqe1d.fsf@ruckus.brouhaha.com><1gqsayh.th49i518ixczeN%aleaxit@yahoo.com><7xpszxljra.fsf@ruckus.brouhaha.com> <7x4qh9pqhw.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> > Some languages let you say things like: >> > for (var x = 0; x < 10; x++) >> > do_something(x); >> > and that limits the scope of x to the for loop. >> >> depending on the compiler version, compiler switches, IDE settings, etc. > > Huh? I'm not sure what you're talking about. guess you haven't used some languages that do this long enough. in some early C++ compilers, the scope for "x" was limited to the scope containing the for loop, not the for loop itself. some commercial compilers still default to that behaviour. From bob_smith_17280 at hotmail.com Wed Jan 19 22:04:44 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Wed, 19 Jan 2005 22:04:44 -0500 Subject: list item's position Message-ID: Hi, I have a Python list. I can't figure out how to find an element's numeric value (0,1,2,3...) in the list. Here's an example of what I'm doing: for bar in bars: if 'str_1' in bar and 'str_2' in bar: print bar This finds the right bar, but not its list position. The reason I need to find its value is so I can remove every element in the list before it so that the bar I found somewhere in the list becomes element 0... does that make sense? Thanks, Bob From quentel.pierre at wanadoo.fr Sat Jan 8 09:36:09 2005 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Sat, 08 Jan 2005 15:36:09 +0100 Subject: The best way to do web apps with Python? In-Reply-To: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41dfefdc$0$8011$8fcfb975@news.wanadoo.fr> worzel a ?crit : > What is the best way to web developemnt with Python? Is there anything > close to PHP style in-page script placement that can create and use > other Python objects? I am not really interested in Zope (I believe that > is more a CMS than anything else?) I am also looking for something a > little more structured than a series of CGI Scripts. > There are quite a few web frameworks in Python, see http://www.python.org/moin/WebProgramming I'm biaised in favour of Karrigell (http://karrigell.sourceforge.net), the "Python Inside HTML" pages look and behave very much like PHP Regards, Pierre From jepler at unpythonic.net Thu Jan 13 18:43:01 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 13 Jan 2005 17:43:01 -0600 Subject: Octal notation: severe deprecation In-Reply-To: <41e6f606.777680996@news.oz.net> References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> <39ednWfqlrgB6HvcRVn-iA@powergate.ca> <41e6f606.777680996@news.oz.net> Message-ID: <20050113234300.GA1513@unpythonic.net> On Thu, Jan 13, 2005 at 11:04:21PM +0000, Bengt Richter wrote: > One way to do it consistently is to have a sign digit as the first > digit after the x, which is either 0 or base-1 -- e.g., +3 and -3 would be > > 2x011 2x101 > 8x03 8x75 > 16x03 16xfd > 10x03 10x97 ... so that 0x8 and 16x8 would be different? So that 2x1 and 2x01 would be different? Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From christian at mvonessen.de Wed Jan 26 15:20:25 2005 From: christian at mvonessen.de (Christian von Essen) Date: Wed, 26 Jan 2005 21:20:25 +0100 Subject: how to comment out a block of code References: <1106767695.572974.98920@z14g2000cwz.googlegroups.com> Message-ID: A bit of a hack of course, but you can enclose the code that should be commented out with ''' and ''' or """ and """ (not sure about the name of this tripple-quoting) OTOH, some (or even most if not all) Python editors support blockquoting by pushing a button or using shortcuts. SPE and IDLE for example. From ncoghlan at iinet.net.au Sun Jan 23 00:37:59 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 23 Jan 2005 15:37:59 +1000 Subject: dynamic call of a function In-Reply-To: <1106394057.320879.319110@f14g2000cwb.googlegroups.com> References: <3BCFE666.C8C6136C@c-s.fr> <1106394057.320879.319110@f14g2000cwb.googlegroups.com> Message-ID: <41F33837.6020306@iinet.net.au> kishore wrote: > Hi Luigi Ballabio, > > Thankyou very much for your reply, > it worked well. It does work in most cases, but "getattr(self, methodName)" is generally to be preferred over "vars(self.__class__)[methodName]", as the latter does not use Python's standard attribute lookup scheme. The semantics of the following two statements are basically identical: getattr(t, 'bar')() t.bar() Using vars() directly, however, results in a slightly different lookup process that will *usually* give the same answer as above, but not always. It's that 'not always' which can end up hurting. . . Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steve at holdenweb.com Thu Jan 20 09:04:00 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 20 Jan 2005 09:04:00 -0500 Subject: Zen of Python In-Reply-To: <7xekggbrns.fsf@ruckus.brouhaha.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Tim Peters writes: > >>>Huh? [1,2,[3,4,5],[6,[[[[7]],8]]]] is a perfectly valid Python list. >> >>You're claiming not to know any relevant difference between Python >>lists and Lisp lists? Heh. > > > Python doesn't provide syntactic sugar for [1,[2,[3,[4,[]]]]] if > that's what you mean. In Lisp you'd say (1 2 3 4). It's still > a perfectly valid list in Python. Python by convention uses > multi-element arrays instead of lists of conses. > But how, in Lisp, would you transliterate the Python list [1, 2, 3, 4]? Clearly the Python list *is* different, and the tradeoff was to obtain speed of random access, presumably (I wasn't taking an interest in Python in its early days) anticipating that non-recursive algorithms would be the norm. > >>>And you can break out of a containing loop from a nested loop >>>with try/raise. >> >>Heh heh. Yes, you can. I've never seen a real Python program that >>did, but there's nothing to stop you. > > > I do that on a fairly routine basis. I won't say "often", but it's a > standard technique that finds a use now and then. > Well, I blush to say I have done that (once, if my memory serves me correctly), but it was an ugly program, and I did eventually refactor the code so that the loops were in separate scopes, which made it much cleaner. [...] > > There's a technique in numerical analysis called Richardson > extrapolation, where you compute an integral by [...] Wow. Anyone who feels the need to explain numerical analysis techniques to Tim Peters is wasting keystrokes big-time. Anyway, Richardson extrapolation is merely one of many successive approximation techniques, which is what you are talking about, no? > > I see the same thing happening in Python. It's going through > successively better approximations to get closer to a limit. Python > has it harder than some other languages, because it tries to serve the > needs of both throwaway scripts and large-scale development projects. > The result is that feature after feature starts out with an > implementation sufficient for small scripts, and then edges towards > the needs of large-scale projects. But it's often predictable at the > beginning what the final destination is going to be. So once we can > see where it's going, why not proceed to the finish line immediately > instead of bothering with the intermediate steps? Perhaps because we don't all have your psychic powers? 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 ruses at users.ch Sat Jan 1 20:10:37 2005 From: ruses at users.ch (not [quite] more i squared) Date: Sun, 02 Jan 2005 02:10:37 +0100 Subject: Jython & IronPython Under Active Development? In-Reply-To: <1104039182.718016.78800@f14g2000cwb.googlegroups.com> References: <1104033303.754319.269650@c13g2000cwb.googlegroups.com> <1104039182.718016.78800@f14g2000cwb.googlegroups.com> Message-ID: <33ovhlF4174m3U1@individual.net> Simon John a ?crit : > jython just had a new and (thus) secret afaik > release From aleaxit at yahoo.com Sun Jan 9 06:41:47 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 9 Jan 2005 12:41:47 +0100 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1gq4ebf.17qqy8dk9ccr6N%aleaxit@yahoo.com> Message-ID: <1gq4frz.qt7y5notvifvN%aleaxit@yahoo.com> Nick Coghlan wrote: > Alex Martelli wrote: > > I wonder if 'with', which GvR is already on record as wanting to > > introduce in 3.0, might not be overloaded instead. > > Perhaps we could steal 'using' from the rejected decorator syntax. > > x = [f(x) for x in seq] using: > def f(x): > return x * x If 'with' is going to become a keyword anyway, I suspect that many, Guido included, would see giving 'with' two distinct syntax roles as a lower 'price' than introducing yet another keyword, as long of course as no ambiguity results. 'import', for example, is happily reused for both 'import foo' and 'from foo import bar'. In terms of readability I see nothing in it, either way, between 'with' and 'using' (and 'where', were it not for the wildly different semantics it has in SQL) -- e.g. your example seems to read just fine with any of these keywords. If the use Guido intends for 'with' is something like: with aname: .x = .y meaning aname.x = aname.y then there would be no ambiguity between this use of with as a leading keyword in the new statement, always followed by a name; and its use in the "with clause", where it always comes after an expression and is immediately followed by a colon. I mean, no ambiguity for either the parser or a human reader, I believe. Once the AST-branch is folded back into the CVS head, playing around with syntax should be much easier than today... Alex From belovedbob at XXgreennet.net Thu Jan 27 21:06:04 2005 From: belovedbob at XXgreennet.net (Robert Kaplan) Date: Thu, 27 Jan 2005 21:06:04 -0500 Subject: Greetings and win32 com events question Message-ID: <41f9d4f2$1@news.greennet.net> Hi, I'm new to the group, so greetings all! I'm working on an application try to respond to events in Microsoft Access using Python and win32com. However, I'm having trouble in setting up the event handlers. I can think of 2 approaches both of which yield win32com errors. First is the approach used the MSOfficeEvents.py test program. The problem is that the events to be picked up are not on the Application object but on a Form object created from it. class AcEvents def OnActivate(self): print "Hello from Access" return 1 self. ac = Dispatch ("Access.Application") self. db = self. ac. NewCurrentDatabase ("d:\\pyhack\\foo") self. fm = self. ac. CreateForm () self. ac. Visible = true self. fm = DispatchWithEvents (self. fm, AcEvents) blows out with self. fm = DispatchWithEvents (self. fm, AcEvents) File "D:\PYTHON22\Lib\site-packages\win32com\client\__init__.py", line 258, in DispatchWithEvents clsid = disp_class.CLSID AttributeError: 'NoneType' object has no attribute 'CLSID'. I also tried a variety of string arguments, but all of those also yielded an invalid class id error. The other approach is more Visual Basic like: self. ac = Dispatch ("Access.Application") self. db = self. ac. NewCurrentDatabase ("d:\\pyhack\\foo") self. fm = self. ac. CreateForm () self. ac. Visible = true self. ev = AcEvents () self. fm. OnActivate = self. ev. OnActivate this couldn't set the OnActivate attribute with the following error. File "D:\pyhack\1\Bob.py", line 132, in DoAccess self. fm. OnActivate = self. ev. OnActivate File "D:\PYTHON22\Lib\site-packages\win32com\client\__init__.py", line 503, in __setattr__ d.__setattr__(attr, value) File "D:\PYTHON22\Lib\site-packages\win32com\client\__init__.py", line 463, in __setattr__ self._oleobj_.Invoke(*(args + (value,) + defArgs)) TypeError: Objects of type 'instance method' can not be converted to a COM VARIANT Anyone know how to do this, either strategy is fine. Thanks Robert Kaplan (Remove XX for e-mail) From daniel.dittmar at sap.corp Tue Jan 18 13:05:37 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Tue, 18 Jan 2005 19:05:37 +0100 Subject: One-Shot Property? In-Reply-To: <20050118115456510-0500@braeburn.themorgue.org> References: <20050118115456510-0500@braeburn.themorgue.org> Message-ID: Kevin Smith wrote: > I have many cases in my code where I use a property for calculating a > value on-demand. Quite a few of these only need to be called once. > After that the value is always the same. In these properties, I set a > variable in the instance as a cached value and return that value on > subsequent calls. It would be nice if there was a descriptor that would > do this automatically. Actually, what would be really nice is if I > could replace the property altogether and put the calculated value in > its place after the first call, but the property itself prevents me from > doing that. Is this possible? If you use the old-fashioned __getattr__ method instead of properties. __getattr__ gets called only if the value can't be found in the instance dictionary. def __getattr__ (self, attrname): try: method = getattr (self, 'calculate_' + attrname) except AttributeError: raise AttributeError, attrname value = method () setattr (self, attrname, value) return value And probably also through metaclasses. And decorators. Daniel From cam.ac.uk at mh391.invalid Tue Jan 11 20:31:08 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 12 Jan 2005 01:31:08 +0000 Subject: shutil.move has a mind of its own In-Reply-To: References: Message-ID: Daniel Bickett wrote: > As it happens, the > desired locations are system folders (running windows xp, the folders > are as follows: C:\WINDOWS, C:\WINDOWS\SYSTEM, C:\WINDOWS\SYSTEM32). > To see if this factor was causing the problem, I tried it using the > interpreter, and found it to be flawless. I'm not entirely sure what that last sentence means. But does it mean that shutil.move() works fine if you do it interactively but not in your code? The simplest interpretation then would be that there is something wrong in your code. Why don't you post the debug output of that quoted section of code? What version of Python are you using? Is it the standard Windows distribution? -- Michael Hoffman From lists at swaroopch.info Tue Jan 4 09:56:38 2005 From: lists at swaroopch.info (Swaroop C H) Date: Tue, 04 Jan 2005 20:26:38 +0530 Subject: How to access database? In-Reply-To: References: Message-ID: Florian Lindner wrote: > Hello, > AFAIK python has a generic API for database access which adapters are > supposed to implement. How can I found API documentation on the API? I found these pages useful when learning the DB API: * http://www.kitebird.com/articles/pydbapi.html * http://www.amk.ca/python/writing/DB-API.html HTH, -- Swaroop C H Blog: http://www.swaroopch.info/ From Scott.Daniels at Acm.Org Mon Jan 10 19:11:29 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 10 Jan 2005 16:11:29 -0800 Subject: Writing huge Sets() to disk In-Reply-To: References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <41e2f24d$1@nntp0.pdx.net> Message-ID: <41e316cf@nntp0.pdx.net> Martin MOKREJ? wrote: >.... But I don't think I can use one-way hashes, as I need to reconstruct > the string later. I have to study hard to get an idea what the proposed > code really does. > > Scott David Daniels wrote: >> Tim Peters wrote: >>> .... Call the set of all English words E; G, C, and P similarly. >>> >>> This Python expression then gives the set of words common to all 4: >>> E & G & C & P >>> and for those unique to Polish. >>> P - E - G - C >> >> One attack is to define a hash to get sizes smaller. Suppose you find >> your word sets are 10**8 large, and you find you need to deal with sets >> of size 10**6. Then if you define a hash that produces an integer below >> 100, you'll find: >> E & G & C & P == Union(E_k & G_k & C_k & P_k) for k in range(100) >> P - E - G - C == Union(P_k - E_k - G_k - C_k) for k in range(100) >> where X_k = [v for v in X if somehash(v) == k] > > I don't understand here what would be the result from the hashing > function. :( ... Can you clarify this please in more detail? The trick is to build the X_k values into files. For example: for base in range(0, 100, 10): # work in blocks of 10 (or whatever) for language in ('English', 'German', 'Czech', 'Polish'): source = open(language) dests = [open('%s_%s.txt' % (language.lower(), base + n), 'w') for n in range(10)] for word in source: # Actually this is probably more involved code = somehash(word) - base if 0 <= code < base: dests[code].write(word + '\n') for dest in dests: dest.close() source.close() After running the above code, you get 400 files with names like, for example, 'english_33.txt'. 'english_33.txt' contains only words in English which hash to 33. Then you need to sort the different files (like 'english_33.txt') before using them in the next phase. If you can sort and dupe-elim in the same step, do that and get rid of the calls to dupelim below. Otherwise use dupelim below when reading the sorted files. If you must, you might want to do the sort and dupe-elim in Python: for language in ('english', 'german', 'czech', 'polish'): for hashcode in range(100): filename = '%s_%s.txt' % (language, hashcode) source = open(filename) lines = sorted(source) source.close() dest = open(filename, 'w') for line in dupelim(lines): dest.write(line) dest.close() >> def inboth(left, right): .... >> def leftonly(left, right): .... > Aaaah, so the functions just walk one line in left, one line in right, > if values don't match the value in left is unique, it walks again one > line in left and checks if it already matches the value in right file > in the last position, and so on until it find same value in the right file? Exactly, you must make sure you deal with cases where you pass values, match values, and run out of source -- that keeps these from being four- liners. >> For example: >> >> Ponly = open('polishonly.txt', 'w') >> every = open('every.txt', 'w') >> for hashcode in range(100): >> English = open('english_%s.txt' % hashcode) > ^^^^^^^^^^^^^^^^^^^^^^^^^^ this is some kind of eval? If hashcode == 33 then 'english_%s.txt' % hashcode == 'english_33.txt' So we are just finding the language-specific for-this-hash source. >>... for unmatched in leftonly(leftonly(leftonly(dupelim(Polish), >> dupelim(English)), dupelim(German)), dupelim(Czech)): >> Ponly.write(unmatched) >> for source in (Polish, English, German, Czech):#(paraphrased) >> source.seek(0) >> for match in inboth(inboth(dupelim(Polish), upelim(English)), >> inboth(dupelim(German), dupelim(Czech))): >> every.write(match) >> for source in (Polish, English, German, Czech):#(paraphrased) >> source.close() >> Ponly.close() >> every.close() --Scott David Daniels Scott.Daniels at Acm.Org From harold.fellermann at upf.edu Tue Jan 18 14:03:03 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 18 Jan 2005 20:03:03 +0100 Subject: pickling extension class Message-ID: <94A09CD0-6983-11D9-831B-003065FB7B26@upf.edu> Hi all, I have a problem pickling an extension class. As written in the Extending/Embedding Manual, I provided a function __reduce__ that returns the appropreate tuple. This seams to work fine, but I still cannot pickle because of the following error: >>> from model import hyper >>> g = hyper.PeriodicGrid(4,4,1) >>> g.__reduce__() (,(4.,4.,1.)) >>> import pickle >>> pickle.dump(g,file("test","w")) Traceback (most recent call last): File "pickle_test.py", line 5, in ? pickle.dump(g,file("test","w")) File "/sw/lib/python2.4/pickle.py", line 1382, in dump Pickler(file, protocol, bin).dump(obj) File "/sw/lib/python2.4/pickle.py", line 231, in dump self.save(obj) File "/sw/lib/python2.4/pickle.py", line 338, in save self.save_reduce(obj=obj, *rv) File "/sw/lib/python2.4/pickle.py", line 414, in save_reduce save(func) File "/sw/lib/python2.4/pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "/sw/lib/python2.4/pickle.py", line 760, in save_global raise PicklingError( pickle.PicklingError: Can't pickle : it's not found as hyper.PeriodicGrid >>> dir(hyper) ['Dir', 'Neighbors', 'PeriodicGrid', 'PeriodicPos', '__doc__', '__file__', '__name__', 'refcount'] >>> hyper.PeriodicGrid So pickle complains about the class PeriodicGrid not being found in the module hyper, but a dir() proves that python can find it. Has anyone an idea what's going wrong here? Any help appreceated, - harold - -- What is mind? -- Doesn't matter. What is matter? -- Never mind! -- From joh12005 at yahoo.fr Fri Jan 28 10:39:42 2005 From: joh12005 at yahoo.fr (Joh) Date: 28 Jan 2005 07:39:42 -0800 Subject: some kind of LFU dict... Message-ID: <63b5e209.0501280739.3887d82@posting.google.com> Hello, (first i'm sorry for my bad english...) for a program, i need to have some kind of dictionary which will contain a huge amount of keys and values. i have tried 'to do it simple' using a normal dict but when available memory was exhausted, my computer started to be really slow as it swap-ed. so i wondered if i can not use some kind of cache, i googled and found information on LRU, LFU, and LFU interested me : keep only most frequently used items inside dict (and memory) and writing others on disk for a possible future reuse. here is a silly attempt to do it, it still missed some features but before to continue i would like to have your opinions. i'm interested in any propositions or refactorisations :) and btw i may have missed others already/tuned/better solutions... best. --- import fileinput, pickle, random, shutil, sys class sLFU: TMP = """%s.bak""" """ a simple kind of Least Frequently Used container""" def __init__(self, size, ratio, filename = None): """ filename = a temporary file which will could be deleted""" self.d = {} # container self.size, self.ratio = size, ratio self.freqs, self.fmin = {}, 0 self.filename = filename if self.filename: open(self.filename, 'w') def __setitem__(self, obj, v): self.d[obj] = v self.freqs[obj] = self.freqs.get(obj, self.fmin) + 1 if len(self.d) > self.size: """ lfu = { (size / ratio) least frequently used objects... }""" freqs = [(f, obj) for (obj, f) in self.freqs.items()] # maybe should i use a generator () like # ((f, obj) for (obj, f) in self.freqs.items()) freqs.sort() lfu = {} # and here enumerate(sorted(freqs)) for i, (f, obj) in enumerate(freqs): if i > self.size / self.ratio: break lfu[obj] = self.d[obj] """ next minimal frequency will be max frequency of the lfu (maybe it would be better to substract this from others in self.freqs)""" self.fmin = f """ and now delete theses objects...""" for obj in lfu: del self.freqs[obj] del self.d[obj] if self.filename: """ now must save lfu to disk... as i do not managed to do otherwise, copy file to a tmp file and read it line by line, updating when necessary... there must be plenty rooms for improvement here :(""" shutil.copy(self.filename, self.TMP % self.filename) fhs = open(self.TMP % self.filename) fh = open(self.filename, 'w') """ flag to ignore 'value' line""" ignoreNext = False for i, line in enumerate(fhs): """ first copy old lfu which were already set, updating them if necessary...""" if ignoreNext: ignoreNext = False continue line = line.rstrip() if i % 2 == 0: obj = self.loads(line) if obj not in lfu and obj in self.d: """ obj available from memory, do not to keep it on disk...""" ignoreNext = True continue elif obj in lfu: """ obj was available from memory, but as a lfu, was removed and must be updated on disk""" fh.write("%s\n" % line) fh.write("%s\n" % self.dumps(lfu[obj])) del lfu[obj] ignoreNext = True continue """ default behaviour : copy line...""" fh.write("%s\n" % line) """ from now lfu should contain only unseen lfu objects, add them to file...""" fh = open(self.filename, 'a') for obj in lfu: fh.write("%s\n" % self.dumps(obj)) fh.write("%s\n" % self.dumps(lfu[obj])) def __getitem__(self, obj): if obj in self.d: """ from memory :)""" return self.d[obj] if self.filename: """ if a filename was provided, search inside file if such an obj is present, then return it ; else raise IndexErrror.""" fh = open(self.filename) found = False for i, line in enumerate(fh): line = line.rstrip() if found: v = self.loads(line) self.d[obj] = v self.freqs[obj] = self.fmin + 1 return v if obj == self.loads(line): found = True raise KeyError(obj) """ maybe class methods would have been better here, actually i would have liked static + class... totally arbitrary format, haved choosed to use pickle, odd line contain 'obj' (next) even line contain 'value' """ def dumps(self, s): return pickle.dumps(s).replace("\n", "\t") staticmethod(dumps) def loads(self, s): return pickle.loads(s.replace("\t", "\n")) staticmethod(loads) lfu = sLFU(2, 2, 'slfu.txt') lfu[1] 8 = {'1': 1fd2 'a'} lfu[2] = [] lfu[3] = '3' lfu[2] = [1,] lfu[2] = [1,2] lfu[4] = 4 lfu[5] = '5' print "#d", len(lfu.d) print lfu.d print "".join(open(lfu.filename).readlines()) From firstname.lastname at iki.fi-spam Sat Jan 1 16:26:59 2005 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 01 Jan 2005 23:26:59 +0200 Subject: Securing a future for anonymous functions in Python References: <10t84q9icqjnie7@news.supernews.com> <41d607d8.1558267600@news.oz.net> Message-ID: bokr at oz.net (Bengt Richter) writes: > ISTM you don't need "end" -- just put the def expression in parens, > and let the closing paren end it, e.g.: I first rejected any parens as not being native to how classes/toplevel functions/control blocks are written in Python. However, this looks quite clear to me. I'd expect that in most cases it would be difficult to mistake a block of statements in parentheses with e.g. tuple notation. And parensing works with the old "lambda" already, of course. br, S From steven.bethard at gmail.com Fri Jan 21 14:44:30 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 12:44:30 -0700 Subject: problems with duplicating and slicing an array In-Reply-To: References: <7cffadfa05012017337858d171@mail.gmail.com> Message-ID: py> import numarray as na py> a = na.array([[1,2,3],[4,5,6]]) Yun Mao wrote: > Thanks for the help. numarray doesn't provide what I look for either. e.g. > a = array( [[1,2,3],[4,5,6]] ) > I sometimes what this: a[ [1,0], :], py> a[[1,0]] array([[4, 5, 6], [1, 2, 3]]) > or even a[ [1,0], [0,1] ] , which should give me > [[4, 5], [1,2]] py> a[:,:2][[1,0]][[0,1]] array([[4, 5], [1, 2]]) Not the same syntax, of course, but doable. Steve From invalidemail at aerojockey.com Tue Jan 25 12:39:16 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 25 Jan 2005 09:39:16 -0800 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: <1106624803.825442.73870@f14g2000cwb.googlegroups.com> Message-ID: <1106674756.039497.232880@c13g2000cwb.googlegroups.com> Roy Smith wrote: > "Carl Banks" wrote: > > > > Imbed > > EMBED. > > My apologies for being sloppy. And with an initial capital, so it just > jumps off the page at you :-) Ok. Prescriptive language isn't normally my cup of tea, but there's always something. And usually it's very silly. > > > Python, or Perl, or TCL, or Ruby, or PHP, > > > > Not PHP. PHP is one of the better (meaning less terrible) examples of > > what happens when you do this sort of thing, which is not saying a lot. > > But, that's exactly my point. To be honest, I've never used PHP. But > however bad it may be, at least it's got a few years of people fixing > bugs, writing books, writing add-on tools, etc, behind it. Better to > use somebody else's well-known and well-supported mess of a scripting > language than to invest several person-years inventing your own mess > that's no better. Well, if you look at it that way, I guess so. My mindset was closer to "hacked-up quasi-languages are evil" than "hacked-up quasi-languages are not worth the time to implement when there are plenty of hacked-up quasi-languages already out there, not to mention some real languages." -- CARL BANKS From flupke at nonexistingdomain.com Fri Jan 7 08:38:40 2005 From: flupke at nonexistingdomain.com (flupke) Date: Fri, 07 Jan 2005 13:38:40 GMT Subject: 2 versions of python on 1 machine In-Reply-To: <0fydnX5CmoCCwkDcRVn-2w@powergate.ca> References: <0fydnX5CmoCCwkDcRVn-2w@powergate.ca> Message-ID: Peter Hansen wrote: > > On my machine, I have a folder called c:\bin where I put useful > batch files. I have a python23.bat and a python24.bat file, > which basically just call c:\python23\python.exe or > c:\python24\python.exe as required. For various reasons which > may or may not apply to you as well, I also have each of them > set the PYTHONHOME variable to point to the right folder > as well. > > The content of each batch file is like this: > @echo off > c:\python23\python.exe %1 %2 %3 %4 %5 %6 %7 %8 %9 > > -Peter I used the 2 batch files technique and removed c:\python23 from my path var and all is fine now. Where did you find more info on PYTHONHOME and PYTHONPATH because the docs don't seem to contain a whole lot of info. Thanks Benedict From tzot at sil-tec.gr Fri Jan 21 04:02:52 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 21 Jan 2005 11:02:52 +0200 Subject: tkinter socket client ? References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> Message-ID: <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> On 20 Jan 2005 22:25:52 -0800, rumours say that "Tonino" might have written: [tkinter gui for a socket client, lots of data from the socket] >NOW - HOW do I get the server's sent data to continuiosly print in the >Text() widget ? You need to use: yourTextWidget.insert(Tkinter.END, data) # to insert the data yourRootWindow.update_idletasks() # to update the GUI -- 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 fortepianissimo at gmail.com Fri Jan 21 09:40:59 2005 From: fortepianissimo at gmail.com (fortepianissimo) Date: 21 Jan 2005 06:40:59 -0800 Subject: Example of resolving an alias using Carbon.File module? In-Reply-To: <1106286928.806519.67720@c13g2000cwb.googlegroups.com> References: <1106286928.806519.67720@c13g2000cwb.googlegroups.com> Message-ID: <1106318459.779438.181380@f14g2000cwb.googlegroups.com> Problem solved: from Carbon.File import * fs, _, _ = ResolveAliasFile('/some/path', 1) print fs.as_pathname() From ncoghlan at iinet.net.au Mon Jan 31 07:08:07 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 31 Jan 2005 22:08:07 +1000 Subject: test_socket.py failure In-Reply-To: References: Message-ID: <41FE1FA7.7000508@iinet.net.au> 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. > Two questions. First, what does the following code give when you run it at the interactive prompt?: Py> import socket Py> socket.getservbyname('daytime') 13 Second, is there an entry for 'daytime' in /etc/services? Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From http Sat Jan 22 13:46:01 2005 From: http (Paul Rubin) Date: 22 Jan 2005 10:46:01 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> Message-ID: <7xpszxcnfa.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > "lack of understanding of how Python is used" > > wonderful. I'm going to make a poster of your post, and put it on my > office wall. Excellent. I hope you will re-read it several times a day. Doing that might improve your attitude. From timj at tolisgroup.com Mon Jan 17 16:18:04 2005 From: timj at tolisgroup.com (brucoder) Date: 17 Jan 2005 13:18:04 -0800 Subject: Adjusting the 1024 byte stdin buffer limit References: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> <1105989764.168794.113430@z14g2000cwz.googlegroups.com> Message-ID: <1105996684.110078.303400@f14g2000cwb.googlegroups.com> Hi All, - Thanks, but it seems I may have been a bit more confused that even I thought. It turns out to be an issue with Apple's OS X pty/tty interface. Even though the mediator tool is set up to read in up to 20K of data, the pty interface blocks at 1024 bytes. When testing this under Linux, I'm fine. And, Solaris 8 weaves an even more diabolical 255 character limit :( . - Looks like I'll need to be a bit more creative than simply spawning a shell. - Tim Fredrik Lundh wrote: > "brucoder" wrote: > > > Currently, when sending a data stream that exceeds 1024 bytes via > > stdin, the stream blocks at the 1024th byte. This precludes completion > > of the submission of the data stream. > > you can pass in a buffer size when you open a file: > > >>> help(open) > > class file(object) > | file(name[, mode[, buffering]]) -> file object > | > | Open a file. The mode can be 'r', 'w' or 'a' for reading (default), > | writing or appending. The file will be created if it doesn't exist > | when opened for writing or appending; it will be truncated when > | opened for writing. Add a 'b' to the mode for binary files. > | Add a '+' to the mode to allow simultaneous reading and writing. > | If the buffering argument is given, 0 means unbuffered, 1 means line > | buffered, and larger numbers specify the buffer size. > | Add a 'U' to mode to open the file for input with universal newline > | support. Any line ending in the input file will be seen as a '\n' > | in Python. Also, a file so opened gains the attribute 'newlines'; > | the value for this attribute is one of None (no newline read yet), > | '\r', '\n', '\r\n' or a tuple containing all the newline types seen. > | > | 'U' cannot be combined with 'w' or '+' mode. > | > | Note: open() is an alias for file(). > > or use os.fdopen() to reopen an existing file handle: > > >>> help(os.fdopen) > > fdopen(fd [, mode='r' [, bufsize]]) -> file_object > > Return an open file object connected to a file descriptor. > > assuming "sending via stdin" means using a pipe, this page explains why all > this probably won't matter: > > http://www.opengroup.org/onlinepubs/7990989799/xsh/write.html > > (see the "Write requests to a pipe or FIFO" section) > > From steve at holdenweb.com Sat Jan 8 14:22:33 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 08 Jan 2005 14:22:33 -0500 Subject: Working with recordsets In-Reply-To: References: <1105119853.927871.293390@z14g2000cwz.googlegroups.com> Message-ID: AdSR wrote: > chema.rey at gmail.com wrote: > >> Hi. >> >> I have one recorset that I would like to pass to 2 functions, one is >> for create an CSV file and the other one is to create a HTML file. The >> problem is that the recordset is totally read in the first function, >> and then when I pass it to the second funtion the recordset is in the >> last record. >> >> I've read docs, but I think that one cursor doesn't have something >> like movefirst() method. Anybody have an idea to solve this? >> >> Thank's. >> > > Try loading the whole recordset with the fetchall() method and use the > resulting sequence in your functions. It won't be memory-efficient but > it will be easy to do. > > AdSR Or, if this doesn't suit, try creating two separate cursors from the same connection and execute the same query on each. There's some chance that your database driver/backend combination will optimize the queries then. 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 yaniv_vi at yahoo.com Tue Jan 4 14:52:17 2005 From: yaniv_vi at yahoo.com (yaniv_vi at yahoo.com) Date: 4 Jan 2005 11:52:17 -0800 Subject: python and activex Message-ID: <1104868337.380580.247840@z14g2000cwz.googlegroups.com> Hi , Has anybody used jython and visual j++ togheter to do python and activeX integration ? is there a simpler way (except win32all , which i feel is non trivial , at least not as dragging components ) Thanks ,yaniv From fredrik at pythonware.com Mon Jan 24 07:44:18 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 13:44:18 +0100 Subject: Py2.4 .exe installer References: Message-ID: Facundo Batista: > The bigger problem I'm facing is that the "official" operating system > installed in the PCs is Win NT 4.0, tweaked and restricted, and it's > impossible to install the Microsoft package that enables the .msi as a > installer. > > Result: they can not install Py24.msi. > > There's somewhere a Py24.exe installer? you could of course install it on a W2K or WXP box, and zip it up (don't forget the python24.dll under /windows/system32; you can copy it to the \python24 directory before zipping it all). copy, unzip, and you're done. if you need to register the interpreter on the target machine (so you can install extensions), use this little script: http://effbot.org/zone/python-register.htm From craig at postnewspapers.com.au Fri Jan 7 00:54:18 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 07 Jan 2005 13:54:18 +0800 Subject: File Handling Problems Python I/O In-Reply-To: <1105034789.700445.291380@z14g2000cwz.googlegroups.com> References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> <1105034789.700445.291380@z14g2000cwz.googlegroups.com> Message-ID: <1105077258.28776.67.camel@rasputin.localnet> On Fri, 2005-01-07 at 02:06, Josh wrote: > Peter, > > Thank you for the rookie correction. That was my exact problem. I > changed the address to use forward slashes and it works perfect. I did > not know that a backslash had special meaning within a string, but now > I do! Thanks again There's another common mistake you might want to head off now, too. Consider the following program: -------- directory = r"c:\mydata" datafilename = "something.txt" datafile = open(directory + datafilename,"r") --------- It's very common for this to happen, usually when the paths are originally written with trailing slashes then changed to not have them later. Rather than saying "all paths must have trailing slashes", manually formatting in slashes, or other platform-specific uglyness, consider using the os.path module to take care of it: -------- import os directory = r"c:\mydata" datafilename = "something.txt" datafile = open(os.path.join(directory,datafilename),"r") -------- This will work on any platform (so long as the literal paths are correct) and will work no matter whether or not there are trailing path separators on the input strings. os.path.join can take more than two arguments, too. os.path has lots of other handy tools, so I strongly recommend checking it out. -- Craig Ringer From guy at NOSPAM.r-e-d.co.nz Mon Jan 17 06:05:10 2005 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Tue, 18 Jan 2005 00:05:10 +1300 Subject: getting a class attribute using a keyword argument Message-ID: Hello, I have a list of class instances. I wish to get the appropriate class attribute in each class instance depending on a SINGLE keyword in the calling class. How do I get the calling method to correctly recognise the keyword as a keyword and not a class attribute? See example code below (which doesn't work). class tocall: def __init__(self): self.title = "test" self.name = "name" def callingmethod(self,**kw): for key in kw: if tocall.key == kw[key]: return tocall.key which should work as such(but doesn't): print callmethod(title = "test") print callmethod(name = "name") Regards, Guy From beliavsky at aol.com Sun Jan 9 18:40:15 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 9 Jan 2005 15:40:15 -0800 Subject: read numbers from file and covert to integer References: Message-ID: <1105314015.776099.151250@c13g2000cwb.googlegroups.com> If you have a file "ints.txt" with contents 10 20 30 40 50 60 You could read integers into a list with ivec = [] for text in open("ints.txt","r"): words = text.split() for x in words: ivec.append(int(x)) print ivec If you know you want to read two integers into variables a,b from a line you could write a,b = int(words[0]),int(words[1]) Excuse me, but if your question is really so elementary that this post answered it, you should probably read a book or tutorial. From http Mon Jan 10 20:11:41 2005 From: http (Paul Rubin) Date: 10 Jan 2005 17:11:41 -0800 Subject: Port blocking References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> <34f8ovF47d783U1@individual.net> Message-ID: <7xvfa43h2q.fsf@ruckus.brouhaha.com> Mark Carter writes: > >>Also, is there a good tool for writing database UIs? > > Yes, quite a few. > > Ah yes, but is there really? For example, I did a search of the TOC of > GTK+ Reference Manual: Try looking on freshmeat or sourceforge instead. From peter at engcorp.com Wed Jan 26 16:30:30 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 Jan 2005 16:30:30 -0500 Subject: Inherting from object. Or not. In-Reply-To: References: Message-ID: <3eSdndWMePFqlmXcRVn-jg@powergate.ca> Frans Englich wrote: > What is the difference between inherting form object, and not doing it? Although this doesn't provide a description of all the implications, it does give you the basic answer to the question and you can easily do further research to learn more: http://www.python.org/doc/2.2.1/whatsnew/sect-rellinks.html#SECTION000310000000000000000 (Summary: inheriting from object gives you a "new-style" class, not doing so gives you a classic class, and there are a variety of differences resulting from that.) -Peter From ncoghlan at iinet.net.au Sat Jan 8 01:08:43 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 16:08:43 +1000 Subject: python3: 'where' keyword In-Reply-To: <3480qqF46jprlU1@individual.net> References: <3480qqF46jprlU1@individual.net> Message-ID: <41DF78EB.6040502@iinet.net.au> Andrey Tatarinov wrote: > Hi. > > It would be great to be able to reverse usage/definition parts in > haskell-way with "where" keyword. Since Python 3 would miss lambda, that > would be extremly useful for creating readable sources. > > Usage could be something like: > > >>> res = [ f(i) for i in objects ] where: > >>> def f(x): > >>> #do something Hmm, this is actually a really interesting idea. Avoiding accidental namespace conflicts is certainly one of the advantages of using lambdas. This idea has the virtue of being able to do the same thing, but have full access to Python's function syntax and assignment statements in the 'expression local' suite. In fact, any subexpressions in a complicated expression can be extracted and named for clarity without fear of screwing up the containing namespace, which would be an enormous boon for software maintainers. It also allows the necessary but uninteresting setup for an expression to be moved "out of the way", bringing the expression that does the real work to prominence. From the interpreter's point of view, the meaning would probably be something like: namespace = locals() exec where_suite in globals(), namespace exec statement in globals(), namespace res = namespace["res"] del namespace Making the 'where' clause part of the grammar for the assignment statement should be enough to make the above example parseable, too. The clause might actually make sense for all of the simple statement forms in the grammar which contain an expression: expression statement assignment statement augmented assignment statement del statement print statement return statement yield statement raise statement exec statement The clause really isn't appropriate for break, continue, import or global statements, as they don't contain any expressions :) For compound statements, a where clause probably isn't appropriate, as it would be rather unclear what the where clause applied to. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tzot at sil-tec.gr Mon Jan 3 09:25:32 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 03 Jan 2005 16:25:32 +0200 Subject: Switch statement (was: Lambda going out of fashion) References: <3e8ca5c8041222201332fb0b92@mail.gmail.com> Message-ID: On Thu, 23 Dec 2004 19:57:27 GMT, rumours say that rzed might have written: [Why did PEP 275 stall?] >It seems to me that it was regarded as misguidod. QOTPE +1 (PE=Python Era) Oncoming Python book: "Hitchhiker's Guido to the Python Language" -- 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 fred at adventistcare.org Mon Jan 3 13:12:25 2005 From: fred at adventistcare.org (Sells, Fred) Date: Mon, 3 Jan 2005 13:12:25 -0500 Subject: Developing Commercial Applications in Python Message-ID: <777056A4A8F1D21180EF0008C7DF75EE03317240@sunbelt.org> At Sunrise Software International, we build commercial applications for Cabletron and the Florida DMV. This was ~10 years ago; so no useful docs available, but we had no problems with license. -----Original Message----- From: Richards Noah (IFR LIT MET) [mailto:Noah.Richards at infineon.com] Sent: Monday, January 03, 2005 12:20 PM To: python-list at python.org Subject: Re: Developing Commercial Applications in Python > wrote in message > news:1104750017.235937.181370 at c13g2000cwb.googlegroups.com... > > Hello All, > > I am trying to convince my client to use Python in his new product. He > > is worried about the license issues. Can somebody there to point me any > > good commercial applications developed using python ?. The licence > > clearly says Python can be used for commercial applications. Is there > > any other implications like that of GPL to make the source open ? > > Thanks for any help. > > eeykay > > "It's me" wrote in message news:mBeCd.5832$5R.1770 at newssvr21.news.prodigy.com... > Shaw-PTI (www.pti-us.com) uses Python in their software. See: > http://www.pti-us.com/pti/news/index.cfm and search "2004 PSS/E User Group > Meeting" > Begging your pardon, but a better resource would be the brochure available (http://www.pti-us.com/PTI/company/brochures/PSSE.pdf). It appears that the program was probably (originally) written in C/C++ (using MFC for the GUI), and now employs Python for adding modules and scripting support. Very interesting stuff :) -- http://mail.python.org/mailman/listinfo/python-list From fredrik at pythonware.com Thu Jan 13 18:30:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 14 Jan 2005 00:30:50 +0100 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com> <41e6f4b7.777345834@news.oz.net> Message-ID: Bengt Richter wrote: > Hm, that makes me wonder, is there an intermediate "returning of value" in > x = y = z = 123 > ? no. that statement evaluates the expression (123 in this case), and assigns the result (the integer object 123) to each target (x, y, z), in order. or to quote the language reference: An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. From br44114 at yahoo.com Tue Jan 18 22:49:54 2005 From: br44114 at yahoo.com (bogdan romocea) Date: Tue, 18 Jan 2005 19:49:54 -0800 (PST) Subject: DDE client help Message-ID: <20050119034955.75129.qmail@web50306.mail.yahoo.com> Dear Python experts, I'm facing a simple problem which however I'm having a hard time solving. I have a DDE server with data that changes from time to time. I need to put together a DDE client that would 'notice' updated values on the server and append them as a new row in a text file. 1. How do I connect to the DDE server, and ask for data? In OpenOffice.org it looks very simple: =DDE("FPS";"TIME";"PRC") I also have some VB code which does the same thing: Private Sub Command1_Click() Text1.LinkTopic = "FPS|TIME" Text1.LinkItem = Text4.Text Text1.LinkMode = vbLinkAutomatic I checked the DDE client sample code from C:\Python24\Lib\site-packages\win32\Demos\dde, however I got stuck here: conversation.ConnectTo("FPS","PRC") Traceback (most recent call last): File "", line 1, in ? conversation.ConnectTo("FPS","PRC") error: ConnectTo failed 2. Once I manage to connect to the DDE server, how do I append the new data values in a text file? Suggestions and sample code will be highly appreciated. Thank you, b. __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail From merkosh at hadiko.de Fri Jan 7 05:49:25 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 07 Jan 2005 11:49:25 +0100 Subject: missing sys.setappdefaultencoding Message-ID: Hi, well, I wrote a nice python program which won't work if the default encoding has not been set from ascii to latin-1 or latin-15. However, the command sys.setappdefaultencoding is missing on a Python installation with Python 2.3.4 on Gentoo where it is present on Debian. Any ideas how to deal with this? Thanks in advance, Ciao Uwe From fumanchu at amor.org Sun Jan 23 01:34:30 2005 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 22 Jan 2005 22:34:30 -0800 Subject: Python Scripting Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398260@exchange.hqamor.amorhq.net> Ali Polatel wrote: > I want to ask you a question about python scripting. > I want to know if I can design web-pages with python Yes. > or at least write html files with python. Yes. > and if I write html files with python and some CGI scripts > and upload them to the web-page .. does the people who view > those pages have to have python interpreters in their computers? No. > Another question is ... I am writing a bot for a chess server > in python and this bot should update a web-page when it gets > some commands from the server. How can i make a programme update > a web-page? If the file is local: open(filename, 'w').write(content) If the file is remote and you need to upload it via ftp, check out the ftplib module in the standard library, for starters. Robert Brewer MIS Amor Ministries fumanchu at amor.org From mwm at mired.org Sun Jan 2 18:18:43 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 02 Jan 2005 17:18:43 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <86ekh3qv1o.fsf@guru.mired.org> Bulba! writes: > This "free software" (not so much OSS) notion "but you can > hire programmers to fix it" doesn't really happen in practice, > at least not frequently: because this company/guy remains > ALONE with this technology, the costs are unacceptable. Yes, but fixing python software - even sloppily written python software - is pretty easy. I regularly see contracts to add a feature to or fix a bug in some bit of OSS Python. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From club4_2 at mail.ru Tue Jan 25 23:41:27 2005 From: club4_2 at mail.ru (Club-B42) Date: Wed, 26 Jan 2005 14:41:27 +1000 Subject: py2exe problem Message-ID: i've compiled my programm using command "python setup.py py2exe >1" python script works fine, but .exe version fails with ===================================================================== D:\[Egor]\Scripts\B-4-2\la2luncher\dist>la2launcher.exe Traceback (most recent call last): File "la2launcher.py", line 9, in ? File "config.pyc", line 11, in ? File "config.pyc", line 8, in u LookupError: no codec search functions registered: can't find encoding ===================================================================== python 2.3 ===================================================================== running py2exe creating D:\[Egor]\Scripts\B-4-2\la2launcher\build creating D:\[Egor]\Scripts\B-4-2\la2launcher\build\bdist.win32 creating D:\[Egor]\Scripts\B-4-2\la2launcher\build\bdist.win32\winexe creating D:\[Egor]\Scripts\B-4-2\la2launcher\build\bdist.win32\winexe\collect creating D:\[Egor]\Scripts\B-4-2\la2launcher\build\bdist.win32\winexe\temp creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist *** searching for required modules *** *** parsing results *** creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 copying C:\Python23\tcl\tcl8.4\auto.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\ascii.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\big5.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1250.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1251.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1252.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1253.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1254.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1255.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1256.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1257.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1258.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp437.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp737.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp775.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp850.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp852.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp855.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp857.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp860.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp861.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp862.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp863.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp864.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp865.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp866.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp869.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp874.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp932.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp936.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp949.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp950.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\dingbats.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\ebcdic.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\euc-cn.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\euc-jp.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\euc-kr.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\gb12345.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\gb1988.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\gb2312-raw.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\gb2312.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso2022-jp.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso2022-kr.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso2022.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-1.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-10.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-13.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-14.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-15.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-16.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-2.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-3.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-4.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-5.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-6.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-7.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-8.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-9.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\jis0201.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\jis0208.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\jis0212.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\koi8-r.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\koi8-u.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\ksc5601.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macCentEuro.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macCroatian.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macCyrillic.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macDingbats.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macGreek.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macIceland.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macJapan.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macRoman.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macRomania.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macThai.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macTurkish.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macUkraine.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\shiftjis.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\symbol.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\tis-620.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\history.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\http1.0 copying C:\Python23\tcl\tcl8.4\http1.0\http.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\http1.0 copying C:\Python23\tcl\tcl8.4\http1.0\pkgIndex.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\http1.0 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\http2.4 copying C:\Python23\tcl\tcl8.4\http2.4\http.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\http2.4 copying C:\Python23\tcl\tcl8.4\http2.4\pkgIndex.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\http2.4 copying C:\Python23\tcl\tcl8.4\init.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 copying C:\Python23\tcl\tcl8.4\ldAout.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\msgcat1.3 copying C:\Python23\tcl\tcl8.4\msgcat1.3\msgcat.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\msgcat1.3 copying C:\Python23\tcl\tcl8.4\msgcat1.3\pkgIndex.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\msgcat1.3 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\opt0.4 copying C:\Python23\tcl\tcl8.4\opt0.4\optparse.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\opt0.4 copying C:\Python23\tcl\tcl8.4\opt0.4\pkgIndex.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\opt0.4 copying C:\Python23\tcl\tcl8.4\package.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 copying C:\Python23\tcl\tcl8.4\parray.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 copying C:\Python23\tcl\tcl8.4\safe.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 copying C:\Python23\tcl\tcl8.4\tclIndex -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\tcltest2.2 copying C:\Python23\tcl\tcl8.4\tcltest2.2\pkgIndex.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\tcltest2.2 copying C:\Python23\tcl\tcl8.4\tcltest2.2\tcltest.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\tcltest2.2 copying C:\Python23\tcl\tcl8.4\word.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\bgerror.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\button.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\choosedir.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\clrpick.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\comdlg.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\console.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\arrow.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\bind.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\bitmap.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\browse -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\button.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\check.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\clrpick.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\colors.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\cscroll.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\ctext.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\dialog1.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\dialog2.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\entry1.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\entry2.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\entry3.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\filebox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\floor.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\form.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\hello -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\hscale.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\icon.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\image1.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\image2.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\earth.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\earthris.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\face.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\flagdown.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\flagup.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\gray25.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\letters.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\noletter.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\pattern.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\tcllogo.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\teapot.ppm -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\items.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\ixset -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\label.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\labelframe.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\license.terms -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\menu.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\menubu.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\msgbox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\paned1.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\paned2.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\plot.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\puzzle.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\radio.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\README -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\rmt -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\rolodex -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\ruler.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\sayings.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\search.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\spin.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\square -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\states.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\style.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\tclIndex -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\tcolor -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\text.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\timer -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\twind.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\unicodeout.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\vscale.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\widget -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\dialog.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\entry.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\focus.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\logo.eps -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\logo100.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\logo64.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\logoLarge.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\logoMed.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\pwrdLogo.eps -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\pwrdLogo100.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\pwrdLogo150.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\pwrdLogo175.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\pwrdLogo200.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\pwrdLogo75.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\README -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\tai-ku.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\license.terms -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\listbox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\menu.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\mkpsenc.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\msgbox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\cs.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\de.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\el.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\en.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\en_gb.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\es.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\fr.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\it.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\nl.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\ru.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\obsolete.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\optMenu.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\palette.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\panedwindow.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\pkgIndex.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\safetk.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\scale.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\scrlbar.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\spinbox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\tclIndex -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\tearoff.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\text.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\tk.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\tkfbox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\unsupported.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\xmfbox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 creating python loader for extension '_sre' creating python loader for extension '_tkinter' *** finding dlls needed *** *** create binaries *** *** byte compile python files *** byte-compiling C:\Python23\lib\UserDict.py to UserDict.pyc byte-compiling C:\Python23\lib\atexit.py to atexit.pyc byte-compiling C:\Python23\lib\copy.py to copy.pyc byte-compiling C:\Python23\lib\copy_reg.py to copy_reg.pyc byte-compiling C:\Python23\lib\lib-tk\FixTk.py to FixTk.pyc byte-compiling C:\Python23\lib\lib-tk\Tkconstants.py to Tkconstants.pyc byte-compiling C:\Python23\lib\lib-tk\Tkinter.py to Tkinter.pyc byte-compiling C:\Python23\lib\linecache.py to linecache.pyc byte-compiling C:\Python23\lib\macpath.py to macpath.pyc byte-compiling C:\Python23\lib\ntpath.py to ntpath.pyc byte-compiling C:\Python23\lib\os.py to os.pyc byte-compiling C:\Python23\lib\os2emxpath.py to os2emxpath.pyc byte-compiling C:\Python23\lib\popen2.py to popen2.pyc byte-compiling C:\Python23\lib\posixpath.py to posixpath.pyc byte-compiling C:\Python23\lib\re.py to re.pyc byte-compiling C:\Python23\lib\repr.py to repr.pyc byte-compiling C:\Python23\lib\shutil.py to shutil.pyc byte-compiling C:\Python23\lib\sre.py to sre.pyc byte-compiling C:\Python23\lib\sre_compile.py to sre_compile.pyc byte-compiling C:\Python23\lib\sre_constants.py to sre_constants.pyc byte-compiling C:\Python23\lib\sre_parse.py to sre_parse.pyc byte-compiling C:\Python23\lib\stat.py to stat.pyc byte-compiling C:\Python23\lib\string.py to string.pyc byte-compiling C:\Python23\lib\traceback.py to traceback.pyc byte-compiling C:\Python23\lib\types.py to types.pyc byte-compiling C:\Python23\lib\warnings.py to warnings.pyc byte-compiling D:\[Egor]\Scripts\B-4-2\la2launcher\build\bdist.win32\winexe\temp\_sre.py to _sre.pyc byte-compiling D:\[Egor]\Scripts\B-4-2\la2launcher\build\bdist.win32\winexe\temp\_tkinter.py to _tkinter.pyc byte-compiling D:\[Egor]\Scripts\B-4-2\la2launcher\config.py to config.pyc byte-compiling D:\[Egor]\Scripts\B-4-2\la2launcher\my_os.py to my_os.pyc *** copy extensions *** copying C:\Python23\DLLs\_sre.pyd -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist copying C:\Python23\DLLs\_tkinter.pyd -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist *** copy dlls *** copying C:\WINDOWS\system32\python23.dll -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist copying C:\Python23\DLLs\tcl84.dll -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist copying C:\Python23\w9xpopen.exe -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist copying C:\Python23\DLLs\tk84.dll -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist setting sys.winver for 'D:\[Egor]\Scripts\B-4-2\la2launcher\dist\python23.dll' to 'py2exe' copying C:\Python23\lib\site-packages\py2exe\run.exe -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\la2launcher.exe ===================================================================== From sedolan at bellsouth.net Sat Jan 8 20:27:06 2005 From: sedolan at bellsouth.net (Sean Dolan) Date: Sat, 08 Jan 2005 20:27:06 -0500 Subject: tuples vs lists In-Reply-To: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: worzel wrote: > I get what the difference is between a tuple and a list, but why would I > ever care about the tuple's immuutability? > Also, do you say 'too-ple' or 'chu-ple' - if you get my drift. (tomato or > tomato kind of thing) > TIA > > I use the Festival Speech Synthesis System to learn pronunciations sometimes. The American english voice is quite accurate. -- Sean Dolan From ialbert at mailblocks.com Mon Jan 17 10:39:41 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 17 Jan 2005 10:39:41 -0500 Subject: Integration with java (Jpype vs. JPE) In-Reply-To: References: <34s5krF4c85d5U1@individual.net> Message-ID: Cameron Laird wrote: > Someone really ought to include a couple of sentences to that effect > on the front page of . Now I remember visiting this site, but never understood how it actually worked. Examples such as: from jpype import * startJVM("d:/tools/j2sdk/jre/bin/client/jvm.dll", "-ea") java.lang.System.out.println("hello world") shutdownJVM() in three different versions are the only code examples that to show "complete" working snippets. I'm still clueless as to how would one say share a list between python and java. Istvan. From kartic.krishnamurthy at gmail.com Wed Jan 26 10:43:16 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 26 Jan 2005 07:43:16 -0800 Subject: FTP Server In-Reply-To: <1106748382.746575.52550@c13g2000cwb.googlegroups.com> References: <1106743852.600769.72820@c13g2000cwb.googlegroups.com> <1106746068.798541.219240@c13g2000cwb.googlegroups.com> <1106748382.746575.52550@c13g2000cwb.googlegroups.com> Message-ID: <1106754196.016985.289680@f14g2000cwb.googlegroups.com> Michele - Listen to your inner voice :-) If simple is all you want, try twisted. You can use mktap to create a simple ftp server and be ready to serve in a few minutes. And if you are upto it, get buried in the documents and you can customize your ftp server. If you are looking for something simpler but not asynchronous, I found this at the Vault called pyFTPDrop, which is aimed at *NIX. http://www.mythi.cx/python/pyFTPdrop.py / Thank you, --Kartic PS: I am sure Medusa is fairly straightforward too, but I have no experience with it. From martin at v.loewis.de Sat Jan 29 05:24:54 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 29 Jan 2005 11:24:54 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xacqt56ga.fsf@ruckus.brouhaha.com> References: <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> Message-ID: <41fb646a$0$31784$9b622d9e@news.freenet.de> Paul Rubin wrote: > Oops, sorry, it's in the os module: > > http://docs.python.org/lib/os-miscfunc.html > > The difference is simply a matter of the packaging. No, it's not. It also is a matter of code size, and impact. Small additions can be reviewed and studied more easily, and need to be tested on less users. A new module is on a larger scale than a mere new function. > Unless you're saying that if I > wanted to add AES to the string module (so you could say > 'spam and sausage'.aes_encrypt('swordfish banana')) instead of writing a > separate module, then we wouldn't need this discussion. Indeed, if it was a single new function to an existing module, I would not require that this be delivered to users first. It is entire new libraries that I worry about. If you would propose a change to the string module to add an aes_encrypt function, I would immediately reject that patch, of course, because that function does not belong to the string module. > What matters is the code complexity, not whether > something is in a separate module or not. A module *is* typically more complex than a single function. If your new module has only a single new function, we should discuss whether it really needs to be a separate module. > Well, if he indicates that it's not a policy and that the question is > still open, then I could see getting interested again in writing an > AES module. At the moment I continue to see his python-dev post as > quite discouraging. And, again, I consider this perfectly fine. This would be a volunteer effort, and volunteers are free to work on whatever they please. Furthermore, people who want an AES module for Python could get one from http://sourceforge.net/projects/cryptkit/ Maybe Bryan Mongeau will contribute this code to Python some day. > Not true. For example, you once invited me to work on an ancillary > message feature for the socket module (SF bug 814689), and so it's > been on my want-to-do-one-of-these-days list since then. I think it's > reasonable for me to have taken your message there as an expression of > interest, sufficient to get me to want to work on it. So it's bogus > to say the Python developers should avoid expressing interest in > something that hasn't already been written. I did not say that. I said we don't normally invite people to work on anything - I said not that we *should* not invite them. Now that you mention it, I find that there is an important exception from my factual statement: I do regularly ask people reporting bugs or requesting features to work fixing the bugs or implementing the features. It is perfectly fine if they say "no" then. If they say yes, there is an implied promise that I'll review their code when they are done. As it appears to be clear that you are not going to implement an AES module in the foreseeable future, and as it also seems to be clear that you cannot talk me into changing my views on how Python should be developed, I think further discussing this entire thing is pointless. Regards, Martin From Scott.Daniels at Acm.Org Fri Jan 7 12:39:02 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 07 Jan 2005 09:39:02 -0800 Subject: sorting on keys in a list of dicts In-Reply-To: <10tr9ejf05pv660@corp.supernews.com> References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: <41dec66b$1@nntp0.pdx.net> Jeff Shannon wrote: > Jp Calderone wrote: >> L2 = [(d[key], i, d) for (i, d) in enumerate(L)] >> L2.sort() >> L = [d for (v, i, d) in L2] > Out of curiosity, any reason that you're including the index? Others have already remarked that this preserves sort stability (which is, in fact a lovely property). There is another property which hasn't been mentioned: As written, only the key and the index are compared. Try sorting: tricky = [dict(a=5j, b=1), dict(a=4j, b=1)] or: similar = [(5j, 1), (4j, 1)] without the index. --Scott David Daniels Scott.Daniels at Acm.Org From ziongmail-py at yahoo.com Fri Jan 14 13:02:28 2005 From: ziongmail-py at yahoo.com (Ziong) Date: Sat, 15 Jan 2005 02:02:28 +0800 Subject: Newbie: module structure and import question References: <8fb821f9.0501120706.499dd04c@posting.google.com> Message-ID: <41e80972$1_1@rain.i-cable.com> Thx Rob. yes i know it's related to search path, but i don't know how to set it in a practical way (beside hard coding). my concern is, if i want to create a custom module/library, i don't know what py file will import it and where the working directory should be. sometime like my example, even i don't know where the root directory of my module will place, and i expect it can place in anywhere, how should i set the sys.path? i know that maybe a stupid question, please forgive me, i'm just a newbie. i have read all online documents in python.org. but i wouldn't find the answer. yes, i'm asking is it normally only put one class in one py file. thanks for your advice. But if i put a set of classes in a py file as a module, will it increase the dependency of each class? back to my example, of course, i can put BaseA and ClassA together in one py file. what should i do when i need to add one more class later, "ClassB", which also extend BaseA. Put it into the same file or in a new file? if put in in the same file, i think it should difficult to maintain versioning. i'm quite confuse in this, maybe because i learn Java before. Thx again, Rob. "Rob Emmons" ??? news:pan.2005.01.14.01.59.50.569440 at member.fsf.org ???... > > hi all, > > i have question on how to design a module structure. > > for example, i have 3 files. > > [somewhere]/main.py > > [somewhere]/myLib/Base/BaseA.py > > [somewhere]/myLib/ClassA.py > > .... > > ..... > > It's fine when i run main.py. > > however when i run ClassA.py individually, it would fail in import > > statment since the import path is incorrect. > > I would like to know is something wrong in my design, or something i > > missed. > > I think your issue is your module search path. Take a look at the doc for > sys.path in the library reference. These are the directories that python > searchies for modules. Usually the "." directory is included in this > which makes python search the current working directory. Your example > fails because your working directories are probably different when you ran > the two modules. In any case always consider how you've setup sys.path > and your libraries and modules. > > > Also, in practical usage, is that one class in one py file? > > I'm not exactly clear what your asking -- but I think yor asking if you'd > normally only put one class in one py file. My answer is no -- generally > you'd put many functions and classes in each py file. Modules are high > level and should be used to create libraries essentailly -- this means > many fucntions and classes per module. > > Rob > > From steven.bethard at gmail.com Thu Jan 27 15:29:35 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 13:29:35 -0700 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: Francis Girard wrote: > Le jeudi 27 Janvier 2005 20:16, Steven Bethard a ?crit : > >>flamesrock wrote: >> >>>The statement (1 > None) is false (or any other value above 0). Why is >>>this? >> >>What code are you executing? I don't get this behavior at all: >> >>py> 100 > None >>True >>py> 1 > None >>True >>py> 0 > None >>True >>py> -1 > None >>True >>py> -100 > None >>True >> > > > Wow ! What is it that are compared ? I think it's the references (i.e. the > adresses) that are compared. The "None" reference may map to the physical 0x0 > adress whereas 100 is internally interpreted as an object for which the > reference (i.e. address) exists and therefore greater than 0x0. > > Am I interpreting correctly ? Actually, I believe None is special-cased to work like this. From object.c: static int default_3way_compare(PyObject *v, PyObject *w) { ... if (v->ob_type == w->ob_type) { ... Py_uintptr_t vv = (Py_uintptr_t)v; Py_uintptr_t ww = (Py_uintptr_t)w; return (vv < ww) ? -1 : (vv > ww) ? 1 : 0; } ... /* None is smaller than anything */ if (v == Py_None) return -1; if (w == Py_None) return 1; ... } So None being smaller than anything (except itself) is hard-coded into Python's compare routine. My suspicion is that even if/when objects of different types are no longer comparable by default (as has been suggested for Python 3.0), None will still compare as smaller than anything... Steve From steven.bethard at gmail.com Tue Jan 4 09:35:57 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 04 Jan 2005 14:35:57 GMT Subject: why does UserDict.DictMixin use keys instead of __iter__? In-Reply-To: <1104836152.639270.196200@z14g2000cwz.googlegroups.com> References: <1104836152.639270.196200@z14g2000cwz.googlegroups.com> Message-ID: <1RxCd.847728$8_6.18665@attbi_s04> John Machin wrote: > Steven Bethard wrote: > >>So I was looking at the Language Reference's discussion about >>emulating container types[1], and nowhere in it does it mention that >> .keys() is part of the container protocol. > > I don't see any reference to a "container protocol". Sorry, I extrapolated "container protocol" from this statement: "Containers usually are sequences (such as lists or tuples) or mappings (like dictionaries), but can represent other containers as well. The first set of methods is used either to emulate a sequence or to emulate a mapping" and the fact that there is a "sequence protocol" and a "mapping protocol". But all I was really reading from this statement was that the "first set of methods" (__len__, __getitem__, __setitem__, __delitem__ and __iter__) were more integral than the second set of methods (keys(), values(), ...). > What I do see is > (1) """It is also recommended that mappings provide the methods keys(), > ...""" You skipped the remaining 13 methods in this list: "It is also recommended that mappings provide the methods keys(), values(), items(), has_key(), get(), clear(), setdefault(), iterkeys(), itervalues(), iteritems(), pop(), popitem(), copy(), and update() behaving similar to those for Python's standard dictionary objects." This is the "second set of methods" I mentioned above. I don't understand why the creators of UserDict.DictMixin decided that keys(), from the second list, is more important than __iter__, from the first list. >>Because of this, I would assume that to >>use UserDict.DictMixin correctly, a class would only need to define >>__getitem__, __setitem__, __delitem__ and __iter__. > > > So I can't see why would you assume that, given that the docs say in > effect "you supply get/set/del + keys as the building blocks, the > DictMixin class will provide the remainder". This message is reinforced > in the docs for UserDict itself. Sorry, my intent was not to say that I didn't know from the docs that UserDict.DictMixin required keys(). Clearly it's documented. My question was *why* does it use keys()? Why use keys() when keys() can be derived from __iter__, and __iter__ IMHO looks to be a more basic part of the mapping protocol. > In any case, isn't UserDict past history? Why are you mucking about > with it? UserDict is past history, but DictMixin isn't. As you note, DictMixin is even mentioned in the section of the Language Reference that we're discussing: "The UserDict module provides a DictMixin class to help create those methods from a base set of __getitem__(), __setitem__(), __delitem__(), and keys()." Steve From ishwor.gurung at gmail.com Fri Jan 28 07:40:46 2005 From: ishwor.gurung at gmail.com (Ishwor) Date: Fri, 28 Jan 2005 23:10:46 +1030 Subject: How to test that an exception is raised ? In-Reply-To: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> Message-ID: <34534aed05012804402d870dc1@mail.gmail.com> [snipped alot of codes that doesn't mean much ] if you want to check for exception then it goes like this try: catch IOError: sorry i won't bother to read your code because i can't read, i think i am tired and need to go to bed. ;-) -- cheers, Ishwor Gurung From Scott.Daniels at Acm.Org Fri Jan 7 11:22:39 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 07 Jan 2005 08:22:39 -0800 Subject: Python evolution: Unease In-Reply-To: References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7x4qhw859p.fsf@ruckus.brouhaha.com><7xk6qrnbum.fsf@ruckus.brouhaha.com><41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> Message-ID: <41deb485$1@nntp0.pdx.net> Terry Reedy wrote: > Even though I currently only have 80 ... I realize that my stinginess > with disk space for more serious stuff is obsolete. A gigabyte would > cover Python + Wxpython + numarray + scipy + pygame + a lot > of other stuff. > > Would it be possible, at least for Windows, to write a Python script > implementing a 'virtual distribution'? > IE, download Python, install it, download next package, install it, > etc. -- prefereably table driven? I would suggest looking to the Enthought distribution as a reasonable base (gets you an awful lot). Enthought has a _large_ collection, covering a lot of stuff that has general utility. Their production stuff is still at Python 2.3.3, but I believe they have a 2.4 version coming soon. The list of what they put in the 2.3.3 package is truly impressive: wxPython, PIL, VTK, MayaVi, Numeric, SciPy, ScientificPython, F2PY, Chaco, Traits, PyCrust, ZODB, Gadfly, PySQLite, and ctypes. All for one sub-90-Meg download. I add VPython to get dirt-simple 3-D stuff; you'd probably add pygame. The key to this is Enthought's attention to testing a stable "sumo" collection. I add a few packages that are much more anachronistic. My thought basically is that, since I want at least four of the packages, getting a "blessed" superset eases my installation woes. If you can wait, the plan for MacEnthon (Python 2.4 on Mac) looks great: http://www.scipy.org/wikis/featurerequests/MacEnthon I seem to remember discussion about synchronizing with the windows 2.4 version to have essentially the same list. --Scott David Daniels Scott.Daniels at Acm.Org From aleaxit at yahoo.com Sat Jan 1 05:01:26 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 1 Jan 2005 11:01:26 +0100 Subject: what is lambda used for in real code? References: <1104531721.3724.18.camel@localhost.localdomain> Message-ID: <1gpphwq.1n4ahpdanj12jN%aleaxit@yahoo.com> Terry Reedy wrote: > "Adam DePrince" wrote in message > news:1104531721.3724.18.camel at localhost.localdomain... > > In sort, we must preserve the ability to create an anonymous function > > simply because we can do so for every other object type, and functions > > are not special enough to permit this special case. > > Please show me how to create an anonymous type, module, or class, > especially with an expression. Number, sequences, and dicts have easily new.module('') creates a module and can be used within an expression. Of course 'anonymous' is doubtful, i.e.: >>> new.module('').__name__ '' but then >>> (lambda:23).__name__ '' So the parallel is there, roughly. You can create old-style classes similarly, with new.classobj, and new-style ones by calling type, which is more analogous to, say, creating sets by calling set, decimal numbers by calling decimal.Decimal, and so on. So the creating isn't a big problem -- by analogy with other types it should be done by calling some callable, either built-in or from the library. And, we do have new.function for that; problem is the code object that you need to pass as the first argument... there's new.code, too, but it wants a gazillion args, including a codestring that's not nice to put together;-). "Not for the faint of heart" as the docs say. Contents of modules and classes are less problematic. Well, new.module should perhaps take an optional dict argument, like new.classobj or calling type -- right now it's hard to create _and populate_ the module within the same expression. Not that I have any use case for this, though. And there's the rub...: > printable values. Functions, like classes and module do not*, so > definition names act as a standin and as a pointer to the source code that > produced the object. If functions are not special relative to classes and > modules, which is the grouping they belong with, then we should get rid of > lambda ;-) Yes but... we DO have a few real use cases for functions, which we don't really have for modules and classes, _and_ making the *contents* of a function object is harder too...:-( Alex From fuzzyman at gmail.com Wed Jan 26 03:23:06 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 26 Jan 2005 00:23:06 -0800 Subject: snakespell and myspell In-Reply-To: References: <1106657932.301181.150050@z14g2000cwz.googlegroups.com> Message-ID: <1106727786.284129.309420@z14g2000cwz.googlegroups.com> Jarek Zgoda wrote: > Fuzzyman wrote: > > > I'm looking to implement a plugin spell checker. > > > > I'm probably going to go with PyEnchant, as it looks to be the most > > promising currently maintained spell checker. > > > > I just wondered if anyone knew what happened to snakespell and myspell. > > Both seem to have dissapeared from the net. People have reported good > > results from both - and it seems a shame to lose them. > > Well, myspell-python is no longer maintained, original author resigned > some time ago and I didn't found anybody who would like to take > responsibility on this package. I provide myspell-1.0 download from my > project page at BerliOS (http://developer.berlios.de/projects/jpa/), but > I do not maintain this package. > > If you look for spell-checking library, I'd consider using python > binding for aspell, available at > http://www.republika.pl/wmula/proj/aspell-python/ (currently I'm > rewriting my program to use python-aspell). This library is actively > maintained and Wojtek Mula is active member of Polish Python community. > The problem with aspell is (as far as I can see anyway) that the library you mention is aimed at aspell 0.50.5 or the up to date 0.60 series. aspell for windows is currently only at 0.50.3. Hmmm.... I think I'll explore PyEnchant for the moment. I need to see how easy it is to add words to a user dictionary. Regards, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > -- > Jarek Zgoda > http://jpa.berlios.de/ | http://www.zgodowie.org/ From bob_smith_17280 at hotmail.com Mon Jan 24 22:31:32 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Mon, 24 Jan 2005 22:31:32 -0500 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: Message-ID: Rocco Moretti wrote: > Python's also dangerous. Every time you do an "import module", you put > your system at risk of crashing, having the hard-drive wiped Have you been drinking again? From marklists at mceahern.com Mon Jan 24 10:52:54 2005 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 24 Jan 2005 09:52:54 -0600 Subject: Finding a script's home directory? In-Reply-To: <41F516ED.3090503@mediapulse.com> References: <41F516ED.3090503@mediapulse.com> Message-ID: <41F519D6.8040009@mceahern.com> Gabriel Cooper wrote: > In one of my python programs has a data file I need to load. My > solution was to say: > > if os.path.exists(os.path.join(os.getcwd(), "config.xml")): > self.cfgfile = os.path.join(os.getcwd(), "config.xml") > > Which works fine... as long as you're *in* the script's home directory > when you run it (as in, run it as: ./startApp.py as opposed to > ./myApp/startApp.py). > > If I run it from an alternate directory the program looks for the > config.xml file in my current directory not the app's home directory. > So how do I get the script's home directory? import os.path dirname = os.path.dirname(__file__) // m From danb_83 at yahoo.com Wed Jan 19 00:50:58 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 18 Jan 2005 21:50:58 -0800 Subject: python/cgi/html bug In-Reply-To: References: Message-ID: <1106113858.360940.298900@c13g2000cwb.googlegroups.com> Dfenestr8 wrote: > Hi. > > I've written a cgi messageboard script in python, for an irc chan I happen > to frequent. > > Bear with me, it's hard for me to describe what the bug is. So I've > divided this post into two sections: HOW MY SCRIPTS WORKS, and WHAT THE > BUG IS. > ... > The problem is when someone posts a new topic, and that topic happens to > have "" double quotes, or any other strange character, some strange > glitches occur. Use cgi.escape(topic, True) to convert HTML special characters to the equivalent ampersand escape sequences. From aleaxit at yahoo.com Thu Jan 6 07:25:09 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 6 Jan 2005 13:25:09 +0100 Subject: Python evolution: Unease References: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> <41dcc35a$0$3872$afc38c87@news.optusnet.com.au> Message-ID: <1gpyxxv.wxsci81e0054aN%aleaxit@yahoo.com> Robert Kern wrote: ... > >> I love eric3, but if you're an eclipse fan, look at enthought's > >> "envisage" IDE -- it seems to me that it has superb promise. ... > > Is it available for download somewhere? > > Alex is, I think, jumping the gun a bit. Envisage isn't quite ready for > prime time as your day to day IDE. It might be useful to you right now I apologize if I gave a misleading impression: I did not mean it was ready to use, or _already_ here; I suggested "looking at" in the sense of "paying attention to", and specifically mentioned "promise". Since the subthread was about future IDE developments, I thought it was appropriate to mention envisage, in the context of comparisons with eclipse's plugin-centered architecture. > as a platform to build a dynamic GUI application (Envisage's intended > use) if you are willing to get your hands dirty and help us build > Envisage. Hence, it is not being advertised widely. I saw a Pycon proposed talk about it, so I didn't stop to consider the "not advertised widely" issue. Thinking about it, I realize Pycon is almost 3 months from now, so wanting to enthuse about envisage then doesn't imply already wanting to widely advertise it now; sorry. > But Alex is right; Envisage does hold a lot of promise. The very concept of an architecture based on a spare skeleton and copious plugins is intrinsically excellent, and I think that by now eclipse has proven it's also practically viable for real-world powerful IDEs/platforms/frameworks. Alex From http Thu Jan 6 18:38:53 2005 From: http (Paul Rubin) Date: 06 Jan 2005 15:38:53 -0800 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: <7xhdluxh4i.fsf@ruckus.brouhaha.com> Bulba! writes: > Making derived work proprietary in no way implies that the base > work is publicly unavailable anymore. Since you want to be able to incorporate GPL code in your proprietary products, and say there's no problem since the base work is still available from the same places it was available from before, fairness would say you shouldn't mind that people incorporate code from your products into THEIR products, since your version is still available from you. Really, you're just a freeloader looking for handouts. From just at xs4all.nl Mon Jan 17 07:52:47 2005 From: just at xs4all.nl (Just) Date: Mon, 17 Jan 2005 13:52:47 +0100 Subject: (objects as) mutable dictionary keys References: Message-ID: In article , Peter Maas wrote: > Antoon Pardon schrieb: > > Dictionary lookup with mutable types like lists is a source of > > unpleasant surprises for the programmer and therefore impossible in > > Python. > > > > > > It is not impossible in Python. Is too. > > It may be discouraged but it is not > > impossible since I have already done so. > > Wouldn't this raise a TypeError? Or did you wrap them with an object? He created a list subclass that redefines __hash__, so he cheated :). Just From reinhold-birkenfeld-nospam at wolke7.net Sat Jan 15 04:57:42 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 15 Jan 2005 10:57:42 +0100 Subject: How to del item of a list in loop? In-Reply-To: <34rvjqF4f6l70U1@individual.net> References: <34rvjqF4f6l70U1@individual.net> Message-ID: <34s7omF4emdsaU1@individual.net> Reinhold Birkenfeld wrote: > skull wrote: >> Hi everybody, it is my first post in this newsgroup. >> I am a newbie for python though I have several years development experience in c++. >> recently, I was stumped when I tried to del item of a list when iteration. >> >> here is the wrong way I did: >> >> lst = [1, 2, 3] >> for i in lst: >> print i >> if i == 2: >> lst.remove(i) >> >> the result is: >> >> 1 >> 2 >>>>> >> >> as you would see, '3' is missing. this problem is caused by 'lst.remove(i)'. >> apparently, 'marked-and-sweep' is a solution to deal with this issue. >> but I think there SHOULD BE more 'wise' trick. I want to get your help. > > Quick solution: > > for i in lst[:] > > iterates over a copy. Addition: In Py2.4, I can't find a problem with for i in reversed(lst) Any objections? Reinhold From rm at rm.net Sat Jan 22 15:00:04 2005 From: rm at rm.net (rm) Date: Sat, 22 Jan 2005 21:00:04 +0100 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> Message-ID: <35fpq0F4mh1ffU1@individual.net> Fredrik Lundh wrote: > "rm" wrote: > > >>100% right on, stuff (like this)? should be easy on the users, and if possible, on the developers, >>not the other way around. > > > I guess you both stopped reading before you got to the second paragraph > in my post. YAML (at least the version described in that spec) isn't easy on > users; it may look that way at a first glance, and as long as you stick to a > small subset, but it really isn't. that's not just bad design, that's plain evil. > > and trust me, when things are hard to get right for developers, users will > suffer too. > > > > > you stopped reading too early as well, I guess: "maybe their stated goal is not reached with this implementation of their idea" and the implementation being the spec, furthermore, "users will suffer too", I'm suffering if I have to use C++, with all its exceptions and special cases. BTW, I pickpocketed the idea that if there is a choice where to put the complexity, you never put it with the user. "pickpocket" is strong, I've learned it from an analyst who was 30 years in the business, and I really respect the guy, basically he was always right and right on. On the other hand, the management did not always like what he thought :-) bye, rm From aleaxit at yahoo.com Fri Jan 7 04:05:09 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 10:05:09 +0100 Subject: Excluded and other middles in licensing References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> <75r0b2-ohg.ln1@lairds.us> Message-ID: <1gq0jpn.1es49j7jrk3k5N%aleaxit@yahoo.com> Robert Kern wrote: ... > >>While most people may not think of such programs as "closed source", > >>they most definitely ARE: the definition of open source is very strict > >>about this aspect. ... > > With my mathematical background, I'm consistent about calling > > these "non-open" rather than "closed". I don't insist others > > adopt my nomenclature ... > > I'm with Cameron on this one. There is no "official" definition of closed-source as there is of open-source, but I'm with the Wikipedia: http://en.wikipedia.org/wiki/Closed_source "any program whose licensing terms do not qualify as open source". I'm not disputing it would be useful to draw many distinctions within the universe of programs with non-opensource licenses, just pointing out that such distinctions are not currently reflected in a popular definition. Since it's a wiki, it may be worthwhile editing it to add some materials to start influencing popular usage and perception, maybe. Alex From ncoghlan at iinet.net.au Thu Jan 20 04:49:16 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 20 Jan 2005 19:49:16 +1000 Subject: Dictionary keys (again) (was Re: lambda) In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: <41EF7E9C.7010006@iinet.net.au> Antoon Pardon wrote: > As you said yourself, people use shortcuts when they express themselves. > With 'mutable key' I mean a mutable object that is used as a key. > That doesn't contradict that the key itself can't change because > it is inaccessible. Yeah - this was the point of terminology that was getting confused, I think. And your interpretation was closer to the strict sense of the words. >>Well, the Zen of Python states "In the face of ambiguity, refuse the temptation >>to guess". > > But python does guess in the case of the value. If I want to establish a > relationship between "foo" and [3, 5, 8] then I can be in big trouble > if that list gets mutated in something else. However, the actual promise a Python dict makes is that it maps from keys by value to values by identity. That is, "k1 == k2" implies "d[k1] is d[k2]". An identity test on mutable objects is entirely unambiguous (hence they can be values), but comparison is not (hence they cannot be keys). Restricting keys to immutable objects eliminates the ambiguity. Copying keys would also prevent mutation and eliminate the ambiguity. The restriction approach is a *definite* performance enhancement over the copying approach, though (this is probably the origin of the mantra "the restriction to mutable keys is a performance enhancement"). The resulting semantics of the restriction to immutable objects are also significantly less surprising than those of the copying approach. An identity dict would make the promise that "k1 is k2" implies "d[k1] is d[k2]". In this case, the mutability of the key is irrelevant, so the behaviour is unambiguous without any additional restrictions. > But they don't have to be immutable within the dictionary itself, that > is just an implementation detail. The only thing that matters is that > the dictionary can reproduce the relationship. How that is done is > immaterial. Given the Python interpreter's current definition of "immutable" as "defines __hash__", it's a little hard to have an unhashable object as a key :) >>In short, sane hash tables require immutable keys, and how mutable keys acquire >>the requisite immutability is going to be application dependent. > > > No they don't, that is just the most easy implementation. If some > implementation would constantly change the internal objects but > consulting the dictionary wouldn't show any different effect then > that would be fine too. And even in this case a mutation > from the outside would probably cause havoc because it would ruin > the sanity of the internal structure. If you insist: s/immutable/effectively immutable/ And no data type can be expected to tolerate having their invariants violated by external code messing with internal data structures. >>Provision of a safe_dict or identity_dict would merely allow a programmer to >>state their intent at the time the container is created, rather than having to >>state it whenever keys are generated or referenced. > > Well that would be a good thing IMO. True - I'm not sure how that 'merely' snuck in there :) > Good enough in any case for me to > spend some time analyzing the requirements. Whether I'll actually > implement something depends on how much time I have and how often I > need it. My preference is for the identity dict - its performance would actually be *better* than that of a standard dict in the domains where it applies (annotation and classification of objects are the two main uses I can see for such a data structure). This aligns quite well with the stated goal of the collections module (providing data structures that are less general purpose than the standard builtins, but deliver better performance for their particular use cases) Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From claird at lairds.us Thu Jan 27 09:08:08 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 27 Jan 2005 14:08:08 GMT Subject: Point of Sale References: Message-ID: In article , Andreas Pauley wrote: >Hi, > >My company has given me a rather cool project: >I have to provide them with an open-source python-based point-of-sale / >cash register system that can integrate with their existing ERP backend. > >The project will include development to ensure that the features they >require are included in the open-source POS system. > >Can you recommend anything that I can use? . . . Research. I think you're expecting an answer of the "I used open-source openPOS project, and it worked great for me", but I suspect all that is premature. What does POS mean to you? What are your platform constraints? Does your company have expectations about how POS will work? What access (CORBA? RMI? SOAP? ...) is there to the ERP? From steve at holdenweb.com Mon Jan 17 15:16:10 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 15:16:10 -0500 Subject: Adjusting the 1024 byte stdin buffer limit In-Reply-To: <1105989764.168794.113430@z14g2000cwz.googlegroups.com> References: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> <1105989764.168794.113430@z14g2000cwz.googlegroups.com> Message-ID: brucoder wrote: > Currently, when sending a data stream that exceeds 1024 bytes via > stdin, the stream blocks at the 1024th byte. This precludes completion > of the submission of the data stream. > But surely the blocking will only last as long as the consuming process leaves buffered input unread? 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 2004b at usenet.alexanderweb.de Wed Jan 12 11:48:27 2005 From: 2004b at usenet.alexanderweb.de (Alexander Schremmer) Date: Wed, 12 Jan 2005 17:48:27 +0100 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> <7xekgr7lpy.fsf@ruckus.brouhaha.com> <7x4qhn9q3g.fsf@ruckus.brouhaha.com> Message-ID: On 11 Jan 2005 21:24:51 -0800, Paul Rubin wrote: [backlinks] >> Searching instead of indexing makes it very resilient :-) > > How does it do that? It has to scan every page in the entire wiki?! > That's totally impractical for a large wiki. So you want to say that c2 is not a large wiki? :-) Kind regards, Alexander From grante at visi.com Sat Jan 15 13:08:54 2005 From: grante at visi.com (Grant Edwards) Date: 15 Jan 2005 18:08:54 GMT Subject: interpret 4 byte as 32-bit float (IEEE-754) References: <34t1p2F4foiplU1@individual.net> <41e952b9$1@nntp0.pdx.net> Message-ID: <41e95c36$0$82380$a1866201@visi.com> On 2005-01-15, Scott David Daniels wrote: >> I've read some bytes from a file and just now I can't interpret 4 bytes >> in this dates like a real value. > OK, here's the skinny (I used blocks & views to get the answer): > > import struct > bytes = ''.join(chr(int(txt, 16)) for txt in '3F 8C CC CD'.split()) > struct.unpack('>f', bytes) Just be careful. That doesn't work for all 32-bit IEEE floating point values: >>> import struct >>> bytes = '\xff\xff\xff\xff' >>> print struct.unpack('>f',bytes) (-6.8056469327705772e+38,) 0xffffff is _not_ -6.8...e38. It's a NaN. IIRC, it doesn't work for infinities either. I haven't tried denormals. -- Grant Edwards grante Yow! It's hard being at an ARTIST!! visi.com From peter at engcorp.com Wed Jan 12 10:41:23 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Jan 2005 10:41:23 -0500 Subject: Excel module for Python In-Reply-To: References: Message-ID: sam wrote: >> On Wed, 12 Jan 2005 15:18:09 +0800, sam wrote: >>> I m wondering which Excel module is good to be used by Python? [snip] > No, I don't use MS windows. I need to generate Excel file by printing > data to it, just like Perl module Spreadsheet::WriteExcel. Excel can read CSV files, so just use the standard Python module "csv" and write your files that way. -Peter From kp8 at mac.com Tue Jan 11 16:53:48 2005 From: kp8 at mac.com (kpp9c) Date: 11 Jan 2005 13:53:48 -0800 Subject: Time script help sought! In-Reply-To: <1105480151.431987.327080@c13g2000cwb.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> <1105477084.525279.312970@f14g2000cwb.googlegroups.com> <1105479292.689762.155510@f14g2000cwb.googlegroups.com> <1105480151.431987.327080@c13g2000cwb.googlegroups.com> Message-ID: <1105480428.116581.24040@c13g2000cwb.googlegroups.com> so all the imput will look more like this now... ( no comments either) tem_133, DAT_20, 7, 00:58:25, 01:15:50 Item_134, DAT_20, 8, 01:15:50, 01:32:15 Item_135, DAT_21, 1, 00:01:00, 00:36:15 Item_136, DAT_60, 3, 00:18:30 Item_136, DAT_60, 4, 00:19:30 Item_136, DAT_60, 5, 00:23:00, 00:28:00 Item_137, DAT_21, 4, 00:37:00, 00:47:00 Item_139, DAT_21, 2, 00:36:15 Item_139, DAT_21, 3, 00:42:15, 01:00:50 Item_140, DAT_21, 4, 01:00:50 Item_140, DAT_21, 5, 01:25:10, 01:26:35 ..... snip... From fredrik at pythonware.com Sun Jan 23 13:04:19 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 19:04:19 +0100 Subject: What is print? A function? References: <200501231801.50080.frans.englich@telia.com> Message-ID: Frans Englich wrote: > Nah, I don't think it's a function, but rather a builtin "statement". But it's > possible to invoke it as an function; print( "test" ) works fine. > > So I wonder, what _is_ exactly the print statement? The untraditional way of > invoking it(without paranteses) makes me wonder. it's a statement. (expr) is an expression (in parenthesis), so when you type print("test") python sees: print ("test") (see the language reference for details) > The reason I thinks about this is I need to implement a debug print for my > program; very simple, a function/print statement that conditionally prints > its message whether a bool is true. Not overly complex. > > I tried this by overshadowing the print keyword, but that obviously didn't > work.. Is defining a two-liner function the right way to go yup. something like this might be useful: def printif(cond, fmt, *args): if cond: print fmt % args From http Thu Jan 6 20:24:21 2005 From: http (Paul Rubin) Date: 06 Jan 2005 17:24:21 -0800 Subject: The Industry choice References: <7xhdluxh4i.fsf@ruckus.brouhaha.com> Message-ID: <7xzmzmni9m.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > >I don't like what I perceive as end effect of what GPL license > >writers are attempting to achieve: vendor lock-in. > And my counter-argument is that I believe your perception is wrong. If > I agreed with your focus on lock-in, I'd say that what the GPL is trying > to lock in is a specific legal philosophy by subverting the existing > system. Bulba's perception is wrong in a different way too. The GPL tries to encourage the enlargement of a public resource, namely a codebase shareable by a worldwide community of users and developers, a cyber equivalent of a public park whose facilities anyone can visit and use but nobody can take away and exclude others from using. The idea of referring to such a shared community resource as a "vendor" is just bizarre. From aleaxit at yahoo.com Tue Jan 11 13:35:08 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 11 Jan 2005 19:35:08 +0100 Subject: how to set doc-string of new-style classes References: Message-ID: <1gq8p18.109u52rvr55yoN%aleaxit@yahoo.com> harold fellermann wrote: ... > But, I cannot > even find out a way to set the doc string, when I CREATE a class using > type(name,bases,dict) ... At least this should be possible, IMHO. >>> x=type('x',(),dict(__doc__='hi there')) >>> x.__doc__ 'hi there' Alex From roy at panix.com Fri Jan 7 12:12:15 2005 From: roy at panix.com (Roy Smith) Date: 7 Jan 2005 12:12:15 -0500 Subject: Getting rid of "self." References: <740c3aec05010705393048a374@mail.gmail.com> <10ttf1slqmefi28@news.supernews.com> Message-ID: In article <10ttf1slqmefi28 at news.supernews.com>, John Roth wrote: > >"Roy Smith" wrote in message >news:crmdqk$jo6$1 at panix2.panix.com... >> Simon Brunning wrote: >>>On 7 Jan 2005 08:10:14 -0800, Luis M. Gonzalez wrote: >>>> The word "self" is not mandatory. You can type anything you want >>>> instead of self, as long as you supply a keyword in its place (it can >>>> be "self", "s" or whatever you want). >>> >>>You *can*, yes, but please don't, not if there's any chance that >>>anyone other than you are going to have to look at your code. >>>'self.whatever' is clearly an instance attribute. 's.whatever' isn't >>>clearly anything - the reader will have to go off and work out what >>>the 's' object is. >> >> +1. >> >> If there is one coding convention which is constant through the Python >> world, it's that the first argument to a class method is named >> "self". Using anything else, while legal, is just being different for >> the sake of being different. > >Didn't you mean instance method? Class methods are a different >beast, and the few examples I've seen seem to use the word "klas". Sorry, yes. My bad. I used to work with a C++ guy who always used "class" when he should have used "instance". It drove me crazy. :-) From FBatista at uniFON.com.ar Tue Jan 4 13:42:41 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 4 Jan 2005 15:42:41 -0300 Subject: Python evolution: Unease Message-ID: [Skip Montanaro] #- This being the Internet and all, it's not clear that #- referencing external #- documentation is somehow worse than incorporating it #- directly into the #- distribution. The problem is Internet access. For example, once I put together a "Python CD" as a present for my father. Inside it put Linux & Windows installers (Python itself and wxWindows (this name then)). And of course, the whole documentation package, in PDF. Of course, I didn't parse the whole docs to see what other documents I could include. And to my father is kinda complicated (and expensive!) access internet and read the docs there. I mean, it's perfectly possible, but would be better IMO to have the docs concentrated. . 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 steve at holdenweb.com Sat Jan 1 11:46:55 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Jan 2005 11:46:55 -0500 Subject: The Industry choice In-Reply-To: <7xfz1lal5d.fsf@ruckus.brouhaha.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xfz1lal5d.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: [...] > There's lots of times when I have a cool programming idea, and find > when I sit down at the computer that I can implement the main points > of the idea and get a neat demo running rather quickly. That creates > a very happy, liberating feeling, plus gives me something to show off > to friends or co-workers. But turning it into a finished product with > no rough edges is an order of magnitude more work. It seems to me > that IDLE and a lot of the rest of Python are examples of someone > having a cool idea and writing a demo, then releasing it with a lot of > missing components and rough edges, without realizing that it can't > reasonably be called complete without a lot more work. ^Python^open source^ 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 steve at holdenweb.com Sat Jan 1 15:08:01 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Jan 2005 15:08:01 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: Rob Emmons wrote: >>For managers of companies it's worse: the company makes >>VERY substantial investments into any technology it "marries", >>and that means big losses if it goes. Long-term stability >>of this technology in terms of "we're not going to be left out >>in cold alone with this technology to feed it" means a lot >>to them. Even a poor technology with external backing >>of big, stable vendor is better than the excellent technology >>without ...... > > > There is the stability issue you mention... but also probably the fear > issue. If you choose a solution from a major company -- then it fails for > some reason or they drop the product -- it's their fault -- you've got an > automatic fall guy. On the other hand, an open source solution or > otherwise less accepted solution ... it will probably be consider > your fault by the organization. It's a rational decision to avoid > personal risk when you don't get much reward for choosing something > different. > You are ignoring the fact that with the open source solution you do at least have the option of hiring bright programmers to support the framework which has now become moribund, whereas when a company goes bust there's no guarantee the software IP will ever be extricated from the resulting mess. So I'm not sure I'd agree with "rational" there, though "comprehensible" might be harder to argue with. Personally I'd feel in a better position standing before a Board of Directors and saying "While it's true that our chosen software platform isn't being supported by the original team any more, we do have options to continue to move it forward, including forming a consortium with other users". Avoidance of blame is way too large a motivator in large organizations, and it leads to many forms of sub-optimal decision making. 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 nick at craig-wood.com Thu Jan 13 03:31:44 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 13 Jan 2005 08:31:44 GMT Subject: Refactoring; arbitrary expression in lists References: <41e5cb07.701137402@news.oz.net> Message-ID: Stephen Thorne wrote: > Why not use a regexp based approach. Good idea... You could also use sre.Scanner which is supposed to be fast like this... import re, sre scanner = sre.Scanner([ (r"\.php$", "application/x-php"), (r"\.(cc|cpp)$", "text/x-c++-src"), (r"\.xsl$", "xsl"), (r"Makefile", "text/x-makefile"), (r".", None), ]) def detectMimeType( filename ): t = scanner.scan(filename)[0] if len(t) < 1: return None # raise NoMimeError return t[0] for f in ("index.php", "index.php3", "prog.cc", "prog.cpp", "flodge.xsl", "Makefile", "myMakefile", "potato.123"): print f, detectMimeType(f) ... prints index.php application/x-php index.php3 None prog.cc text/x-c++-src prog.cpp text/x-c++-src flodge.xsl xsl Makefile text/x-makefile myMakefile text/x-makefile potato.123 None -- Nick Craig-Wood -- http://www.craig-wood.com/nick From philippecmartin at sbcglobal.net Tue Jan 25 09:55:16 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Tue, 25 Jan 2005 08:55:16 -0600 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) In-Reply-To: <8c7f10c605012502281d9c9b29@mail.gmail.com> References: <1106590633.15475.3.camel@localhost> <8c7f10c605012502281d9c9b29@mail.gmail.com> Message-ID: <1106664916.7197.2.camel@localhost> Well I _was_ a bit slow on that one ! So I will happily stick to the double underscore. Regards, Philippe Le mardi 25 janvier 2005 ? 10:28 +0000, Simon Brunning a ?crit : > On Mon, 24 Jan 2005 12:17:13 -0600, Philippe C. Martin > wrote: > > > > I use "__"for private variables because I must have read on net it was > > the way to do so - yet this seems to have changed - thanks: > > > > http://www.network-theory.co.uk/docs/pytut/tut_77.html > > Nope, that's still the right way to make a member 'really' private. > Stephen was pointing out a very common Python idiom - "private by > convention", and suggesting that using it would be more appropriate. > > A member with a single preceding underscore is private by convention. > That is to say, there is no mechanism in place to prevent clients of > the class accessing these members, but they should consider themselves > to have been warned that they do so at their own risk. > > If you take the back off the radio, the warranty is void. ;-) > > I (and by inference Stephen) feel that this is a more "Pythonic" > approach. Give the programmer the information that they need, but > don't try to stop them from doing what they need to do. > -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From francis.girard at free.fr Mon Jan 24 08:09:25 2005 From: francis.girard at free.fr (Francis Girard) Date: Mon, 24 Jan 2005 14:09:25 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <20050123222743.GA32583@unpythonic.net> References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501232255.08496.francis.girard@free.fr> <20050123222743.GA32583@unpythonic.net> Message-ID: <200501241409.25598.francis.girard@free.fr> Ok, I think that the bottom line is this : For all the algorithms that run after their tail in an FP way, like the Hamming problem, or the Fibonacci sequence, (but unlike Sieve of Eratosthene -- there's a subtle difference), i.e. all those algorithms that typically rely upon recursion to get the beginning of the generated elements in order to generate the next one ... ... so for this family of algorithms, we have, somehow, to abandon recursion, and to explicitely maintain one or many lists of what had been generated. One solution for this is suggested in "test_generators.py". But I think that this solution is evil as it looks like recursion is used but it is not and it depends heavily on how the m235 function (for example) is invoked. Furthermore, it is _NOT_ memory efficient as pretended : it leaks ! It internally maintains a lists of generated results that grows forever while it is useless to maintain results that had been "consumed". Just for a gross estimate, on my system, percentage of memory usage for this program grows rapidly, reaching 21.6 % after 5 minutes. CPU usage varies between 31%-36%. Ugly and inefficient. The solution of Jeff Epler is far more elegant. The "itertools.tee" function does just what we want. It internally maintain a list of what had been generated and deletes the "consumed" elements as the algo unrolls. To follow with my gross estimate, memory usage grows from 1.2% to 1.9% after 5 minutes (probably only affected by the growing size of Huge Integer). CPU usage varies between 27%-29%. Beautiful and effecient. You might think that we shouldn't be that fussy about memory usage on generating 100 digits numbers but we're talking about a whole family of useful FP algorithms ; and the best way to implement them should be established. For this family of algorithms, itertools.tee is the way to go. I think that the semi-tutorial in "test_generators.py" should be updated to use "tee". Or, at least, a severe warning comment should be written. Thank you, Francis Girard FRANCE Le dimanche 23 Janvier 2005 23:27, Jeff Epler a ?crit?: > Your formulation in Python is recursive (hamming calls hamming()) and I > think that's why your program gives up fairly early. > > Instead, use itertools.tee() [new in Python 2.4, or search the internet > for an implementation that works in 2.3] to give a copy of the output > sequence to each "multiply by N" function as well as one to be the > return value. > > Here's my implementation, which matched your list early on but > effortlessly reached larger values. One large value it printed was > 6412351813189632 (a Python long) which indeed has only the distinct > prime factors 2 and 3. (2**43 * 3**6) > > Jeff > > from itertools import tee > import sys > > def imerge(xs, ys): > x = xs.next() > y = ys.next() > while True: > if x == y: > yield x > x = xs.next() > y = ys.next() > elif x < y: > yield x > x = xs.next() > else: > yield y > y = ys.next() > > def hamming(): > def _hamming(j, k): > yield 1 > hamming = generators[j] > for i in hamming: > yield i * k > generators = [] > generator = imerge(imerge(_hamming(0, 2), _hamming(1, 3)), _hamming(2, > 5)) generators[:] = tee(generator, 4) > return generators[3] > > for i in hamming(): > print i, > sys.stdout.flush() From rublind at gmail.com Mon Jan 10 00:46:12 2005 From: rublind at gmail.com (rublind at gmail.com) Date: 9 Jan 2005 21:46:12 -0800 Subject: Datetime module Message-ID: <1105335972.454019.46450@c13g2000cwb.googlegroups.com> I am writing a script that acts as an AIM bot [using twisted.IM's base scripts] and I want to add a logging feature. I got it to log who sends what to whom, but what I want to add is the date and time that the message was sent (or recieved by the bot), I tried to look at datetime on my own, and I couldn't get anything to work. Anyone know a simple way to get the current date and/or time? Thanks! From gmane-schpam at joefrancia.com Sat Jan 8 18:31:18 2005 From: gmane-schpam at joefrancia.com (Joe Francia) Date: Sat, 08 Jan 2005 18:31:18 -0500 Subject: The best way to do web apps with Python? In-Reply-To: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: worzel wrote: > What is the best way to web developemnt with Python? Is there > anything close to PHP style in-page script placement that can create > and use other Python objects? I am not really interested in Zope (I > believe that is more a CMS than anything else?) I am also looking for > something a little more structured than a series of CGI Scripts. > > While on the topic - what is the expectataion of Python for this kind > of stuff? Would one use Python for certain other things but turn to > PHP for web apps - or would one use their Python skills in place of > PHP? > > TIA > You may want to look here for some thoughts on the matter: http://pyre.third-bit.com/pyweb/index.html I lean towards Quixote and/or CherryPy, with ZODB as the storage. Both are conceptually similar (I'm comparing v2 of both), but I favor Quixote just slightly more, mostly for Quixote's better form handling. Cheetah is a very nice templating package, but in Quixote I just use its own PTL, since it's built-in. If you wanted to stick with PHP for some reason, Drupal is a very nicely designed framework (or CivicSpace, which is developed in parallel with Drupal, with a number of added-on features). Quixote: http://www.mems-exchange.org/software/quixote/ CherryPy: http://www.cherrypy.org/ ZODB: http://zope.org/Wikis/ZODB/FrontPage Cheetah: http://www.cheetahtemplate.org/ Drupal: http://www.drupal.org/ CivicSpace: http://www.civicspacelabs.org/ jf From ianb at colorstudy.com Wed Jan 12 15:41:02 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Wed, 12 Jan 2005 14:41:02 -0600 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: <7xvfa2toed.fsf@ruckus.brouhaha.com> References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> <7xekgr7lpy.fsf@ruckus.brouhaha.com> <7x4qhn9q3g.fsf@ruckus.brouhaha.com> <7xr7kq1rk6.fsf@ruckus.brouhaha.com> <7xvfa2toed.fsf@ruckus.brouhaha.com> Message-ID: <41E58B5E.30805@colorstudy.com> Paul Rubin wrote: > Paul Rubin writes: > >>>>How does it do that? It has to scan every page in the entire wiki?! >>>>That's totally impractical for a large wiki. >>> >>>So you want to say that c2 is not a large wiki? :-) >> >>I don't know how big c2 is. My idea of a large wiki is Wikipedia. >>My guess is that c2 is smaller than that. > > > I just looked at c2; it has about 30k pages (I'd call this medium > sized) and finds incoming links pretty fast. Is it using MoinMoin? > It doesn't look like other MoinMoin wikis that I know of. I'd like to > think it's not finding those incoming links by scanning 30k separate > files in the file system. c2 is the Original Wiki, i.e., the first one ever, and the system that coined the term. It's written in Perl. It's a definitely not an advanced Wiki, and it's generally relied on social rather than technical solutions to problems. Which might be a Wiki principle in itself. While I believe it used full text searches for things like backlinks in the past, I believe it uses some kind of index now. > Sometimes I think a wiki could get by with just a few large files. > Have one file containing all the wiki pages. When someone adds or > updates a page, append the page contents to the end of the big file. > That might also be a good time to pre-render it, and put the rendered > version in the big file as well. Also, take note of the byte position > in the big file (e.g. with ftell()) where the page starts. Remember > that location in an in-memory structure (Python dict) indexed on the > page name. Also, append the info to a second file. Find the location > of that entry and store it in the in-memory structure as well. Also, > if there was already a dict entry for that page, record a link to the > old offset in the 2nd file. That means the previous revisions of a > file can be found by following the links backwards through the 2nd > file. Finally, on restart, scan the 2nd file to rebuild the in-memory > structure. That sounds like you'd be implementing your own filesystem ;) If you are just trying to avoid too many files in a directory, another option is to put files in subdirectories like: base = struct.pack('i', hash(page_name)) base = base.encode('base64').strip().strip('=') filename = os.path.join(base, page_name) -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From http Wed Jan 19 20:09:19 2005 From: http (Paul Rubin) Date: 19 Jan 2005 17:09:19 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> Message-ID: <7xacr4ewjk.fsf@ruckus.brouhaha.com> Robin Becker writes: > > Presumably he is talking about crypo-export rules. In the past strong > > cryptography has been treated as munitions, and as such exporting it > > (especially from the USA) could have got you into very serious > > trouble. > > well since rotor is a german (1930's) invention it is a bit late for > Amricans (Hollywood notwithstanding) to be worried about its export 1. I think the concern was not about exporting from the US, but rather importing into some countries that restrict the use of crypto. But the cat is out of the bag on that one too. Just about every web browser includes an SSL stack and those browsers are in use everywhere. 2. It's irrelevant for the purpose of export rules how old an invention is or where it was invented. I don't know where machine guns were invented, but they're at least 100 years old and you can't export those without a license either. My gripe with the crypto rules are not about the age or nationality of crypto rotor machines (rotor is not a clone of the Enigma by the way; it just operates on related principles) but rather on the control of information in general. Exporting a machine gun is much different from publishing a description of one. Software is just a precise type of description. From kent3737 at yahoo.com Sat Jan 29 21:42:12 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Sat, 29 Jan 2005 21:42:12 -0500 Subject: bound vs unbound functions In-Reply-To: <1107040729.535936.42230@c13g2000cwb.googlegroups.com> References: <1107040729.535936.42230@c13g2000cwb.googlegroups.com> Message-ID: <41fc46e3_1@newspeer2.tds.net> Michael Tobis wrote: > I'm trying to do metaprogramming. I'm sure I've got this all wrong > wrong wrong, but somehow my approach hasn't yet hit a brick wall. > > Anyway, I'd like to dynamically add a method to an instance at > instantiation time. Something like > > ###### > In [71]: class quux(object): > ....: def __init__(self,stuff): > ....: template = "def foo(self,b): print b + %s" % stuff > ....: exec(template) > ....: self.bazz = foo > ....: > > > In [72]: q = quux(5) > > In [73]: q.bazz(4) > --------------------------------------------------------------------------- > TypeError Traceback (most recent call > last) > > /Users/tobis/PyNSol/ > > TypeError: foo() takes exactly 2 arguments (1 given) > > In [74]: q.bazz("not much",4) > 9 > ######## The thread Steve quoted suggests using new.instancemethod(): import new class quux(object): def __init__(self,stuff): template = "def foo(self,b): print b + %s" % stuff exec(template) self.bazz = new.instancemethod(foo, self, quux) There is no need for exec; you can define foo() directly as a nested function: class quux(object): def __init__(self,stuff): def foo(self,b): print b + stuff self.bazz = new.instancemethod(foo, self, quux) Of course for this simple example you can just remember stuff as an attribute: class quux(object): def __init__(self,stuff): self.stuff = stuff def bazz(self, b): print b + self.stuff Kent > > So the straightforward question is why, even though bazz is a method of > class quux, it doesn't have that extra call parameter 'self'. Is this a > problem? If I actually need a reference to self is it OK to do: > > In [76]: q.bazz(q,4) > > ? > > The more vague question is why do people despise 'exec', and how should > I do this sort of thing instead? From drummmachine at aol.commmmm Thu Jan 20 23:27:49 2005 From: drummmachine at aol.commmmm (Drummmachine) Date: 21 Jan 2005 04:27:49 GMT Subject: Does anyone want one? Message-ID: <20050120232749.14147.00000205@mb-m10.aol.com> http://www.freeiPods.com/?r=14249501 just go here to get started. It's very easy and very real. This is no scam. Complete an offer, get 5 others to do the same and you'll receive a free Ipod of your choice. thanks for your time. Free ipods are real. From gilles.arnaud at cea.fr Mon Jan 24 10:00:16 2005 From: gilles.arnaud at cea.fr (Gilles Arnaud) Date: Mon, 24 Jan 2005 16:00:16 +0100 Subject: "bad argument type for built-in operation" Message-ID: Hello, I've got a nasty bug and no idea to deal with : here is the method : def denormer(self, var) : " denorme un vecteur d'entree " try: #a = map(self.decerner, self.param, var) #a = [self.decerner(x, y) for x, y in map(None, self.param, var)] a = [] print 'in', None, self.param, var, len(self.param), len(var), str(self.decerner) #return map(undoc, self.param, var) print map(None, var) print map(None, self.param) #print zip(var, var) #print zip(self.param, self.param) #print map(lambda x, y: (x,y), self.param, var) #print zip(self.param, var) b = [] print '$', ii = range(len(var)) print ii, '$', for i in ii : print '%', b.append((self.param[i], var[i])) print b, '/', print '$', print b for x,y in b : print x, y z = undoc(x, y) print z a.append(z) except TypeError, c : print 'E', str(self.decerner), self.param, var print 'E2', str(c) raise return a in fact the method was initially reduce to return map(self.decerner, self.param, var) all the commented line produced the same exception raised this method unnormalize an input vector (var) and the trace in None [(-2.0, 2.0), (-2.0, 2.0)] [0.1385039192456847, 0.87787941093093491] 2 2 [0.1385039192456847, 0.87787941093093491] [(-2.0, 2.0), (-2.0, 2.0)] $ [0, 1] $ % [((-2.0, 2.0), 0.1385039192456847)] / % [((-2.0, 2.0), 0.1385039192456847), ((-2.0, 2.0), 0.87787941093093491)] / $ [((-2.0, 2.0), 0.1385039192456847), ((-2.0, 2.0), 0.87787941093093491)] (-2.0, 2.0) 0.138503919246 % 0.277007838491 (-2.0, 2.0) 0.877879410931 % 1.75575882186 in None [(-2.0, 2.0), (-2.0, 2.0)] [0.38111874838950943, 0.74880175070169164] 2 2 [0.38111874838950943, 0.74880175070169164] [(-2.0, 2.0), (-2.0, 2.0)] $ [0, 1] $ % [((-2.0, 2.0), 0.38111874838950943)] / % [((-2.0, 2.0), 0.38111874838950943), ((-2.0, 2.0), 0.74880175070169164)] / E [(-2.0, 2.0), (-2.0, 2.0)] [0.38111874838950943, 0.74880175070169164] E2 bad argument type for built-in operation [...] the first call of the methode succeed all following call failed. I've got different scenario which call this low level methode, many succeed, some failed this way. what's happened ? If someone got an idea ? what can raise this exception ? My program is written partially in python and partially in C. the top level is in python which call a C optimisation routine which use a callback (PyObject_CallMethod) to evaluate the cost in python again. From jello at comics.com Wed Jan 12 14:17:09 2005 From: jello at comics.com (rzed) Date: Wed, 12 Jan 2005 19:17:09 GMT Subject: ConfigParser - add a stop sentinel? References: Message-ID: Larry Bates wrote in news:nZqdnQYU7Z5O_XjcRVn-jA at comcast.com: [responding to the idea of placing a sentinel in an ini file, and modifying ConfigParser to stop receiving input when it is encountered]: > You should probably consider NOT doing what you suggest. You > would need to do some rather extensive work so you can support > the .write method of ConfigParser. With a little ingenuity > I've been able to user ConfigParser to support some very > different and complex syntaxes on different projects. If this > won't work, just have two different (separate) files. > > If you are dead set on combining these two, put your foreign > syntax lines into the file as comments. ConfigParser will > not process them, and you can have some other class extract > only the comments and parse them independently. I'm not sure I understand what you mean about the .write method of ConfigParser. I'm not trying to alter the *behavior* of ConfigParser at all, just giving it an alternative end of input (apart from EOF). And I'm not trying to replicate ConfigParser in my own configuration stuff. If I were, I'd just use ConfigParser. What I am doing is specifying a cluster of parameters on a single line in a compact, comma-separated form. I can easily split each parameter line and use the appropriate values, but it's not something ConfigParser is designed to accommodate, as far as I can tell. I don't want to put them into comments (though I could, I see), because I comment my own lines with hashmarks as well. I suppose I could lead off with double hashmarks and just strip off the first to get the desired effect, but it's an annoyance and it doesn't contribute to understanding what the config file is supposed to do. Still, as a workaround, it is something to consider. I just can't imagine that I'm the first person in history to have stumbled on such a use case, though. If ConfigParser would have a way to just take in raw data line-by-line within some group heading, that would work for this case just as well, and it seems to me that *that* might be useful in some other applications also ... though that's not what I'm talking about in this instance. -- rzed From dbasch at yahoo.com Tue Jan 11 18:16:53 2005 From: dbasch at yahoo.com (Derek Basch) Date: Tue, 11 Jan 2005 15:16:53 -0800 (PST) Subject: CGI, anydbm.open() and linux file permissions Message-ID: <20050111231653.84157.qmail@web20825.mail.yahoo.com> Hello, I have a CGI script which uses anydb.open() to create a DBM. However I get this traceback: /usr/lib/python2.3/bsddb/__init__.py in hashopen(file='/var/www/bp/predictor/tools.dbm', flag='c', mode=438, pgsize=None, ffactor=None, nelem=None, cachesize=None, lorder=None, hflags=0) 190 if ffactor is not None: d.set_h_ffactor(ffactor) 191 if nelem is not None: d.set_h_nelem(nelem) 192 d.open(file, db.DB_HASH, flags, mode) 193 return _DBWithCursor(d) 194 d = , d.open = , file = '/var/www/bp/predictor/tools.dbm', global db = , db.DB_HASH = 2, flags = 65, mode = 438 DBAccessError: (13, 'Permission denied') args = (13, 'Permission denied') The permissions on the CGI script (/usr/lib/cgi-bin/evaluator.py) are: -rwxr-xr-x 1 bpeters bpeters 2446 Jan 11 14:42 evaluator.py and the permissions on the target DBM creation directory (/var/www/bp/predictor/) are: drwxr-xr-x 2 bpeters bpeters 4096 Jan 11 14:45 predictor Can anyone tell me what I need to do to allow the CGI script to create the DBM in the target directory? That is short of changing everything to root. Thanks everyone, Derek Basch __________________________________ Do you Yahoo!? Meet the all-new My Yahoo! - Try it today! http://my.yahoo.com From john.abel at pa.press.net Wed Jan 26 08:55:24 2005 From: john.abel at pa.press.net (John Abel) Date: Wed, 26 Jan 2005 13:55:24 +0000 Subject: FTP Server In-Reply-To: <1106746068.798541.219240@c13g2000cwb.googlegroups.com> References: <1106743852.600769.72820@c13g2000cwb.googlegroups.com> <1106746068.798541.219240@c13g2000cwb.googlegroups.com> Message-ID: <41F7A14C.1080303@pa.press.net> michele.simionato at gmail.com wrote: >>If you're after a simple FTP server, have a look at medusa. >> >> >Uhm ... Medusa does not seem actively maintained nowadays. > > M.S. > > > AFAIK, it's maintained to the extent, that if you find bugs/enhance it and let the medusa-dev list know, it more than likely will get fixed/added. For what it's worth, I have a medusa-based FTP server running on Linux (daemon) and Win32 (service), without any problems at all. John From http Sun Jan 9 09:23:49 2005 From: http (Paul Rubin) Date: 09 Jan 2005 06:23:49 -0800 Subject: Python3: on removing map, reduce, filter References: <34csn1F4a46hqU1@individual.net> Message-ID: <7xekguof4a.fsf@ruckus.brouhaha.com> Andrey Tatarinov writes: > How does GvR suggestions on removing map(), reduce(), filter() > correlate with the following that he wrote himself (afaik): > > http://www.python.org/doc/essays/list2str.html I think that article was written before list comprehensions were added to Python. From tim.peters at gmail.com Mon Jan 10 18:36:09 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 10 Jan 2005 18:36:09 -0500 Subject: Writing huve ge Sets() to disk In-Reply-To: <41E2F38C.30200@ribosome.natur.cuni.cz> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> <41E2E69C.7080104@ribosome.natur.cuni.cz> <1f7befae0501101245679b26f2@mail.gmail.com> <41E2F38C.30200@ribosome.natur.cuni.cz> Message-ID: <1f7befae05011015362e17f610@mail.gmail.com> [Tim Peters] >> As I mentioned before, if you store keys in sorted text files, >> you can do intersection and difference very efficiently just by using >> the Unix `comm` utiltity. [Martin MOKREJ?] > Now I got your point. I understand the comm(1) is written in C, but it still > has to scan file1 once and file2 n-times, where n is a number of lines > in file1, right? Without any index ... I'll consider it, actually will test, > thanks! `comm` is much more efficient than that. Note that the input files have to be sorted. Then, in a single pass over both files (not 2 passes, not 3, not n, just 1), it can compute any subset of these three (do `man comm`): 1. The words common to both files. 2. The words unique to "the first" file. 3. The words unique to "the second" file. It's essentially just doing a merge on two sorted lists, and how it works should be obvious if you give it some thought. It takes time proportional to the sum of the lengths of the input files, and nothing *can* be faster than that. > I was really hoping I'll get an answer how to alter the indexes for dictionaries > in python. Sorry, I don't have a guess for what that might mean. > You convinced me not to even try to construct to theoretical dictionary, > as it will take ages just to create. Even if I'd manage, I couldn't > save it (the theoretical and possibly not even the dict(theoret) - dict(real) > result). Worse, it didn't sound like a good approach even if you could save it. > Still, before I give the whole project, once more: > > I'll parse some text files, isolates separate words and add them to > either Set(), list, dict, flatfile line by line. > > Depending on the above, I'll compare them and look for those unique > to some "language". I need to keep track of frequencies used > in every such language, Frequencies of what? "A language" here can contain some words multiple times each? > so the dict approach would be the best. The number stored as a value vould > be a float ^H^H^H^H^H^H Decimal() type - very small number. Integers are the natural type for counting, and require less memory than floats or decimals. > Once more, I expect to have between E4 or E5 to E8??? words > stored in 20 dictionaries (remember words of sizes in range 1-20? > Every of those 20 dictionaries should be, I believe, indexed just once. > The indexing method should know all entries in a given file are of same > size, i.e. 5 chars, 15 chars, 20 chars etc. I think you're making this more complicated than it needs to be. > I already did implement the logic to walk through those 20 different > dictionaries from language a and from language b and find uout those > unique to a or common to both of them. Why I went to ask on this list > was to make sure I took right approach. Sets seemed to be better solution > for the simple comparison (common, unique). To keep track of those > very small frequencies, I anyway have to have dictionaries. I say > that again, how can I improve speed of dictionary indexing? > It doesn't matter here if I have 10E4 keys in dictionary or > 10E8 keys in a dictionary. What reason do you have for believing that the speed of dictionary indexing is worth any bother at all to speed up? Dict lookup is generally considered to be extremely fast already. If you're just *guessing* that indexing is the bottleneck, you're probably guessing wrong -- run a profiler to find out where the real bottleneck is. From mahs at telcopartners.com Tue Jan 25 15:51:25 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 25 Jan 2005 12:51:25 -0800 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: Message-ID: Steven Bethard wrote: > Michael Spencer wrote: > >> Safe eval recipe posted to cookbook: >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 > > > This recipe only evaluates constant expressions: > > "Description: > Evaluate constant expressions, including list, dict and tuple using the > abstract syntax tree created by compiler.parse" > > It means you can't eval arbitrary Python code -- it's basically just a > data parser. Handy in some situations, but not the equivalent of a > limited Python virtual machine. Indeed. But it's easy to extend this to arbitrary constructs. You just need to decide what code to emit for the other 50 or so ast node types. Many of those are boiler-plate binops. > >> Likewise, function calls are easily intercepted > > I'm not sure I follow this... How do you intend to intercept all > function calls? Sorry, should have been more precise. In the AST, Function calls have their own node type, so it is easy to 'intercept' them and execute them conditionally > [snip] > > It sounds like you're suggesting overriding the global attribute access > mechanism. Is that right? So that every time Python encountered an > attribute access, you would verify that the attribute being accessed is > not on the 'dangerous' list? Just in the context of the AST-walker, yes I don't know how to do that without > basically rewriting some of Python's C code, though certainly I'm no > expert in the area... Not messing with the CPython interpreter > > Also, I'm not sure identity is sufficient: > > py> import sys > py> import new > py> new.module('newsys') > py> newsys = new.module('newsys') > py> newsys.__dict__.update(sys.__dict__) > py> newsys is sys > False > py> newsys == sys > False Right - the crux of the problem is how to identify dangerous objects. My point is that if such as test is possible, then safe exec is very easily implemented within current Python. If it is not, then it is essentially impossible. Let's assume that it is indeed not possible to know in general whether an object is safe, either by inspecting its attributes, or by matching its identity against a black list. It might still be possible to have a reliable test within a problem-specific domain i.e., white-listing. This, I think, is what you meant when you said: > I wish there was a way to, say, exec something with no builtins and with import disabled, so you would have to specify all the available bindings, e.g.: > > exec user_code in dict(ClassA=ClassA, ClassB=ClassB) I believe that if you can come up with a white-list, then the rest of the problem is easy. Michael From itsme at yahoo.com Tue Jan 4 10:12:36 2005 From: itsme at yahoo.com (It's me) Date: Tue, 04 Jan 2005 15:12:36 GMT Subject: Hlelp clean up clumpsy code References: Message-ID: Thanks, Steve and Nick. Yes, that's what I need to do. I didn't know it's call "flattening" a list structure but that's precisely what I needed to do. Steve, I am using 2.3 and so I will go with Nick's version. Thanks to both for helping. "Nick Coghlan" wrote in message news:mailman.121.1104833878.22381.python-list at python.org... > It's me wrote: > > Another newbie question. > > > > There must be a cleaner way to do this in Python: > > > > #### section of C looking Python code #### > > a = [[1,5,2], 8, 4] > > a_list = {} > > i = 0 > > for x in a: > > if isinstance(x, (int, long)): > > x = [x,] > > for w in [y for y in x]: > > i = i + 1 > > a_list[w] = i > > print a_list > > ##### > > > > The code prints what I want but it looks so "C-like". How can I make it > > more Python like? > > Firstly, calling your dictionary "a_list" is evil. . . > > Secondly, explaining what you want the code to do in English is handy when > asking for help cleaning up code (since we then know which features are > deliberate, and which are accidental implementation artificacts). > > If I'm reading the code correctly, you want to flatten a data structure which > may contain either substructures or actual elements. > > A custom generator will do nicely: > > Py> def flatten(seq): > ... for x in seq: > ... if hasattr(x, "__iter__"): > ... for y in flatten(x): > ... yield y > ... else: > ... yield x > ... > Py> data = [[1,5,2],8,4] > Py> val_to_pos = {} > Py> for i, x in enumerate(flatten(data)): > ... val_to_pos[x] = i + 1 > ... > Py> print val_to_pos > {8: 4, 1: 1, 2: 3, 4: 5, 5: 2} > > Not any shorter, but this version works correctly for any leaf elements which > don't supply __iter__ (e.g. strings), and internal elements which do (e.g. > tuples) and the depth is limited only by the maximum level of recursion. Don't > try to flatten a circular structure, though :) > > You may not even need to write the generator, since if you have Tkinter, that > already supplies a near-equivalent function: > > Py> from Tkinter import _flatten as flatten > Py> data = [[1,5,2],8,4] > Py> val_to_pos = {} > Py> for i, x in enumerate(flatten(data)): > ... val_to_pos[x] = i + 1 > ... > Py> print val_to_pos > {8: 4, 1: 1, 2: 3, 4: 5, 5: 2} > > It even works with strings as leaf elements: > > Py> data = [["abc","def",2],8,"xyz"] > Py> flatten(data) > ('abc', 'def', 2, 8, 'xyz') > > Cheers, > Nick. > > -- > Nick Coghlan | ncoghlan at email.com | Brisbane, Australia > --------------------------------------------------------------- > http://boredomandlaziness.skystorm.net From http Sat Jan 8 23:33:30 2005 From: http (Paul Rubin) Date: 08 Jan 2005 20:33:30 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> Message-ID: <7xr7kv8bmt.fsf@ruckus.brouhaha.com> "Roose" writes: > My point was that you can't do a lot of hardware interface programming in > pure Python -- there would be so much non-trivial code in C that it would be > hard to call it a Python OS. Why do you say that? Is the same thing not true of C, where you need some assembly code at the lowest levels? Because Linux has some assembly code, would you say that it's not written in C? > So this basically proves my point -- that you need different hardware > altogether in order to make an OS in a high level language like Lisp or > Python. It doesn't prove anything of the sort. The Lisp hardware was needed for performance reasons, back in the day. From yunmao at gmail.com Fri Jan 21 00:10:02 2005 From: yunmao at gmail.com (Yun Mao) Date: Fri, 21 Jan 2005 00:10:02 -0500 Subject: problems with duplicating and slicing an array In-Reply-To: References: <7cffadfa05012017337858d171@mail.gmail.com> Message-ID: <7cffadfa0501202110328c61b5@mail.gmail.com> Hi all, Thanks for the help. numarray doesn't provide what I look for either. e.g. a = array( [[1,2,3],[4,5,6]] ) I sometimes what this: a[ [1,0], :], or even a[ [1,0], [0,1] ] , which should give me [[4, 5], [1,2]] Because I don't really care about arrays with dimension >2, I did a little hacking with Numeric.Matrix.Matrix. It is more compatible with Matlab style slicing (except that the index starts from 0, not 1). This class automatically does copy, which is what I needed. Here is the code if somebody is interested (The wordy getAttr part is due to a "feature" in Numeric.Matrix based on the assumption that probably nobody is going to inherent it again :) ): #==========begin code========= from Numeric import * from Matrix import Matrix, UserArray import types def _isSeq(t): if isinstance(t, types.ListType): return True if (isinstance(t, ArrayType) or isinstance(t, UserArray)): return len(t.shape)==1 or \ (len(t.shape)==2 and t.shape[0]==1) return False class Mat(Matrix): def __getitem__(self, index): """Matlab style slicing: e.g. a[ [3,2], [2,1] ], a[1] """ if isinstance(index, types.TupleType) and len(index)==1 \ or _isSeq(index): if self.array.shape[0]!=1: return self._rc(self.array.flat).__getitem__(index) if not _isSeq(index): return Matrix.__getitem__(self, index) return self._rc(take(self, array(index).flat, 1)) elif isinstance(index, types.TupleType): assert len(index)==2 if not (_isSeq(index[0]) or _isSeq(index[1])): return Matrix.__getitem__(self, index) r = self.array tmp = slice(None, None, None) if _isSeq(index[0]): r = take(r, array(index[0]).flat,0) else: r = self._rc(r).__getitem__(self, (index[0], tmp)) if _isSeq(index[1]): r = take(r, array(index[1]).flat,1) else: r = self._rc(r).__getitem__( (tmp,index[1])) return self._rc(r) elif isinstance(index, types.IntType): return self.array.flat[index] return Matrix.__getitem__(self, index) def __getattr__(self, attr): if attr == 'A': return squeeze(self.array) elif attr == 'T': return self._rc(Numeric.transpose(self.array)) elif attr == 'H': if len(self.array.shape) == 1: self.array.shape = (1,self.array.shape[0]) return self._rc(Numeric.conjugate(Numeric.transpose(self.array))) elif attr == 'I': return self._rc(LinearAlgebra.inverse(self.array)) elif attr == 'real': return self._rc(self.array.real) elif attr == 'imag': return self._rc(self.array.imag) elif attr == 'flat': return self._rc(self.array.flat) elif attr == 'length': return max(self.array.shape) else: raise AttributeError, attr + " not found." #========end code======== > numarray supports matlab style indexing if you pass the ind as an > array or list of indices (but not a tuple, I found to my surprise). > As pointed out already, for Numeric you need to use the take function > > >>> from numarray import array > >>> x = array([1,2,3,4,5,6,7,8,9]) > >>> ind = [3,5,7] > >>> inda = array(ind) > >>> indt = tuple(ind) > >>> x[ind] > array([4, 6, 8]) > >>> x[inda] > array([4, 6, 8]) > >>> x[indt] > Traceback (most recent call last): > File "", line 1, in ? > IndexError: too many indices. > > I'm sure the tuple "surprise" is a documented feature. > > JDH > From sam.wun at authtec.com Sun Jan 23 08:06:51 2005 From: sam.wun at authtec.com (sam) Date: Sun, 23 Jan 2005 21:06:51 +0800 Subject: compile python to binary Message-ID: Hi, I have seen some software written in python and delivered as binary form. How does these binary code get generated by python compiler? Thanks Sam. From flamesrock at gmail.com Tue Jan 4 01:54:22 2005 From: flamesrock at gmail.com (flamesrock) Date: 3 Jan 2005 22:54:22 -0800 Subject: FS: PC Doctor In-Reply-To: <1104817852.587703.310920@c13g2000cwb.googlegroups.com> References: <1104817852.587703.310920@c13g2000cwb.googlegroups.com> Message-ID: <1104821662.790475.237460@c13g2000cwb.googlegroups.com> *blinks* stop spamming asshole From bill.mill at gmail.com Fri Jan 28 11:17:59 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 28 Jan 2005 11:17:59 -0500 Subject: Dynamic class methods misunderstanding In-Reply-To: <35v5jdF4rk3m7U1@individual.net> References: <35v5jdF4rk3m7U1@individual.net> Message-ID: <797fe3d405012808171954a2b4@mail.gmail.com> Diez, On Fri, 28 Jan 2005 16:57:37 +0100, Diez B. Roggisch wrote: > > > > Why doesn't m get the implicit self parameter in the self.method() > > call? How would I make it a proper member of the class, so that a > > self.method() call would work with the above "m" function? > > Use new.instancemethod: > > import new > > class Test: > def __init__(self, method): > self.m = new.instancemethod(method, self, Test) > Beautiful! thank you very much. Looking into the "new" module in python 2.4, that's equivalent to: self.m = type(self.__init__)(method, self, Test) I didn't know that you could call types to create another type. Peace Bill Mill bill.mill at gmail.com From andre.roberge at gmail.com Mon Jan 24 08:52:14 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 24 Jan 2005 05:52:14 -0800 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> Message-ID: <1106574734.302094.93730@f14g2000cwb.googlegroups.com> Ryan Paul wrote: > On Mon, 24 Jan 2005 13:19:45 +0000, Ryan Paul wrote: > > > > > A working solution: > > > > class A: > > pass > > > > a = A() > > b = A() > > c = A() > > > > [x for x,y in locals().items() if > > hasattr(y,"__class__") and y.__class__ == A] > > > > Just wanted to clarify, because I know that the intellectually deficient > amongst you will say that isinstance is better than using __class__... > > In this case isinstance isnt desirable because it will catch > instances of any objects that inherit A, not just instances of A. Observe: > > class A: pass > class B(A): pass > > a = A() > b = A() > c = A() > d = B() > > >>> [x for x,y in locals().items() if isinstance(y,A)] > ['a', 'c', 'b', 'd'] > > >>> [x for x,y in locals().items() if > ... hasattr(y,"__class__") and y.__class__ == A] > ['a', 'c', 'b'] Actually, it this case, isinstance *is* desirable (or rather *would have been*), exactly for the reason that you point out. After teaching about objects, one of the next subject would be that of inheritance. E.G. class BetterRobot(Robot): ... # create a robot that can turn right directly... However, I have been convinced that it would be much truer to Python to give the robot fake names (robot1, robot2, ...), and then have students name their own robots through declarations like: cleese = Robot(name="Cleese") or cleese = Robot() cleese.name = "Cleese" ===== Andr? > > -- SegPhault From fredrik at pythonware.com Mon Jan 24 06:33:46 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 12:33:46 +0100 Subject: delay and force in Python References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com><41EE6658.8000409@iinet.net.au> <41F4DA78.90703@iinet.net.au> Message-ID: Nick Coghlan wrote: >> How's this: >> >> Py> from itertools import islice >> Py> print islice((x for x in xrange(1, 996) if x % 2 == 0), 1, 2).next() >> 4 > > Wouldn't it be nice if this could be spelt: > > print (x for x in xrange(1, 996) if x % 2 == 0)[2] as I've always said, the sooner we can all use the itertools goodies without even noticing, the better. From secun at yahoo.com Thu Jan 27 16:18:56 2005 From: secun at yahoo.com (Chris) Date: Thu, 27 Jan 2005 21:18:56 GMT Subject: Help with web dashboard Message-ID: I've written some python scripts to handle different tasks on my Windows network. I would like for them to be accessible via a single web page (kind of like a dashboard) but have the scripts run on the web server (also a Windows box). Can anyone recommend a way (web server / language / method) of doing this? Security is important since this page will be accessible inside the company, but only people with the appropriate user name / password should be able to run the scripts. From spam at nospam.org Wed Jan 26 22:28:39 2005 From: spam at nospam.org (Erik Johnson) Date: Wed, 26 Jan 2005 20:28:39 -0700 Subject: building Python: up arrow broken on SuSE Linux 8.2 References: <41f6c3f7$1@nntp.zianet.com> Message-ID: <41f85dd8@nntp.zianet.com> > Do you have the GNU readline library installed and within Python's > reach (lib in LD_LIBRARY_PATH or in /etc/ld.so.conf with subsequent > call of ldconfig)? I think you are on the right path. I later found an Apple article online that answered essentially my question saying libreadline wasn't included on the Apple Python distribution the OP was asking about. I now notice this in the output of configure: checking for rl_pre_input_hook in -lreadline... no checking for rl_completion_matches in -lreadline... no My system has /lib/libreadline.so.4.3. I guess it does not define these newer functions and so that is why the readline module was not configured in Setup to start with? That is the presumption I am working on. So I downloaded & built libreadline version 5.0. I have libreadline.a and shlib/libreadline.so.5.0 files. Having done Python & other scripting languages for a while, I have sort of forgotten all the ugly details about C compilation. I'm trying to figure out how to get Python2.3.4. statically linked with the .a file and not muck with the system shared libraries and let other applications fend for themselves. Any advice on how to statically link in this library so the Python build is happy? Thanks, -ej ----- Original Message ----- From: "Peter Maas" Newsgroups: comp.lang.python Sent: Wednesday, January 26, 2005 3:22 AM Subject: Re: building Python: up arrow broken on SuSE Linux 8.2 > Erik Johnson schrieb: > > I am trying to upgrade my Python installation. After downloading > > sources and building Python 2.3.4, I am unable to use the command > > history editing feature in the interactive interpreter (where the > > up-arrow would previously give you the last command line to edit, > > it now just prints "^[[A".) > > > -- > ------------------------------------------------------------------- > Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 > E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') > ------------------------------------------------------------------- From deetsNOSPAM at web.de Fri Jan 28 09:07:23 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 28 Jan 2005 15:07:23 +0100 Subject: a sequence question References: Message-ID: <35uv4oF4rrsjcU1@individual.net> l = [1,2,3,4] for a, b in zip(l[::2], l[1::2]): print a,b -- Regards, Diez B. Roggisch From nnorwitz at gmail.com Fri Jan 21 09:41:09 2005 From: nnorwitz at gmail.com (Neal Norwitz) Date: 21 Jan 2005 06:41:09 -0800 Subject: tkinter socket client ? In-Reply-To: <1106311130.446259.30710@f14g2000cwb.googlegroups.com> References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> Message-ID: <1106318469.311179.126140@c13g2000cwb.googlegroups.com> You are probably looking for Tkinter.createfilehandler(). Here are some snippets to get you started: tk_reactor = Tkinter._tkinter self.sd = socket(AF_INET, SOCK_STREAM) self.sd.connect((HOST, PORT)) tk_reactor.createfilehandler(self.sd, Tkinter.READABLE, self.handle_input) def handle_input(self, sd, mask): data = self.sd.recv(SIZE) (Sorry if the formatting is busted, blame google groups.) HTH, Neal From marc.huffnagle at gmail.com Thu Jan 27 17:42:27 2005 From: marc.huffnagle at gmail.com (enigma) Date: 27 Jan 2005 14:42:27 -0800 Subject: String Fomat Conversion References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Message-ID: <1106865747.829698.119740@c13g2000cwb.googlegroups.com> Do you really need to use the iter function here? As far as I can tell, a file object is already an iterator. The file object documentation says that, "[a] file object is its own iterator, for example iter(f) returns f (unless f is closed)." It doesn't look like it makes a difference one way or the other, I'm just curious. From http Thu Jan 20 02:01:56 2005 From: http (Paul Rubin) Date: 19 Jan 2005 23:01:56 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> <7xacr4ewjk.fsf@ruckus.brouhaha.com> <41ef4a7a.1323588509@news.oz.net> Message-ID: <7xwtu8vb17.fsf@ruckus.brouhaha.com> bokr at oz.net (Bengt Richter) writes: > Isn't the SSL dependent on OS or at least shared lib support? Firefox has its own implementation. IE uses wininet which is built Windows. I'm not aware of any no-crypto version of Windows but even if there is one, the US version is running, like, everywhere. > Wasn't there a default 40-bit version that was ok (weak), but you had > to declare yourself US resident to download 128-bit support? That was years ago. The regulations changed since then, so they all have 128 bits now. > I dimly recall encountering this sort of thing installing Netscape > a long time ago, I think. Is 128 just standard now? And now that 128 > is wobbly(?), will the same thing be replayed with the ante upped? 128 isn't wobbly. It will be a long time before any machine can do 2**128 operations to break a message. From b at b.b Thu Jan 6 20:50:52 2005 From: b at b.b (Roose) Date: Fri, 07 Jan 2005 01:50:52 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <0WlDd.8830$5R.1182@newssvr21.news.prodigy.com> What exactly do you mean by an operating system? If you don't want to program in C/C++ then you're going to have a hard time. I don't want to be too discouraging, but with that attitude I doubt you would get very far. It sounds like you want to make more of an OS shell -- no? You can implement a shell on top of any OS and probably do it in a language like Python. But if it is going to be a complete OS in pure Python, uh, it won't be! You'll have to do a lot of stuff in C, at the least interface with the hardware. "David Brown" wrote in message news:10trb0mgiflcj4f at corp.supernews.com... > Hello. I recently came across a free operating system called Unununium (or > something like that) and it was developed in Python and Assembly. > > Now, I have been looking for a way to make an operating system for a long > long time and the only possibilities I could find were C++ and assembly. I > don't mind assembly so much if I don't have to use it very often. But C++ is > so complicated and errors are pretty much impossible to find in the code for > me. > > So, I was wondering if it would be possible to find a bootloader that loads > a python file at startup or something... > > Is there an example somewhere of a Python OS? > > Thanks! > > From mail at tuxipuxi.org Fri Jan 14 06:50:59 2005 From: mail at tuxipuxi.org (Michael Goettsche) Date: Fri, 14 Jan 2005 12:50:59 +0100 Subject: Using Sqlite with Python under Windows Message-ID: <200501141250.59702.mail@tuxipuxi.org> Hello guys, I succeeded in convincing my CS teacher to use Python and Sqlite instead of Microsoft Access to get started with databases. We are working on a windows terminal server to which I have no admin access, so I'd like to ask you which module is best suited to use Sqlite with Python under windows. The best would be a module which is easy to install without further dependencies. Thanks in advance, Michael From the_schlops at yahoo.de Sat Jan 15 12:51:29 2005 From: the_schlops at yahoo.de (Wolfram Kraus) Date: Sat, 15 Jan 2005 18:51:29 +0100 Subject: Associate objects with Tix.Tree Message-ID: Heyho! I want to associate objects with the nodes of a Tix.Tree. Is this possible, because the following example won't work: --8<-- Cut here ------------------------- import Tix class C: pass root = Tix.Tk() top = Tix.Frame(root, relief=Tix.RAISED, bd=1) tixtree = Tix.Tree(top) tixtree.pack(expand=1, fill=Tix.BOTH, padx=10, pady=10, side=Tix.LEFT) c=C() print c tixtree.hlist.add(c, itemtype=Tix.IMAGETEXT, text='foo', image=tixtree.tk.call('tix', 'getimage', 'folder')) tixtree.setmode(c, 'open') root.mainloop() --8<-- Cut here ------------------------- Can this somehow be done? TIA, Wolfram From ebolonev at mail.ru Thu Jan 13 00:55:10 2005 From: ebolonev at mail.ru (Egor Bolonev) Date: Thu, 13 Jan 2005 15:55:10 +1000 Subject: newbie q Message-ID: <34mgq0F4dq4buU1@individual.net> how to get rid of 'for' operator in the code? import os, os.path def _test(): src = 'C:\\Documents and Settings\\????\\My Documents\\My Music\\' for i in [x for x in os.listdir(src) if os.path.isfile(os.path.join(src, x)) and len(x.split('.')) > 1 and x.split('.')[-1].lower() == 'm3u']: os.remove(os.path.join(src, i)) if __name__ == '__main__': _test() From craig at postnewspapers.com.au Sat Jan 22 06:53:27 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 22 Jan 2005 19:53:27 +0800 Subject: need help on need help on generator... In-Reply-To: <1gqshv6.linw9y1anlov0N%aleaxit@yahoo.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> <1106387175.4103.16.camel@albert.localnet> <1gqshv6.linw9y1anlov0N%aleaxit@yahoo.com> Message-ID: <1106394807.4103.54.camel@albert.localnet> On Sat, 2005-01-22 at 12:20 +0100, Alex Martelli wrote: > Craig Ringer wrote: > > > .>>> data = ''.join(x for x in infile) > > Maybe ''.join(infile) is a better way to express this functionality? > Avoids 2.4 dependency and should be faster as well as more concise. Thanks - for some reason I hadn't clicked to that. Obvious in hindsight, but I just completely missed it. > > Might it be worth providing a way to have file objects seek back to the > > current position of the iterator when read() etc are called? If not, I > > It's certainly worth doing a patch and see what the python-dev crowd > thinks of it, I think; it might make it into 2.5. I'll certainly look into doing so. I'm not dumb enough to say "Sure, I'll do that" before looking into the code involved and thinking more about what issues could pop up. Still, it's been added to my increasingly frightening TODO list. > > favour the suggestion in the referenced post - file should probably fail > > noisily, or at least emit a warning. > > Under what conditions, exactly, would you want such an exception? When read() or other methods suffering from the same issue are called after next() without an intervening seek(). It'd mean another state flag for the file to keep track of - but I doubt it'd make any detectable difference in performance given that there's disk I/O involved. I'd be happier to change the behaviour so that a warning isn't necessary, though, and I suspect it can be done without introducing backward compatibility issues. Well, so long as nobody is relying on the undefined file position after using an iterator - and I'm not dumb enough to say nobody would ever do that. I've really got myself into hot water now though - I'm going to have to read over the `file' source code before impulsively saying anything REALLY stupid. -- Craig Ringer From tjreedy at udel.edu Thu Jan 13 15:18:25 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Jan 2005 15:18:25 -0500 Subject: how to stop google from messing Python code References: <1105620098.878376.110250@z14g2000cwz.googlegroups.com> Message-ID: "Xah Lee" wrote in message news:1105620098.878376.110250 at z14g2000cwz.googlegroups.com... > i'm using groups-beta.google.com to post python code. > > Is there a way to stop google from messing with my format? it seems to > have eaten the spaces in my python code. > thanks. 1. don't post, or 2. don't use google to post -- there is no real excuse for doing so. Just about every computer comes with a newsreader. Get a free account with news.gmane.org and read/post gmane.comp.python. Terry J. Reedy From garabik at kassiopeia.juls.savba.sk Tue Jan 11 03:38:32 2005 From: garabik at kassiopeia.juls.savba.sk (Radovan Garabik) Date: 11 Jan 2005 08:38:32 GMT Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> Message-ID: <34hhk8F4bh2erU1@individual.net> "Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle." wrote: > Hi ! > >>>> and plain Latin letters > > But not all letters (no : ? ? ? ? ? ? ? etc.) > ... and some more letters that are not latin (j,w,u,z) ok, I'd better shut up :-) -- ----------------------------------------------------------- | 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 macrocosm at fastmail.fm Sun Jan 9 09:57:47 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Sun, 09 Jan 2005 09:57:47 -0500 Subject: Python Operating System??? In-Reply-To: References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> Message-ID: <41E1466B.8090508@fastmail.fm> Roose wrote: > .... > >It's a difference of degree, but an important difference. I haven't looked >at Linux or Windows NT source, but my guess is the assembly used is just >small functions for accessing special CPU instructions for atomicity, >context switching, and the like. > >I KNOW they don't have huge amounts of assembly simply because they run on >different architectures. > > >But are you really going to write a virtual memory system in Python? Are >you going to write a file system, and a task scheduler in Python? Are you >going to have people write device drivers in Python? > Cleese!! > I'm not saying it >can't be done, but it would be a poor engineering decision, and the >rationale thus far seems to be "Python is cool, I like OSes, let's write a >whole OS in Python". If that's not the case then let me know what your >rationale is. > > > From mt at 3planes.com Mon Jan 31 22:41:27 2005 From: mt at 3planes.com (Michael Tobis) Date: 31 Jan 2005 19:41:27 -0800 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1107188359.375703.110590@f14g2000cwb.googlegroups.com> <1gr9lyc.1rrm543162uefN%aleaxit@yahoo.com> Message-ID: <1107229287.315380.222790@c13g2000cwb.googlegroups.com> Alex Martelli wrote: > Michael Tobis wrote: > he can perfectly > well correct his misexpression if he cares to -- not my job to try to > read his mind and perform exegesis on his words. Well, I hate to try to tell you your job, but it doesn't seem to be to be all that great of a marketing strategy to actively chase people away... Hey, he might have been a Nutshell customer. > I think it would have been true, but weak and insufficient. Not only > experienced Python users have that opinion: lack of declarations didn't > faze me even I was a total newbie It did me, and it did many others. Perhaps you are unrepresentative. It's one thing to say "no can do, sorry", it's another to say "you don't need this anyway and if you think you do you aren't worthy". In fact, it was your book I spent the most time thumbing through looking for the "use strict" equivalent that I was absolutely certain must exist. Hell, even Fortran eventually gave in to "IMPLICIT NONE". It's practically the only thing I've ever expected to find in Python that hasn't vastly exceeded my expectations, aand I'm sure Alexander is not the only person to be put off by it. 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", and an index listing under "declarations" pointing to a detailed exegesis of their nonexistence. It would have saved me some time. It's true that in some sense an assignment is all the declaration you need. I think Carl Banks's point (what we think of as assignment as a carryover from other languages is really rebinding, and in many cases can be avoided) is also helpful. But that doesn't make the "epselon" bug go away, and wanting to have a way to catch it quickly isn't, to my mind, obviously a criminal act. Also, based on what DogWalker demonstrates, it's really not that alien to Python and should be feasible. > > Also, the assertion that "Python has no declarations whatsoever" is no > > longer obviously true. In the 2.4 decorator syntax, a decorator line is > > not executable, but rather a modifier to a subsequent symbol binding. I > > call it a declaration. > > You may call it a strawberry, if you wish, but that doesn't mean it will > taste good with fresh cream. It's nothing more and nothing less than an > arguably weird syntax for a perfectly executable statement: This may well be true in implementation, but cognitively it is a declaration that modifies the reference and not the referent. I see that it is a big deal to ask for more of these, but I don't see why. > > Let me add that I remain unconvinced that a language cannot combine the > > best features of Python with very high performance, which is ultimately > > I'm also unconvinced. Fortunately, so is the EU, so they have approved > very substantial financing for the pypy project, which aims in good part > exactly at probing this issue. I hope this works out, but it's hard for me to see how pypy will avoid lots of hashing through dictionaries. I'm willing to help it by declaring an immutable reference. Here, don't look this up; it always points to that. I'm guessing that this will also be considered a bad idea, and maybe someday I'll understand why. I'm looking for insight, not controversy. > If any single individual can be called > the ideator of pypy, I think it's Armin Rigo, well-known for his > excellent psyco specializing-compiler for Python: I'm hoping I can make the meeting. Maybe proximity to the core group will help me approach the sort of enlightenment I seek. Just being in the vicinity of Ian Bicking's aura on occasion has been most inspiring. > Almost nobody really liked the splat-syntax for decorators, except of > course Guido, who's the only one who really counts (the BDFL). But that > was strictly a syntax-sugar issue Um, sugar isn't exactly what I'd call it. I think it matters a lot though. Python's being easy on the eyes is not a trivial advantage for some people, myself incuded. > If "declarative statement" means anything, I guess it means "having to > tell stuff to the compiler to be taken into account during compilation > but irrelevant at runtime". Python does have one such wart, the > 'global' statement, and it's just as ugly as one might imagine, but > fortunately quite marginal, so one can almost forget it. I am trying to talk about having expressive power in constraining references as well as the referents. Python studiously avoids this, but decorators change that. I am not deep enough into the mojo as yet to have more than a glimmer of an idea about the distinction you are making. It's not the one I'm trying to make. decorators may not be implemented as declarations, but they cognitively act as declarations, and that's what I care about here. > I have nothing against a declarative style _per se_ -- it just doesn't > fit Python's "everything happens at runtime" overall worldview, and that > simple and powerful worldview is a good part of what makes Python tick > SO well. I'm glad you have said something something I absolutely agree with. I'm alarmed at the suggestions here that class and def blocks are declarative. The fact that they're executable is really a core part of the beauty of Python. However, I don't see how an 'import strict' would necessarily violate this, nor an "import immutableref", which is something I would find useful in trying to wrestle with NumArray, and which a high-performance Python could (I think) use to advantage. Now I may be wrong; in fact I'd bet against me and in favor of you and Frederik if I had to bet. It's just that I don't see why I'm wrong. -- mt From steve at holdenweb.com Sun Jan 9 20:09:58 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 20:09:58 -0500 Subject: path to python file given module In-Reply-To: <1105317971.205487.82770@c13g2000cwb.googlegroups.com> References: <1105315568.887724.260370@c13g2000cwb.googlegroups.com> <1105315923.520581.280580@c13g2000cwb.googlegroups.com> <1105317971.205487.82770@c13g2000cwb.googlegroups.com> Message-ID: Gene wrote: > that method doesn't seem to work as well on UNIX: > > wla apocalypse[94] ~/filegen > ls > filegen.py OLDwla_csv2objects.py wlaclasses.py > filegen.pyc templates/ wlaclasses.pyc > gen_all_from_csv.py test.py* > wla apocalypse[95] ~/filegen > python > .... Use the module's __file__ attribute: >>> import Image >>> Image.__file__ '/usr/lib/python2.4/site-packages/PIL/Image.pyc' >>> While this doesn't give you the source, it goves you enough to make a fair guess about where the source is likely to be, and a littel further manipulation should be able to confirm that. 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 aleaxit at yahoo.com Thu Jan 27 10:19:57 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Jan 2005 16:19:57 +0100 Subject: exclude binary files from os.walk References: <41f8167b$0$8648$a1866201@visi.com> Message-ID: <1gr228k.xxl2uu1om1vprN%aleaxit@yahoo.com> Craig Ringer wrote: > That's not really safe when dealing with utf-8 files though, and IIRC > with UCS2 or UCS4 as well. The Unicode BOM its self might (I'm not sure) > qualify as ASCII. Nope, both bytes in the BOM have the high-order bit set -- they're 0xFF and 0xFE -- so they definitely don't qualify as ASCII. Alex From jeff at ccvcorp.com Mon Jan 24 19:13:57 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 24 Jan 2005 16:13:57 -0800 Subject: Tuple slices In-Reply-To: <35lckuF4kbtbfU1@individual.net> References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> Message-ID: <10vb3enf8qvld4@corp.supernews.com> [My newsreader crapped out on sending this; apologies if it appears twice.] George Sakkis wrote: > "Terry Reedy" wrote in message > news:mailman.1226.1106605134.22381.python-list at python.org... > >>Aside from the problem of not being able to delete the underlying object, >>the view object for a tuple would have to be a new type of object with a >>new set of methods. > > It *could*, but it doesn't have to. One can represent a view as essentially an object with a pointer > to a memory buffer and a (start,stop,step) triple. Then a "real tuple" is just a "view" with the > triple being (0, len(sequence), 1). Except that that's not how Python tuples *are* constructed, and it'd be a pretty big deal to redo the architecture of all tuples to support this relatively special case. Even if this re-architecting were done, you're still constructing a new object -- the difference is that you're creating this (start,stop,step) triple instead of duplicating a set of PyObject* pointers, and then doing math based on those values instead of straightforward pointer access. I'm not at all convinced that this really saves you a significant amount for tuple slices (really, you're still constructing a new tuple anyhow, aren't you?), and it's going to cost a bit in both execution time and complexity in the common case (accessing tuples without slicing). If there's a big cost in object construction, it's probably going to be the memory allocation, and for a reasonable tuple the size of the memory required is not going to significantly affect the allocation time. Jeff Shannon Technician/Programmer Credit International From peter at somewhere.com Thu Jan 6 15:48:46 2005 From: peter at somewhere.com (Peter Maas) Date: Thu, 06 Jan 2005 21:48:46 +0100 Subject: Embedding a restricted python interpreter In-Reply-To: References: Message-ID: <345mkrF46jc4cU1@individual.net> Jp Calderone schrieb: >>But mod_python is an apache module and runs in the same apache process >>with other users' scripts. > > > I am uncertain as to how this differs from mod_php (the alternative > discussed in the OP's story). I've been away from PHP for a while, so > perhaps mod_php has gained some features of which I am unaware? I think PHP has a safe mode which solves the probem of isolating scripts of different users on application level. This is not optimal but better than nothing. Best solution would probably be to create a thread for each request that can operate only with the id of an authenticated user. But this seems to be a problem with Apache or with Linux? -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From francis.girard at free.fr Thu Jan 27 15:06:22 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 27 Jan 2005 21:06:22 +0100 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <200501272106.22291.francis.girard@free.fr> Le jeudi 27 Janvier 2005 20:16, Steven Bethard a ?crit?: > flamesrock wrote: > > The statement (1 > None) is false (or any other value above 0). Why is > > this? > > What code are you executing? I don't get this behavior at all: > > py> 100 > None > True > py> 1 > None > True > py> 0 > None > True > py> -1 > None > True > py> -100 > None > True > Wow ! What is it that are compared ? I think it's the references (i.e. the adresses) that are compared. The "None" reference may map to the physical 0x0 adress whereas 100 is internally interpreted as an object for which the reference (i.e. address) exists and therefore greater than 0x0. Am I interpreting correctly ? > > (The reason I ask is sortof unrelated. I wanted to use None as a > > variable for which any integer, including negative ones have a greater > > value so that I wouldn't need to implement any tests or initializations > > for a loop that finds the maximum of a polynomial between certain x > > values. Anything is greater than nothing, no?) > > Yup, that's the behavior I get with None. > > Steve From marklists at mceahern.com Sun Jan 2 18:19:42 2005 From: marklists at mceahern.com (Mark McEahern) Date: Sun, 02 Jan 2005 17:19:42 -0600 Subject: ? about file() and open() In-Reply-To: <1104706607.022890.314500@c13g2000cwb.googlegroups.com> References: <1104706607.022890.314500@c13g2000cwb.googlegroups.com> Message-ID: <41D8818E.3040503@mceahern.com> Sean wrote: >Was wondering if there was any difference between these two functions. > > None, as shown here: D:\Python23>python 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. >>> file == open True >>> >I have read some text that said file() wasn't introduced until 2.2 and >that it was synonymous with open(). Does this mean that I should be >using file() where I used open() before? > > Google is your friend: http://www.google.com/search?q=file+vs.+open+python http://mail.python.org/pipermail/python-dev/2004-July/045931.html // m From esj at harvee.org Thu Jan 13 23:27:49 2005 From: esj at harvee.org (Eric S. Johansson) Date: Thu, 13 Jan 2005 23:27:49 -0500 Subject: a ConfigParser wtf moment In-Reply-To: <1105675916.355620.324340@f14g2000cwb.googlegroups.com> References: <1105675916.355620.324340@f14g2000cwb.googlegroups.com> Message-ID: <41E74A45.5030605@harvee.org> grahamd at dscpl.com.au wrote: > To avoid this, you need to write something like: > > . list = [] > . for key in configuration.options("core"): > . list.append((key,configuration.get("core",substitution)) > . print list > > This cause me problems for a different reason, ie., that user vars keys > appear in what items() returns. I avoid using items() for this reason. it turns out, I originally discovered this problem through the get with substitutions. It's too late to muck with it now but if you are really interested I will generate a test case showing the failure or else prove I was hallucinating. My current workaround is to look for a %( in every value returned and if so do a string substitution. value = base.get(section,item, 1) if value.find("%(") != -1: value = value% self.interpolation_symbols yes, it is as ugly as a roadkill toad but it gets the job done. I've spent away too much time on this problem for this particular project. I think we all know the feeling. ---eric From aaronwmail-usenet at yahoo.com Fri Jan 7 14:59:25 2005 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 7 Jan 2005 11:59:25 -0800 Subject: OT: google groups bug, or worse? Message-ID: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> I'm concerned that google groups is not correctly reflecting the python lists. A month ago I announced the xsdbXML framework to the python list and the python-announce list. As you can see from the links below the python announce submission was approved by the moderators (thanks!) and the python list submission also went out, but the messages cannot be found at google groups. http://mail.python.org/pipermail/python-list/2004-December/254479.html http://mail.python.org/pipermail/python-announce-list/2004-December/003583.html Is it a google bug? Or is it something darker, like an anti-Python conspiracy at google? Inquiring minds want to know. -- Aaron Watters === There are 3 kinds of people, those who can count and those who can't. -- folklore. From jacek.generowicz at cern.ch Fri Jan 7 03:56:02 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Jan 2005 09:56:02 +0100 Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> Message-ID: Peter Hansen writes: > Jacek Generowicz wrote: > > Peter Hansen writes: > >>Why the heck would I ever have to do "rectangle operations" on a > >>regular basis? ;-) > > Well, given that all editors are cat equivalent[*], you don't _have_ > > to use any of their features :-) > > This "cat equivalent" thing is a red-herring. I can rarely type more > than a line of code without making a typographical error. Sometimes > I won't catch that error until a bit later. Using "cat" alone would > provide me little opportunity to fix the error, so I would never > be able to produce a working program longer than a few lines. And have you ever tried to write a serious program on a Turing Machine? This is exactly my point: Turing Equivalence is only theoretical. In practise some languages are more powerful than others. Same goes for editors. > But the whole argument is fairly moot... I've needed a rectangle > operation only once in the last ten years, Whereas I use rectangle operations, on average, a few times every day ... because they are part of my standard toolbox, they suggest themselves as the right solution to many a problem. There are plenty of programmers out there who "have only needed classes once in the last ten years". More powerful editors, just like more powerful languages, can make their users more productive. Complicated editors, just like complicated programming languages, can make their users less productive[*]. The optimal point in complexity-expressiveness space will be different for different individuals, be it for editors or programming languages. [*] I suspect that there are a few around here who would interpret this as an indictment against the direction in which Python is going :-) From bulba at bulba.com Thu Jan 6 20:22:04 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 02:22:04 +0100 Subject: [OT] Re: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <86ekh3qv1o.fsf@guru.mired.org> <03mlt0di3rcntvu7rlrk9k2m9bq8435bs5@4ax.com> <87r7kyck0m.fsf_-_@hector.domek> Message-ID: On Thu, 06 Jan 2005 22:42:01 +0100, Peter Dembinski wrote: >[...] > >> That's remarkable, first time I see smth like this - >> out of curiosity, could you say a word where was that? >Are you the same Bulba I know from alt.pl.comp.os.hacking? No, but I like to see I have an evil twin out there. :-) -- It's a man's life in a Python Programming Association. From just at xs4all.nl Mon Jan 17 10:29:17 2005 From: just at xs4all.nl (Just) Date: Mon, 17 Jan 2005 16:29:17 +0100 Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: In article , Antoon Pardon wrote: > >> I don't see a big difference between these principles > >> and the hash key principle, > > > > Than you haven't looked hard enough. > > All of these can get unexpected behaviour because of the > assignment-doesn't-copy semantics. The same semantics > that can cause problems if you work with mutable dictionary > keys. Again, the difference is: 1. assigning mutable objects *can* cause unexpected behavior (however, it's a useful feature, everyone using Python for longer than a day or two knows this, and then it's *expected* behavior. 2. mutating dict keys *does* *always* cause problems. (unless you use an identity hash/cmp) It's nonsense to forbid 1) since it's a useful feature. It's useful to forbid ("discourage") 2) since mutating dict keys is seldom useful (and when it is, Python lets you support it in your own objects). Just From ed at leafe.com Mon Jan 10 20:39:03 2005 From: ed at leafe.com (Ed Leafe) Date: Mon, 10 Jan 2005 20:39:03 -0500 Subject: Dabo 0.3 Released Message-ID: <930D4114-6371-11D9-B1AE-003065B11E84@leafe.com> We are pleased to announce Dabo 0.3, the third major release of our data application framework. The Dabo framework is a true 3-tier design, with data access and UI code separated from your business logic. And since it's Python, and uses wxPython for its UI, it is completely cross-platform, having been tested on Linux, Windows and OS X. Download from http://dabodev.com/download This marks the first major release of Dabo since we changed the licensing of Dabo. It is now released under the MIT License, which gives you much more freedom to do what you want with the code. See http://www.opensource.org/licenses/mit-license.html for the exact terms of the license. It is our hope that this will remove any reservations that people may have had about working with GPL software, and as a result grow the user base of the framework. Over the past few months we have gotten some wonderful feedback from people who are interested in our work and who are interested in a solid application framework for developing database apps. The framework is now very solid and reliable, and Dabo applications are being used daily. But there is still more we plan on adding, so like all pre-release software, use with caution. Anyone interested in contributing to Dabo, or who just want to find out what it is all about is encouraged to join our mailing lists: dabo-users: for those interested in learning how to work with Dabo to create applications, and for general help with Dabo. http://leafe.com/mailman/listinfo/dabo-users dabo-dev: for those interested in the ongoing development of Dabo. This list contains lots of lively discussion on design issues, as well as notices of all commits to the code repository. http://leafe.com/mailman/listinfo/dabo-dev Here is a brief summary of what's new in Dabo 0.3: Dabo Framework: Support for PostgreSQL added in addition to existing support for MySQL and Firebird databases. Improved unicode support in data cursors. Support for fulltext searches added. Child requeries and transaction support added to bizobj and cursor classes. Several new controls have been added, including a window splitter and a grid-like list control. The GridSizer has been added, making laying out of controls in a grid-like pattern a breeze. The API for all the sizers has been greatly simplified, too. Menus have had wxPython-specific code removed, and are now much simpler to create and manage. A 'Command Window' has been added to the base menu. This allows you to enter commands interactively in a running application, which makes debugging and testing so much simpler. Once you've developed an app with a Command Window at your disposal, you'll never want to develop without it! And, of course, more bug fixes than we'd like to say! Dabo IDE: The appWizard has been moved from the Demo project to here, as well as the FieldSpecEditor. There is a new connection editor for visually setting up database connection information and storing it in an XML file. The appWizard can now generate parent/child/grandchild/... relationships. The FieldSpecEditor (for visually controlling the appearance and behavior of wizard-generated apps) has been greatly improved, with interactive ordering and live previews of changes. The editor can now toggle word wrap, jump to any line in the file, and comment/uncomment blocks of code. Dabo Demo: There's now a MineSweeper game - written in Dabo, of course! All of the other demos have been updated to work with the changes in the rest of the framework. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From philippecmartin at sbcglobal.net Sat Jan 8 10:59:23 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Sat, 08 Jan 2005 16:59:23 +0100 Subject: printing line numbers for debugging purpose Message-ID: <1105199963.7467.4.camel@localhost> Hi, All of the methods from my program return None on error (i.e; I do not want to assert and have the program exit). Is it possible to print the current source file name/line number ? ex: in C/C++ I would use the macros __FILE__ and __LINE__. Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From joh12005 at yahoo.fr Mon Jan 24 17:06:49 2005 From: joh12005 at yahoo.fr (Joh) Date: 24 Jan 2005 14:06:49 -0800 Subject: need help on generator... (re) Message-ID: <63b5e209.0501241406.4fb5980b@posting.google.com> hello, thanks to all who replied to my post (2005-01-21) - (i can not post inside the original thread as i get "Unable to retrieve message csr7ep$3db$05$1 at news.t-online.com" from googlenews :( > Do you mean: > [1,2], [2,3], [3,4], [1,2,3], [2,3,4], [1,3,4] > (E.g. all elements in the power set except the empty set, the sets with > one element and the sets with all elements.) > Otherwise, please describe your desired sets in verbal - I cannot see > the point. yes it was my wishes, but having the others empty, one and all elements wasn't a big trouble, actually i wanted to understand more generators. > Here is an (untested) variant that accepts any iterable while trying to > remain memory-efficient. This makes it necessary to shuffle the order of > the output a bit. > from itertools import tee, islice > def gen(iterable, start, end): > it = iter(iterable) > while True: > it, a = tee(it) > a = tuple(islice(a, end-1)) > for sz in xrange(start, len(a)+1): > yield a[:sz] > it.next() > > if __name__ == "__main__": > print list(gen(range(1, 5), 2, 4)) please, this one looks interesting, could you explain a bit how it works and why it "remain memory-efficient" ? thanks, From sumitsu at cc.gatech.edu Thu Jan 20 17:31:12 2005 From: sumitsu at cc.gatech.edu (Branden Smith) Date: Thu, 20 Jan 2005 17:31:12 -0500 Subject: IDLE Problem in Windows XP Message-ID: <41F03130.4080709@cc.gatech.edu> Hi, I am a teaching assistant for an introductory course at Georgia Tech which uses Python, and I have a student who has been unable to start IDLE on her Windows XP Home Edition machine. Clicking on the shortcut (or the program executable) causes the hourglass to appear momentarily (and the process to momentarily appear in the process monitor), but nothing happens thereafter. Attempting to start IDLE from the script results in exactly the same output described in this discussion, suggesting that a socket error occurs, presumably for the Python loopback connection: https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1017978&group_id=5470 The potential solutions mentioned in the discussion have had no effect, however. Obviously, something is preventing Python from establishing a loopback socket connection, but after disabling firewall software, antiviral software, and Windows's built-in firewall, the problem remains. Does anyone have any ideas as to what might cause this problem? It shows up with both Python 2.4 and 2.3. Version 2.2 works as it should. Thanks, Branden Smith .::. CS 1321 TA sumitsu at cc.gatech.edu From andy at andygross.org Mon Jan 10 00:34:17 2005 From: andy at andygross.org (Andy Gross) Date: Mon, 10 Jan 2005 00:34:17 -0500 Subject: a new Perl/Python a day In-Reply-To: References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: <455C5963-62C9-11D9-9ABC-000A95CED3AC@andygross.org> On Jan 10, 2005, at 12:11 AM, Scott Bryce wrote: > > No. Perl may have some interesting idiosyncrasies, especially for a > programmer with little or no Unix experience, but I find it neither > frustrating, inane nor incompetent. The more I use it, the more I like > it. I don't see what UNIX experience has to do with it. I have plenty of it, and still have to look at the documentation to remember that I need to type '$|' to turn buffering off. Ditto for the rest of the perl line-noise syntax. /arg > http://mail.python.org/mailman/listinfo/python-list From donn at drizzle.com Sun Jan 2 14:02:37 2005 From: donn at drizzle.com (Donn Cave) Date: 2 Jan 2005 13:02:37 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1> <7x8y7cjo57.fsf@ruckus.brouhaha.com> Message-ID: <41d8454d$1_1@127.0.0.1> Quoth Paul Rubin : | "Donn Cave" writes: |> Yes, it would be really weird if Python went that way, and the |> sort of idle speculations we were reading recently from Guido |> sure sounded like he knows better. But it's not like there aren't |> some interesting issues farther on downstream there, in the compare |> function. cmp(), and str() and so forth, play a really big role in |> Python's dynamically typed polymorphism. It seems to me they are |> kind of at odds with static type analysis | | I don't understand that. If I see "str x = str(3)", then I know that | x is a string. Sure, but the dynamically typed polymorphism in that function is about its parameters, not its result. If you see str(x), you can't infer the type of x. Of course you don't need to, in Python style programming this is the whole point, and even in say Haskell there will be a similar effect where most everything derives the Show typeclass. But this kind of polymorphism is pervasive enough in Python's primitive functions that it's an issue for static type analysis, it seems to me, especially of the type inference kind. cmp() is more of a real issue than str(), outside of the type inference question. Is (None < 0) a valid expression, for example? Donn Cave, donn at drizzle.com From itsme at yahoo.com Mon Jan 3 11:41:54 2005 From: itsme at yahoo.com (It's me) Date: Mon, 03 Jan 2005 16:41:54 GMT Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: Shaw-PTI (www.pti-us.com) uses Python in their software. See: http://www.pti-us.com/pti/news/index.cfm and search "2004 PSS/E User Group Meeting" wrote in message news:1104750017.235937.181370 at c13g2000cwb.googlegroups.com... > Hello All, > I am trying to convince my client to use Python in his new product. He > is worried about the license issues. Can somebody there to point me any > good commercial applications developed using python ?. The licence > clearly says Python can be used for commercial applications. Is there > any other implications like that of GPL to make the source open ? > Thanks for any help. > eeykay > From X-Man at tj.mx Tue Jan 25 02:33:18 2005 From: X-Man at tj.mx (X-Man) Date: Tue, 25 Jan 2005 07:33:18 GMT Subject: ANNOUNCE: Altova ... blah blah blah References: <8u9Hd.344$Jg7.182@fe51.usenetserver.com> <41ed567c$0$6208$e4fe514c@news.xs4all.nl> Message-ID: In article <41ed567c$0$6208$e4fe514c at news.xs4all.nl>, irmen at -nospam- remove-this-xs4all.nl says... > Altova Announcements wrote: > > Altova Unveils ............. > [spam] > > Well now, I didn't like their products very much already, > but this spam has certainly made them drop another few > steps down on my scale. Hmpf. > > --Irmen > Yes. I find Altova's work to be high-quality but narrow-minded and arrogant. An example: Though all of the marketing material for StyleVision extols its usefulness for arbitrary, free-standing forms and reports, the only HTML or PDF one can actually generate is restricted to a frustrating subset which Altova has decided is useful -- and "useful" to them means "already supported by the Altova Authentic front end". From francis.girard at free.fr Fri Jan 28 08:57:07 2005 From: francis.girard at free.fr (Francis Girard) Date: Fri, 28 Jan 2005 14:57:07 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <7x3bwmggi3.fsf@ruckus.brouhaha.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> <7x3bwmggi3.fsf@ruckus.brouhaha.com> Message-ID: <200501281457.09366.francis.girard@free.fr> Le vendredi 28 Janvier 2005 08:27, Paul Rubin a ?crit?: > Francis Girard writes: > > Thank you Nick and Steven for the idea of a more generic imerge. > > If you want to get fancy, the merge should use a priority queue (like > in the heapsort algorithm) instead of a linear scan through the > incoming iters, to find the next item to output. That lowers the > running time to O(n log k) instead of O(n*k), where k is the number of > iterators and n is the length. The goal was only to show some FP construct on small problems. Here the number of iterators are intended to be fairly small. Otherwise, yes, you could exploit the fact that, at one loop execution, you already seen most of the elements at previous loop execution, storing them in some heap structure and therefore not having to recan the whole list of "already seen" iterator values at each loop execution. Thank you Francis Girard From fuzzyman at gmail.com Wed Jan 5 05:47:11 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2005 02:47:11 -0800 Subject: Embedding a restricted python interpreter In-Reply-To: References: Message-ID: <1104922031.642263.44380@c13g2000cwb.googlegroups.com> Fredrick Lundh (at www.effbot.org ) was working on a 'cut down python' that only implements the bits of python he likes !! It would be great if the core of that interpreter could be used as a 'restricted interpreter'. If you could externally disable os, sys, os.path modules etc and limit the set of modules, then you could have a useful restricted environment. It would need a special interpreter though - so NO is the short answer. Regards, Fuzzy http://www,voidspace.org.uk/python/index.shtml From jacek.generowicz at cern.ch Thu Jan 6 03:41:01 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 06 Jan 2005 09:41:01 +0100 Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> Message-ID: Peter Hansen writes: > Why the heck would I ever have to do "rectangle operations" on a > regular basis? ;-) Well, given that all editors are cat equivalent[*], you don't _have_ to use any of their features :-) But just like Python (particularly in the hands of a skilled Python programmer) is more productive than a Turing Machine, any featureful editor (in the hands of an experienced user) is far more productive than "cat > file". [*] A bit like Turing equivalence: any program you can write in any other editor, you could also write with "cat > file" From matternc at comcast.net Mon Jan 17 14:26:13 2005 From: matternc at comcast.net (Chris Mattern) Date: Mon, 17 Jan 2005 14:26:13 -0500 Subject: [perl-python] 20050116 defining a function References: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> <1105983516.736238.314050@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > errata: > > * the variables in the perl section should be declared inside the > subroutine. > * the @_[0] should've been $_[0] > > thanks for Dave Cross for pointing them out. > > * the Mathematica Apply should be Select... > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html Here's a thought: don't post code you haven't tested! -- Christopher Mattern "Which one you figure tracked us?" "The ugly one, sir." "...Could you be more specific?" From lidaobing at gmail.com Thu Jan 27 08:05:44 2005 From: lidaobing at gmail.com (Li Daobing) Date: 27 Jan 2005 05:05:44 -0800 Subject: a question about boost.python Message-ID: <1106831144.415765.18970@f14g2000cwb.googlegroups.com> I can't use .def(str(self)) I write a simple example, without `str', I can build it well, but with this one, I can't build //Rational.cpp #include #include using namespace std; using namespace boost::python; class Rational {}; ostream& operator<<(ostream& os, Rational r){ return os; } BOOST_PYTHON_MODULE(Rational) { class_("Rational") .def(str(self)) // __str__ ; } // end. I don't know how to write Jamfile, so I write a Makefile, it works if i don't use .def(str(self)) # Makefile CC = g++ CFLAGS = -Wall -W -fPIC -I/usr/include/boost \ -I/usr/include/python2.3 -DBOOST_PYTHON_DYNAMIC_LIB \ -O2 LDFLAGS = -L/usr/local/lib -lboost_python -L/usr/lib/python2.3 \ -Wl,-rpath-link,. -fPIC CXXFLAGS = $(CFLAGS) SLIB = hello.so Rational.so all: $(SLIB) %.so : %.o /usr/bin/objcopy --set-section-flags .debug_str=contents,debug $^ $(CC) $(LDFLAGS) $^ -shared -o $@ clean : rm -f $(WORLD) $(OBJS) # end. or a simple setup.py, it also works if I don't use `str' # setup.py from distutils.core import setup, Extension ext_modules = [Extension('Rational', ['Rational.cpp'], define_macros=[('BOOST_PYTHON_DYNAMIC_LIB', None)], libraries=['boost_python'])] setup(name="itcc", version="0.2.2", author='Li Daobing', author_email='lidaobing at gmail.com', ext_modules = ext_modules ) # end. This is the error message: $ make g++ -Wall -W -fPIC -I/usr/include/boost -I/usr/include/python2.3 -DBOOST_PYTHON_DYNAMIC_LIB -O2 -c -o Rational.o Rational.cpp Rational.cpp: In function `std::ostream& operator<<(std::ostream&, Rational)': Rational.cpp:10: warning: unused parameter `Rational r' /usr/include/boost/python/def_visitor.hpp: In static member function `static void boost::python::def_visitor_access::visit(const V&, classT&) [with V = boost::python::def_visitor, classT = boost::python::class_] ': /usr/include/boost/python/def_visitor.hpp:67: instantiated from `void boost::python::def_visitor::visit(classT&) const [with classT = boost::python::class_, DerivedVisitor = boost::python::api::object]' /usr/include/boost/python/class.hpp:225: instantiated from `boost::python::class_& boost::python::class_::def(const boost::python::def_visitor&) [with Derived = boost::python::api::object, W = Rational, X1 = boost::python::detail::not_specified, X2 = boost::python::detail::not_specified, X3 = boost::python::detail::not_specified]' Rational.cpp:15: instantiated from here /usr/include/boost/python/def_visitor.hpp:31: error: no matching function for call to `boost::python::api::object::visit(boost::python::class_&) const' make: *** [Rational.o] Error 1 From bokr at oz.net Thu Jan 13 15:39:44 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 20:39:44 GMT Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> <34o183F4b3in3U1@individual.net> Message-ID: <41e6d952.770332109@news.oz.net> On Thu, 13 Jan 2005 22:41:54 +0300, Andrey Tatarinov wrote: >Nick Coghlan wrote: >> Nick Coghlan wrote: >> >>> Semantics >>> --------- >>> The code:: >>> >>> with: >>> >>> >>> translates to:: >>> >>> def unique_name(): >>> >>> >>> unique_name() >> I've come to the conclusion that these semantics aren't what I would >> expect from the construct. Exactly what I would expect can't really be >> expressed in current Python due to the way local name bindings work. The >> main thing to consider is what one would expect the following to print: >> >> def f(): >> a = 1 >> b = 2 >> print 1, locals() >> print 3, locals() using: >> a = 2 >> c = 3 >> print 2, locals() >> print 4, locals() >> >> I think the least suprising result would be: >> >> 1 {'a': 1, 'b': 2} # Outer scope >> 2 {'a': 2, 'c': 3} # Inner scope >> 3 {'a': 2, 'b': 2, 'c': 3} # Bridging scope >> 4 {'a': 1, 'b': 2} # Outer scope > >as for me, I would expect following: > >1 {'a': 1, 'b': 2} >2 {'a': 2, 'b': 2, 'c': 3'} >3 {'a': 2, 'b': 2, 'c': 3'} >4 {'a': 1, 'b': 2} locals() doesn't automatically show everything that is visible from its local scope: >>> def foo(): ... a = 1 ... b = 2 ... print 1, locals() ... def inner(): ... a = 2 ... c = 3 ... print 2, locals() ... inner() ... print 4, locals() ... >>> foo() 1 {'a': 1, 'b': 2} 2 {'a': 2, 'c': 3} 4 {'a': 1, 'b': 2, 'inner': } -- unless you actually use it (this is a bit weird maybe?): >>> def foo(): ... a = 1 ... b = 2 ... print 1, locals() ... def inner(): ... a = 2 ... c = 3 ... print 2, locals(), 'and b:', b ... inner() ... print 4, locals() ... >>> foo() 1 {'a': 1, 'b': 2} 2 {'a': 2, 'c': 3, 'b': 2} and b: 2 4 {'a': 1, 'b': 2, 'inner': } of course a difference using the new syntax is that 'inner' is not bound to a persistent name. > >otherwise that would be impossible to do calculations based on scope >variables and "using:" would be useless =), consider example of usage: > >current_position = 1 >current_environment # = ... >current_a_lot_of_other_parameters # = ... >scores = [count_score(move) for move in aviable_moves] using: > def count_score(move): > #walking through current_environment > return score No worry, UIAM. Regards, Bengt Richter From pinard at iro.umontreal.ca Mon Jan 10 09:09:03 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Mon, 10 Jan 2005 09:09:03 -0500 Subject: a new Perl/Python a day In-Reply-To: <455C5963-62C9-11D9-9ABC-000A95CED3AC@andygross.org> References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> <455C5963-62C9-11D9-9ABC-000A95CED3AC@andygross.org> Message-ID: <20050110140903.GA23895@alcyon.progiciels-bpi.ca> [Andy Gross] > On Jan 10, 2005, at 12:11 AM, Scott Bryce wrote: > >No. Perl may have some interesting idiosyncrasies > I [...] still have to look at the documentation to remember that I > need to type '$|' to turn buffering off. Ditto for the rest of the > perl line-noise syntax. Behind each language, there is a culture. The Perl man pages give many mnemonic tricks to remember special variable names like the above, and if you are willing to play the game the way it was written, you might even have some fun at it, and easily be proficient at this "line-noise". I did a lot of Perl for many years, and still appreciate what Perl is (or at least was). Python does not change Perl in my eyes. However, Python is significantly more legible and maintainable, the comparison merely stresses the unreadability of Perl. No doubt that I prefer Python, but Python not being there, Perl would be quite useful to me. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From phil at freehackers.org Mon Jan 31 23:32:40 2005 From: phil at freehackers.org (Philippe Fremy) Date: Tue, 01 Feb 2005 05:32:40 +0100 Subject: Python's idiom for function overloads In-Reply-To: References: Message-ID: <41ff066c$0$6473$636a15ce@news.free.fr> Hi Frans, > Since Python doesn't have static typing, how is the same result as traditional > function overloads results in acheived? With dynamic typing obviously. :-) 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) ... As you see, it is a bit tedious sometimes. If you want to juggle with completely different signatures, you have to play with variable argument lists. But I have found in my experience that the best way to get close to the C++ idiom, while improving readbility, is by using kwparams: def a(**kwparams): if kwparams.has_key('argInt'): aWithInt(kwparams['argInt']) if kwparams.has_key('argString'): aWithString(kwparams['argString']) The parsing code is the same, but the intent of the user is better expressed and you can catch misuse in a better fashion: if kwparams.has_key('argInt') and kwparams.has_key('argString'): print "You stupid moron, a can be used only with string or int but not both at the same time!" sys.exit(1) The example speaks better in a real case. Imagine a processPixmap function: processPixmap( pixmap=QPixmap(...) ) processPixmap( filename='my_pixmap.png' ) processPixmap( buffer=my_pixmap_string_content ) It works actually even better with multiple arguments. regards, Philippe From gsakkis at rutgers.edu Sun Jan 9 13:10:08 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sun, 9 Jan 2005 20:10:08 +0200 Subject: Pre/Postconditions with decorators References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com><34814fF43bm4cU1@individual.net> Message-ID: <34dac0F47d7tlU1@individual.net> "Stephen Thorne" wrote: > Unresolved Problems: > 1) How do you handle duck types, i.e. a method that accepts StringIO, > cStringIO or any other object that has a .readlines(), .seek() and > .read() method? I think the 'proper' way of checking duck types (among other things) is by defining appropriate protocols; check pyProtocols (http://peak.telecommunity.com/PyProtocols.html) for details. > 2) How do you turn off the type checking for production code? Currently I don't, but that's easy to do if desired by checking __debug__ in the decorator and return the passed function if it is false: def params(**checkedArgs): if not __debug__: return lambda function: function # else return a typechecked proxy of function (...) > Otherwise I quite like it. Please publish it somewhere. Thanks. I'll post an entry on Vaults of Parnassus as soon as I publish it. George From steve at holdenweb.com Sun Jan 9 11:01:27 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 11:01:27 -0500 Subject: use a file as a database, access rights In-Reply-To: References: Message-ID: Torsten Mohr wrote: > Hi, > > i'd like to write a script that makes use of a database. > > It would be great if the database would store all its data > in a file, that would be great for data exchange. > > It would also be great if i could use SQL, as i have some > experience in that. > > Also, i NEED access rights to certain parts of the database. > Several people should work on it and NEED to have different > access rights. > > > Can anybody give me some recommendations on what to use? > > Sounds to me like you need to add a rights layer to gadfly. 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 tjreedy at udel.edu Tue Jan 25 02:38:05 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 Jan 2005 02:38:05 -0500 Subject: is extending an object considered acceptable usage? References: Message-ID: "mike" wrote in message news:qijJd.14679$Gc2.13828 at fe06.lga... > sometimes i want a list of categories, and from each i want to be able to > access a list of its items. in this case is it considered acceptable to > just create a list of those items and assign it as a property of their > category? eg: To me, Python is about being what it is, and not any other language. It is about writing correct readable algorithms. It is about enjoying programming. It is about programmers being responsible for their own code. I hope you find this more helpful than any yes or no could be. Terry J. Reedy From brion at pobox.com Tue Jan 11 17:14:32 2005 From: brion at pobox.com (Brion Vibber) Date: Tue, 11 Jan 2005 14:14:32 -0800 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: <7xu0pn4x88.fsf@ruckus.brouhaha.com> References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <34h7m9F43vomsU1@individual.net> <7xsm58lcms.fsf@ruckus.brouhaha.com> <7xu0pn4x88.fsf@ruckus.brouhaha.com> Message-ID: <34j1dbF4cd4ocU1@individual.net> Paul Rubin wrote: > I think mod_php doesn't play nice with apache2 but am not aware of any > cgi interoperability problems. Generally it's recommended to configure apache2 in the child process mode (eg the way that 1.3 works) when using PHP as many library modules are alleged not to be threadsafe. Some Linux distributions ship standard this way. -- brion vibber (brion @ pobox.com) From cookedm+news at physics.mcmaster.ca Fri Jan 28 18:42:26 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 28 Jan 2005 18:42:26 -0500 Subject: LinearAlgebra incredibly slow for eigenvalue problems References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> <1106952951.834888.65430@f14g2000cwb.googlegroups.com> Message-ID: "drife" writes: > Hi David, > > I performed the above check, and sure enough, Numeric > is --not-- linked to the ATLAS libraries. > > I followed each of your steps outlined above, and Numeric > still is not linking to the ATLAS libraries. > > My setup.py file is attached below. > # delete all but the first one in this list if using your own LAPACK/BLAS > sourcelist = [os.path.join('Src', 'lapack_litemodule.c')] > # set these to use your own BLAS; > > library_dirs_list = ['/d2/lib/atlas'] > libraries_list = ['lapack', 'ptcblas', 'ptf77blas', 'atlas', 'g2c'] > > # set to true (1), if you also want BLAS optimized matrixmultiply/dot/innerproduct > use_dotblas = 1 > include_dirs = ['/d2/include'] This all look right (assuming you've got the right stuff in /d2). When it compiles, does it look like it's actually doing the linking? After doing python setup.py build, you can run ldd on the libraries in the build directory (something like build/lib.linux-i386-2.3/lapack_lite.so). If that's linked, then it's not being installed right. You don't have a previous Numeric installation that's being picked up instead of the one you're trying to install, do you? At the interpreter prompt, check that >>> import Numeric >>> Numeric.__file__ gives you something you're expecting, and not something else. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From wolfgang.keller.nospam at gmx.de Fri Jan 21 10:51:01 2005 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Fri, 21 Jan 2005 16:51:01 +0100 Subject: Python-enterprise (integration) SIG/mailinglist/etc.? Message-ID: <15x0cn5gc5nhv.fnluxjlz7ljj.dlg@40tude.net> Hello, Python seems to be used quite a lot for (the integration of) enterprise applications. Just as an example, there are at least three (projects for the implementation of) ERP systems in Python: - GNUenterprise - ERP5 - TinyERP There are also a lot of different modules already available which supply useful functionalities for (the integration of) enterprise applications, such as PEAK, Twisted, OmniORBpy, Modeling, etc... However, what seems to be missing is some kind of coordination/communication resource and/or (link) repository for such modules, so that one can find out easily what exists already, whether it fits one's requirements and if not, where to find other people who would participate in the implementation of what's missing. So, here's the question: How about creating a Python-Enterprise(-Integration)-SIG/-mailinglist/whatever? Such a group could also start standardisation for such things as a "Python Messaging System", a "Python Component Model" and maybe (reference) implementations could be included in the Python distribution some day (no I don't think it should be called "PEE" :-). TIA, Wolfgang Keller From skip at pobox.com Fri Jan 21 11:04:33 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 21 Jan 2005 10:04:33 -0600 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> Message-ID: <16881.10257.653477.308921@montanaro.dyndns.org> Steve> The fact that a bright bunch like the Python developers didn't Steve> realize that it would be sensible to have a local scope for the Steve> list comprehension variable is a perfect demonstration of that Steve> point. Actually, I seem to recall that the topic came up, but at the time the goal was that list comprehensions be semantically the same as for loops, so the fact that the loop variable survived to pollute the namespace was deemed okay. Skip From kent3737 at yahoo.com Tue Jan 4 07:48:17 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Tue, 04 Jan 2005 07:48:17 -0500 Subject: The Industry choice In-Reply-To: <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> Message-ID: <41da8e78$1_3@newspeer2.tds.net> Alex Martelli wrote: > Roy Smith wrote: > > >>Stefan Axelsson wrote: >> >>>Yes, ignoring most of the debate about static vs. dynamic typing, I've >>>also longed for 'use strict'. >> >>You can use __slots__ to get the effect you're after. Well, sort of; it >>only works for instance variables, not locals. And the gurus will argue >>that __slots__ wasn't intended for that, so you shouldn't do it. > > > There's a simple, excellent recipe by Michele Simionato, on both the > online and forthcoming 2nd edition printed Cookbook, showing how to do > that the right way -- with __setattr__ -- rather than with __slots__ . The recipe is here (it took me a few minutes to find it, I found the title misleading): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 Kent From j.p.t.j.berends at [N0SP4M].nl Thu Jan 6 10:05:57 2005 From: j.p.t.j.berends at [N0SP4M].nl (J Berends) Date: Thu, 06 Jan 2005 16:05:57 +0100 Subject: sorting on keys in a list of dicts In-Reply-To: References: Message-ID: Jp Calderone wrote: > On Thu, 06 Jan 2005 15:31:22 +0100, J Berends wrote: > >>Suppose I have a list of dictionaries and each dict has a common keyname >>with a (sortable) value in it. >> >>How can I shuffle their position in the list in such way that they >>become sorted. >> > > > In Python 2.4, > > import operator > L.sort(key=operator.itemgetter(key)) > > In Python 2.3, > > L2 = [(d[key], i, d) for (i, d) in enumerate(L)] > L2.sort() > L = [d for (v, i, d) in L2] > > Jp the 2.3 version seems to work quite nicely! thanks. Using the 2.3 for version compatibility. Thanks! From eurleif at ecritters.biz Thu Jan 20 02:13:05 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 20 Jan 2005 02:13:05 -0500 Subject: Solutions for data storage? In-Reply-To: References: Message-ID: <3593spF4i5j1dU1@individual.net> Robert Brewer wrote: > Try svn://casadeamor.com/dejavu/trunk if you want a truly Pythonic query > syntax. Wait a couple of days, and I'll have version 1.3 ready and > online at http://www.aminus.org/rbre/python -- lots of changes from > 1.2.6 which is there now, but at least you can read old docs online now > without svn. Thanks a lot for the reply. I've skimmed the documentation (very well-written, by the well), and I really like the looks of what I've seen so far. I'm a bit confused about where sandboxes get created, though; in a Web application, would I give each request a sandbox of its own, or create one for the entire application, or what? From alipolatel at yahoo.com Sun Jan 23 13:46:44 2005 From: alipolatel at yahoo.com (Ali Polatel) Date: Sun, 23 Jan 2005 10:46:44 -0800 (PST) Subject: on the way to find pi! In-Reply-To: <1d6cdae30501231034140ba539@mail.gmail.com> Message-ID: <20050123184644.20812.qmail@web61006.mail.yahoo.com> that's just little near to pi... pi is so far away ;) __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Wed Jan 5 21:20:00 2005 From: grante at visi.com (Grant Edwards) Date: 06 Jan 2005 02:20:00 GMT Subject: Example of using pty to control a process? References: <1104976111.041702.255710@c13g2000cwb.googlegroups.com> Message-ID: <41dca050$0$64503$a1866201@visi.com> On 2005-01-06, morphex wrote: > I'm trying to get the output from the command top on Linux, using > python. I'd like to start top, get a page of output, and then send top > the letter 'q' to end the process. Man, you like to do things the hard way. Me OTOH, I'm lazy. I'd use popen(), start top in "batch" mode and tell it to execute one iteration. import os lines = os.popen("top -b -n 1","r").read().split('\n') print lines > Looking around I've figured that the module pty can be used > for this, however, I can't find any good examples of how to > use it. Any ideas as to where I can look? I've you're dead set on using pty, I can tell you how to do it in C, and maybe you can extrapolate. -- Grant Edwards grante Yow! .. I think I'd at better go back to my DESK visi.com and toy with a few common MISAPPREHENSIONS... From steven.bethard at gmail.com Wed Jan 26 16:25:02 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 14:25:02 -0700 Subject: Help With Python In-Reply-To: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> References: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Nick Vargish wrote: > Here's my Monty Pythonic answer: > > ## cut here > class Viking(): > > def __init__(): > pass > > def order(): > return 'Spam' > > # this is one viking making one order repeated 511 times. if you want > # 511 vikings making seperate orders, you'll have to write a loop. > v = Viking() > orders = [ v.order() ] * 511 > > print ', '.join(orders) No need to write a loop: py> class Viking(object): ... def order(self): ... return 'Spam' ... py> v = Viking() py> orders = [v.order()] * 7 py> ', '.join(orders) 'Spam, Spam, Spam, Spam, Spam, Spam, Spam' py> orders = [Viking().order()] * 7 py> ', '.join(orders) 'Spam, Spam, Spam, Spam, Spam, Spam, Spam' Steve From danb_83 at yahoo.com Sat Jan 1 00:20:28 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 31 Dec 2004 21:20:28 -0800 Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <1104549662.978986.77480@c13g2000cwb.googlegroups.com> Message-ID: <1104556828.320101.74750@z14g2000cwz.googlegroups.com> M.E.Farmer wrote: > Grant Edwards wrote: > >Not sure what Google Groups does to it... > The usual... it mangles it. > I don't get it, Google uses Python too, they know it is whitespace > signifigant. And for a long time, Google groups postings *were* whitespace significant. But the new interface broke it. > I made a complaint several weeks ago to Google support, > asking them too quit stripping leading whitespace, > and the sent me a reply saying they appreciated my feedback. > Maybe they just need more feedback :) I send them some earlier today. So far, I've only received their auto-reply. From stephen.thorne at gmail.com Thu Jan 6 18:02:40 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Fri, 7 Jan 2005 09:02:40 +1000 Subject: Pre/Postconditions with decorators In-Reply-To: References: Message-ID: <3e8ca5c80501061502203041ff@mail.gmail.com> On 6 Jan 2005 13:33:42 -0800, Rittersporn wrote: > @condition("number>0 and number<2","result>=0") > def sqrt(number): > import math > return math.sqrt(number) > > @condition("list(seq) is not None","sum(seq)==result") > def my_sum(seq): > tmp=0 > for element in seq: > tmp+=element > return tmp > > print sqrt(1.2) > print my_sum([1,2,3]) I think it would be nicer to have the pre and post conditions being compilable. @condition((list(seq) is not None for seq in args), (sum(seq)==result for ((seq,), result) in (args, result)) or something silly like that. Personally, I'd prefer this: @precondition(list(seq) is not None for seq in args) @postcondition(sum(seq)==result for ((seq,), result) in (args, result)) (this is, of course, using the framehack lambda replacement presented in a thread about a week ago). Stephen. Stephen. From jamesthiele.usenet at gmail.com Sun Jan 30 14:57:23 2005 From: jamesthiele.usenet at gmail.com (jamesthiele.usenet at gmail.com) Date: 30 Jan 2005 11:57:23 -0800 Subject: type() takes one or *three* arguments!? Message-ID: <1107115043.242733.259890@z14g2000cwz.googlegroups.com> I was looking at Simon Burton's Povray.py code (part of pypov) and saw this line: globals()[name] = type( name, (KWItem,), {} ) # nifty :) where 'KWItem' was a class. It did seem nifty, but it was unclear to me what was happening. I went to python.org's online documentation which said that type() takes one argument. So I fired up python: >>> type(42) >>> type("x", (type(42),), {}) OK, It appears that type() with 3 arguments constructs a class. Is this documented somewhere? If not can someone explain what is going on? james From phil_nospam_schmidt at yahoo.com Thu Jan 13 08:43:06 2005 From: phil_nospam_schmidt at yahoo.com (phil_nospam_schmidt at yahoo.com) Date: 13 Jan 2005 05:43:06 -0800 Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> <39ednWfqlrgB6HvcRVn-iA@powergate.ca> Message-ID: <1105623786.097982.94650@c13g2000cwb.googlegroups.com> Peter Hansen wrote: > and-google at doxdesk.com wrote: > > In Mythical Future Python I would like to be able to use any base in > > integer literals, which would be better. Example random syntax: > > > > flags= 2x00011010101001 > > umask= 8x664 > > answer= 10x42 > > addr= 16x0E800004 # 16x == 0x > > gunk= 36x8H6Z9A0X > > I think I kinda like this idea. Allowing arbitrary values, > however, would probably be pointless, as there are very > few bases in common enough use that a language should make > it easy to write literals in any of them. So I think "36x" > is silly, and would suggest limiting this to 2, 8, 10, and > 16. At the very least, a range of 2-16 should be used. > (It would be cute but pointless to allow 1x000000000. :-) > > -Peter > > > How about base 24 and 60, for hours and minutes/seconds? From steve at holdenweb.com Tue Jan 25 21:21:17 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 25 Jan 2005 21:21:17 -0500 Subject: Open Folder in Desktop In-Reply-To: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> References: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> Message-ID: Kamilche wrote: > Is there a command you can execute in Python that will open a window on > the desktop, such as 'My Documents'? Kind of like 'system', but for > folder names, not just programs. I'm running on Windows 2000. > os.system("start .") works for me. 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 peter at engcorp.com Thu Jan 13 08:56:10 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 08:56:10 -0500 Subject: Unclear On Class Variables In-Reply-To: References: Message-ID: Simon Brunning wrote: > On 13 Jan 2005 07:18:26 EST, Tim Daneliuk wrote: > But you are being mislead by the fact that integers are immutable. > 'spam.eggs = 2' is *creating* an instance member - there wasn't one > before. Have a look at what happens with a mutable object: Simon, it's really not about mutability at all. You've changed the example, which was binding a name (specifically setting an attribute), to one in which you are simply calling a method on the object. If you change your example to bind the name the same way, even with a mutable, it will work the same way as Tim's original did with integers: >>> class Spam(object): ... eggs = [3] ... >>> spam = Spam() >>> spam2 = Spam() >>> spam.eggs = [7] >>> spam2.eggs [3] -Peter From mwm at mired.org Wed Jan 5 14:59:35 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 05 Jan 2005 13:59:35 -0600 Subject: smtp question References: Message-ID: <868y77pryw.fsf@guru.mired.org> "Philippe C. Martin" writes: > Hi, > > I am testing the smtp module and have the following question: > > in the code below (taken from net sample) prior to adding the "Subject:" > field, the email client found the "From" and the "To". Without the > "Subject:" field on I get this: > > Email client = Evolution: the "From" field is blank > Email client = KMail: the "To" field is blank > > Any clue ? > > Thanks and regards, > > Philippe > ********************** > > import smtplib > > def prompt(prompt): > return raw_input(prompt).strip() > > > fromaddr = prompt("From: ") > toaddrs = prompt("To: ").split() > print "Enter message, end with ^D (Unix) or ^Z (Windows):" > > # Add the From: and To: headers at the start! > msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs))) > while 1: > try: > line = raw_input() > except EOFError: > break > if not line: > break > msg = msg + line > > print "Message length is " + repr(len(msg)) > > server = smtplib.SMTP('smtp.sbcglobal.yahoo.com') > server.set_debuglevel(1) > server.login ('xxxxx','yyyyyyy') > server.sendmail(fromaddr, toaddrs, 'Subject:from python\n\n'+msg) You've got \n\n after the Subject line, not \r\n. That is being treated as two newlines, thus ending the headers. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From warren.ali at gmail.com Thu Jan 20 18:08:06 2005 From: warren.ali at gmail.com (warren ali) Date: 20 Jan 2005 15:08:06 -0800 Subject: DbfilenameShelf instance has no attribute 'writeback' Message-ID: <1106262486.089616.99130@f14g2000cwb.googlegroups.com> Anyone have any idea why this is failing with the following error class _IndexFile: """An _IndexFile is an implementation class that presents a Sequence and Dictionary interface to a sorted index file.""" def __init__(self, pos, filenameroot): self.pos = pos self.file = open(_indexFilePathname(filenameroot), _FILE_OPEN_MODE) self.offsetLineCache = {} # Table of (pathname, offset) -> (line, nextOffset) self.rewind() self.shelfname = os.path.join(WNSEARCHDIR, pos + ".pyidx") try: import shelve self.indexCache = shelve.open(self.shelfname, 'r') except: pass Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute 'writeback'" in Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute 'writeback'" in Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute 'writeback'" in Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute 'writeback'" in The code still returns the correct restults but each result come back with this exception. From http Tue Jan 4 08:56:29 2005 From: http (Paul Rubin) Date: 04 Jan 2005 05:56:29 -0800 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <7xpt0liawq.fsf@ruckus.brouhaha.com> Message-ID: <7xk6qtb8mq.fsf@ruckus.brouhaha.com> Ville Vainio writes: > But the people working on wxPython, pygtk, pyqt, pydev, whatever, are > largely not the same guys that commit stuff to CPython CVS. Right, but for that reason, they don't count as being working on Python. > Type declarations are a feature that might benefit IronPython and > Jython more than they would CPython. CPython seems to be what drives quite a few language design decisions. From Scott.Daniels at Acm.Org Sat Jan 15 12:43:45 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 15 Jan 2005 09:43:45 -0800 Subject: interpret 4 byte as 32-bit float (IEEE-754) In-Reply-To: <34t1p2F4foiplU1@individual.net> References: <34t1p2F4foiplU1@individual.net> Message-ID: <41e952b9$1@nntp0.pdx.net> franzkowiak wrote: > I've read some bytes from a file and just now I can't interpret 4 bytes > in this dates like a real value. An extract from my program: > def l32(c): > return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) + (ord(c[3])<<24) > ... > value = l32(f.read(4)) <--- 3F 8C CC CD should be 1.11 > OK, here's the skinny (I used blocks & views to get the answer): import struct bytes = ''.join(chr(int(txt, 16)) for txt in '3F 8C CC CD'.split()) struct.unpack('>f', bytes) I was suspicious of that first byte, thought it might be an exponent, since it seemed to have too many on bits in a row to be part of 1.11. -Scott David Daniels Scott.Daniels at Acm.Org From fuzzyman at gmail.com Mon Jan 24 09:32:56 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Jan 2005 06:32:56 -0800 Subject: Py2.4 .exe installer In-Reply-To: References: Message-ID: <1106577176.109945.273940@z14g2000cwz.googlegroups.com> I built Movable Python for use on a windows box where I didn't have admin rights. See : http://sourceforge.net/projects/movpy Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From steven.bethard at gmail.com Mon Jan 10 11:13:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 10 Jan 2005 09:13:17 -0700 Subject: else condition in list comprehension In-Reply-To: <1105372193.185270.279290@c13g2000cwb.googlegroups.com> References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> <1105305000.052714.188980@c13g2000cwb.googlegroups.com> <1105372193.185270.279290@c13g2000cwb.googlegroups.com> Message-ID: Luis M. Gonzalez wrote: > It's me wrote: >>> z = [i + (2, -2)[i % 2] for i in range(10)] >> >> But then why would you want to use such feature? Wouldn't that make >> the code much harder to understand then simply: >> >> z=[] >> for i in range(10): >> if i%2: >> z.append(i-2) >> else: >> z.append(i+2) >> >> Or are we trying to write a book on "Puzzles in Python"? > > Once you get used to list comprehensions (and it doesn't take long), > they are a more concise and compact way to express these operations. After looking the two suggestions over a couple of times, I'm still undecided as to which one is more readable for me. The problem is not the list comprehensions (which I love and use extensively). The problem is the odd syntax that has to be used for an if/then/else expression in Python. I think I would have less trouble reading something like: z = [i + (if i % 2 then -2 else 2) for i in range(10)] but, of course, adding a if/then/else expression to Python is unlikely to ever happen -- see the rejected PEP 308[1]. Steve [1] http://www.python.org/peps/pep-0308.html From irmen at -nospam-remove-this-xs4all.nl Thu Jan 20 12:06:56 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 20 Jan 2005 18:06:56 +0100 Subject: xml parsing escape characters In-Reply-To: <41efb72d$1_2@newspeer2.tds.net> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efb72d$1_2@newspeer2.tds.net> Message-ID: <41efe52f$0$6220$e4fe514c@news.xs4all.nl> Kent Johnson wrote: [...] > This is an XML document containing a single tag, , whose content > is text containing entity-escaped XML. > > This is *not* an XML document containing tags , , > , etc. > > All the behaviour you are seeing is a consequence of this. You need to > unescape the contents of the tag to be able to treat it as > structured XML. The unescaping is usually done for you by the xml parser that you use. --Irmen From pierre.barbier at cirad.fr Mon Jan 24 03:06:19 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Mon, 24 Jan 2005 09:06:19 +0100 Subject: Help with Threading In-Reply-To: References: Message-ID: <41f4ac17$0$29097$626a14ce@news.free.fr> Philip Smith a ?crit : > Hi > > I am fairly new to Python threading and my needs are simple(!) > > I want to establish a number of threads each of which work on the same > computationally intensive problem in different ways. > > I am using the thread module rather than the threading module. > > My problem is I can't see how (when one thread completes) to ensure that the > other threads terminate immediately. > > Appreciate some simple advice > > Phil > > With Python's threads, you have to handle this kindd a feature yourself. For example, you can create a single object containing a boolean set to False by default. When one of your algorithm finishes, the boolean is set to True. All your algorithm should regularly test this boolean and exit if it is True ! Note that the boolean has to be inside another object because Boolean types is not mutable. Now, if you really want to be able to "kill" your threads, you will need another thread interface. For example, Qt threads allows that ... and WxPython offers you some functions to do exactly what I described. Pierre From apardon at forel.vub.ac.be Fri Jan 28 04:56:40 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Jan 2005 09:56:40 GMT Subject: A proposal idea for string.split with negative maxsplit References: Message-ID: Op 2005-01-28, Fredrik Lundh schreef : > Antoon Pardon wrote: > >> This behaviour would remain but additionally we would have the >> following. >> >>>>> "st1:st2:st3:st4:st5".split(':',-2) >> ["st1:st2:st3" , "st4" , "st5"] >> >> What do people think here? > >>>> "st1:st2:st3:st4:st5".rsplit(':', 2) > ['st1:st2:st3', 'st4', 'st5'] Damn, I was looking in the wrong version of the docs when I was looking for this. Sorry about that. -- Antoon Pardon From chris.peressotti at utoronto.ca Thu Jan 27 14:47:53 2005 From: chris.peressotti at utoronto.ca (Chris P.) Date: 27 Jan 2005 11:47:53 -0800 Subject: PythonWin (build 203) for Python 2.3 causes Windows 2000 to grind to a halt? Message-ID: <3f233389.0501271147.43572416@posting.google.com> I've been having a problem with PythonWin that seemed to start completely spontaneously and I don't even know where to START to find the answer. The only thing I can think of that marks the point between "PythonWin works fine" and "PythonWin hardly every works fine" was that I changed the size of my Virtual Paging file, noticing that it was too small (I currently have a P4 with 1G of RAM). I tried returning it to its original (smaller) size, but it didn't fix the problems. The first time I noticed it, I was using PythonWin and then right-clicked on My Computer to use "Explore". Instead of the usual full listing (approx 10 items), I got a mini-listing of 4 items. Then, after clicking "Explore", I either don't get a new window at all OR I get a strange file explorer that won't let me look at files, won't let me copy files, etc. The "mini-lising" thing also happens if I click the "Start" button while PythonWin is open. Another problem is trying to open another program while PythonWin is running - generally, the program will not start, but I also don't get any kind of error popping up on the screen. My request is just ignored (although I sometimes get a "system beep".) If I already have other programs open and then open PythonWin, my menu bar might refuse to function. Is it significant that, when the menu bar IS working, the drop-down menu fades in quite slowly, instead of popping up immediately? At the end of this message, I've pasted a screen dump of a message I get when I try to open a file and I've got other apps open (note that I can have very few, non-memory intensive apps open and I still get it). Thanks for any help you can give, - Chris [SCREEN DUMP AFTER I TRY TO OPEN A .PY FILE] File "C:\Python23\Lib\site-packages\pythonwin\pywin\mfc\docview.py", line 91, in CreateNewFrame wnd.LoadFrame(self.GetResourceID(), -1, None, context) # triggers OnCreateClient... win32ui: LoadFrame failed win32ui: CreateNewFrame() virtual handler (>) raised an exception TypeError: PyCTemplate::CreateNewFrame must return a PyCFrameWnd object. From stephen.thorne at gmail.com Mon Jan 10 16:17:54 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Tue, 11 Jan 2005 07:17:54 +1000 Subject: a new Perl/Python a day In-Reply-To: References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: <3e8ca5c805011013175ff50988@mail.gmail.com> On Mon, 10 Jan 2005 18:38:14 GMT, gabriele renzi wrote: > > You're joking, right? > > please consider that the message you all are asking are crossposted to > comp.lang.perl.misc and comp.lang.python, avoid the crossgroup flames :) Yuck. I'm on the python-list at python.org and I was extremely confused until you pointed out the crossposting. Maybe that mail2news gateway should be upgraded to point out crossposted usenet posts... Stephen. From skip at pobox.com Sun Jan 30 22:21:02 2005 From: skip at pobox.com (Skip Montanaro) Date: Sun, 30 Jan 2005 21:21:02 -0600 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> Message-ID: <16893.42014.312134.252550@montanaro.dyndns.org> Nick> I think one of the special things about Python is its batteries Nick> included approach, and a crypto library would seem to be an Nick> obvious battery to install since it doesn't (or needn't) depend on Nick> any other library or application. Obvious for some I suppose (I've never used any). While it might be convenient to not have to distribute some third party library in addition to Python, there is a fundamental problem implementing a crypto algorithm from scratch for inclusion into Python. There is always the problem that the new code has to be more rigorously tested than typical code and new bugs means a new distribution of Python, not just a replacement library. A bug in code that is not security-related generally means something doesn't work and only rarely means a security hole has been opened on the computer. A bug in security-related code more often means the latter as well. I'd much rather trust a widely-disseminated piece of crypto code that is simply wrapped by Python than one that was written expressly written for Python (and that will likely not be exercised much outside the Python community). I realize the sha module is incorporated this way. It has this comment: * This code for the SHA algorithm was noted as public domain. The original * headers are pasted below. * * Several changes have been made to make it more compatible with the * Python environment and desired interface. While I imagine the changes were fairly small, the guys involved are all very smart, and the code is fairly straightforward (little, if any, memory allocation going on), there is still the possibility that a bug lurks in either the incorporated code or in the changes to it. How quickly could the Python community respond if a bug was found and fixed in the public domain SHA code? How much harder would it be for people to adapt if they had to reinstall Python instead of just an external library? Skip From jpmieville at bluewin.ch Tue Jan 18 15:55:48 2005 From: jpmieville at bluewin.ch (jean-paul) Date: 18 Jan 2005 12:55:48 -0800 Subject: Excel module for Python In-Reply-To: References: <87brbpdqct.fsf@andreasen.org> Message-ID: <1106081748.579677.222140@f14g2000cwb.googlegroups.com> I generate a lot pseudo excel file. Just write row by row on file and separate every cell of a row by a tab and put an .xls extension on the file name. When you double click. It opens directly EXCEL and you have directly the column and the row. It is easier than the CSV or SYLK files. If you want to format it automatically you can either define a VBA macro or use python com. Cheers, Jean-Paul From apardon at forel.vub.ac.be Tue Jan 11 03:22:30 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 11 Jan 2005 08:22:30 GMT Subject: tuples vs lists References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dfe2a6$0$22729$636a15ce@news.free.fr> <41e2e8cf$0$5744$626a14ce@news.free.fr> Message-ID: Op 2005-01-10, Bruno Desthuilliers schreef : > Antoon Pardon a ?crit : >> Op 2005-01-08, Bruno Desthuilliers schreef : >> >>>worzel a ?crit : >>> >>>>I get what the difference is between a tuple and a list, but why would I >>>>ever care about the tuple's immuutability? >>> >>>Because, from a purely pratical POV, only an immutable object can be >>>used as kay in a dict. > > s/kay/key/ > >> This is not true. > > Chapter and verse, please ? I don't need chapter and verse. I have already used mutable objects as keys and it works just fine. >>> class hlst(list): >>> >>> def __hash__(self): >>> sum = 0 >>> for el in self: >>> sum += hash(el) >>> return sum % 0x37777777 >>> >>> lst = hlst([3,5,7]) >>> lst [3, 5, 7] >>> lst[0] = 12 >>> lst [12, 5, 7] >>> d = {} >>> d[lst] = 4 >> >>>So you can use tuples for 'composed key'. >> >> lists can be so used too. Just provide a hash. > > Please show us an example, and let's see how useful and handy this is > from a "purely practical POV" ?-) It is handy from a pratical point of view when most operations you do on your data are the equivalent of appending, deleting and changing one element. Simulating these with tuples will cost you more than putting a copy of your list in the dictionary as a precaution against accidently mutating a key. -- Antoon Pardon From ovazquez at gmail.SPAM.com Tue Jan 25 00:22:05 2005 From: ovazquez at gmail.SPAM.com (Orlando Vazquez) Date: Tue, 25 Jan 2005 05:22:05 GMT Subject: Retrieving modification time of file class was declared in In-Reply-To: <1106627951.152900.135310@z14g2000cwz.googlegroups.com> References: <1106627951.152900.135310@z14g2000cwz.googlegroups.com> Message-ID: <1IkJd.53158$06.43207@clgrps12> nathan_kent_bullock at yahoo.ca wrote: > Assume I am using a class Foo. I want to find out the modification time > of the file that that class was defined in. How would I go about this? > > If I could find out the name of the file that Foo was defined in then > it is easy, I could use os.path.getmtime(), but I can't even figure > that out. > > I realize that this wouldn't be a completely accurate way to tell the > last time this class was modified because it could inherit info from > other classes, or use functions from other modules that have been > modified, etc. > > Nathan Bullock > Off the top of my head, without having done too much experimentation here's what you could try. Caveat: there may be a more robust/cleaner way of doing this: # Checking the modificationtime of the Thread class in the threading # module >>> import threading >>> import time >>> >>> module_filename = vars()[threading.Thread.__module__].__file__ >>> >>> mtime = os.path.getmtime(module_filename) >>> >>> print time.ctime(mtime) Sun Nov 14 20:29:42 2004 I hope that answer's your question :-) -- Orlando Vazquez From nemesis at nowhere.invalid Wed Jan 19 13:26:38 2005 From: nemesis at nowhere.invalid (Nemesis) Date: Wed, 19 Jan 2005 18:26:38 GMT Subject: [ANN] XPN - X Python Newsreader 0.4.0 released Message-ID: <7k7msc.7m1.ln@orion.homeinvalid> XPN is a multiplatform newsreader written in Python+GTK2. It is unicode compliant and has features like scoring/action rules, configurable attribution lines and random taglines, search facilities and filtered views, import/export newsrc ... You can find it on: http://xpn.altervista.org/index-en.html or http://sf.net/projects/xpn I'd really appreciate every type of feedback. Changes in this release: * v0.4.0: added off-line reading. Now you can download the whole bodies, or mark some article and download their bodies. * v0.4.0: added Keep Article and Watch/Ignore SubThread * v0.4.0: added actions rule, now you can !keep, !watch, !ignore (and so on) your article through rules * v0.4.0: now XPN stores the position and the size of Main Window and Edit Window * v0.4.0: now you can customize the charsets list XPN use to encode your outgoing articles * v0.4.0: improved speed when loading groups list in Groups Window. * v0.4.0: fixed a bug in the binary version that caused a crash trying to subscribe a group * v0.4.0: added Oriental Charsets support (thanks to Python2.4) * v0.4.0: added Global Search, you can search the whole groups and put the results in a virtual group * v0.4.0: added filtered views * v0.4.0: moved to GTK2.4 and Python2.4 * v0.4.0: added a TraceBack viewer and an error logger * v0.4.0: reorganized some menus * v0.4.0: now the background color is changed also on Groups Pane and Headers pane * v0.4.0: added a lot of little features/enhancements * v0.4.0: fixed a lot of bugs -- I'm not a complete idiot - several parts are missing. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From roy at panix.com Sat Jan 8 00:19:08 2005 From: roy at panix.com (Roy Smith) Date: Sat, 08 Jan 2005 00:19:08 -0500 Subject: how to extract columns like awk $1 $5 References: <487rklcxbidr$.gwsa68us9f3a.dlg@40tude.net> Message-ID: Dan Valentine wrote: > On Fri, 07 Jan 2005 12:15:48 -0500, Anand S Bisen wrote: > > > Is there a simple way to extract words speerated by a space in python > > the way i do it in awk '{print $4 $5}' . I am sure there should be some > > but i dont know it. > > i guess it depends on how faithfully you want to reproduce awk's behavior > and options. > > as several people have mentioned, strings have the split() method for > simple tokenization, but blindly indexing into the resulting sequence > can give you an out-of-range exception. out of range indexes are no > problem for awk; it would just return an empty string without complaint. It's pretty easy to create a list type which has awk-ish behavior: class awkList (list): def __getitem__ (self, key): try: return list.__getitem__ (self, key) except IndexError: return "" l = awkList ("foo bar baz".split()) print "l[0] = ", repr (l[0]) print "l[5] = ", repr (l[5]) ----------- Roy-Smiths-Computer:play$ ./awk.py l[0] = 'foo' l[5] = '' Hmmm. There's something going on here I don't understand. The ref manual (3.3.5 Emulating container types) says for __getitem__(), "Note: for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence." I expected my little demo class to therefore break for loops, but they seem to work fine: >>> import awk >>> l = awk.awkList ("foo bar baz".split()) >>> l ['foo', 'bar', 'baz'] >>> for i in l: ... print i ... foo bar baz >>> l[5] '' Given that I've caught the IndexError, I'm not sure how that's working. From ods at strana.ru Wed Jan 12 03:23:43 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Wed, 12 Jan 2005 11:23:43 +0300 Subject: os.spawnv & stdin trouble In-Reply-To: <20050111180707.304A41F9268C@mwinf0103.wanadoo.fr> References: <20050111200526.1bd60ebd.ods@strana.ru> <20050111180707.304A41F9268C@mwinf0103.wanadoo.fr> Message-ID: <20050112112343.60ce9e3c.ods@strana.ru> On Tue, 11 Jan 2005 19:08:01 +0100 "Jelle Feringa // EZCT / Paris" wrote: > Using the subprocess module, but still not making any real progress... > I'm trying to make the examples given in the __doc__ work, without any > success I'm afraid, have you had more luck with it? [...] > p = Popen("xform" + " -t 0 8 0 wallo.rad", stdout=PIPE, > shell=True).communicate()[0] > p.stdout > > p = Popen("dir" + " /w", stdout=PIPE, shell=True).communicate()[0] > p.stdout If you want passing parameters via shell (shell=True), than just use os.system. Nevertheless below is correct example of subprocess usage with stdout redirected to file: out_fp = open('wall0.TRANS.rad', 'wb') subprocess.call(['c:\\Radiance\\bin\\xform.exe', '-t', '0', '8', '0', 'wallo.rad'], stdout=out_fp) -- Denis S. Otkidach http://www.python.ru/ [ru] From rittersporn at gmail.com Fri Jan 7 05:47:08 2005 From: rittersporn at gmail.com (rittersporn at gmail.com) Date: 7 Jan 2005 02:47:08 -0800 Subject: Pre/Postconditions with decorators In-Reply-To: References: Message-ID: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> Hi Stephen I have not read anything about the "framehack lambda replacement" yet, but I do compile the pre- and postconditions. Syntax erros e.g. will be raised if the module is compiled. Although I must admit that your code snippets look more like compiled code ;-) Hi Robert thanks for the link to the Ian Bicking blog. Hi George, it would be nice to see how you have tackled the task. Maybe we will have a checker module in Python one day... ;-) Well, I have attached my latest attempt to model pre/postconditions (without "framehack lambda replacement") which does wrap the original function with a class which delegates attribute access. Now I can split my "condition" into pre- and postcondition and the "tracer" prints the original function name. I have also fixed a bug with keyword arguments. Major difference compared to other examples is probably only that I can refer to function arguments by name: class Delegate(object): def __init__(self,function): self.function=function def __getattr__(self,key): return getattr(self.function,key) def condition(pretext,posttext=""): precode=compile(pretext or "True","","eval") postcode=compile(posttext or "True","","eval") # function -> decorated(function) def decorate_condition(function): argcount=function.func_code.co_argcount var=function.func_code.co_varnames[0:argcount] class EvalCond(Delegate): def __call__(self,*args,**kargs): # FIXME: check if "var" always contains ordered list of arguments # map arguments and args_seq=[(argname,args[pos]) for pos,argname in \ enumerate(var) if (argname not in kargs)] # key-arguments to value kargs_seq=[(k,v) for k,v in kargs.iteritems()] environment=args_seq+kargs_seq # precondition assert eval(precode,{},dict(environment)),pretext tmp=function(*args,**kargs) environment2=environment+[('result',tmp)] # postcondition assert eval(postcode,{},dict(environment2)),posttext return tmp return EvalCond(function) return decorate_condition def trace(function): class Trace(Delegate): def __call__(self,*args,**kargs): print "enter function %s with " % \ self.function.func_name,args,kargs result=self.function(*args,**kargs) print "leave function %s with " % \ self.function.func_name,args,kargs return result return Trace(function) def precondition(prgtext): return condition(prgtext) def postcondition(prgtext): return condition("",prgtext) @precondition("number>0 and number<2") @postcondition("result>=0") def sqrt(number): import math return math.sqrt(number) @trace @precondition("len(seq)>0 is not None and str(more)") @postcondition("sum(seq)==result") def my_sum(seq,more): tmp=0 for element in seq: tmp+=element return tmp print sqrt(1.2) print my_sum([1,2,3],more="more") From tjreedy at udel.edu Wed Jan 12 19:34:48 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Jan 2005 19:34:48 -0500 Subject: Why would I get a TypeEror? References: Message-ID: "Peter Hansen" wrote in message news:XOOdnSCB9NmJ-HjcRVn-2w at powergate.ca... > What did you expect the "length" of the integer 3 to be? Perhaps 2 (bits in a minimal binary representation). I once, for maybe a minute, considered proposing this as an overloaded meaning of len, but realized that that would more often mask errors than save time. If case bits(i) is what the OP wants: def bits(i): i = abs(i) b = 0 while i: i >>= 1 b += 1 return b Terry J. Reedy From paschott at no.yahoo.spamm.com Wed Jan 19 14:34:13 2005 From: paschott at no.yahoo.spamm.com (Peter A. Schott) Date: Wed, 19 Jan 2005 19:34:13 GMT Subject: FTPLIB & FTPS or SFTP? Message-ID: <9b9tu0te197u3bmheldg2hsvkbtuivlov6@4ax.com> Does the ftplib support SFTP or FTPS? Is that part of a different module? We have a handful of partners who use FTPS or SFTP and I need to pull/push files to/from them. Thank you for all of your help. -Pete Schott From paschott at no.worldnet.spamm.att.net Mon Jan 17 15:06:31 2005 From: paschott at no.worldnet.spamm.att.net (Peter A. Schott) Date: Mon, 17 Jan 2005 20:06:31 GMT Subject: python to mssql References: <1lmwxbtst8x8x$.10hwcoinem3cs.dlg@40tude.net> Message-ID: <941ou05t4he374tit92pomsj0kf56h8iei@4ax.com> Brane, What are you wanting to know specifically? What is your client machine running? I've started using the Win32 modules to connect using ADODB and that works for me on Windows XP (hopefully 2003 as well, but not tested yet). I pulled those samples from someplace on the net using Google and adapted a couple of times until they worked the way I needed them to. I looked at pymssql and it didn't seem to be updated recently where I felt comfortable. Just my opinion, it may be the best out there. I guess knowing more about what you're looking for would help. -Pete Schott Brane wrote: > can someone please give me some info regarding subject > please advice > regards > brane From theaney at cablespeed.com Mon Jan 17 09:58:18 2005 From: theaney at cablespeed.com (Tim Heaney) Date: Mon, 17 Jan 2005 09:58:18 -0500 Subject: Native widgets for Python References: <41EBC7F3.5050807@web.de> Message-ID: <87oefom7at.fsf@mrbun.watterson> Stephen Thorne writes: > > there's someone writing 'dabo', which is apparently "wxpython but > more python". It looks like dabo uses, not replaces, wxPython http://dabodev.com/about From simoninusa2001 at yahoo.co.uk Wed Jan 19 18:14:06 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 19 Jan 2005 15:14:06 -0800 Subject: Python and Excel References: Message-ID: <1106176446.569712.316040@c13g2000cwb.googlegroups.com> Hmm, sounds interesting, I've always resorted to using CSV (or even HTML!) when exporting to Excel. As far as how to open it up, have a look at creating a project on www.sourceforge.net or just zip it up and bung it on your own website if you have one. I've got the feeling there are also Python-specific repositories too. Or you could just paste the code into a blog or something free like Livejournal. Good luck on the France thing, that's where my folks live now (I'm an Englishman who retreated to the US!) From merkosh at hadiko.de Sun Jan 2 17:57:16 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Sun, 02 Jan 2005 23:57:16 +0100 Subject: UserDict deprecated References: Message-ID: Saturday 01 January 2005 23:34 pm Steven Bethard wrote: [...] > If you implemented the file interface functions yourself, why do you > want to inherit from file? [...] > But just inheriting from list won't make this work, will it? Don't you > want to do something like: [...] Right. I guess the thing I was looking for is an interface specification as in Java's Interfaces. I could write an abstract base class, where all methods just raise NotImplemented(). I don't know wether this is a good idea after all...:/ Thanks Uwe From exarkun at divmod.com Thu Jan 6 10:54:06 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 06 Jan 2005 15:54:06 GMT Subject: Embedding a restricted python interpreter In-Reply-To: <7xbrc2a7zq.fsf@ruckus.brouhaha.com> Message-ID: <20050106155406.25734.561189532.divmod.quotient.3824@ohm> On 06 Jan 2005 07:32:25 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: >Jp Calderone writes: > > A Python sandbox would be useful, but the hosting provider's excuse > > for not allowing you to use mod_python is completely bogus. All the > > necessary security tools for that situation are provided by the > > platform in the form of process and user separation. > > But mod_python is an apache module and runs in the same apache process > with other users' scripts. I am uncertain as to how this differs from mod_php (the alternative discussed in the OP's story). I've been away from PHP for a while, so perhaps mod_php has gained some features of which I am unaware? Jp > -- > http://mail.python.org/mailman/listinfo/python-list > From ville at spammers.com Fri Jan 28 03:06:29 2005 From: ville at spammers.com (Ville Vainio) Date: 28 Jan 2005 10:06:29 +0200 Subject: IPython Article on O'Reilly's ONLamp site References: Message-ID: >>>>> "Jeremy" == Jeremy Jones writes: Jeremy> feedback is welcome. Regardless of what you may think of Jeremy> the article, I hope it encourages everyone to at least try Jeremy> out IPython. IPython has become an indispensible tool in Jeremy> my toolbox. I cannot say enough great things about it. I've said this before, but I'd just like to add that IPython (with the pysh profile) makes a damn fine command prompt for Windows. The loss of job control is not a problem there, because it never was there in the first place. Even if you never use the underlying Python functionality, you can enjoy the Bash-like filename completion (the only way to fly - the windows "4dos-style" completion doesn't cut it for me). I've never really trusted Bash (from cygwin) in Windows, it has always felt very alien. Just install ipython and the "unxutils" package, and windows command prompt suddenly becomes usable. What is essential for me (because I deal with complex source trees) is the persistent "bookmark functionality" for directories (yes, Fernando, this is a shameless plug ;-): Lines starting w/ @POR078 are commands typed by the user. ------- ipython session ------------- @POR078[prj]|22> %bookmark? Manage IPython's bookmark system. %bookmark - set bookmark to current dir %bookmark - set bookmark to %bookmark -l - list all bookmarks %bookmark -d - remove bookmark %bookmark -r - remove all bookmarks You can later on access a bookmarked folder with: %cd -b or simply '%cd ' if there is no directory called AND there is such a bookmark defined. Your bookmarks persist through IPython sessions, but they are associated with each profile. @POR078[testrunner]|24> %bookmark tr @POR078[testrunner]|25> cd /prj/SyncML/doc/ @POR078[doc]|26> %bookmark smldoc @POR078[doc]|27> Exit (IPython exits, I start a new session) @POR078[environmentswitch]|1> cd tr (bookmark:tr) -> C:\prj\testrunner @POR078[testrunner]|3> cd smldoc (bookmark:smldoc) -> C:\prj\SyncML\doc @POR078[doc]|4> -- Ville Vainio http://tinyurl.com/2prnb From aisaac0 at verizon.net Fri Jan 28 13:00:37 2005 From: aisaac0 at verizon.net (David Isaac) Date: Fri, 28 Jan 2005 18:00:37 GMT Subject: extract files from MS-TNEF attachments Message-ID: <95vKd.152$wM.78@trnddc05> I'm looking for Python code to extract files from MS-TNEF attachments. (I'm aware of the C code at http://tnef.sourceforge.net/ ) Thanks, Alan Isaac From rmemmons at member.fsf.org Mon Jan 3 20:56:10 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Mon, 03 Jan 2005 19:56:10 -0600 Subject: How do I make Windows Application with Python ? References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> Message-ID: > Well, I programmed a little in MS Visual Studio 2003, and there you have > Console apllication and Windows application (among others). Windows one is > with buttons and other gadgets. So, I want to make applications that > doesn't open console to display result, I want to display it into the > message box. Also, I want to use that application on the computers where > Python isn't installed First there is a good book: Python Prgoramming on Win32, by Hammond & Robinson, O'Reilly is the publisher. I believe one of these guys wrote the python windows extension. Second, on MS Windows you need two python installs, the basic python install, and the python for windows extension (also sometimes call win32all or something like that). These two together give you a great basic set to work with. I've done MS Windows programming with these and they work great. With the win32 extension module -- you can use ActiveX, you can use the standard MS Windows calls, and it also defines a python intepretor mode where it does not open the console window if you name the main program module as .pyw (as opposed to .py). It does other things too. This is all discribed in the book I recommended. Note also, if you don't want to see the console window -- even without use .pyw files, you can tell the launcher to open the console window minimized -- not great but it does work. I believe also if you want to use MS Visual Studio -- Active State sells python programming tools that plug into MS Visual Studio if you want to do that. I've not tried these so I don't know how they work or if they are any good. It's also possible to program on MS Windows so your app is protable to Linux and other systems. You can use Tkinter or wxWidgets (was called wxWindows -- until maybe MS made them change it) to do that. I've used Tkinter before for example, though I think wxWidgets is probalby more of the wave of the future. Others may know. If you want to run the program on other computers not having python, you have two basic choices. One -- what I do, I just made up a python setup CD that installs python, python windows extensions, and the basic libraries I usually use so that it's easy to setup a python environment on other systems. Then I install my code. The other alternative is to use one of the tools that wraps up a python program with the needed executables. Some of these are py2exe, cx-freeze, McMillan Installer, Fractel Mountains, StarKits, UPX, and InnoSetup. I've not used any of these -- and so this list may not be correct/complete. Others may know what's best. There are also some compilers too - pyrex, pysco starkiller, and pypy. Again, I've not used any of these and this is just from some cryptic notes I've taken. So ask others for input. Probabably you want one of the installers rather than the compilers because python compilers are kind of new, but that's just a guess. Hope that helps. Rob From PPNTWIMBXFFC at spammotel.com Mon Jan 31 03:58:54 2005 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Mon, 31 Jan 2005 09:58:54 +0100 Subject: COM on a network drive can't find pywintypes23.dll Message-ID: Hi I have installed Python (2.3.4) on a shared network drive. I use it to run a bunch of application on the workstations (Win2K). Now I am running into the first problem ever. I try to use COM to generate a word-file. It runs fine on my machine (Python installed locally). When I deploy it and start the app on another workstation from the fileserver - it runs but as soon as it comes to the COM part it exits saying: The procedure entry point ?PyWinObject_AsDEVMODE@@YAHPAU_object@@PAPAU_devicemodeA@@H at Z could not be located in the dynamic link library pywintypes23.dll Heck... I copied the files: pythoncom23.dll pywintypes23.dll to about "1000" locations to make it run (Application's dir, Workstation's System Dirs, Fileserver's Python main and bin dir, ...). I tried setting the path on the workstations. But nothing seems to solve the problem. Do you have any proposals how to solve this problem? Thanks in advance, Marco From ncoghlan at iinet.net.au Tue Jan 11 05:24:21 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 11 Jan 2005 20:24:21 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: <34hmnuF4cvj0uU1@individual.net> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> <34hmnuF4cvj0uU1@individual.net> Message-ID: <41E3A955.6030900@iinet.net.au> Andrey Tatarinov wrote: > afair you told yourself that > > var = where: > > > translates to: > > def unique_name(): > > return > var = unique_name() > > in this case class gets unique_name() function? is it that bad? No, I wasn't thinking clearly and saw problems that weren't there. However, you're right that the semantic definition should include unbinding the unique name after the statement finishes. E.g. for assignments: def unique_name(): return = unique_name() del unique_name > anyway I'd prefer to change semantics deeper. adding new statement-only > scope and adding our suite-definitions there. A new scope essentially *is* a nested function :) My main purpose with the nested function equivalent is just to make the intended semantics clear - whether an implementation actually _does_ things that way is immaterial. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From apardon at forel.vub.ac.be Thu Jan 13 08:26:05 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 13:26:05 GMT Subject: Unclear On Class Variables References: Message-ID: Op 2005-01-13, Simon Brunning schreef : > On 13 Jan 2005 07:18:26 EST, Tim Daneliuk wrote: >> I am a bit confused. I was under the impression that: >> >> class foo(object): >> x = 0 >> y = 1 >> >> means that x and y are variables shared by all instances of a class. >> But when I run this against two instances of foo, and set the values >> of x and y, they are indeed unique to the *instance* rather than the >> class. > > I can see why you might think that: > >>>> class Spam(object): > ... eggs = 4 > ... >>>> spam = Spam() >>>> spam2 = Spam() >>>> spam.eggs > 4 >>>> spam2.eggs > 4 >>>> spam.eggs = 2 >>>> spam.eggs > 2 >>>> spam2.eggs > 4 > > But you are being mislead by the fact that integers are immutable. > 'spam.eggs = 2' is *creating* an instance member - there wasn't one > before. Have a look at what happens with a mutable object: > >>>> class Spam(object): > ... eggs = [3] > ... >>>> spam = Spam() >>>> spam2 = Spam() >>>> spam.eggs > [3] >>>> spam2.eggs > [3] >>>> spam.eggs.append(5) >>>> spam.eggs > [3, 5] >>>> spam2.eggs > [3, 5] > Well I find this a confusing behaviour on python's part. The fact that instance.field can mean something different, depending on where in a statement you find it, makes the behaviour inconsistent. I know people in general here are against declarations, but declarations could IMO provide more consistency here and thus more obvious behaviour. -- Antoon Pardon From fperez.net at gmail.com Sun Jan 23 19:47:37 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Sun, 23 Jan 2005 17:47:37 -0700 Subject: Installer made with bdist_wininst segfaulting... Message-ID: Hi all, I am seeking advice/help from those with more win32 experience than myself. I am trying to build a proper win32 installer for IPython, after a user did most of the hard work. For the most part, it's working very well, but I am running into a nasty problem, which took me a few hours to finally understand. This smells to me like a python bug, but I could be wrong. Much googling didn't turn up anything relevant. Here is a brief summary: if the installer file is run from a windows drive which is different from the one where python resides (and hence where ipython will end up), the installer segfaults. No traceback, nothing, just a segfault (well, one of those Windows dialogs asking me to send a binary traceback to Redmond, but not a proper Python traceback). The win32 laptop where I'm testing, for example, has user stuff in the D: drive, and Python installed in C:\Python23. I was running the installer from D:\Temp, and getting this segfault. If I run it from C:\Temp, it works perfectly. I have put the installer here, in case someone else is willing to test this on a different machine: http://amath.colorado.edu/faculty/fperez/tmp/ipython-0.6.9.win32.exe I have narrowed down to a single os.chdir() call in the post-install script. The code is simply: # Lookup path to common startmenu ... d = get_special_folder_path('CSIDL_COMMON_PROGRAMS') + r'\IPython' # Create IPython entry ... if not os.path.isdir(d): os.mkdir(d) directory_created(d) # XXX - The binary installer segfaults here if it was being run from a # different drive than it is trying to change to. In my case, I have # everything in D:, but Python lives in C:, so the chdir() call is going # from D: to C:, and this is crashing things. print "Current dir:",os.getcwd() # dbg print "Going to :",d # dbg os.chdir(d) By forcing a return before the chdir() call, I was able to see that when the source/destination are both on C:, it's all OK, but when the source is in D: and the destination in C:, I get the crash. This is really frustrating, since I'd like to be able to stop distributing .zip sources to Windows users, and would like to be able to provide a proper installer/deinstaller. But having this thing crash if two drives are involved is just not acceptable. Any help from the win32 gurus out there would be much appreciated. For reference, the binary installer linked above was created on a Fedora3 box running pyhton 2.3.4, with the command line: ./setup.py bdist_wininst --install-script=ipython_win_post_install.py Cheers, f From MrJean1 at gmail.com Tue Jan 11 20:48:00 2005 From: MrJean1 at gmail.com (python) Date: 11 Jan 2005 17:48:00 -0800 Subject: readline, rlcompleter In-Reply-To: <1105429869.770262.14360@c13g2000cwb.googlegroups.com> References: <1105429869.770262.14360@c13g2000cwb.googlegroups.com> Message-ID: <1105494480.002007.68390@c13g2000cwb.googlegroups.com> There is a pretty complete (no pun intended) example in the standard cmd module Check file cmd.py in your Python installation .../lib/pythonX.Y/cmd.py, specifically the methods Cmd.preloop() and Cmd.complete(). Another, more elaborate example is in PySH at /Jean Brouwers PS) A version of readline for Windows is here michele.simionato at gmail.com wrote: > This a case where the documentation is lacking. The standard library > documentation > (http://www.python.org/dev/doc/devel/lib/module-rlcompleter.html) gives > this example > try: > import readline > except ImportError: > print "Module readline not available." > else: > import rlcompleter > readline.parse_and_bind("tab: complete") > > but I don't find a list of recognized key bindings. For instance, can I > would like to bind shift-tab to rlcompleter, is that possible? Can I use > function keys? I did various attempt, but I did not succed :-( > Is there any readline-guru here with some good pointers? > Michele Simionato From jbperez808 at wahoo.com Mon Jan 17 22:37:25 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Tue, 18 Jan 2005 11:37:25 +0800 Subject: huygens lands on titan In-Reply-To: <1105704719.374905.239790@f14g2000cwb.googlegroups.com> References: <1105704719.374905.239790@f14g2000cwb.googlegroups.com> Message-ID: <353ejaF4hc5goU1@individual.net> I sure as hell bet it didn't too. Fuzzyman wrote: > John Thingstad wrote: > >>-- >>huygens lands on titan >>Using M2, Opera's revolutionary e-mail client: > > http://www.opera.com/m2/ > > I bet it didn't....... > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml > From invalidemail at aerojockey.com Sat Jan 8 01:15:44 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 7 Jan 2005 22:15:44 -0800 Subject: sorting on keys in a list of dicts In-Reply-To: <10tr9ejf05pv660@corp.supernews.com> References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: <1105164944.059936.80960@c13g2000cwb.googlegroups.com> Jeff Shannon wrote: > Jp Calderone wrote: > > > L2 = [(d[key], i, d) for (i, d) in enumerate(L)] > > L2.sort() > > L = [d for (v, i, d) in L2] > > Out of curiosity, any reason that you're including the index? I'd > have expected to just do > > L2 = [(d[key], d) for d in L] > L2.sort() > L = [d for (v, d) in L2] Suppose L is a list of objects that can't be compared (for example, they are dicts that have complex number items) and the keys are not all distinct. If sort tries to compare two equal keys, it'll proceed to compare the objects themselves, which could throw an exception. Stick the index in there, and that possibility is gone. -- CARL BANKS From nick at craig-wood.com Mon Jan 31 08:30:10 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 31 Jan 2005 13:30:10 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> <7xmzuqqn5s.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Actually and surprisingly, that's not really true. Crypto algorithms > are pretty straightforward, so if you examine the code and check that > it passes a bunch of test vectors, you can be pretty sure it's > correct. I was going to write pretty much the same thing. If a security flaw is found in a block cipher (say) it won't be because it has a buffer overflow etc, it will be because the algorithm is flawed. You can't patch up crypto algorithms, you have to throw them away and start again (you can't have two incompatible versions of DES for instance). -- Nick Craig-Wood -- http://www.craig-wood.com/nick From pythongnome at hotmail.com Tue Jan 11 19:56:34 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 12 Jan 2005 00:56:34 GMT Subject: Game programming in Python In-Reply-To: References: Message-ID: <6B_Ed.4796$C52.3460@newsread2.news.atl.earthlink.net> Mike C. Fletcher wrote: > Lucas Raab wrote: > >> Baza wrote: >> >>> I'm looking for any books or on-line resources on game programming using >>> Python. Does anyone have any advice? >>> -- Computer says, 'no' >>> >>> >> >> www.panda3d.com, www.pygame.org, www.blender3d.com ... > > > http://www.vrplumber.com/py3d.py?category=game > > HTH, > Mike > > ________________________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://www.vrplumber.com > http://blog.vrplumber.com > My apologies. :) From simon.brunning at gmail.com Tue Jan 25 05:28:02 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 25 Jan 2005 10:28:02 +0000 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) In-Reply-To: <1106590633.15475.3.camel@localhost> References: <1106590633.15475.3.camel@localhost> Message-ID: <8c7f10c605012502281d9c9b29@mail.gmail.com> On Mon, 24 Jan 2005 12:17:13 -0600, Philippe C. Martin wrote: > > I use "__"for private variables because I must have read on net it was > the way to do so - yet this seems to have changed - thanks: > > http://www.network-theory.co.uk/docs/pytut/tut_77.html Nope, that's still the right way to make a member 'really' private. Stephen was pointing out a very common Python idiom - "private by convention", and suggesting that using it would be more appropriate. A member with a single preceding underscore is private by convention. That is to say, there is no mechanism in place to prevent clients of the class accessing these members, but they should consider themselves to have been warned that they do so at their own risk. If you take the back off the radio, the warranty is void. ;-) I (and by inference Stephen) feel that this is a more "Pythonic" approach. Give the programmer the information that they need, but don't try to stop them from doing what they need to do. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From jerf at jerf.org Wed Jan 5 23:26:51 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 05 Jan 2005 23:26:51 -0500 Subject: Concepts RE: Python evolution: Unease References: <20050105002302.542768387.EP@zomething.com> Message-ID: On Wed, 05 Jan 2005 12:15:29 +0300, Roman Suzi wrote: > As for concepts, they are from Generic Programming (by Musser and > Stepanov) and I feel that Python is in position to implement them to the > fullest extent. And IMHO it will be nicer than just Java-like interfaces > or Eiffel's contract approach. > > I can try to write a PEP "Generic Programming Concepts". I'd like to see this. As corey says, sooner rather than later is good. Release Early, Release Often :-) I'm still skeptical on how *most* Generic Programming concepts are an improvement, but while I don't know much about how "concepts" formally work I know I like the name... and that's a start. I'd love to see my skepticism proved wrong. From fperez.net at gmail.com Tue Jan 25 12:49:39 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Tue, 25 Jan 2005 10:49:39 -0700 Subject: Installer made with bdist_wininst segfaulting... References: Message-ID: Thomas Heller wrote: > There are a couple of known bugs in bdist_wininst, and you just reported > another one. All these bugs are related to using the > post_install_script, and show up when either (thats what I currently > remember): > > - the installer is run from a readonly location, > - the installer is run from a different drive (as you reported) > - the installer installs for Python 2.4 > > I will fix these issues in Python 2.3.5, which will probably be out as a > release candidate this week, and in Python 2.4.1. One more small thing I just remembered... In my testing, I noticed the installer, even when it succeeds, leaves little temp files littering the root directory of the drive it was run from. These seem to be the files where stdout is captured, but they should be explicitly removed at the end. Cheers, f From rbt at athop1.ath.vt.edu Mon Jan 24 10:26:33 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 24 Jan 2005 10:26:33 -0500 Subject: urllib2 and proxy question In-Reply-To: <1106575675.520424.155310@f14g2000cwb.googlegroups.com> References: <1106575675.520424.155310@f14g2000cwb.googlegroups.com> Message-ID: Fuzzyman wrote: > urllib2 (under windows) will auto-detect your proxy settings and use > those. > > Normally that's a good thing (I guess), except when it's not ! > > How do I switch off this behaviour ? I'm behind a censoring proxy and > wanting to test things *locally*. IE is set to not use the proxy when > fetching local adresses, but urllib2 ignores that part of the setting > and uses the proxy for everything. > > The only way I can test are changing my IE settings back and forth > every time. Most annoying. > > I can see how to *add* a new proxy to urllib2, but not how to force it > to not use a proxy. I may well be missing something obvious though. > Anyone able to help ? > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml > "Alternatively, the optional proxies argument may be used to explicitly specify proxies. It must be a dictionary mapping scheme names to proxy URLs, where an empty dictionary causes no proxies to be used" # Don't use any proxies filehandle = urllib.urlopen(some_url, proxies={}) From wodefey at iun.edu Mon Jan 17 10:21:02 2005 From: wodefey at iun.edu (Bill) Date: 17 Jan 2005 07:21:02 -0800 Subject: Install Python 2.4 on Fedora 3 Core Message-ID: <1105975262.047782.6010@z14g2000cwz.googlegroups.com> I have less than a week experience on linux, so I am a new newbie. Python 2.3 came preinstalled. I installed version 2.4. All seemed to go well except it installed to usr/local? 1. Was it wrong to install when logged in as 'root'? Does it make a difference? 2. I looked in the package editor and there was no way to uninstall 2.3? Should I? If so, how can I? If not,what are the problems, if any, of having both. Thank you for your help. From ncoghlan at iinet.net.au Tue Jan 18 04:10:01 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 18 Jan 2005 19:10:01 +1000 Subject: generator expressions: performance anomaly? In-Reply-To: References: Message-ID: <41ECD269.3050207@iinet.net.au> Raymond Hettinger wrote: > [Delaney, Timothy C] > >>Nick's other suggestion - that genexps propagate __len__ - might >>still be interesting. Of course, it would only be applicable for >>unconditional genexps(i.e. no if clause). > > Length transparency for iterators is not as general as one would expect. I once > spent a good deal of effort exploring where it made sense, and I was surprised > to find that it only rarely works out. Length transparency is an unexpectedly > thorny subject with many dead-ends which precludes a fully general solution such > as that proposed by Nick. > > For a recap of my research, see the docstring for Lib/test/test_iterlen.py . """The situation slightly more involved whenever an object allows length mutation during iteration. """ Ouch. Nice understatement. It's rather unfortunate that we can't make use of the length information even when the source *doesn't* mutate, though. I'll have to think some more to see if I can come up with any concrete ideas for you to shoot down :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From adam at cognitcorp.com Tue Jan 4 22:38:13 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Tue, 04 Jan 2005 22:38:13 -0500 Subject: what is lambda used for in real code? In-Reply-To: References: <1104531721.3724.18.camel@localhost.localdomain> Message-ID: <1104894177.5050.28.camel@localhost.localdomain> On Fri, 2004-12-31 at 22:09, Terry Reedy wrote: > "Adam DePrince" wrote in message > news:1104531721.3724.18.camel at localhost.localdomain... > > In sort, we must preserve the ability to create an anonymous function > > simply because we can do so for every other object type, and functions > > are not special enough to permit this special case. > > Please show me how to create an anonymous type, module, or class, You can create anonymous instances of classes and types. The actual type, module or class .. well, that is another special case that isn't special enough ... but that is somewhat beyond the scope of this thread. I've seen a number of responses similar to this; I feel that the lack of anonymous classes, types and modules are flaws with the language that should be fixed, not used to justify introducing another flaw. It is my humble opinion that a good language design is completely orthogonal. The curse of anonymity in the language can be "cured" at a management/specification level by requiring the use of the name space. The alternative, the removal of anonymous functions, adds a "special case" and dumbs down the language. Personally, I'd like to see Python evolve in the direction of ML instead of Visual Basic. There are actually times when I've wanted anonymous classes. Very often, I've written code that accepts as a parameter, a class. Of course, the code instantiates this class with the expectation that it provides a particular interface. And sometimes, it would have been nice to, in a single invocation of such a function, change a single method of the class before passing it. In a sense, I've written code for which a class or type equivalent to a lambda would actually have been really nice. > especially with an expression. Number, sequences, and dicts have easily > printable values. Functions, like classes and module do not*, so So do lambdas, classes, types, etc. And I've encountered a good many lists and dicts that don't qualify as "easily printable." Quite frankly, it seems a bit capricious to *require* the use of the name space on the basis of the similarity between the repr of the object and line noise. And here is a counter example ... this def fits nicely on one line: Python 2.4 (#1, Dec 27 2004, 15:19:19) [GCC 3.4.1] on linux2 >>> def a( b ): return b+1 ... >>> a( 2 ) 3 >>> > definition names act as a standin and as a pointer to the source code that > produced the object. If functions are not special relative to classes and > modules, which is the grouping they belong with, then we should get rid of > lambda ;-) > > *Now that memory is 'cheap', someone recently proposed that code objects > (and hence functions) get .source attribute. Maybe, someday... The .source attribute could be free from a memory consumption perspective if the source -> byte code conversion is reversible. > > Terry J. Reedy Adam DePrince From sjmachin at lexicon.net Thu Jan 20 23:00:17 2005 From: sjmachin at lexicon.net (John Machin) Date: 20 Jan 2005 20:00:17 -0800 Subject: Unbinding multiple variables In-Reply-To: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> Message-ID: <1106280017.761035.82490@z14g2000cwz.googlegroups.com> Johnny Lin wrote: > Hi! > > Is there a way to automate the unbinding of multiple variables? Say I > have a list of the names of all variables in the current scope via > dir(). Is there a command using del or something like that that will > iterate the list and unbind each of the variables? Yes. It's called "return". From reinhold-birkenfeld-nospam at wolke7.net Sun Jan 9 16:38:43 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 09 Jan 2005 22:38:43 +0100 Subject: else condition in list comprehension In-Reply-To: References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: <34dmj3F4aj2t2U1@individual.net> Matteo Dell'Amico wrote: > Luis M. Gonzalez wrote: >> Hi there, >> >> I'd like to know if there is a way to add and else condition into a >> list comprehension. I'm sure that I read somewhere an easy way to do >> it, but I forgot it and now I can't find it... >> >> for example: >> z=[i+2 for i in range(10) if i%2==0] >> what if I want i to be "i-2" if i%2 is not equal to 0? > > You could use > > [(i-2, i+2)[bool(i%2 == 0)] for i in range(10)] > > or, in a less general but shorter way > > [(i+2, i-2)[i%2] for i in range(10)] > > or even > > [i%2 and i-2 or i+2 for i in range(10)] One should note that the (cond and X or Y) construct only works if X can never produce a false value (such as 0, "", []). In this example, it is okay, but replace 2 with 1 and you will run into trouble for i = 1. Reinhold From johnpote at blueyonder.co.uk Fri Jan 7 08:36:50 2005 From: johnpote at blueyonder.co.uk (John Pote) Date: Fri, 07 Jan 2005 13:36:50 GMT Subject: Python application extending, plugins Message-ID: Hi, Has anyone any thoughts on structuring a program so that it can be extended simply and elegantly by a user who only has a compiled (.pyc) version of the application? I wish to write an application, myApp, that provides a GUI to, amongst other things, a simulator implimented as a class. myApp's simulator may then be extended by more python code to produce what is effectively 'myApp2'. The simulator might then be further extended from myApp2 to myApp3 in a similar manor. Don't think there would be much call, if at all, to go beyond myApp3 level. But who knows! Any thoughts would be appreciated. John Pote From sean_mcilroy at yahoo.com Sat Jan 8 23:40:37 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 8 Jan 2005 20:40:37 -0800 Subject: mysterious buggy behavior Message-ID: While fiddling with a little script I ran into a problem that baffles me completely. Maybe I'm missing something completely obvious, and somebody out there can diagnose the problem at a glance. Anyway, that's the hope. Here's the code (it plays tic tac toe): """ Something goes wrong with the "time saver" section of the function makeMove. The section needs to be there to ensure that the computer makes its move in a reasonable amount of time when it is making the first or the second move. That section of code is so simple that I can't even imagine what could be going wrong with it. """ """ 012 345 678 """ ex,oh,blank = range(3) lines = [(0,3,6),(1,4,7),(2,5,8),(0,1,2),(3,4,5),(6,7,8),(0,4,8),(2,4,6)] def subs(board,player,i): b = board[:] b[i] = player return b def valMove(board): winners = [x for x in (ex,oh) for L in lines if board[L[0]]==board[L[1]]==board[L[2]]==x] if winners: return winners[0]==ex and (+1,None) or (-1,None) if board.count(blank)==0: return (0,None) player = (oh,ex)[board.count(ex)==board.count(oh)] optimal = (min,max)[player==ex] blankIndices = [i for i in range(9) if board[i]==blank] return optimal([(valMove(subs(board,player,i))[0],i) for i in blankIndices]) BOARD = [blank]*9 def clickButton(i): def f(): BOARD[i] = ex (topButtons,midButtons,botButtons)[i//3][i%3]['text'] = 'X' return f def newGame(): BOARD = [blank]*9 for x in topButtons+midButtons+botButtons: x['text'] = '' def makeMove(): i = None ## if i==None: i = valMove(BOARD)[1] BOARD[i] = oh (topButtons,midButtons,botButtons)[i//3][i%3]['text'] = 'O' from Tkinter import * root = Tk() ############################################################### topRow = Frame(master=root) topButtons = [Button(master=topRow,width=1,command=clickButton(i)) for i in range(3)] ############################################################### midRow = Frame(master=root) midButtons = [Button(master=midRow,width=1,command=clickButton(3+i)) for i in range(3)] ############################################################### botRow = Frame(master=root) botButtons = [Button(master=botRow,width=1,command=clickButton(6+i)) for i in range(3)] ############################################################### map(lambda x: x.pack(side=TOP),[topRow,midRow,botRow]) map(lambda x: x.pack(side=LEFT),topButtons + midButtons + botButtons) ############################################################### dummyRow = Frame(master=root) placeHolder = Label(master=dummyRow,text='') dummyRow.pack(side=TOP) placeHolder.pack(side=TOP) ############################################################### ctrlRow = Frame(master=root) computerMoveButton = Button(master=ctrlRow,text='computer move',command=makeMove) newGameButton = Button(master=ctrlRow,text='new game',command=newGame) ctrlRow.pack(side=TOP) computerMoveButton.pack(side=TOP) newGameButton.pack(side=TOP) ############################################################### root.title('tic tac toe') root.mainloop() From fredrik at pythonware.com Mon Jan 17 15:26:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Jan 2005 21:26:39 +0100 Subject: Adjusting the 1024 byte stdin buffer limit References: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> <1105989764.168794.113430@z14g2000cwz.googlegroups.com> Message-ID: "brucoder" wrote: > Currently, when sending a data stream that exceeds 1024 bytes via > stdin, the stream blocks at the 1024th byte. This precludes completion > of the submission of the data stream. you can pass in a buffer size when you open a file: >>> help(open) class file(object) | file(name[, mode[, buffering]]) -> file object | | Open a file. The mode can be 'r', 'w' or 'a' for reading (default), | writing or appending. The file will be created if it doesn't exist | when opened for writing or appending; it will be truncated when | opened for writing. Add a 'b' to the mode for binary files. | Add a '+' to the mode to allow simultaneous reading and writing. | If the buffering argument is given, 0 means unbuffered, 1 means line | buffered, and larger numbers specify the buffer size. | Add a 'U' to mode to open the file for input with universal newline | support. Any line ending in the input file will be seen as a '\n' | in Python. Also, a file so opened gains the attribute 'newlines'; | the value for this attribute is one of None (no newline read yet), | '\r', '\n', '\r\n' or a tuple containing all the newline types seen. | | 'U' cannot be combined with 'w' or '+' mode. | | Note: open() is an alias for file(). or use os.fdopen() to reopen an existing file handle: >>> help(os.fdopen) fdopen(fd [, mode='r' [, bufsize]]) -> file_object Return an open file object connected to a file descriptor. assuming "sending via stdin" means using a pipe, this page explains why all this probably won't matter: http://www.opengroup.org/onlinepubs/7990989799/xsh/write.html (see the "Write requests to a pipe or FIFO" section) From merkosh at hadiko.de Sat Jan 1 16:38:17 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Sat, 01 Jan 2005 22:38:17 +0100 Subject: UserDict deprecated Message-ID: Hi, Why is the UserDict module is deprecated after Python 2.2. The application of it I have in mind is, i.e. multiple inheritance from "file" and "dic" - which is not possible. If I used UserDict I would not need to specify all methods UserDict provides alreay, anyway. Ciao Uwe From danb_83 at yahoo.com Sun Jan 9 12:05:25 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 9 Jan 2005 09:05:25 -0800 Subject: Long strings as function parameters References: <1105288564.441842.13060@c13g2000cwb.googlegroups.com> Message-ID: <1105290325.030128.146490@c13g2000cwb.googlegroups.com> onlyonemc at gmail.com wrote: > I would like to have functions that operate on long strings, 10-100 MB. > In C I would of course pass a pointer to the string for a quick > function call. What is an efficient way to do this in python? > Cheers, In Python, *every* expression is a pointer. This fact is clearest when you look a C-implemented Python functions (which have parameter types and return types of PyObject*), or when using mutable types. >>> class Spam: ... def __init__(self): ... self.foo = 0 ... >>> x = Spam() >>> y = x >>> y.foo = 17 >>> x.foo 17 Compare this to the C code: typedef struct {int foo;} Spam; ... Spam *x, *y; ... y = x; y->foo = 17; printf("%d\n", x->foo); From pdemb at illx.org Sun Jan 2 06:30:17 2005 From: pdemb at illx.org (Peter Dembinski) Date: Sun, 02 Jan 2005 12:30:17 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1> <7x8y7cjo57.fsf@ruckus.brouhaha.com> Message-ID: <87zmzsax12.fsf@hector.domek> Paul Rubin writes: [...] > I don't understand that. If I see "str x = str(3)", then I know > that x is a string. def foo(x): return str(x) str = foo(x) And now, let's say that foo()'s definition is in another module. It is hard for a programmer to quickly determine the type for str, that's the problem with programming in languages that don't have type declarations. From jwaixs at gmail.com Mon Jan 3 08:35:09 2005 From: jwaixs at gmail.com (Noud Aldenhoven) Date: Mon, 03 Jan 2005 14:35:09 +0100 Subject: removing comments form a file Message-ID: <5b617$41d956df$53e8229a$22273@freeler.nl> Hello everyone, I was wondering how to remove comments away form a file. So that's why I made this script. =============================== #!/usr/bin/env python import sys import string import time helptext = "usage: python rmcomment [oldfile] [newfile] [comment]" def rmcomment(oldfile, newfile, comment): oldfile = open(oldfile, 'r') newfile = open(newfile, 'w') ccount = 0 lcount = 0 for line in oldfile.readlines(): splitline = string.split(line) pstest = 0 fileline = "" for word in splitline: if word[:2] == comment: pstest = -1 ccount += 1 pass elif pstest == -1: pass else: fileline += word + " " if len(fileline) == 0: pass else: newfile.write(fileline + "\n") lcount += 1 print "Done... in %s seconds\nRemoved comment from %s lines\nWrote % lines to %s" % (time.time()-start , ccount, lcount, newfile) raw_input("Push the enter button to quit>") if __name__ == "__main__": if sys.argv[1] == "-h" or sys.argv[1] == "-help": print helptext else: start = time.time() oldfile = sys.argv[1] newfile = sys.argv[2] comment = sys.argv[3] rmcomment(oldfile, newfile, comment) ======================================== This script works fine with standard text files. An example is this one: example.txt: Hello Fuckin' World //how are you doing today //I think it delete this sentence and the next sentence too! But this one not! #Even not this comment end example.txt If I use my script, named rmcomment.py I get this: jwaixs at linux:~/programmeren/python/rmcomment$ cat example.txt Hello Fuckin' World //how are you doing today //I think it delete this sentence and the next sentence too! But this one not! #Even not this comment's jwaixs at linux:~/programmeren/python/rmcomment$ python rmcomment.py example.txt newexample.txt // Done... in 0.00104999542236 seconds Removed comment from 2 lines Wrote 2nes to Push the enter button to quit> jwaixs at linux:~/programmeren/python/rmcomment$ cat newexample.txt Hello Fuckin' World But this one not! #Even not this comment jwaixs at linux:~/programmeren/python/rmcomment$ works fine... but here's my problem. If I use rmcomment.py also the whitelines will be removed. And I don't want that to happen. Here's another example: jwaixs at linux:~/programmeren/python/rmcomment$ cat otherexample.txt //This shows what whitelines are doing here left from me is a nice white line tabs and here left are at least 3 white line tabs //and ofcourse, comments will be deleted jwaixs at linux:~/programmeren/python/rmcomment$ python rmcomment.py otherexample.txt newotherexample.txt // Done... in 0.0011351108551 seconds Removed comment form 2 lines Wrote 2nes to Push the enter button to quit> jwaixs at linux:~/programmeren/python/rmcomment$ cat newotherexample.txt left from me is a nice white line tabs and here left are at least 3 white line tabs jwaixs at linux:~/programmeren/python/rmcomment$ My beautiful whitelines are gone! And I don't want that! I've thaught how to fix this for a time, but I can't make it on my own. Too less programming experiance, I'm afraid. Could someone help me with this problem? Or fix the script or give a hint or something? Thank you at least for reading this post, Noud Aldenhoven The Netherlands (In de beurt bij Nijmegen, voor de nieuwschierigen) ps. Yes, I'm a Dyslextion and can't write correct english. I'm sorry for that. From rkern at ucsd.edu Sun Jan 9 10:06:19 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 09 Jan 2005 07:06:19 -0800 Subject: Python3: on removing map, reduce, filter In-Reply-To: <34ctkpF4b9ijlU1@individual.net> References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> Message-ID: Andrey Tatarinov wrote: > anyway list comprehensions are just syntaxic sugar for > > >>> for var in list: > >>> smth = ... > >>> res.append(smth) > > (is that correct?) > > so there will be no speed gain, while map etc. are C-implemented It depends. Try def square(x): return x*x map(square, range(1000)) versus [x*x for x in range(1000)] Hint: function calls are expensive. -- 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 stephen.thorne at gmail.com Thu Jan 20 22:37:14 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Fri, 21 Jan 2005 13:37:14 +1000 Subject: Unbinding multiple variables In-Reply-To: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> Message-ID: <3e8ca5c80501201937332919d4@mail.gmail.com> On 20 Jan 2005 19:24:43 -0800, Johnny Lin wrote: > Hi! > > Is there a way to automate the unbinding of multiple variables? Say I > have a list of the names of all variables in the current scope via > dir(). Is there a command using del or something like that that will > iterate the list and unbind each of the variables? > > Thanks much! (If anyone posts an answer, if you could also cc your > reply to my email air_jlin at yahoo.com, would be much obliged. Thanks > again!) My immediate reaction is "You never want to do that" If you're doing something along these lines: #some code #create lots of variables #do stuff with those variables # References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> <1104672631.884144.294730@c13g2000cwb.googlegroups.com> Message-ID: <41D8311A.9090009@yahoo.it> mirnazim at gmail.com wrote: >I have started a topic that is really vauge. I knew that this topic is >very general and abstract but I think it turned out to be more general >that I had expected. > >Let me make an attemp at defining "Non-Content Oriented Web >Applications". > >A "Non-Content Oriented Web Application": >(1) will be accessed from web browser(obviously). > >(2) will be developed using 'W3C' and other open standards(STRICTLY, to >ensure compatibility and portablity). > >(3) will expose some kind of functionality to the user, not just some >document to read. > >(4) functionality can be very simple to very complex. > >I sat down to define what I actually mean by "Non-Content Oriented Web >Applications" with a fairly clear idea, But suddenly every thing >vanished from my mind, "OH MY GOD, I AM OUT OF WORDS". I think all of >you have been i such situation at least once. So please help me in >defining these "Non-Content Oriented Web Applications". To give a >example, I think GMAIL comes quite close to what I am talking aout. > > > Well,this is what we are working on,about point 2) 1) ~3) ~4) ,but I really don't think it has something strongly related with gmail. We are using nevow and rdf,mainly.Nevow for rendering pages,and rdf to build them on the fly. Probably,what I find related to your questions in this project is the open server ontology we are trying to build. Eventually ontologies and semantics have nothing to do with python core( :-(( ),but with a good scripting language it's easy to mix semantic net querying with pages ,rendering technical, nevow code. This way functionalities of the service are changed,and built during the service run,just adding triples to the semantic net and changing the contents sticked to its nodes. We hope to have code in the contents of the semantic net soon.This will allow to upload a piece of code ,some templates,together with the right metadatas in the semantic net and see the service implied running around in the pages which URI is matched by the pattern coded in the metadata of the service. It's not clear to me also,but this is how it works:using semantic matching(which can be very complex) to decide the interface to information pieces an URL renders. Last but not least,all the informations ,their logic and the rendering engine end functionalities(templates and their specific code),are distribuited as definition as the reside in the semantic net service.My poor english(and stoned mind). I hope I got something of your lost words,have fun and have a look at www.pytypus.org. Yours From andybak at gmail.com Mon Jan 3 15:24:48 2005 From: andybak at gmail.com (andybak at gmail.com) Date: 3 Jan 2005 12:24:48 -0800 Subject: Ann: CherryPy-2.0-beta released In-Reply-To: <1104774372.943278.302050@f14g2000cwb.googlegroups.com> References: <1104774372.943278.302050@f14g2000cwb.googlegroups.com> Message-ID: <1104783888.664232.72720@f14g2000cwb.googlegroups.com> I'm a great believer that avoiding query strings in URL's is good practise ( http://www.holloway.co.nz/book/9 for good arguments why). How tricky is it to remap URL's to query strings in cherryPy? Also how much does it complicate matters to run cherryPy under an existing webserver? Is any functionality lost? From peter at engcorp.com Tue Jan 11 21:25:01 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Jan 2005 21:25:01 -0500 Subject: appending data to an xml file In-Reply-To: References: Message-ID: Thomas Heller wrote: > I want to append/insert additional data to an xml file. [...] > Better, imo, would be to add the dumped info into a proper xml tag, and > inject it into the original file. Is that (efficiently) possible? My technique, when I can't just strip the root element and have a document fragment consisting of a huge list of the other elements, is just to seek to the end of the file, back up to the beginning of the '', and begin overwriting the file from that point... seems to work nicely, and in most cases since I'm the one who wrote the file in the first place I know that I've written '\n' and can just seek to the end minus 8 bytes (when on Windows, anyway...). -Peter From ptmcg at austin.rr._bogus_.com Thu Jan 20 14:54:50 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 20 Jan 2005 19:54:50 GMT Subject: Overloading ctor doesn't work? References: <35ab8oF4idc25U1@individual.net> <41effd30$1_1@newspeer2.tds.net> Message-ID: "Kent Johnson" wrote in message news:41effd30$1_1 at newspeer2.tds.net... > > Martin H?cker wrote: > > > >> Hi there, > >> > >> I just tried to run this code and failed miserably - though I dunno > >> why. Could any of you please enlighten me why this doesn't work? > > Here is a simpler test case. I'm mystified too: > > from datetime import datetime > > class time (datetime): > def __init__(self, hours=0, minutes=0, seconds=0, microseconds=0): > datetime.__init__(self, 2001, 10, 31, hours, minutes, seconds, microseconds) > > print time(1,2,3,4) # => 0001-02-03 04:00:00 > print time() # => TypeError: function takes at least 3 arguments (0 given) > > > What happens to the default arguments to time.__init__? What happens to the 2001, 10, 31 arguments > to datetime.__init__? > > I would expect the output to be > 2001-10-31 01:02:03.000004 > 2001-10-31 00:00:00.000000 > > Kent I can't explain this behavior, but this version does work (uses datetime.combine instead of ctor) -- Paul from datetime import datetime, date as dt_date, time as dt_time class time_d (datetime): def __new__(cls, *args): # default to no microseconds if len(args)==3: args = args + (0,) if len(args)==4: tmpdate = datetime.today() h, mi, s, ms = args return datetime.combine(tmpdate, dt_time(h,mi,s,ms)) elif len(args)==7: y,m,d,h,mi,s,ms = args return datetime.combine(dt_date(y,m,d), dt_time(h,mi,s,ms)) else: raise TypeError, "wrong number of args" print time_d(2001,10,31,1,2,3,4) print time_d(1,2,3,4) print time_d(1,2,3) From sjmachin at lexicon.net Sun Jan 16 02:01:00 2005 From: sjmachin at lexicon.net (John Machin) Date: 15 Jan 2005 23:01:00 -0800 Subject: How to del item of a list in loop? In-Reply-To: <41ea0a87.979537159@news.oz.net> References: <41ea0a87.979537159@news.oz.net> Message-ID: <1105858860.860419.30900@c13g2000cwb.googlegroups.com> Bengt Richter wrote: > No one seems to have suggested this in-place way yet, > so I'll trot it out once again ;-) > > >>> lst = [1, 2, 3] > >>> i = 0 > >>> for item in lst: > ... if item !=2: > ... lst[i] = item > ... i += 1 > ... > >>> del lst[i:] > >>> lst > [1, 3] Works, but slowly. Here's another that appears to be the best on large lists, at least for removing 1 element. It's O(len(list) * number_to_be_removed). !def method_try_remove(lst, remove_this): ! try: ! while 1: ! lst.remove(remove_this) ! except: ! pass From lbates at syscononline.com Wed Jan 12 18:35:39 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 12 Jan 2005 17:35:39 -0600 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: You don't say how this will be used, but here goes: 1) Read the records and put into dictionary with key of sequence (from header) and data being the sequence data. Use shelve to store the dictionary for subsequent runs (if load time is excessive). 2) Take a look at Gadfly (gadfly.sourceforge.net). It provides you with Python SQL-like database and may be better solution if data is basically static and you do lots of processing. All depends on how you use the data. Regards, Larry Bates Syscon, Inc. Chris Lasher wrote: > Hello, > I have a rather large (100+ MB) FASTA file from which I need to > access records in a random order. The FASTA format is a standard format > for storing molecular biological sequences. Each record contains a > header line for describing the sequence that begins with a '>' > (right-angle bracket) followed by lines that contain the actual > sequence data. Three example FASTA records are below: > > >>CW127_A01 > > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACAT > >>CW127_A02 > > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACATTCCGCCTGGGGAGTACGGTCGCAAGATTAAAACTCAAAGGAATAGACGG > >>CW127_A03 > > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACATTCCGCCTGGG > ... > > Since the file I'm working with contains tens of thousands of these > records, I believe I need to find a way to hash this file such that I > can retrieve the respective sequence more quickly than I could by > parsing through the file request-by-request. However, I'm very new to > Python and am still very low on the learning curve for programming and > algorithms in general; while I'm certain there are ubiquitous > algorithms for this type of problem, I don't know what they are or > where to look for them. So I turn to the gurus and accost you for help > once again. :-) If you could help me figure out how to code a solution > that won't be a resource whore, I'd be _very_ grateful. (I'd prefer to > keep it in Python only, even though I know interaction with a > relational database would provide the fastest method--the group I'm > trying to write this for does not have access to a RDBMS.) > Thanks very much in advance, > Chris > From sese at 263.net Mon Jan 3 04:13:18 2005 From: sese at 263.net (SeSe) Date: Mon, 03 Jan 2005 17:13:18 +0800 Subject: [Twisted-Python] Problem with Echoserver (TCP), Help! In-Reply-To: <1104730160.375967.119070@c13g2000cwb.googlegroups.com> References: <1104730160.375967.119070@c13g2000cwb.googlegroups.com> Message-ID: Thanks. I have disabled my firewall. But still failed. It is a bit strange that echo server UDP works. Only TCP doesn't. Regards, SeSe Kartic wrote: > Hi, > > My experience with Twisted is also limited but let me try to help you. > I tried the same combo as you and it worked well with the following > responses: > receive: Hello, world! > receive: What a fine day it is. > receive: Bye-bye! > connection lost: Connection was closed cleanly. > > I am sure you started the server before the client. > > Do you have some firewall software installed that prevents the client > from connecting to the server? > > Thanks > --Kartic > From sesquile at gmail.com Mon Jan 31 13:41:18 2005 From: sesquile at gmail.com (mh) Date: 31 Jan 2005 10:41:18 -0800 Subject: [ANN] Spike Asset Manager release 0.13 Message-ID: <1107196878.026930.154270@c13g2000cwb.googlegroups.com> Spike Asset Manager (SAM) is an open-source cross-platform framework written in python for probing a system for components and reporting them. It includes a driver file that probes for components commonly found in a LAMPJ stack (Apache, MySQL, PHP, Tomcat, etc). Note that the L in LAMP could be Linux, Solaris, Windows or Mac. SAM can find multiple versions that are installed, query the rpm database and indicate whether components are running. Release 0.13 changes: - Migrate to ElementTree from minidom - Migrate to Cheetah from xsl - Preliminary MacOSX support thanks Matt From http Mon Jan 31 23:20:32 2005 From: http (Paul Rubin) Date: 31 Jan 2005 20:20:32 -0800 Subject: Next step after pychecker References: <41ff0308$0$6503$636a15ce@news.free.fr> Message-ID: <7xis5cq5bj.fsf@ruckus.brouhaha.com> 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. From craig at postnewspapers.com.au Fri Jan 28 02:46:15 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 28 Jan 2005 15:46:15 +0800 Subject: Hello In-Reply-To: References: Message-ID: <1106898375.3909.9.camel@albert.localnet> On Thu, 2005-01-27 at 19:39 -0500, g_xo wrote: > Hello everyone, > > I am a python beginner and look forward to learning the language and > working on some interesting projects using it. > > I was wondering if anybody may help me get access to the news group > comp.lang.python I am trying to access it using KNode but I get an > "unable to resolve host name" error. comp.lang.python is gatewayed to this mailing list, and vice versa. You just posted on c.l.p . If you want to access it over NNTP as a newsgroup, rather than receiving it as a mailing list, you just need to ensure you provide your newsreader with a news server that you have access to. Most ISPs provide news servers, often at 'news.ispname.net' if the ISP is 'ispname.net'. You need to get the correct details of which news server to use from your ISP and configure your newsreader to use that. Once your newsread is talking correctly to your ISP's news server, *then* you can subscribe to comp.lang.python. -- Craig Ringer From tonino.greco at gmail.com Fri Jan 21 07:38:50 2005 From: tonino.greco at gmail.com (Tonino) Date: 21 Jan 2005 04:38:50 -0800 Subject: tkinter socket client ? In-Reply-To: <35cae5F4jvrirU1@individual.net> References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> Message-ID: <1106311130.446259.30710@f14g2000cwb.googlegroups.com> thanks for the info - but I really do not want to learn twisted before I can understand Tkinter ;) another thread seems the way - will try that ... Thanks Tonino From ashot at removethismolsoft.com Mon Jan 17 02:19:42 2005 From: ashot at removethismolsoft.com (Ashot) Date: Sun, 16 Jan 2005 23:19:42 -0800 Subject: video analysis with python References: <20050116114407.GE3276@zoran.com> Message-ID: On Mon, 17 Jan 2005 08:08:46 +0100, Alexander 'boesi' B?secke wrote: > Hi > > Am 16.01.2005 12:44:27 schrieb Miki Tebeka: > >> 1. There is PyMedia (http://pymedia.org/) > > Is this library able to extract single images from a video? AFAICS it > can only convert videos from one format to another. But I didn't try it, > I've looked only in the docu. > > Maybe pyVideo (http://www.geocities.com/rtrocca/python/) would be a > solution. But for me the AVIFile-Module doesn't work stable, it > regularly crashes the python-interpreter. > > And there is a library for accessing DirectShow called PyDShowCam. > > cu boesi I haven't tried it yet, but yes its pretty full featured library, there is a tutorial here on extracting images: http://java.sun.com/products/java-media/jmf/2.1.1/solutions/FrameAccess.html -- Ashot Petrosian University of Texas at Austin, Computer Sciences From irmen at -nospam-remove-this-xs4all.nl Tue Jan 18 13:33:32 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 18 Jan 2005 19:33:32 +0100 Subject: ANNOUNCE: Altova ... blah blah blah In-Reply-To: <8u9Hd.344$Jg7.182@fe51.usenetserver.com> References: <8u9Hd.344$Jg7.182@fe51.usenetserver.com> Message-ID: <41ed567c$0$6208$e4fe514c@news.xs4all.nl> Altova Announcements wrote: > Altova Unveils ............. [spam] Well now, I didn't like their products very much already, but this spam has certainly made them drop another few steps down on my scale. Hmpf. --Irmen From ncoghlan at iinet.net.au Thu Jan 13 09:46:04 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 14 Jan 2005 00:46:04 +1000 Subject: else condition in list comprehension In-Reply-To: <34mt3dF4ejn17U1@individual.net> References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> <34mt3dF4ejn17U1@individual.net> Message-ID: <41E689AC.2020001@iinet.net.au> Andrey Tatarinov wrote: >> I presume the point of this is to avoid polluting the local namespace >> with "newval". I further presume you also have plans to do something >> about "i"? ;-) > > no, the point is in grouping definition of newval() with place where it > is used. I'd have said the point was both :) But yeah, unfortunately the 'leaking list comp' problem won't be fixed in the 2.x series due to the compatibility problem. Fortunately, generator expressions didn't inherit the issue. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tim.golden at viacom-outdoor.co.uk Mon Jan 24 06:23:49 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 24 Jan 2005 11:23:49 -0000 Subject: Pointer: CfV de.comp.lang.python Message-ID: <9A28C052FF32734DACB0A288A35339910359E1@vogbs009.gb.vo.local> [Christian Helmbold] | I ask german speaking python programmers to contest the election to | establish the german python newsgroup de.comp.lang.python. It strikes me that this would have been one of the few occasions when it *would* have made sense to write in a language other than English on c.l.py. Although, thinking about it, us non-German speakers wouldn't have known that the post wouldn't apply to us by definition! 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 flaxeater at gmail.com Thu Jan 6 18:42:46 2005 From: flaxeater at gmail.com (flaxeater at gmail.com) Date: 6 Jan 2005 15:42:46 -0800 Subject: wxPython clipboard In-Reply-To: <1105010770.911397.278520@c13g2000cwb.googlegroups.com> References: <1105010770.911397.278520@c13g2000cwb.googlegroups.com> Message-ID: <1105054966.693860.59270@f14g2000cwb.googlegroups.com> Ok well you should look at this module http://www.rutherfurd.net/python/sendkeys/#id1 I then you could take frequent snapshots and use and OCR to find your stuff. Then use the above library to type to the window. From ark at acm.org Mon Jan 17 14:19:19 2005 From: ark at acm.org (Andrew Koenig) Date: Mon, 17 Jan 2005 19:19:19 GMT Subject: Adjusting the 1024 byte stdin buffer limit References: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> Message-ID: "brucoder" wrote in message news:1105989047.516986.59990 at z14g2000cwz.googlegroups.com... > Are there runtime settings that can be used to adjust the default 1024 > byte stdin buffer limit or a buildtime setting in pyconfig.h? I have a > need to pump this up to permit input of a large data block via stdin. What do you think you are being prevented from doing? From aahz at pythoncraft.com Tue Jan 4 10:18:15 2005 From: aahz at pythoncraft.com (Aahz) Date: 4 Jan 2005 10:18:15 -0500 Subject: Unicode universe (was Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)) References: <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> Message-ID: In article <1104849206.111461.70500 at c13g2000cwb.googlegroups.com>, wrote: > >BTW what's the difference between .encode and .decode ? >(yes, I have been living in happy ASCII-land until now ... ;) Here's the stark simple recipe: when you use Unicode, you *MUST* switch to a Unicode-centric view of the universe. Therefore you encode *FROM* Unicode and you decode *TO* Unicode. Period. It's similar to the way floating point contaminates ints. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From steve at holdenweb.com Mon Jan 3 15:55:49 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 15:55:49 -0500 Subject: Python! Is! Truly! Amazing! In-Reply-To: References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: <9niCd.67881$Jk5.63344@lakeread01> Ron Garret wrote: > In article , > jfj wrote: > > >>Ron Garret wrote: >> >>>In article <1104657461.868175.252380 at c13g2000cwb.googlegroups.com>, >>> "Erik Bethke" wrote: >>> >>> >>> >>>>I have NEVER experienced this kind of programming joy. >>> >>> >>>Just wait until you discover Lisp! >>> >>>;-) >> >> >>I've had it with all those lisp posts lately ;-) >> >>There were functional and non-functional programming languages (the >>first being *much* simpler to implement). There is a *reason* people >>chose C over lisp. It's not that we were all blind and didn't see the >>amazingness of lisp. Procedural languages are simply better, and I'm not >>replying to this flamewar. > > > Then neither am I. > > Yes, there's a reason people choose C over Lisp, just as there is a > reason that people choose Windows over OS X, the Ford Taurus over the > Lexus SC400, and Perl over Python. But I'm pretty sure joy isn't that > reason. If joy is part of your quality metric for a programming > language then Lisp is worth a look. (And it costs a lot less than a > Lexus.) Well, in the Computer Programming for Everyone stakes I'm pretty sure that LISP and its derivatives don't stand a chance, simply because of the rebarbative syntax one must use to express even relatively simple algorithms and data structures. While the language has a lot going for it in the hands of an experienced and determined LISPer, the average programmer just isn't going to "get it". 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 vincent at visualtrans.de Thu Jan 13 00:04:04 2005 From: vincent at visualtrans.de (vincent wehren) Date: Thu, 13 Jan 2005 06:04:04 +0100 Subject: py2exe Excludes In-Reply-To: References: Message-ID: Ed Leafe wrote: > I'm trying to make a Windows runtime for Dabo, and I want to exclude > the framework code itself from the exe file, so that people can update > with new releases as they are made. The relevant section of setup.py has: > > setup( > # The first three parameters are not required, if at least a > # 'version' is given, then a versioninfo resource is built from > # them and added to the executables. > version = "0.3.0", > description = "Dabo Runtime Engine", > name = "daborun", > # targets to build > console = ["daborun.py"], > #exclude the actual framework > options = { "py2exe": {"excludes" : ["dabo"]} }, > ) > > Yet the generated library.zip still contains all of the Dabo module > code. Why is this? What am I doing wrong? Just a guess: What happens if you remove everything that's in the "build" directory before running setup.py? There may still be files around from an earlier build that *did* include the Dabo modules. -- Vincent Wehren > > ___/ > / > __/ > / > ____/ > Ed Leafe > http://leafe.com/ > http://dabodev.com/ > From claird at lairds.us Thu Jan 27 09:08:07 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 27 Jan 2005 14:08:07 GMT Subject: Please suggest on the book to follow References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> <1106829519.540737.164210@z14g2000cwz.googlegroups.com> Message-ID: In article <1106829519.540737.164210 at z14g2000cwz.googlegroups.com>, Fuzzyman wrote: >We've only just had Python 2.4. Based on previous experience that means >it will be about 18 months before python 2.5..... > >I learned to program from 'Programming Python'. Particularly the stuff >on Tkinter is very helpful. I don't think you'll have much to >'unlearn', although obviously there is stuff it doesn't cover (like new >style classes). . . . Python is considerate of programmers. While experience with commercial products might lead to an expectation that 2.0 and 2.4 differ greatly, in fact it's quite feasible to learn from books aimed at 1.5 or even before, and have your results work perfectly well under 2.4. From xah at xahlee.org Wed Jan 26 14:28:15 2005 From: xah at xahlee.org (Xah Lee) Date: 26 Jan 2005 11:28:15 -0800 Subject: how to comment out a block of code Message-ID: <1106767695.572974.98920@z14g2000cwz.googlegroups.com> is there a syntax to comment out a block of code? i.e. like html's or perhaps put a marker so that all lines from there on are ignored? thanks. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From Scott.Daniels at Acm.Org Thu Jan 20 10:57:32 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 20 Jan 2005 07:57:32 -0800 Subject: Print to Windows default Printer In-Reply-To: References: Message-ID: <41efd18e$1@nntp0.pdx.net> Tim Golden wrote: > [Samantha] > | I am new to Python and I am having considerable trouble > | trying to print > | (using a simple script) to the default printer rather than the screen. > | Thanks for any help. > | S > > It may be that something here will help you: > > http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html > > Specifically, I think that the section print raw text is > closest to what you're asking (although not necessarily > to what you'll eventually want): > > http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html#win32print > You might be interested in using PDFCreator to save paper during your tests. It is a windows printer driver that creates a PDF file: http://sourceforge.net/projects/pdfcreator/ --Scott David Daniels Scott.Daniels at Acm.Org From ncoghlan at iinet.net.au Tue Jan 11 05:30:29 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 11 Jan 2005 20:30:29 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: <34frdmF42p2jrU1@individual.net> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <34frdmF42p2jrU1@individual.net> Message-ID: <41E3AAC5.7040703@iinet.net.au> Andrey Tatarinov wrote: > I think using 'with' keyword can cause some ambiguity. for example I > would surely try to write > > >>> x = a+b with self: > >>> b = member > > and using with at the end of block brings more ambiguity: > > >>> stmt1() > >>> stmt2() > >>> with self: > >>> member = stmt3() > > compare to: > > >>> stmt1() > >>> stmt2() > >>> with: > >>> variable = stmt3() > > a way different semantics with just one word added/deleted. Except that for a "with :" block, attributes of the expression must be preceded by a dot: Py> stmt1() Py> stmt2() Py> with self: ... .member = stmt3() The advantages of the 'with' block are that 'self' is only looked up once, and you only need to type it once. The leading dot is still required to disambiguate attribute references from standard name references. Despite that, I think you are right that the ambiguity is greater than I first thought. Correct code is reasonably easy to distinguish, but in the presence of errors it is likely to be unclear what was intended, which would make life more difficult than it needs to be. However, I still agree with Alex that the dual life of "where" outside of Python (as an 'additional definitions' clause, as in mathematics, and as a 'conditional' clause, as in SQL), and the varied background of budding Pythoneers is a cause for concern. 'in' is worth considering, as it is already used by Python at least once for declaring use of a namespace (in the 'exec' statement). However, I suspect it would suffer from ambiguity problems similar to those of 'with' (consider " in " and " in: "). There's also the fact that the statement isn't *really* executed in the inner namespace - any name binding effects are seen in the outer scope, whereas 'exec x in dict' explicitly protects the containing namespace from alteration. So of the four keywords suggested so far ('where', 'with', 'in', 'using'), I'd currently vote for 'using' with 'where' a fairly close second. My vote goes to 'using' because it has a fairly clear meaning ('execute the statement using this extra information'), and doesn't have the conflicting external baggage that 'where' does. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From cdavisNOSP at NOSPstaffmail.ed.ac.uk Thu Jan 13 05:00:08 2005 From: cdavisNOSP at NOSPstaffmail.ed.ac.uk (Cory Davis) Date: Thu, 13 Jan 2005 10:00:08 +0000 Subject: distutils linux script installation broken? In-Reply-To: <1105544059.595961.157780@c13g2000cwb.googlegroups.com> References: <1105535625.443343.326560@z14g2000cwz.googlegroups.com> <1105544059.595961.157780@c13g2000cwb.googlegroups.com> Message-ID: Thanks for the help Chris. I tried the -E option, and also installing as root with no change - the scripts in the bin directory still end up with #!None on the first line. Next step is to reinstall Python 2.4, and if that doesn't work I'll just stick with 2.3.4. Cheers, Cory. Christopher De Vries wrote: > I've got python 2.3.3, 2.4, and 1.5.2 (which came preinstalled) on my > linux box. It's redhat 7.2 (I know... I would upgrade, but it would > void my service contract, so I just install things in /usr/local). You > can check if PYTHONHOME or PYTHONPATH are set, which may somehow be > interfering. I don't have those variables set. If they are set, you > could try running: > > python -E setup.py install > > The -E option should make python ignore those environment variables. > Good luck, I hope this helps. > > Chris > From steven.bethard at gmail.com Mon Jan 10 01:22:27 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 09 Jan 2005 23:22:27 -0700 Subject: Python3: on removing map, reduce, filter In-Reply-To: <1105316438.272475.313670@c13g2000cwb.googlegroups.com> References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> <1105316438.272475.313670@c13g2000cwb.googlegroups.com> Message-ID: beliavsky at aol.com wrote: > Steve Bethard wrote: >> Robert Kern wrote: >>> def square(x): >>> return x*x >>> map(square, range(1000)) >>> >>> versus >>> [x*x for x in range(1000)] >>> >>> Hint: function calls are expensive. >> >> $ python -m timeit -s "def square(x): return x*x" "map(square, range(1000))" >> 1000 loops, best of 3: 693 usec per loop >> >> $ python -m timeit -s "[x*x for x in range(1000)]" >> 10000000 loops, best of 3: 0.0505 usec per loop > > Functions will often be complicated enought that inlining them is not > feasible. True, true. However, list comprehensions still seem to be comparable in speed (at least in Python 2.4): $ python -m timeit -s "def f(x): return x*x" "[f(x) for x in xrange(1000)]" 1000 loops, best of 3: 686 usec per loop $ python -m timeit -s "def f(x): return x*x" "map(f, xrange(1000))" 1000 loops, best of 3: 690 usec per loop Presumably this is because the C code for the byte codes generated by a list comprehension isn't too far off of the C code in map. I looked at bltinmodule.c for a bit, but I'm not ambitious enough to try verify this hypothesis. ;) Steve From swaroopch at gmail.com Fri Jan 28 02:46:48 2005 From: swaroopch at gmail.com (Swaroop C H) Date: Fri, 28 Jan 2005 13:16:48 +0530 Subject: Hello In-Reply-To: <1106898375.3909.9.camel@albert.localnet> References: <1106898375.3909.9.camel@albert.localnet> Message-ID: <351e887105012723467f3eb873@mail.gmail.com> > Most ISPs provide > news servers, often at 'news.ispname.net' if the ISP is 'ispname.net'. > You need to get the correct details of which news server to use from > your ISP and configure your newsreader to use that. Once your newsread > is talking correctly to your ISP's news server, *then* you can subscribe > to comp.lang.python. If you can't find a Usenet server, try news.gmane.org -- Swaroop C H Blog: http://www.swaroopch.info Book: http://www.byteofpython.info From FBatista at uniFON.com.ar Wed Jan 12 17:58:39 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 12 Jan 2005 19:58:39 -0300 Subject: What strategy for random accession of records in massive FAST A file? Message-ID: [Chris Lasher] #- I have a rather large (100+ MB) FASTA file from which I need to #- access records in a random order. The FASTA format is a #- standard format #- for storing molecular biological sequences. Each record contains a #- header line for describing the sequence that begins with a '>' #- (right-angle bracket) followed by lines that contain the actual #- sequence data. Three example FASTA records are below: #- #- >CW127_A01 #- TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG #- TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA #- GCATTAAACAT #- >CW127_A02 #- TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG #- TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA #- GCATTAAACATTCCGCCTGGGGAGTACGGTCGCAAGATTAAAACTCAAAGGAATAGACGG #- >CW127_A03 #- TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG #- TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA #- GCATTAAACATTCCGCCTGGG #- ... I think of two ways. If you have enough memory you could load everything in memory, each record as the element of a list, and then access randomly to the list. If you want to keep the memory usage low, you can parse the file once and store in a list the byte position where the record starts and ends. Then access the list randomly and read each record with seek() and read(). . 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 steve at holdenweb.com Sun Jan 9 10:44:20 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 10:44:20 -0500 Subject: python3: 'where' keyword In-Reply-To: <1gq4ebf.17qqy8dk9ccr6N%aleaxit@yahoo.com> References: <3480qqF46jprlU1@individual.net> <1gq4ebf.17qqy8dk9ccr6N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > AdSR wrote: > > >>I don't know haskell, but it looks SQL-ish to me (only by loose > > > Indeed, the fact that many MANY more people are familiar with SQL than > with Haskell may be the strongest practical objection to this choice of > syntax sugar; the WHERE clause in an SQL SELECT has such wildly > different semantics from Haskell's "where" that it might engender huge > amounts of confusion. I.e., reasoning by analogy with SQL only, one > might reasonably expect that minor syntax variations on: > > print a, b where a = b > > could mean roughly the same as "if a==b: print a, b", rather than > roughly the same as: > > a = b > print a, b > > I wonder if 'with', which GvR is already on record as wanting to > introduce in 3.0, might not be overloaded instead. > IIRC the proposed meaning seems to be most closely related (in my own experience, annyway) to the use of "where" in BCPL (heavens, *that* was a long time ago). I never found that entirely natural either. 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 me at privacy.net Sat Jan 1 08:14:23 2005 From: me at privacy.net (Mark Carter) Date: Sat, 01 Jan 2005 13:14:23 +0000 Subject: Which blog tool Message-ID: <41d6a22f$0$42579$ed2619ec@ptn-nntp-reader03.plus.net> I currently use python to automatically summarise a certain newsgroup daily, and post the findings that it makes. Someone has suggested that they would like a to see a blog of the posts. I wondered if there was a python tool/library that could automate the blog postings. Any ideas? Some details: * the summaries are basically just text files * I already have a blog at www.blogger.com (http://markcarterturriff.blogspot.com/), so I would like to use that if possible; although any alternative free one that I can use to achieve my objective would be OK, too. * I do have my own hosted website, which can use perl but not python; but I'd rather use a freebie blog site * the whole thing must be scriptable, because it will run daily. A GUI would therefore likely get in the way. * generating an RSS feed would be nice From fuzzyman at gmail.com Fri Jan 28 05:23:27 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 28 Jan 2005 02:23:27 -0800 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: Message-ID: <1106907807.471215.105110@f14g2000cwb.googlegroups.com> Dieter Maurer wrote: > Steven Bethard writes on Tue, 25 Jan 2005 12:22:13 -0700: > > Fuzzyman wrote: > > ... > > > A better (and of course *vastly* more powerful but unfortunately only > > > a dream ;-) is a similarly limited python virutal machine..... > > I already wrote about the "RestrictedPython" which is part of Zope, > didn't I? > Not in this thread. > Please search the archive to find a description... > Interesting. I'd be interested in whether it requires a full Zope install and how easy (or otherwise) it is to setup. I'll investigate. Regards, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > > Dieter From grahamd at dscpl.com.au Thu Jan 27 16:59:24 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 27 Jan 2005 13:59:24 -0800 Subject: Who should security issues be reported to? Message-ID: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Who are the appropriate people to report security problems to in respect of a module included with the Python distribution? I don't feel it appropriate to be reporting it on general mailing lists. From erikbethke at gmail.com Thu Jan 20 09:42:35 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 20 Jan 2005 06:42:35 -0800 Subject: ElementTree cannot parse UTF-8 Unicode? In-Reply-To: <5861401.FEXqi8ioxF@strongwill.g2ctech> References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106181323.553028.290370@z14g2000cwz.googlegroups.com> <5861401.FEXqi8ioxF@strongwill.g2ctech> Message-ID: <1106232155.502249.95650@c13g2000cwb.googlegroups.com> That was a great clue. I am an idiot and tapped on the wrong download link... now I can read and parse the xml file fine - as long as I create it in XML spy - if I create it by this method: d=wxFileDialog( self, message="Choose a file", defaultDir=os.getcwd(), defaultFile="", wildcard="*.xml", style=wx.SAVE | wxOVERWRITE_PROMPT | wx.CHANGE_DIR) if d.ShowModal() == wx.ID_OK: # This returns a Python list of files that were selected. paths = d.GetPaths() layout = '\n' L1Word = self.t1.GetValue() L2Word = 'undefined' layout += '\n' layout += ' \n' layout += '' open( paths[0], 'w' ).write(layout) I get hung up on the write statement, I am off to look for a a Unicode capable file write I think... -Erik From kent3737 at yahoo.com Wed Jan 26 11:32:37 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Wed, 26 Jan 2005 11:32:37 -0500 Subject: Help With Python In-Reply-To: References: Message-ID: <41f7c39c$1_1@newspeer2.tds.net> Thomas Guettler wrote: > # No comma at the end: > mylist=[] > for i in range(511): > mylist.append("Spam") or just mylist = ["Spam"] * 511 Kent > print ", ".join(mylist) > > Thomas > From cam.ac.uk at mh391.invalid Sun Jan 9 09:33:44 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 09 Jan 2005 14:33:44 +0000 Subject: Recent infoworld column In-Reply-To: References: <41DEEF0F.5000300@nospamyahoo.com> Message-ID: Carlos Ribeiro wrote: > """ > When people talk about the heroes of open source, you tend to hear > such familiar names as Linus Torvalds, Larry Wall, Brendan Eich, Guido > van Rossum, Monty Widenius, Miguel de Icaza, and Rasmus Lerdorf... > """ Of course, I had to look up who Rasmus Lerdorf was... -- Michael Hoffman From bac at OCF.Berkeley.EDU Thu Jan 6 02:44:09 2005 From: bac at OCF.Berkeley.EDU (Brett C) Date: Wed, 05 Jan 2005 23:44:09 -0800 Subject: python-dev Summary for 2004-11-16 through 2004-11-30 Message-ID: <41DCEC49.9090908@ocf.berkeley.edu> python-dev Summary for 2004-11-16 through 2004-11-30 ++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from November 16, 2004 through November 30, 2004. It is intended to inform the wider Python community of on-going developments on the list. To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! This is the fifty-third summary written by Brett Cannon (Another quarter begins). To contact me, please send email to brett at python.org ; I do not have the time to keep up on comp.lang.python and thus do not always catch follow-ups posted there. All summaries are archived at http://www.python.org/dev/summary/ . Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sf.net/rst.html . Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it, although I suggest learning reST; it's simple and is accepted for `PEP markup`_ and gives some perks for the HTML output. Also, because of the wonders of programs that like to reformat text, I cannot guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _PEP Markup: http://www.python.org/peps/pep-0012.html The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation on new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to forward the development and use of Python. But the PSF_ cannot do this without donations. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation (you can donate through PayPal or by check) helps. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. contents:: .. _last summary: http://www.python.org/dev/summary/2004-11-01_2004-11-15.html .. _original text file: http://www.python.org/dev/summary/2004-11-16_2004-11-30.ht ===================== Summary Announcements ===================== PyCon_ is coming up! Being held March 23-25 in Washington, DC, registration is now open at http://www.python.org/pycon/2005/register.html for credit card users (you can pay by check as well; see the general info page for the conference). .. _PyCon: http://www.python.org/pycon/2005/ ========= Summaries ========= --------------------------------------------- Would you like the source with your function? --------------------------------------------- Would you like all functions and classes to contain a __pycode__ attribute that contains a string of the code used to compile that code object? Well, that very idea was proposed. You would use a command-line switch to turn on the feature in order to remove the memory and any performance overhead for the default case of not needing this feature. Some might ask why this is needed when inspect.getsource and its ilk exist. The perk is that __pycode__ would always exist while inspect.getsource is a best attempt but cannot guarantee it will have the source. Beyond a suggested name change to __source__, various people have suggested very different uses. Some see it as a convenient way to save interpreter work easily and thus not lose any nice code snippet developed interactively. Others see a more programmatic use (such as AOP "advice" injection). Both are rather different and led to the thread ending on the suggestion that a PEP be written that specifies what the intended use-case to make sure that need is properly met. Contributing threads: - `__pycode__ extension `__ =============== Skipped Threads =============== - PEP 310 Status - python 2.3.5 release? look for 2.3.5 possibly in January - Current CVS, Cygwin and "make test" - syntactic shortcut - unpack to variably sizedlist mostly discussed `last summary`_ - Python 2.4, MS .NET 1.1 and distutils - Trouble installing 2.4 - Looking for authoritative documentation on packages, import & ihooks no docs exist, but feel free to write some! =) - String literal concatenation & docstrings literal string concatenation only works if the newline separating the strings is not significant to the parser - print "%X" % id(object()) not so nice does 'id' need to return only a positive? No, but it would be nice. - Bug in PyLocale_strcoll - Multilib strikes back - File encodings file.write does not work with Unicode strings; have to decode them to ASCII on your own From amk at amk.ca Fri Jan 21 08:32:56 2005 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 21 Jan 2005 07:32:56 -0600 Subject: PyCon Preliminary Program Announced! References: <20050121000607.DE1261E4010@bag.python.org> <41F061C3.3000802@gmail.com> Message-ID: On Thu, 20 Jan 2005 22:52:13 -0500, Tim Peters wrote: > The web page needs better formatting. In general, there are no more Suggestions for improvement are welcome. Perhaps the Wiki version of the schedule, at http://www.python.org/moin/PyConDC2005/Schedule, may be better. --amk From erikbethke at gmail.com Sun Jan 2 07:20:55 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 2 Jan 2005 04:20:55 -0800 Subject: Python! Is! Truly! Amazing! In-Reply-To: <1104657909.340055.283710@z14g2000cwz.googlegroups.com> References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <1104657909.340055.283710@z14g2000cwz.googlegroups.com> Message-ID: <1104668455.691428.12670@c13g2000cwb.googlegroups.com> somehow lost my j's: www.erikbethke.com/Python/screenshot02.jpg www.erikbethke.com/Python/screenshot03.jpg www.erikbethke.com/Python/screenshot04.jpg www.erikbethke.com/Python/screenshot05.jpg From uche at ogbuji.net Sun Jan 2 01:46:26 2005 From: uche at ogbuji.net (Uche Ogbuji) Date: 1 Jan 2005 22:46:26 -0800 Subject: Any Python XML Data Binding Utilities Avaiable? In-Reply-To: References: Message-ID: <1104648386.567624.274170@c13g2000cwb.googlegroups.com> Sounds like generateDS is closest to what you want: http://www.rexx.com/~dkuhlman/generateDS.html If you can bind from instances only and don't need schema, see Amara Bindery: http://uche.ogbuji.net/tech/4Suite/amara/ Also consider Gnosis Utilities and ElementTree. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://4Suite.org http://fourthought.com Use CSS to display XML - http://www.ibm.com/developerworks/edu/x-dw-x-xmlcss-i.html Full XML Indexes with Gnosis - http://www.xml.com/pub/a/2004/12/08/py-xml.html Be humble, not imperial (in design) - http://www.adtmag.com/article.asp?id=10286UBL 1.0 - http://www-106.ibm.com/developerworks/xml/library/x-think28.html Use Universal Feed Parser to tame RSS - http://www.ibm.com/developerworks/xml/library/x-tipufp.html Default and error handling in XSLT lookup tables - http://www.ibm.com/developerworks/xml/library/x-tiplook.html A survey of XML standards - http://www-106.ibm.com/developerworks/xml/library/x-stand4/ The State of Python-XML in 2004 - http://www.xml.com/pub/a/2004/10/13/py-xml.html From bulba at bulba.com Thu Jan 6 15:34:23 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 21:34:23 +0100 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <16859.16548.249527.30210@montanaro.dyndns.org> <864d37090501050117761a32e6@mail.gmail.com> Message-ID: On Wed, 05 Jan 2005 17:25:08 -0800, Robert Kern wrote: >> Yes, I know, it can be written by hand. But by this line of logic why >> bother learning VHLL and not just stay with C? >I'm not sure what you mean by "written by hand." I mean the same way as you do mylist.sort() in Python instead of writing the list sorting function yourself in the application / script. >Someone is going to >have to write the functions in the first place. Sure, they can be >written once, well, and placed in the standard library so they don't >have to be *re*written by anyone else again. Well of course - the only point I mean here is getting high-level stuff is one of the main motives of getting into VHLL (aside from issues like automatic memory management, of course). >I still think numarray is a good start for this. It handles more than >just numbers. And RecArray (an array that has different types in each >column, as you seem to require) can be subclassed to add these methods >to it. I have downloaded it, playing with it and like it. I esp. like things like: >>> print a + a [2 4 6] or >>> b.getshape() (4,3) Very Pythonic. :-) However, not all things are generic enough like I meant. That is not to criticize, but merely to point out that the library is for obvious reasons slanted towards numerical work, so e.g. while the following works: .>>> from numarray import transpose .>>> transpose([[1,2],[3,4]]) array([[1, 3], [2, 4]]) ...this doesn't: >>> transpose([('phone1', 12345), ('phone2', 67890)]) Traceback (most recent call last): File "", line 1, in ? [....] TypeError: Expecting a python numeric type, got something else. Why would someone want to do such a thing: suppose he wants 'phone1' and 'phone2' and number records sequenced horizontally instead vertically, while when he read that from a file, such was the file structure. It's a boneheaded example, but you get the idea. It's obvious why that exception happens: in recarray I have to have the same type of the data type in every column, so transpose(recarray) cannot be done. This is not the situation with other builtin Python data types, where whatever with can be mixed, i.e. placed in any "cell" of data type and all the functions will still work as long as the operand type is proper. This is obviously the consequence of numarray being based on the matrices designed for working on numerical data, so it's probably very fast and I'm sure people who use it find it useful. But personally I would happily sacrifice much or even most of that speed for sake of flexibility. Because, sure, I can keep the matrix header with strings separately in a list, do the transformation just on numbers, adjust the list as well - it's not like I'm just lazy to make an additional programming effort, but that eliminates one of the greatest advantages of Python: terseness without foregoing clarity. Yes, now it's probably much harder to do once the simpler things have been done. All I'm saying is that it would be so frigging nice to have it with even richer data structures. >> and clear_ manipulations of rich data structures in Python. Why not >> extend them with flexible tables / matrices / arrays that would work >> in as "Pythonic" ways as dictionaries and lists already do? >Sure. We're working on it! Excellent! Great, I'm really grateful to you all for doing that. Honestly. >Come check out numarray; I think you'll like >it. And if, along the way, you write a CSV-to-RecArray converter, we'd >*love* to include it in the distribution. First I have to learn Python (and programming in general) well enough to produce smth that isn't as bug-infested as a software of certain well-known vendor and that I would not be ashamed of to show to the world. :-) I'm afraid it will take me some time. >I think that a more complete >integration with the other core Python facilities like the csv module >will help numarray become more suited for inclusion into the standard >library. I'm sure people would find it useful. I play with numarray to get the idea how I could apply it in my work. -- It's a man's life in a Python Programming Association. From jbperez808 at wahoo.com Sun Jan 9 04:55:57 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Sun, 09 Jan 2005 17:55:57 +0800 Subject: The best way to do web apps with Python? In-Reply-To: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <34cddlF48eck2U1@individual.net> worzel wrote: > What is the best way to web developemnt with Python? Is there anything > close to PHP style in-page script placement that can create and use > other Python objects? Spyce ( http://spyce.sf.net ) is what you're looking for. I was looking exactly for the same thing as you are - a PHP workalike - and tried around half a dozen or so alternatives before I settled upon Spyce as the best one. If Spyce's [[ and ]] delimiters are not to your liking, you can actually switch to using <% and %> without any problem. Spyce also handles the Python indent issue quite nicely and elegantly, imo, while you can use the free and open source SciTE text editor to separately syntax highlight Spyce source code + Javascript + HTML very nicely (config file tweaking required). > what is the expectataion of Python for this kind of > stuff? Would one use Python for certain other things but turn to PHP for > web apps - or would one use their Python skills in place of PHP? Python can be a full (and superior) replacement for PHP. The only caveat would be third party hosting support. The following post by on the Spyce mailing list (by Andy of Neotitans.com web development) explains why: "One major roadblock to Spyce and other Python server side technologies seeing acceptance on the scale of PHP is the fact that mod_python deployment on 3rd party shared hosting solutions is more complex and involved than mod_php. Apparently, security considerations mean that each mod_python user will need to get their own instance of an Apache server acting as a proxy behind a central instance of an Apache server (which is what's responsible for accepting requests at the shared server's http port). A per-shared user Spyce proxy server approach would likely be more economical (of server resources) and more easily set up than multiple mod_python-enabled Apache server instances. If your hosting solution will permit you to have your own long-running processes (afaik, most won't :-( ), and if they are willing make the necessary httpd.conf mods to pass Spyce page requests over to your own instance of the Spyce proxy server or their .htaccess setup allows you to do that yourself, then you're all set. I'm also happy to report that Spyce CGI works great on any hosting solution that supports CGI and has Python installed. This means that virtually all Linux-based hosting solutions (including those ultra-cheap shared server ones) will support Spyce CGI. It would seem that FastCGI support is probably the hardest to come by." From aleaxit at yahoo.com Thu Jan 6 07:45:09 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 6 Jan 2005 13:45:09 +0100 Subject: Cookbook 2nd ed Credits References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <41DC613D.1020806@holdenweb.com> Message-ID: <1gpyyi0.7sc9va1t3ze86N%aleaxit@yahoo.com> Steve Holden wrote: ... > > 1: 25 u'Luther Blissett' > > 2: 21 u'Alex Martelli' ... > And I *still* think we deserve to be told the Luther Blissett story ... > > conspiratorial-ly y'rs - steve Martin Elster's post back in Aug '02 already had just about all of the necessary info...: ''' I had just been reading about Luther Blissett, and this name is a sort of umbrella name that is available for anyone that is interested, and that has been used in different "underground" projects and pranks, especially in Italy. ''' Add other well-known facts, such as the fact that Bologna is or was a hotbed of situationist pranks, Umberto Eco is a professor at Bologna University, Umberto Eco's best-known historical novels from "The Name of the Rose" onwards may be interestingly compared with Luther Blissett's "Q", and so forth, and I'm sure you can design a perfectly adequate conspiracy theory. Alex From bill.mill at gmail.com Wed Jan 19 14:46:29 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 19 Jan 2005 14:46:29 -0500 Subject: Zen of Python In-Reply-To: <972ec5bd050119111359e358f5@mail.gmail.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> Message-ID: <797fe3d405011911465ab59acd@mail.gmail.com> The example that occurs to me is that "import smtplib" is better than "import stdlib.inet.services.smtp". Peace Bill Mill bill.mill at gmail.com On Wed, 19 Jan 2005 14:13:47 -0500, Timothy Fitz wrote: > While I agree that the Zen of Python is an amazingly concise list of > truisms, I do not see any meaning in: > > Flat is better than nested. > > I strive for balance between flat and nested. Does anyone have a good > example of where this is applied? (specifically to python, or in > general) > -- > http://mail.python.org/mailman/listinfo/python-list > From beliavsky at aol.com Sat Jan 8 07:47:06 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 8 Jan 2005 04:47:06 -0800 Subject: Another look at language comparisons References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> Message-ID: <1105188426.955508.263030@c13g2000cwb.googlegroups.com> >From the web site: "Why Microsoft can Blow-Off with C#? These people have thought up programming languages Fortran, Prologue, Ada." The author is ignorant. Fortran was invented by IBM in the late 1950s, long before Microsoft existed. Ada was commissioned by the U.S. Department of Defense in the 1970s. The Prolog programming language is not spelled "Prologue". From jaco.smuts at clover.co.za Wed Jan 5 01:28:02 2005 From: jaco.smuts at clover.co.za (Jaco Smuts) Date: Wed, 05 Jan 2005 08:28:02 +0200 Subject: python intergration bus ? In-Reply-To: <1104849906.019872.153800@z14g2000cwz.googlegroups.com> References: <1104849906.019872.153800@z14g2000cwz.googlegroups.com> Message-ID: <41DB88F2.3040305@clover.co.za> Tonino wrote: >Hi, > >Just an interested question - I friend is testing a few JAVA >intergration bus's that will be used to intergrate his companies >services - I was wondering if there was a python intergration bus ? >other than maybe Pyro ? > > > >Thanks >Tonino > > > Hello Tonino There is a Python module (http://www.python.org/other/spread/) for Spread (http://www.spread.org/ ) that is worth looking at. There is also some work on a rpc module using spread. http://pyhacks.suddenthinks.com/spreadrpc/, never worked with this one though. There is a great module for IBM's websphere mq, pymqi ( http://pymqi.sourceforge.net/) by L Smithson. This obviously depends on using the Commercial websphere MQ product though. If web services are an option you can also have a look at Clarence (http://clarens.sourceforge.net) and / or http://pywebsvcs.sourceforge.net/ I've previously stumbled accross some others at sourceforge, but this should get you started. jaco From mail.python.org at bdash.net.nz Thu Jan 27 19:05:11 2005 From: mail.python.org at bdash.net.nz (Mark Rowe) Date: Fri, 28 Jan 2005 13:05:11 +1300 Subject: Question: "load"ing a shared object in python In-Reply-To: References: Message-ID: <2e82e836a9fe632159b03821655404e0@bdash.net.nz> On Jan 28, 2005, at 6:48 AM, Rick L. Ratzel wrote: > Pro Grammer writes: > >> Hello, all, >> I am not sure if this is the right place to ask, but could you kindly >> tell me >> how to "load" a shared object (like libx.so) into python, so that the >> methods in >> the .so can be used? That too, given that the shared object was >> written in c++, >> compiled with g++ ? >> Thanks, >> Pro Grammer > > Will the dl standard library module help you? From the Python docs > at: > > http://docs.python.org/lib/module-dl.html As Simon Brunning notes, ctypes () is a robust alternative to the `dl' module. > Example: > >>>> import dl, time >>>> a=dl.open('/lib/libc.so.6') >>>> a.call('time'), time.time() > (929723914, 929723914.498) A note about this example: the `dl' call returns an integer as that is what the C time function returns. time.time() in Python is implemented in terms of C's gettimeofday, ftime or time depending on the platform. > I'm guessing that there might be some C++ issues, but maybe it's worth > looking into. As far as I am aware, neither dl nor ctypes natively support C++. This is a tricky matter, due to the lack of standards for C++ ABI's covering name mangling and vtable layout etc. See the thread starting at for more information. Regards, Mark Rowe From pierre.barbier at cirad.fr Fri Jan 14 03:41:47 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri, 14 Jan 2005 09:41:47 +0100 Subject: Unclear On Class Variables In-Reply-To: <41e77621$0$19576$636a15ce@news.free.fr> References: <41e77621$0$19576$636a15ce@news.free.fr> Message-ID: <41e7855f$0$31553$626a14ce@news.free.fr> Pierre Barbier de Reuille a ?crit : > Antoon Pardon a ?crit : > >>> Well I find this a confusing behaviour on python's part. The fact >>> that instance.field can mean something different, depending on >>> where in a statement you find it, makes the behaviour inconsistent. >>> >>> I know people in general here are against declarations, but declarations >>> could IMO provide more consistency here and thus more obvious behaviour. >> >> >> >> Well just to show how confusing python can be, the following piece of >> code. >> >> | class Spam: >> | eggs = [2, 3] >> | | | sp1 = Spam() >> | sp2 = Spam() >> | | print sp1.eggs, id(sp1.eggs) >> | print sp2.eggs, id(sp2.eggs) >> | print '--------------------' >> | | sp1.eggs += [4,] >> | >> | print sp1.eggs, id(sp1.eggs) >> | print sp2.eggs, id(sp2.eggs) >> | print '--------------------' >> | >> | Spam.eggs = [3,5] >> | >> | print sp1.eggs, id(sp1.eggs) >> | print sp2.eggs, id(sp2.eggs) >> | print '--------------------' >> >> Which produces: >> >> [2, 3] 1075958860 >> [2, 3] 1075958860 >> -------------------- >> [2, 3, 4] 1075958860 >> [2, 3, 4] 1075958860 >> -------------------- >> [2, 3, 4] 1075958860 >> [3, 5] 1075959084 >> -------------------- >> > > Well ... and could someone explain this behaviour ? > I don't catch it ! > > Pierre Ok, I think I got it ! I speak with friends working with Python too ... It seems that "a += l" if "a" and "l" are lists is equivalent to : a.extend(l) a = a The second line could seem meaningless but it is not ! Indeed, in the example above, the first "sp1.eggs" (the one with the extend) is a class variable but, the second "sp1.eggs" (the one before the "=") is an instance variable ! So, at the end, we append to get sp1.eggs and Spam.eggs references to the same structure. But sp1.eggs is an instance variable of sp1 and no more the class variable. To test that, it's possible to modify slightly the code with : |sp1.eggs += [4,] |del sp1.eggs Then, sp1.eggs still exists !!! But it's again the class variable ... Ok, back to the documentation ... In the doc, there is a special case for the use of "+=" with the class members. IMHO, this should not be !!! But, it says that : ob.a += b is translated into : ob.__setattr__( "a", ob.__getattr__("a").__iadd__(b) ) My opinion is : it would be much more simpler to explain than : a += b <=> a.__iadd__(b); a = a and not give any special case for class members. In both cases, the resulting behaviour is the same, but it would be less confusing. Then, this change of scope of variables in python is very very annoying. Both for new and old programmers (we have both in my lab ...). Well, I hope I got it write this time ... but this is a feature to fear !!! Pierre From apardon at forel.vub.ac.be Mon Jan 17 03:34:59 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2005 08:34:59 GMT Subject: (objects as) mutable dictionary keys References: Message-ID: Op 2005-01-14, Steve Holden schreef : > Antoon Pardon wrote: > >> Op 2005-01-14, Peter Maas schreef : >> >>>I have summarized the discussion about the usability of lists (and >>>and other mutable types) as dictionary keys and put it into the >>>Python wiki.URL: http://www.python.org/moin/DictionaryKeys. >>> >>>This summary might be used as a reference should the 'mutable >>>dictionary keys' issue come up again in c.l.py. >>> >> >> I had a look and I think you should correct the followingr: >> >> Dictionary lookup with mutable types like lists is a source of >> unpleasant surprises for the programmer and therefore impossible in >> Python. >> > Better, perhaps, to say: > > Dictionary lookup with mutable types like lists can be a > source of unpleasant surprises for the programmer and > therefore not recommended in Python. IOW Python discourages mutable types in any type of container. >> It is not impossible in Python. It may be discouraged but it is not >> impossible since I have already done so. >> > If I discouraged you from shooting yourself in the foot would you do > that too? If I chose not to shoot my self in the foot, it wouldn't be because you discouraged me. It would be because I heard good arguments. What are good arguments or bad and how much weight they have depends on the person and on the circumstances. So a simple rule like: Never use a mutable as a key in a dictionary will sometimes not be the best solution. -- Antoon Pardon From deetsNOSPAM at web.de Tue Jan 18 09:08:44 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 18 Jan 2005 15:08:44 +0100 Subject: generator expressions: performance anomaly? References: <377Hd.77904$Jk5.30235@lakeread01> <354gj7F4etgn8U1@individual.net> <354h9gF4fgsqgU1@individual.net> Message-ID: <354jhnF4gk8l6U1@individual.net> > My thoughts where to let the 'leftmost' section of the expression to be > intact so that any of the dynamic things done to this part, i.e. > replacing time.time with random.random are taken into consideration. > What can be done is to extract the expression into a loopless structure > > lst = list(time.time() for i in xrange(10)) > would be compiled to the bytecode version of: > lst = [time.time(), time.time(), time.time(), time.time() ...] > > Then time.time can do whatever it wants to. It's the (x)range function > that we need to enshure returns the same values in every execution. This > *IS* a useless feature, but I think it's possible to make it work. What makes the leftmost expression different from the iterable returning expression inside the for? The same arguments apply there. -- Regards, Diez B. Roggisch From maxm at mxm.dk Sat Jan 8 14:24:56 2005 From: maxm at mxm.dk (Max M) Date: Sat, 08 Jan 2005 20:24:56 +0100 Subject: Weekly Python Patch/Bug Summary In-Reply-To: References: Message-ID: <41e03383$0$284$edfadb0f@dread12.news.tele.dk> Kurt B. Kaiser wrote: > Remove witty comment in pydoc.py (2005-01-01) > CLOSED http://python.org/sf/1094007 opened by Reinhold Birkenfeld This is not a joke? :-) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From elephantum at dezcom.mephi.ru Mon Jan 10 12:13:25 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Mon, 10 Jan 2005 20:13:25 +0300 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> Message-ID: <34frdmF42p2jrU1@individual.net> Nick Coghlan wrote: > Abstract > -------- > The proposal is to add the capacity for statement local namespaces to > Python. This allows a statement to be placed at the current scope, while > the statement's 'setup code' is indented after the statement:: > > with: > I think using 'with' keyword can cause some ambiguity. for example I would surely try to write >>> x = a+b with self: >>> b = member and using with at the end of block brings more ambiguity: >>> stmt1() >>> stmt2() >>> with self: >>> member = stmt3() compare to: >>> stmt1() >>> stmt2() >>> with: >>> variable = stmt3() a way different semantics with just one word added/deleted. From air_jlin at yahoo.com Mon Jan 24 15:27:45 2005 From: air_jlin at yahoo.com (Johnny Lin) Date: 24 Jan 2005 12:27:45 -0800 Subject: Unbinding multiple variables In-Reply-To: References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> <35bnkeF4jpeetU1@individual.net> <1106334800.868412.27650@f14g2000cwb.googlegroups.com> <41f232b8.1514053864@news.oz.net> Message-ID: <1106598465.731935.237820@z14g2000cwz.googlegroups.com> thanks again for all the help! especially the advice on ideas of tracking down the memory leak :). (sorry for not mentioning it earlier...i had thought deleting everything might be a quick and dirty way short-term fix. :P) best, -Johnny From gandalf at geochemsource.com Fri Jan 21 09:22:48 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Fri, 21 Jan 2005 15:22:48 +0100 Subject: need help on generator... In-Reply-To: <63b5e209.0501210558.686f5c10@posting.google.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> Message-ID: <41F11038.1000903@geochemsource.com> Joh wrote: >hello, > >i'm trying to understand how i could build following consecutive sets >from a root one using generator : > >l = [1,2,3,4] > >would like to produce : > >[1,2], [2,3], [3,4], [1,2,3], [2,3,4] > > Do you mean: [1,2], [2,3], [3,4], [1,2,3], [2,3,4], [1,3,4] (E.g. all elements in the power set except the empty set, the sets with one element and the sets with all elements.) Otherwise, please describe your desired sets in verbal - I cannot see the point. From aurora00 at gmail.com Sun Jan 23 12:00:59 2005 From: aurora00 at gmail.com (aurora) Date: Sun, 23 Jan 2005 09:00:59 -0800 Subject: list unpack trick? References: Message-ID: On Sat, 22 Jan 2005 10:03:27 -0800, aurora wrote: > I am think more in the line of string.ljust(). So if we have a > list.ljust(length, filler), we can do something like > > name, value = s.split('=',1).ljust(2,'') > > I can always break it down into multiple lines. The good thing about > list unpacking is its a really compact and obvious syntax. Just to clarify the ljust() is a feature wish, probably should be named something like pad(). Also there is another thread a few hours before this asking about essentially the same thing. "default value in a list" http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/f3affefdb4272270 From aleaxit at yahoo.com Sun Jan 23 09:46:01 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 23 Jan 2005 15:46:01 +0100 Subject: Reload Tricks References: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> <1gqsb7j.1tbzcqn1f431kdN%aleaxit@yahoo.com> <1106489066.098048.212390@z14g2000cwz.googlegroups.com> Message-ID: <1gqumac.1azcimi14uzz30N%aleaxit@yahoo.com> Kamilche wrote: > Well, I look forward to seeing the new version. I have the old version > of the Python cookbook, it was very useful! I hope the new one is even better -- many more recipes, all updated to Python 2.3 and 2.4. The old one will remain useful for all those who need to keep using older versions of Python, though; to fit more recipes in, the historical discussions of how you did things with Python 1.5.2, 1.6, 2.0 etc have been ruthlessly snipped... Alex From steven.bethard at gmail.com Mon Jan 31 02:11:52 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 31 Jan 2005 00:11:52 -0700 Subject: a Python bug in processing __del__ method ?? In-Reply-To: References: <1107154011.859866.23480@z14g2000cwz.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Baoqiu Cui wrote: > >>The error returned is this: >> >>$ python bug.py >>Exception exceptions.AttributeError: "'NoneType' object has no >>attribute 'population'" in ><__main__.Person instance at 0xa0c9fec>> ignored >> >>However, if I rename variable name 'peter' to something like 'peter1' >>or 'david', the error is gone. Looks to me the >>error only happens to variable name 'peter'. >> >>Does anyone know what is wrong? Is this a bug only on Cygwin? > > it is not a bug, and the documentation has the answer: > > language reference -> index -> __del__ > > http://docs.python.org/ref/customization.html#l2h-175 > > Warning: Due to the precarious circumstances under which __del__() > methods are invoked, exceptions that occur during their execution are > ignored, and a warning is printed to sys.stderr instead. Also, when > __del__() is invoked in response to a module being deleted (e.g., > when execution of the program is done), other globals referenced by > the __del__() method may already have been deleted. For this reason, > __del__() methods should do the absolute minimum needed to > maintain external invariants. > > if you absolutely need to have reliable access to globals, you need to make > sure they're available as instance variables, or are bound in some other way. Along these lines, I think changing your code to: class Person(object): population = 0 def __del__(self): self.__class__.population -= 1 peter = Person() solves the problem. (At least it did for me.) Steve From manatlan_no_s_p_a_m at free.fr Mon Jan 31 17:23:46 2005 From: manatlan_no_s_p_a_m at free.fr (manatlan) Date: Mon, 31 Jan 2005 23:23:46 +0100 Subject: "Mail receiver server" Message-ID: <41feaff2$0$2068$626a14ce@news.free.fr> In an intranet/lan, i'd like to put a "python server script" (which run forever) on a computer A... On another computer B, I'd like to send smtp-email to the computer A ... (send to "user at 126.52.12.12", for example ...126.52.12.12 is the ip address of "B") in fact, i'd like to control "computer A" by sending smtp email from "computer B". What kind of server should i write on computer "B", a smtp server ? a pop server ? (i think i have to make a script which listen on a port, and execute some handlers ... but i don't know how to start) i know python very well, but i dont know anything about smtp/lan if you have a recipe to build this kind of server, it could be good but i'm pretty sure it can be easy to do ... From andre.roberge at gmail.com Sun Jan 23 07:29:22 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 23 Jan 2005 04:29:22 -0800 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> <1106397218.724722.172660@c13g2000cwb.googlegroups.com> Message-ID: <1106483362.505871.172050@z14g2000cwz.googlegroups.com> Nick Coghlan wrote: > Andr? wrote: > > So, students will be able to write: > > pete = CreateRobot(2, 3) > > pete.move() > > > > learning about objects and methods. > > > > As for things like > > for robot in robots: > > do stuff > > > > that will be for my use only: drawing robots on the screen, updating > > the 'world' when robots pick stuff up, etc. My intention is that the > > students will use the EXACT python syntax, so that they don't know that > > *I* have given a *name* to their robot(s) behind the scene. > > I have to cut this short; I hope it clarifies my intentions. > > My (and, if I understand him correctly, Jeremy's) concern would be that error > messages like "Robot 'pete' has hit a wall!" would give students the impression > that the robots automatically know their name as a result of the assignment. In > standard Python, that simply isn't true. > It was not my intention to reveal that I had assigned a 'name' to the robot; it was only for internal purpose. (However, see below) > If, instead, CreateRobot looked something like: > > def CreateRobot(street, avenue, name=None): > if name is None: > name = "Robot" + Robot.getNextNumber() > return Robot(street, avenue, name) > > > Then, using a simple assignment: > > pete = CreateRobot(2, 3) > pete.move() > > Would give an error like: > > "Robot1 has hit a wall" That might be an excellent way to solve my problem. > > This could then be used to point out that objects named using assignment don't > know about the names they have been given, and need to be told: > > pete = CreateRobot(2, 3, "Pete") > pete.move() > > "Pete has hit a wall" > > Instead of misleading the students ("objects know what names they have been > given"), you have taught them a powerful truth - objects and the names you give > them via assignment are entirely independent. Good point. > > It also directly addresses the question of aliasing. Think about how Steven's > modified dictionary would react to this code: > > pete = CreateRobot(2, 3) > dad = pete > dad.move() > pete.move() > > Internally, idioms like "for robot in robots" should be entirely unaffected - > the registration of the robot instance with the global list of robots can be > handled by the robot initialisation method. > You make some excellent points. What I implemented (last night) was the "code pre-processing" suggestion. Instead of simply "exec"uting the code, I changed it first so that statements like pete = CreateRobot(2, 3) john = CreateRobot() albert = CreateRobot(colour="blue") get translated to pete = CreateRobot(2, 3, name="pete") john = CreateRobot(name="john") albert = CreateRobot(colour="blue", name="albert") I just checked with: pete = CreateRobot() dad = pete dad.move() pete.move() and I got (I haven't implemented the gui part of dealing with multiple robots) == robot pete move() robot pete move() == which worked the same way as your method would (except with "pete" as a common name instead of "Robot1"). [As an aside, it was an *interesting* experience to learn enough about regular expressions to do this.] Now, after reading your post, I realise that I would have to deal with the problem of figuring out how to handle cases where the users has already given a name to the robot. Your solution takes care of this in a very simple way. Furthermore, I could probably base a lesson around it, about how instances have no name. Thank you very much for your suggestions. Andr? From cookedm+news at physics.mcmaster.ca Thu Jan 13 22:47:24 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 13 Jan 2005 22:47:24 -0500 Subject: Pyrex-0.9.3: definition mismatch with distutils of Python24 References: <41e6e1c5.8718906@news.muenster.de> Message-ID: mb at muenster.de (Martin Bless) writes: > Now that I've got my extension building machine using the VC++ Toolkit > 2003 up and running I'm keen on using Pyrex (Pyrex-0.9.3, > Python-2.4.0). > > But the definition of the swig_sources() method seems to have changed. > > When I try to build the examples from Pyrex I get a TypeError: > > > c:\Pyrex-0.9.3\Demos> python Setup.py build_ext --inplace > running build_ext > building 'primes' extension > [...] > File "C:\Python24\lib\distutils\command\build_ext.py", line 442, in > build_extension > sources = self.swig_sources(sources, ext) > TypeError: swig_sources() takes exactly 2 arguments (3 given) > > > I can see that Pyrex.Distutils.build_ext.py subclasses > distutils.command.build_ext.build_ext, and the number of arguments of > the swig_sources method seems to have changed. > > Pyrex uses: > > def swig_sources (self, sources): > > whereas the distutils use: > > def swig_sources (self, sources, extension): > > If I just add the "extension" arg to the Pyrex definitions everything > seems to work. But I have to admit that I don't really know what I'm > doing here and I feel sorry I can't contribute more than just > reporting the error. Yep, that's it. Greg must know now, it's been reported a few times. You'll want to change it to def swig_sources(self, sources, extension=None): so that if you use an older python it won't complain about missing arguments. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From newsgroups at jhrothjr.com Sat Jan 8 22:29:47 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 8 Jan 2005 21:29:47 -0600 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <41e09808.360402200@news.oz.net> Message-ID: <10u19a32e5affc1@news.supernews.com> "Bengt Richter" wrote in message news:41e09808.360402200 at news.oz.net... > On Sat, 08 Jan 2005 12:47:52 -0500, Peter Hansen > wrote: > >>Paul Rubin wrote: >>> When Unix was first written, people thought implementing an OS in C >>> was ludicrous. Everyone knew OS's had to be written in assembler. >> >>Actually, when Unix was first written that belief was entirely >>correct, and OSes *did* have to be written in assembler. >> >>That is, pure C did not have the capability to handle all >>that was required. I recall it taking a good decade before it >>became *common* to find C compilers with, for example, @interrupt >>support to let the compiler generate code that properly saved >>all registers and used RTI instead of RTS (or whatever it might >>have been called one one's particular flavour of CPU). >> >>Now, once you added a few tiny interrupt handlers, and some context >>switching (stack manipulation) routines, pretty much everything else >>*could* be done in C, but that doesn't invalidate the point. >> >>I think it's safe to say that none of pure C, pure Lisp, or pure Python >>are really capable of being used as the *sole* language to build >>an operating system. >> >>It's also safe to say that this is a largely irrelevant point. >>It would probably only be of academic interest to try to do >>something like that. Any practical attempt would not think more >>than twice of resorting to a little "glue" in assembler or in >>the form of "canned" byte sequences built by hand and stuck >>into the appropriate places in memory... > Well, usually there's more than one tool in the chain from source > to bootable loader and OS image, even if you are writing in C and > assembler, > and there's usually more to an OS than the bootable image contains. > > So ISTM "writing an OS in " is pretty loose talk ;-) Most people who work in the field know what it means, though. One of the touchstones of language design is whether you can write the compiler and runtime in that language. PyPy is working on that for Python, Squeak Smalltalk is written in Smalltalk and then converted to C for compilation of the runtime. Both of them are completely virtualizable: you can run them (very slowly) under themselves for testing. Given that everything in Python is an object, I see no reason why one couldn't create a set of objects that are appropriate for an operating system kernel and can also be converted cleanly to the operating system subset of C, and write a converter that does it. That's the easy part. The hard part is writing the operating system. Look at the (lack of) progress the GNU HURD project has been making recently. John Roth > > Regards, > Bengt Richter From erwin+usenet at andreasen.org Sun Jan 16 16:19:14 2005 From: erwin+usenet at andreasen.org (Erwin S. Andreasen) Date: Sun, 16 Jan 2005 22:19:14 +0100 Subject: Excel module for Python References: Message-ID: <87brbpdqct.fsf@andreasen.org> Simon Brunning writes: > On Wed, 12 Jan 2005 23:19:44 +0800, sam wrote: >> >> No, I don't use MS windows. I need to generate Excel file by printing >> data to it, just like Perl module Spreadsheet::WriteExcel. > If you need to write out formulae, formratting, that kind of thing, > then I think you'll need to write a 'real' Excel file. I don't have a > clue how to do that - sorry. There's actually an ancient open spreadsheet format called SYLK which is a step above CSV: it allows formatting of data, formulas etc. Google for SYLK to get the rather sparse specification (and skip over the first few links!) If you want to generate "real" Office files from UNIX, another alternative is to automate OpenOffice (which has a COM-like interface too) or generate OO XML files and feed them to OO asking to conver them with a bit of OO macro magic. -- =============================================================== Herlev, Denmark <*> =============================================================== From __peter__ at web.de Thu Jan 6 03:32:35 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Jan 2005 09:32:35 +0100 Subject: No typical loops, and other crazy ideas References: Message-ID: Bulba! wrote: > motivation). I've tried to manipulate the data just in Python > and not in typical loops. One thing that may not be entirely A list comprehension is just a fancy way to write a loop. Resisting the temptation to use it can sometimes improve your code. > [Also, for some reason the advice by another poster, to > use: > > oldl=list(orig) > > instead of: > > oldl=[x for x in orig] > > ..somehow didn't work. The first instruction has produced only empty > lists.] > > > #---------Code follows----------- [...] > #oldl=list(orig) > #newl=list(orig) Because you used the same reader twice newl will always be empty. Peter From pushlinque at hotmail.com Tue Jan 11 23:13:08 2005 From: pushlinque at hotmail.com (Jane) Date: Tue, 11 Jan 2005 23:13:08 -0500 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <1105497928.471241.13590@z14g2000cwz.googlegroups.com> Message-ID: "La bouche de la v?rit? - D?j? Vu Le Proph?te" wrote in message news:1105497928.471241.13590 at z14g2000cwz.googlegroups.com... > Your Uncle Wally just luuirrrrrrrrrrrrrvs > Monty Python -- especially John Clesse, Eric Idle > & Michael Palin -- very funny !!!!!!!! > > he he he ;-) Believe it or not, we have something in common! I love 'em, too! Jane > From sesquile at gmail.com Mon Jan 31 16:04:03 2005 From: sesquile at gmail.com (mh) Date: 31 Jan 2005 13:04:03 -0800 Subject: [ANN] Spike Asset Manager release 0.13 In-Reply-To: References: <1107196878.026930.154270@c13g2000cwb.googlegroups.com> Message-ID: <1107205443.213015.28550@z14g2000cwz.googlegroups.com> The idea is to have a framework to do this in a semi-crossplatform manner. The framework could be updated to know about apt, portage repositories as well as talk to to the windows registry. Not everyone is running redhat ;) From beliavsky at aol.com Sat Jan 29 09:53:09 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 29 Jan 2005 06:53:09 -0800 Subject: Coding style article with interesting section on white space References: Message-ID: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> Nick Coghlan wrote: > Thought some folks here might find this one interesting. No great revelations, > just a fairly sensible piece on writing readable code :) > > The whole article: > http://www.acmqueue.com/modules.php?name=Content&pa=showpage&pid=271&page=1 > > The section specifically on white space: > http://www.acmqueue.com/modules.php?name=Content&pa=showpage&pid=271&page=3 The suggestions in the cited article, "How Not to Write FORTRAN in Any Language", are reasonable but elementary and can be followed in Fortran 90/95/2003 as well as any other language. What infuriates me is that the author writes as if Fortran has not evolved since the 1960s. It has. To be specific, Fortran 90 (1) allows variable names up to 31 characters long (2) has a free source form where (a) there are no rigid rules about starting code in a certain column (b) white space is significant (3) has a full set of control structures -- goto's are almost never needed More detailed rebuttals of the article are in the archives of the Fortran 90 discussion group at http://www.jiscmail.ac.uk/cgi-bin/webadmin?A1=ind0501&L=comp-fortran-90 -- search for "Fortran bashing". Python looks more like Fortran 90 than one of the curly-brace/semicolon languages, and both languages have modules and array slices. One ought to do a little research before publishing an article. Apparently, many authors and editors are too lazy to do so. From aleaxit at yahoo.com Fri Jan 7 04:15:08 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 10:15:08 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: <1gq0k50.1ooqtco97v2sN%aleaxit@yahoo.com> Bulba! wrote: > Suppose they want to ensure "no forking" or that "bugfixes > and enhancements of original software are given back". > > OK, LGPL is fine for this goal. When you say "they see it Neither LGPL nor GPL can ``ensure "no forking"'', nor can any other open-source license. Alex From fccoelho at gmail.com Sun Jan 9 17:13:28 2005 From: fccoelho at gmail.com (Flavio codeco coelho) Date: 9 Jan 2005 14:13:28 -0800 Subject: Python serial data aquisition Message-ID: Hi, I am using pyserial to acquire data from an A/D converter plugged to my serial port. my hardware represents analog voltages as 12bit numbers. So, according to the manufacturer, this number will be stored in two bytes like this; |-------------bits(1-8)-----------| Byte1: x x x n1 n2 n3 n4 n5 Byte2: x n6 n7 n8 n9 n10 n11 n12 where x is some other information, and nx are the digits of my number. My problem is to how to recover my reading from these bytes, since pyserial gives me a character (string) from each byte... I dont know how to throw away the unneeded bits and concatenate the remaining bits to form a number... Fl?vio Code?o Coelho From steven.bethard at gmail.com Fri Jan 7 18:05:31 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 16:05:31 -0700 Subject: Notification of PEP Updates In-Reply-To: <41df128d.260695390@news.oz.net> References: <41df128d.260695390@news.oz.net> Message-ID: Bengt Richter wrote: > On Sat, 08 Jan 2005 03:28:34 +1000, Nick Coghlan wrote: > > >>I can't recall which thread this came up in, so I'm starting a new one. . . >> >>Barry Warsaw has kindly added a "peps" topic to the python-checkins mailing >>list. If you want to be notified only when PEP's get updated, then subscribe to >>python-checkins and edit your settings to select just the 'peps' topic. > > How does one get to editing one's settings? Go to the bottom of the page http://mail.python.org/mailman/listinfo/python-checkins under "Python-checkins Subscribers", fill in your email address and click "Unsubscribe or edit options". Fill in the "password" field on the next page and click "Log in". The topic option should be near the bottom of the page. Steve From fredrik at pythonware.com Sun Jan 30 02:40:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Jan 2005 08:40:15 +0100 Subject: Coding style article with interesting section on white space References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com><1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> Message-ID: beliavsky at aol.com wrote: > The recent "Pystone Benchmark" message says that Python is only 75% as > fast on Linux as on Windows. no, it really only says that the Pystone benchmark is 75% as fast as Linux as on Windows, on the poster's hardware, using his configuration, and using different compilers. From apardon at forel.vub.ac.be Mon Jan 17 06:41:20 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2005 11:41:20 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-17, Steve Holden schreef : > Antoon Pardon wrote: > [...] >>>"A foolish consistency is the hobgoblin of little minds". Rules are made >>>to be broken. >> >> >> Like only use immutables as dictionary keys. >> > Fair enough, but don;t go advising newbies to do this. How about something like this. Because of the extra precautions one has to take when using mutables as hash keys, we advise newbies to stick with immutable keys until they have gathered enough knowledge and experience to adequatly weight the pro and cons of a mutable key solution against an immutable key solution. -- Antoon Pardon From steven.bethard at gmail.com Wed Jan 12 12:42:06 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 10:42:06 -0700 Subject: property () for Java Programmers ? In-Reply-To: References: Message-ID: michael wrote: > Hi there, > > I am somewhat confused by the following : > > class C(object): > def getx(self): return self.__x > def setx(self, value): self.__x = "extended" + value > def delx(self): del self.__x > x = property(getx, setx, delx, "I'm the 'x' property.") > > So far so good :-) But what to do with this now > > >>>>c = C >>>>c > > > >>>>dir (c) > > ['__class__', '__delattr__', '__dict__', '__doc__', > '__getattribute__', '__hash__', '__init__', '__module__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', > '__weakref__', 'delx', 'getx', 'setx', 'x'] > >>>>c.x > > > > > ?????? What can I do with this "property object" now. Well, if you actually want your getx/setx/delx to be called, then you need an *instance* of class C: py> c = C() py> c.x Traceback (most recent call last): File "", line 1, in ? File "", line 2, in getx AttributeError: 'C' object has no attribute '_C__x' py> c.x = "42" py> c.x 'extended42' py> del c.x py> c.x Traceback (most recent call last): File "", line 1, in ? File "", line 2, in getx AttributeError: 'C' object has no attribute '_C__x' Note that I used 'c = C()' instead of 'c = C' as in your code. STeve From elephantum at dezcom.mephi.ru Fri Jan 7 07:31:54 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Fri, 07 Jan 2005 15:31:54 +0300 Subject: embedded scripts debugging Message-ID: <347dpqF45nskbU1@individual.net> Hi all. I have custom resource editor and wish python to be scripting language in it. But I don't want to lose ability of debugging which I currently have implementing all logic in C++. So the question is: Is there suitable library for simple python gui debugger, or may be there are some other techniques for debugging embedded scripts? From dek at pabst.lbl.gov Wed Jan 12 19:19:47 2005 From: dek at pabst.lbl.gov (David E. Konerding DSD staff) Date: Thu, 13 Jan 2005 00:19:47 +0000 (UTC) Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: In article <1105569967.129284.85470 at c13g2000cwb.googlegroups.com>, Chris Lasher wrote: > Hello, > I have a rather large (100+ MB) FASTA file from which I need to > access records in a random order. The FASTA format is a standard format > for storing molecular biological sequences. Each record contains a > header line for describing the sequence that begins with a '>' > (right-angle bracket) followed by lines that contain the actual > sequence data. Three example FASTA records are below: Use biopython. They have dictionary-style classes which wrap FASTA files using indexes. http://www.biopython.org Dave From bulba at bulba.com Thu Jan 6 16:35:31 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 22:35:31 +0100 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 06 Ja